{"version":3,"sources":["../../../../../src/client/components/segment-cache/cache.ts"],"sourcesContent":["import type {\n  TreePrefetch,\n  RootTreePrefetch,\n  SegmentPrefetch,\n  InlinedPrefetchResponse,\n  InlinedSegmentPrefetch,\n} from '../../../server/app-render/collect-segment-data'\nimport type {\n  CacheNodeSeedData,\n  FlightData,\n  Segment as FlightRouterStateSegment,\n} from '../../../shared/lib/app-router-types'\nimport {\n  readVaryParams,\n  type VaryParams,\n  type VaryParamsThenable,\n} from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport {\n  NEXT_DID_POSTPONE_HEADER,\n  NEXT_INSTANT_PREFETCH_HEADER,\n  NEXT_ROUTER_PREFETCH_HEADER,\n  NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n  NEXT_ROUTER_STALE_TIME_HEADER,\n  NEXT_ROUTER_STATE_TREE_HEADER,\n  NEXT_URL,\n  RSC_CONTENT_TYPE_HEADER,\n  RSC_HEADER,\n} from '../app-router-headers'\nimport {\n  createFetch,\n  createFromNextReadableStream,\n  type RSCResponse,\n  type RequestHeaders,\n} from '../router-reducer/fetch-server-response'\nimport {\n  pingPrefetchTask,\n  isPrefetchTaskDirty,\n  type PrefetchTask,\n  type PrefetchSubtaskResult,\n} from './scheduler'\nimport {\n  type RouteVaryPath,\n  type SegmentVaryPath,\n  type PartialSegmentVaryPath,\n  getRouteVaryPath,\n  getFulfilledRouteVaryPath,\n  getFulfilledSegmentVaryPath,\n  getSegmentVaryPathForRequest,\n  appendLayoutVaryPath,\n  finalizeLayoutVaryPath,\n  finalizePageVaryPath,\n  clonePageVaryPathWithNewSearchParams,\n  type PageVaryPath,\n  type LayoutVaryPath,\n  finalizeMetadataVaryPath,\n  getPartialPageVaryPath,\n  getPartialLayoutVaryPath,\n  getRenderedSearchFromVaryPath,\n} from './vary-path'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport type {\n  NormalizedPathname,\n  NormalizedSearch,\n  NormalizedNextUrl,\n  RouteCacheKey,\n} from './cache-key'\nimport { createCacheKey as createPrefetchRequestKey } from './cache-key'\nimport {\n  doesStaticSegmentAppearInURL,\n  getCacheKeyForDynamicParam,\n  getRenderedPathname,\n  getRenderedSearch,\n  parseDynamicParamFromURLPart,\n} from '../../route-params'\nimport {\n  createCacheMap,\n  getFromCacheMap,\n  setInCacheMap,\n  setSizeInCacheMap,\n  deleteFromCacheMap,\n  isValueExpired,\n  type CacheMap,\n  type UnknownMapEntry,\n} from './cache-map'\nimport {\n  appendSegmentRequestKeyPart,\n  convertSegmentPathToStaticExportFilename,\n  createSegmentRequestKeyPart,\n  HEAD_REQUEST_KEY,\n  ROOT_SEGMENT_REQUEST_KEY,\n  type SegmentRequestKey,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport type {\n  FlightRouterState,\n  NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\nimport {\n  type NormalizedFlightData,\n  normalizeFlightData,\n  prepareFlightRouterStateForRequest,\n} from '../../flight-data-helpers'\nimport { STATIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'\nimport { pingVisibleLinks } from '../links'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport { FetchStrategy } from './types'\nimport { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'\nimport { readFromBFCache, UnknownDynamicStaleTime } from './bfcache'\nimport { discoverKnownRoute, matchKnownRoute } from './optimistic-routes'\nimport { convertServerPatchToFullTree, type NavigationSeed } from './navigation'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\n\n/**\n * Ensures a minimum stale time of 30s to avoid issues where the server sends a too\n * short-lived stale time, which would prevent anything from being prefetched.\n */\nexport function getStaleTimeMs(staleTimeSeconds: number): number {\n  return Math.max(staleTimeSeconds, 30) * 1000\n}\n\n// A note on async/await when working in the prefetch cache:\n//\n// Most async operations in the prefetch cache should *not* use async/await,\n// Instead, spawn a subtask that writes the results to a cache entry, and attach\n// a \"ping\" listener to notify the prefetch queue to try again.\n//\n// The reason is we need to be able to access the segment cache and traverse its\n// data structures synchronously. For example, if there's a synchronous update\n// we can take an immediate snapshot of the cache to produce something we can\n// render. Limiting the use of async/await also makes it easier to avoid race\n// conditions, which is especially important because is cache is mutable.\n//\n// Another reason is that while we're performing async work, it's possible for\n// existing entries to become stale, or for Link prefetches to be removed from\n// the queue. For optimal scheduling, we need to be able to \"cancel\" subtasks\n// that are no longer needed. So, when a segment is received from the server, we\n// restart from the root of the tree that's being prefetched, to confirm all the\n// parent segments are still cached. If the segment is no longer reachable from\n// the root, then it's effectively canceled. This is similar to the design of\n// Rust Futures, or React Suspense.\n\ntype RouteTreeShared = {\n  requestKey: SegmentRequestKey\n  // TODO: Remove the `segment` field, now that it can be reconstructed\n  // from `param`.\n  segment: FlightRouterStateSegment\n  refreshState: RefreshState | null\n  slots: null | {\n    [parallelRouteKey: string]: RouteTree\n  }\n  // Bitmask of PrefetchHint flags. Encodes route structure metadata:\n  // root layout, loading boundaries, instant configs, and runtime prefetch\n  // hints.\n  prefetchHints: number\n}\n\nexport type RefreshState = {\n  canonicalUrl: string\n  renderedSearch: NormalizedSearch\n}\n\ntype LayoutRouteTree = RouteTreeShared & {\n  isPage: false\n  varyPath: LayoutVaryPath\n}\n\ntype PageRouteTree = RouteTreeShared & {\n  isPage: true\n  varyPath: PageVaryPath\n}\n\nexport type RouteTree = LayoutRouteTree | PageRouteTree\n\ntype RouteCacheEntryShared = {\n  // This is false only if we're certain the route cannot be intercepted. It's\n  // true in all other cases, including on initialization when we haven't yet\n  // received a response from the server.\n  couldBeIntercepted: boolean\n\n  // Map-related fields.\n  ref: UnknownMapEntry | null\n  size: number\n  staleAt: number\n  version: number\n}\n\n/**\n * Tracks the status of a cache entry as it progresses from no data (Empty),\n * waiting for server data (Pending), and finished (either Fulfilled or\n * Rejected depending on the response from the server.\n */\nexport const enum EntryStatus {\n  Empty = 0,\n  Pending = 1,\n  Fulfilled = 2,\n  Rejected = 3,\n}\n\nexport type PendingRouteCacheEntry = RouteCacheEntryShared & {\n  status: EntryStatus.Empty | EntryStatus.Pending\n  blockedTasks: Set<PrefetchTask> | null\n  canonicalUrl: null\n  renderedSearch: null\n  tree: null\n  metadata: null\n  supportsPerSegmentPrefetching: false\n}\n\ntype RejectedRouteCacheEntry = RouteCacheEntryShared & {\n  status: EntryStatus.Rejected\n  blockedTasks: Set<PrefetchTask> | null\n  canonicalUrl: null\n  renderedSearch: null\n  tree: null\n  metadata: null\n  supportsPerSegmentPrefetching: boolean\n}\n\nexport type FulfilledRouteCacheEntry = RouteCacheEntryShared & {\n  status: EntryStatus.Fulfilled\n  blockedTasks: null\n  canonicalUrl: string\n  renderedSearch: NormalizedSearch\n  tree: RouteTree\n  metadata: RouteTree\n  supportsPerSegmentPrefetching: boolean\n  // When true, this entry should not be used as a template for route\n  // prediction. Set when we discover that the URL was rewritten by middleware\n  // to a different route structure (e.g., /foo was rewritten to /bar). Since\n  // rewrite behavior can vary by param value, we can't safely predict the\n  // route structure for other URLs matching this pattern.\n  hasDynamicRewrite: boolean\n}\n\nexport type RouteCacheEntry =\n  | PendingRouteCacheEntry\n  | FulfilledRouteCacheEntry\n  | RejectedRouteCacheEntry\n\ntype SegmentCacheEntryShared = {\n  fetchStrategy: FetchStrategy\n\n  // Map-related fields.\n  ref: UnknownMapEntry | null\n  size: number\n  staleAt: number\n  version: number\n}\n\nexport type EmptySegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Empty\n  rsc: null\n  isPartial: true\n  promise: null\n}\n\nexport type PendingSegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Pending\n  rsc: null\n  isPartial: boolean\n  promise: null | PromiseWithResolvers<FulfilledSegmentCacheEntry | null>\n}\n\ntype RejectedSegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Rejected\n  rsc: null\n  isPartial: true\n  promise: null\n}\n\nexport type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {\n  status: EntryStatus.Fulfilled\n  rsc: React.ReactNode | null\n  isPartial: boolean\n  promise: null\n}\n\nexport type SegmentCacheEntry =\n  | EmptySegmentCacheEntry\n  | PendingSegmentCacheEntry\n  | RejectedSegmentCacheEntry\n  | FulfilledSegmentCacheEntry\n\nexport type NonEmptySegmentCacheEntry = Exclude<\n  SegmentCacheEntry,\n  EmptySegmentCacheEntry\n>\n\nconst isOutputExportMode =\n  process.env.NODE_ENV === 'production' &&\n  process.env.__NEXT_CONFIG_OUTPUT === 'export'\n\nconst MetadataOnlyRequestTree: FlightRouterState = [\n  '',\n  {},\n  null,\n  'metadata-only',\n]\n\nlet routeCacheMap: CacheMap<RouteCacheEntry> = createCacheMap()\nlet segmentCacheMap: CacheMap<SegmentCacheEntry> = createCacheMap()\n\n// All invalidation listeners for the whole cache are tracked in single set.\n// Since we don't yet support tag or path-based invalidation, there's no point\n// tracking them any more granularly than this. Once we add granular\n// invalidation, that may change, though generally the model is to just notify\n// the listeners and allow the caller to poll the prefetch cache with a new\n// prefetch task if desired.\nlet invalidationListeners: Set<PrefetchTask> | null = null\n\n// Incrementing counters used to track cache invalidations. Route and segment\n// caches have separate versions so they can be invalidated independently.\n// Invalidation does not eagerly evict anything from the cache; entries are\n// lazily evicted when read.\nlet currentRouteCacheVersion = 0\nlet currentSegmentCacheVersion = 0\n\nexport function getCurrentRouteCacheVersion(): number {\n  return currentRouteCacheVersion\n}\n\nexport function getCurrentSegmentCacheVersion(): number {\n  return currentSegmentCacheVersion\n}\n\n/**\n * Invalidates all prefetch cache entries (both route and segment caches).\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */\nexport function invalidateEntirePrefetchCache(\n  nextUrl: string | null,\n  tree: FlightRouterState\n): void {\n  currentRouteCacheVersion++\n  currentSegmentCacheVersion++\n\n  pingVisibleLinks(nextUrl, tree)\n  pingInvalidationListeners(nextUrl, tree)\n}\n\n/**\n * Invalidates all route cache entries. Route entries contain the tree structure\n * (which segments exist at a given URL) but not the segment data itself.\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */\nexport function invalidateRouteCacheEntries(\n  nextUrl: string | null,\n  tree: FlightRouterState\n): void {\n  currentRouteCacheVersion++\n\n  pingVisibleLinks(nextUrl, tree)\n  pingInvalidationListeners(nextUrl, tree)\n}\n\n/**\n * Invalidates all segment cache entries. Segment entries contain the actual\n * RSC data for each segment.\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */\nexport function invalidateSegmentCacheEntries(\n  nextUrl: string | null,\n  tree: FlightRouterState\n): void {\n  currentSegmentCacheVersion++\n\n  pingVisibleLinks(nextUrl, tree)\n  pingInvalidationListeners(nextUrl, tree)\n}\n\nfunction attachInvalidationListener(task: PrefetchTask): void {\n  // This function is called whenever a prefetch task reads a cache entry. If\n  // the task has an onInvalidate function associated with it — i.e. the one\n  // optionally passed to router.prefetch(onInvalidate) — then we attach that\n  // listener to the every cache entry that the task reads. Then, if an entry\n  // is invalidated, we call the function.\n  if (task.onInvalidate !== null) {\n    if (invalidationListeners === null) {\n      invalidationListeners = new Set([task])\n    } else {\n      invalidationListeners.add(task)\n    }\n  }\n}\n\nfunction notifyInvalidationListener(task: PrefetchTask): void {\n  const onInvalidate = task.onInvalidate\n  if (onInvalidate !== null) {\n    // Clear the callback from the task object to guarantee it's not called more\n    // than once.\n    task.onInvalidate = null\n\n    // This is a user-space function, so we must wrap in try/catch.\n    try {\n      onInvalidate()\n    } catch (error) {\n      if (typeof reportError === 'function') {\n        reportError(error)\n      } else {\n        console.error(error)\n      }\n    }\n  }\n}\n\nexport function pingInvalidationListeners(\n  nextUrl: string | null,\n  tree: FlightRouterState\n): void {\n  // The rough equivalent of pingVisibleLinks, but for onInvalidate callbacks.\n  // This is called when the Next-Url or the base tree changes, since those\n  // may affect the result of a prefetch task. It's also called after a\n  // cache invalidation.\n  if (invalidationListeners !== null) {\n    const tasks = invalidationListeners\n    invalidationListeners = null\n    for (const task of tasks) {\n      if (isPrefetchTaskDirty(task, nextUrl, tree)) {\n        notifyInvalidationListener(task)\n      }\n    }\n  }\n}\n\nexport function readRouteCacheEntry(\n  now: number,\n  key: RouteCacheKey\n): RouteCacheEntry | null {\n  const varyPath: RouteVaryPath = getRouteVaryPath(\n    key.pathname,\n    key.search,\n    key.nextUrl\n  )\n  const isRevalidation = false\n  const existingEntry = getFromCacheMap(\n    now,\n    getCurrentRouteCacheVersion(),\n    routeCacheMap,\n    varyPath,\n    isRevalidation\n  )\n  if (existingEntry !== null) {\n    return existingEntry\n  }\n\n  // No cache hit. Attempt to construct from template using the new\n  // optimistic routing mechanism (pattern-based matching).\n  if (process.env.__NEXT_OPTIMISTIC_ROUTING) {\n    return matchKnownRoute(key.pathname, key.search)\n  }\n\n  return null\n}\n\nexport function readSegmentCacheEntry(\n  now: number,\n  varyPath: SegmentVaryPath\n): SegmentCacheEntry | null {\n  const isRevalidation = false\n  return getFromCacheMap(\n    now,\n    getCurrentSegmentCacheVersion(),\n    segmentCacheMap,\n    varyPath,\n    isRevalidation\n  )\n}\n\nfunction readRevalidatingSegmentCacheEntry(\n  now: number,\n  varyPath: SegmentVaryPath\n): SegmentCacheEntry | null {\n  const isRevalidation = true\n  return getFromCacheMap(\n    now,\n    getCurrentSegmentCacheVersion(),\n    segmentCacheMap,\n    varyPath,\n    isRevalidation\n  )\n}\n\nexport function waitForSegmentCacheEntry(\n  pendingEntry: PendingSegmentCacheEntry\n): Promise<FulfilledSegmentCacheEntry | null> {\n  // Because the entry is pending, there's already a in-progress request.\n  // Attach a promise to the entry that will resolve when the server responds.\n  let promiseWithResolvers = pendingEntry.promise\n  if (promiseWithResolvers === null) {\n    promiseWithResolvers = pendingEntry.promise =\n      createPromiseWithResolvers<FulfilledSegmentCacheEntry | null>()\n  } else {\n    // There's already a promise we can use\n  }\n  return promiseWithResolvers.promise\n}\n\nfunction createDetachedRouteCacheEntry(): PendingRouteCacheEntry {\n  return {\n    canonicalUrl: null,\n    status: EntryStatus.Empty,\n    blockedTasks: null,\n    tree: null,\n    metadata: null,\n    // This is initialized to true because we don't know yet whether the route\n    // could be intercepted. It's only set to false once we receive a response\n    // from the server.\n    couldBeIntercepted: true,\n    // Similarly, we don't yet know if the route supports PPR.\n    supportsPerSegmentPrefetching: false,\n    renderedSearch: null,\n\n    // Map-related fields\n    ref: null,\n    size: 0,\n    // Since this is an empty entry, there's no reason to ever evict it. It will\n    // be updated when the data is populated.\n    staleAt: Infinity,\n    version: getCurrentRouteCacheVersion(),\n  }\n}\n\n/**\n * Checks if an entry for a route exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */\nexport function readOrCreateRouteCacheEntry(\n  now: number,\n  task: PrefetchTask,\n  key: RouteCacheKey\n): RouteCacheEntry {\n  attachInvalidationListener(task)\n\n  const existingEntry = readRouteCacheEntry(now, key)\n  if (existingEntry !== null) {\n    return existingEntry\n  }\n  // Create a pending entry and add it to the cache.\n  const pendingEntry = createDetachedRouteCacheEntry()\n  const varyPath: RouteVaryPath = getRouteVaryPath(\n    key.pathname,\n    key.search,\n    key.nextUrl\n  )\n  const isRevalidation = false\n  setInCacheMap(routeCacheMap, varyPath, pendingEntry, isRevalidation)\n  return pendingEntry\n}\n\n// TODO: This function predates the new optimisticRouting feature and will be\n// removed once optimisticRouting is stable. The new mechanism (matchKnownRoute)\n// handles search param variations more robustly as part of the general route\n// prediction system. This fallback remains for when optimisticRouting is\n// disabled (staticChildren is null).\nexport function deprecated_requestOptimisticRouteCacheEntry(\n  now: number,\n  requestedUrl: URL,\n  nextUrl: string | null\n): FulfilledRouteCacheEntry | null {\n  // This function is called during a navigation when there was no matching\n  // route tree in the prefetch cache. Before de-opting to a blocking,\n  // unprefetched navigation, we will first attempt to construct an \"optimistic\"\n  // route tree by checking the cache for similar routes.\n  //\n  // Check if there's a route with the same pathname, but with different\n  // search params. We can then base our optimistic route tree on this entry.\n  //\n  // Conceptually, we are simulating what would happen if we did perform a\n  // prefetch the requested URL, under the assumption that the server will\n  // not redirect or rewrite the request in a different manner than the\n  // base route tree. This assumption might not hold, in which case we'll have\n  // to recover when we perform the dynamic navigation request. However, this\n  // is what would happen if a route were dynamically rewritten/redirected\n  // in between the prefetch and the navigation. So the logic needs to exist\n  // to handle this case regardless.\n\n  // Look for a route with the same pathname, but with an empty search string.\n  // TODO: There's nothing inherently special about the empty search string;\n  // it's chosen somewhat arbitrarily, with the rationale that it's the most\n  // likely one to exist. But we should update this to match _any_ search\n  // string. The plan is to generalize this logic alongside other improvements\n  // related to \"fallback\" cache entries.\n  const requestedSearch = requestedUrl.search as NormalizedSearch\n  if (requestedSearch === '') {\n    // The caller would have already checked if a route with an empty search\n    // string is in the cache. So we can bail out here.\n    return null\n  }\n  const urlWithoutSearchParams = new URL(requestedUrl)\n  urlWithoutSearchParams.search = ''\n  const routeWithNoSearchParams = readRouteCacheEntry(\n    now,\n    createPrefetchRequestKey(urlWithoutSearchParams.href, nextUrl)\n  )\n\n  if (\n    routeWithNoSearchParams === null ||\n    routeWithNoSearchParams.status !== EntryStatus.Fulfilled\n  ) {\n    // Bail out of constructing an optimistic route tree. This will result in\n    // a blocking, unprefetched navigation.\n    return null\n  }\n\n  // Now we have a base route tree we can \"patch\" with our optimistic values.\n\n  // Optimistically assume that redirects for the requested pathname do\n  // not vary on the search string. Therefore, if the base route was\n  // redirected to a different search string, then the optimistic route\n  // should be redirected to the same search string. Otherwise, we use\n  // the requested search string.\n  const canonicalUrlForRouteWithNoSearchParams = new URL(\n    routeWithNoSearchParams.canonicalUrl,\n    requestedUrl.origin\n  )\n  const optimisticCanonicalSearch =\n    canonicalUrlForRouteWithNoSearchParams.search !== ''\n      ? // Base route was redirected. Reuse the same redirected search string.\n        canonicalUrlForRouteWithNoSearchParams.search\n      : requestedSearch\n\n  // Similarly, optimistically assume that rewrites for the requested\n  // pathname do not vary on the search string. Therefore, if the base\n  // route was rewritten to a different search string, then the optimistic\n  // route should be rewritten to the same search string. Otherwise, we use\n  // the requested search string.\n  const optimisticRenderedSearch =\n    routeWithNoSearchParams.renderedSearch !== ''\n      ? // Base route was rewritten. Reuse the same rewritten search string.\n        routeWithNoSearchParams.renderedSearch\n      : requestedSearch\n\n  const optimisticUrl = new URL(\n    routeWithNoSearchParams.canonicalUrl,\n    location.origin\n  )\n  optimisticUrl.search = optimisticCanonicalSearch\n  const optimisticCanonicalUrl = createHrefFromUrl(optimisticUrl)\n\n  const optimisticRouteTree = deprecated_createOptimisticRouteTree(\n    routeWithNoSearchParams.tree,\n    optimisticRenderedSearch\n  )\n  const optimisticMetadataTree = deprecated_createOptimisticRouteTree(\n    routeWithNoSearchParams.metadata,\n    optimisticRenderedSearch\n  )\n\n  // Clone the base route tree, and override the relevant fields with our\n  // optimistic values.\n  const optimisticEntry: FulfilledRouteCacheEntry = {\n    canonicalUrl: optimisticCanonicalUrl,\n\n    status: EntryStatus.Fulfilled,\n    // This isn't cloned because it's instance-specific\n    blockedTasks: null,\n    tree: optimisticRouteTree,\n    metadata: optimisticMetadataTree,\n    couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted,\n    supportsPerSegmentPrefetching:\n      routeWithNoSearchParams.supportsPerSegmentPrefetching,\n    hasDynamicRewrite: routeWithNoSearchParams.hasDynamicRewrite,\n\n    // Override the rendered search with the optimistic value.\n    renderedSearch: optimisticRenderedSearch,\n\n    // Map-related fields\n    ref: null,\n    size: 0,\n    staleAt: routeWithNoSearchParams.staleAt,\n    version: routeWithNoSearchParams.version,\n  }\n\n  // Do not insert this entry into the cache. It only exists so we can\n  // perform the current navigation. Just return it to the caller.\n  return optimisticEntry\n}\n\nfunction deprecated_createOptimisticRouteTree(\n  tree: RouteTree,\n  newRenderedSearch: NormalizedSearch\n): RouteTree {\n  // Create a new route tree that identical to the original one except for\n  // the rendered search string, which is contained in the vary path.\n\n  let clonedSlots: Record<string, RouteTree> | null = null\n  const originalSlots = tree.slots\n  if (originalSlots !== null) {\n    clonedSlots = {}\n    for (const parallelRouteKey in originalSlots) {\n      const childTree = originalSlots[parallelRouteKey]\n      clonedSlots[parallelRouteKey] = deprecated_createOptimisticRouteTree(\n        childTree,\n        newRenderedSearch\n      )\n    }\n  }\n\n  // We only need to clone the vary path if the route is a page.\n  if (tree.isPage) {\n    return {\n      requestKey: tree.requestKey,\n      segment: tree.segment,\n      refreshState: tree.refreshState,\n      varyPath: clonePageVaryPathWithNewSearchParams(\n        tree.varyPath,\n        newRenderedSearch\n      ),\n      isPage: true,\n      slots: clonedSlots,\n\n      prefetchHints: tree.prefetchHints,\n    }\n  }\n\n  return {\n    requestKey: tree.requestKey,\n    segment: tree.segment,\n    refreshState: tree.refreshState,\n    varyPath: tree.varyPath,\n    isPage: false,\n    slots: clonedSlots,\n    prefetchHints: tree.prefetchHints,\n  }\n}\n\n/**\n * Checks if an entry for a segment exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */\nexport function readOrCreateSegmentCacheEntry(\n  now: number,\n  fetchStrategy: FetchStrategy,\n  tree: RouteTree\n): SegmentCacheEntry {\n  const existingEntry = readSegmentCacheEntry(now, tree.varyPath)\n  if (existingEntry !== null) {\n    return existingEntry\n  }\n  // Create a pending entry and add it to the cache. The stale time is set to a\n  // default value; the actual stale time will be set when the entry is\n  // fulfilled with data from the server response.\n  const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n  const pendingEntry = createDetachedSegmentCacheEntry(now)\n  const isRevalidation = false\n  setInCacheMap(\n    segmentCacheMap,\n    varyPathForRequest,\n    pendingEntry,\n    isRevalidation\n  )\n  return pendingEntry\n}\n\nexport function readOrCreateRevalidatingSegmentEntry(\n  now: number,\n  fetchStrategy: FetchStrategy,\n  tree: RouteTree\n): SegmentCacheEntry {\n  // This function is called when we've already confirmed that a particular\n  // segment is cached, but we want to perform another request anyway in case it\n  // returns more complete and/or fresher data than we already have. The logic\n  // for deciding whether to replace the existing entry is handled elsewhere;\n  // this function just handles retrieving a cache entry that we can use to\n  // track the revalidation.\n  //\n  // The reason revalidations are stored in the cache is because we need to be\n  // able to dedupe multiple revalidation requests. The reason they have to be\n  // handled specially is because we shouldn't overwrite a \"normal\" entry if\n  // one exists at the same keypath. So, for each internal cache location, there\n  // is a special \"revalidation\" slot that is used solely for this purpose.\n  //\n  // You can think of it as if all the revalidation entries were stored in a\n  // separate cache map from the canonical entries, and then transfered to the\n  // canonical cache map once the request is complete — this isn't how it's\n  // actually implemented, since it's more efficient to store them in the same\n  // data structure as the normal entries, but that's how it's modeled\n  // conceptually.\n\n  // TODO: Once we implement Fallback behavior for params, where an entry is\n  // re-keyed based on response information, we'll need to account for the\n  // possibility that the keypath of the previous entry is more generic than\n  // the keypath of the revalidating entry. In other words, the server could\n  // return a less generic entry upon revalidation. For now, though, this isn't\n  // a concern because the keypath is based solely on the prefetch strategy,\n  // not on data contained in the response.\n  const existingEntry = readRevalidatingSegmentCacheEntry(now, tree.varyPath)\n  if (existingEntry !== null) {\n    return existingEntry\n  }\n  // Create a pending entry and add it to the cache. The stale time is set to a\n  // default value; the actual stale time will be set when the entry is\n  // fulfilled with data from the server response.\n  const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n  const pendingEntry = createDetachedSegmentCacheEntry(now)\n  const isRevalidation = true\n  setInCacheMap(\n    segmentCacheMap,\n    varyPathForRequest,\n    pendingEntry,\n    isRevalidation\n  )\n  return pendingEntry\n}\n\nexport function overwriteRevalidatingSegmentCacheEntry(\n  now: number,\n  fetchStrategy: FetchStrategy,\n  tree: RouteTree\n) {\n  // This function is called when we've already decided to replace an existing\n  // revalidation entry. Create a new entry and write it into the cache,\n  // overwriting the previous value. The stale time is set to a default value;\n  // the actual stale time will be set when the entry is fulfilled with data\n  // from the server response.\n  const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n  const pendingEntry = createDetachedSegmentCacheEntry(now)\n  const isRevalidation = true\n  setInCacheMap(\n    segmentCacheMap,\n    varyPathForRequest,\n    pendingEntry,\n    isRevalidation\n  )\n  return pendingEntry\n}\n\nexport function upsertSegmentEntry(\n  now: number,\n  varyPath: SegmentVaryPath,\n  candidateEntry: SegmentCacheEntry\n): SegmentCacheEntry | null {\n  // We have a new entry that has not yet been inserted into the cache. Before\n  // we do so, we need to confirm whether it takes precedence over the existing\n  // entry (if one exists).\n  // TODO: We should not upsert an entry if its key was invalidated in the time\n  // since the request was made. We can do that by passing the \"owner\" entry to\n  // this function and confirming it's the same as `existingEntry`.\n\n  if (isValueExpired(now, getCurrentSegmentCacheVersion(), candidateEntry)) {\n    // The entry is expired. We cannot upsert it.\n    return null\n  }\n\n  const existingEntry = readSegmentCacheEntry(now, varyPath)\n  if (existingEntry !== null) {\n    // Don't replace a more specific segment with a less-specific one. A case where this\n    // might happen is if the existing segment was fetched via\n    // `<Link prefetch={true}>`.\n    if (\n      // We fetched the new segment using a different, less specific fetch strategy\n      // than the segment we already have in the cache, so it can't have more content.\n      (candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&\n        !canNewFetchStrategyProvideMoreContent(\n          existingEntry.fetchStrategy,\n          candidateEntry.fetchStrategy\n        )) ||\n      // The existing entry isn't partial, but the new one is.\n      // (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)\n      (!existingEntry.isPartial && candidateEntry.isPartial)\n    ) {\n      // We're going to leave revalidating entry in the cache so that it doesn't\n      // get revalidated again unnecessarily. Downgrade the Fulfilled entry to\n      // Rejected and null out the data so it can be garbage collected. We leave\n      // `staleAt` intact to prevent subsequent revalidation attempts only until\n      // the entry expires.\n      const rejectedEntry: RejectedSegmentCacheEntry = candidateEntry as any\n      rejectedEntry.status = EntryStatus.Rejected\n      rejectedEntry.rsc = null\n      return null\n    }\n\n    // Evict the existing entry from the cache.\n    deleteFromCacheMap(existingEntry)\n  }\n\n  const isRevalidation = false\n  setInCacheMap(segmentCacheMap, varyPath, candidateEntry, isRevalidation)\n  return candidateEntry\n}\n\nexport function createDetachedSegmentCacheEntry(\n  now: number\n): EmptySegmentCacheEntry {\n  // Default stale time for pending segment cache entries. The actual stale time\n  // is set when the entry is fulfilled with data from the server response.\n  const staleAt = now + 30 * 1000\n  const emptyEntry: EmptySegmentCacheEntry = {\n    status: EntryStatus.Empty,\n    // Default to assuming the fetch strategy will be PPR. This will be updated\n    // when a fetch is actually initiated.\n    fetchStrategy: FetchStrategy.PPR,\n    rsc: null,\n    isPartial: true,\n    promise: null,\n\n    // Map-related fields\n    ref: null,\n    size: 0,\n    staleAt,\n    version: 0,\n  }\n  return emptyEntry\n}\n\nexport function upgradeToPendingSegment(\n  emptyEntry: EmptySegmentCacheEntry,\n  fetchStrategy: FetchStrategy\n): PendingSegmentCacheEntry {\n  const pendingEntry: PendingSegmentCacheEntry = emptyEntry as any\n  pendingEntry.status = EntryStatus.Pending\n  pendingEntry.fetchStrategy = fetchStrategy\n\n  if (fetchStrategy === FetchStrategy.Full) {\n    // We can assume the response will contain the full segment data. Set this\n    // to false so we know it's OK to omit this segment from any navigation\n    // requests that may happen while the data is still pending.\n    pendingEntry.isPartial = false\n  }\n\n  // Set the version here, since this is right before the request is initiated.\n  // The next time the segment cache version is incremented, the entry will\n  // effectively be evicted. This happens before initiating the request, rather\n  // than when receiving the response, because it's guaranteed to happen\n  // before the data is read on the server.\n  pendingEntry.version = getCurrentSegmentCacheVersion()\n  return pendingEntry\n}\n\nexport function attemptToFulfillDynamicSegmentFromBFCache(\n  now: number,\n  segment: EmptySegmentCacheEntry,\n  tree: RouteTree\n): FulfilledSegmentCacheEntry | null {\n  // Attempts to fulfill an empty segment cache entry using data from the\n  // bfcache. This is only valid during a Full prefetch (i.e. one that includes\n  // dynamic data), because the bfcache stores data from navigations which\n  // always include dynamic data.\n\n  // We always use the canonical vary path when checking the bfcache. This is\n  // the same operation we'd use to access the cache during a\n  // regular navigation.\n  const varyPath = tree.varyPath\n\n  // Read from the BFCache without expiring it (pass -1). We check freshness\n  // ourselves using navigatedAt, because the BFCache's staleAt may have been\n  // overridden by a per-page unstable_dynamicStaleTime and can't be used to\n  // derive the original request time.\n  const bfcacheEntry = readFromBFCache(varyPath)\n  if (bfcacheEntry !== null) {\n    // The stale time for dynamic prefetches (default: 5 mins) is different\n    // from the stale time for regular navigations (default: 0 secs). Use\n    // navigatedAt to compute the correct expiry for prefetch purposes.\n    const dynamicPrefetchStaleAt =\n      bfcacheEntry.navigatedAt + STATIC_STALETIME_MS\n    if (now > dynamicPrefetchStaleAt) {\n      return null\n    }\n\n    const pendingSegment = upgradeToPendingSegment(segment, FetchStrategy.Full)\n    const isPartial = false\n    return fulfillSegmentCacheEntry(\n      pendingSegment,\n      bfcacheEntry.rsc,\n      dynamicPrefetchStaleAt,\n      isPartial\n    )\n  }\n  return null\n}\n\n/**\n * Attempts to replace an existing segment cache entry with data from the\n * bfcache. Unlike `attemptToFulfillDynamicSegmentFromBFCache` (which fills an\n * empty entry), this creates a new entry and upserts it, so it works even when\n * the segment is already fulfilled.\n */\nexport function attemptToUpgradeSegmentFromBFCache(\n  now: number,\n  tree: RouteTree\n): FulfilledSegmentCacheEntry | null {\n  const varyPath = tree.varyPath\n  const bfcacheEntry = readFromBFCache(varyPath)\n  if (bfcacheEntry !== null) {\n    const dynamicPrefetchStaleAt =\n      bfcacheEntry.navigatedAt + STATIC_STALETIME_MS\n    if (now > dynamicPrefetchStaleAt) {\n      return null\n    }\n    const pendingSegment = upgradeToPendingSegment(\n      createDetachedSegmentCacheEntry(now),\n      FetchStrategy.Full\n    )\n    const isPartial = false\n    const newEntry = fulfillSegmentCacheEntry(\n      pendingSegment,\n      bfcacheEntry.rsc,\n      dynamicPrefetchStaleAt,\n      isPartial\n    )\n    const segmentVaryPath = getSegmentVaryPathForRequest(\n      FetchStrategy.Full,\n      tree\n    )\n    const upserted = upsertSegmentEntry(now, segmentVaryPath, newEntry)\n    if (upserted !== null && upserted.status === EntryStatus.Fulfilled) {\n      return upserted\n    }\n  }\n  return null\n}\n\nfunction pingBlockedTasks(entry: {\n  blockedTasks: Set<PrefetchTask> | null\n}): void {\n  const blockedTasks = entry.blockedTasks\n  if (blockedTasks !== null) {\n    for (const task of blockedTasks) {\n      pingPrefetchTask(task)\n    }\n    entry.blockedTasks = null\n  }\n}\n\nexport function createMetadataRouteTree(\n  metadataVaryPath: PageVaryPath\n): RouteTree {\n  // The Head is not actually part of the route tree, but other than that, it's\n  // fetched and cached like a segment. Some functions expect a RouteTree\n  // object, so rather than fork the logic in all those places, we use this\n  // \"fake\" one.\n  const metadata: RouteTree = {\n    requestKey: HEAD_REQUEST_KEY,\n    segment: HEAD_REQUEST_KEY,\n    refreshState: null,\n    varyPath: metadataVaryPath,\n    // The metadata isn't really a \"page\" (though it isn't really a \"segment\"\n    // either) but for the purposes of how this field is used, it behaves like\n    // one. If this logic ever gets more complex we can change this to an enum.\n    isPage: true,\n    slots: null,\n    prefetchHints: 0,\n  }\n  return metadata\n}\n\nexport function fulfillRouteCacheEntry(\n  now: number,\n  entry: PendingRouteCacheEntry,\n  tree: RouteTree,\n  metadataVaryPath: PageVaryPath,\n  couldBeIntercepted: boolean,\n  canonicalUrl: string,\n  supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n  // Get the rendered search from the vary path\n  const renderedSearch =\n    getRenderedSearchFromVaryPath(metadataVaryPath) ?? ('' as NormalizedSearch)\n  const fulfilledEntry: FulfilledRouteCacheEntry = entry as any\n  fulfilledEntry.status = EntryStatus.Fulfilled\n  fulfilledEntry.tree = tree\n  fulfilledEntry.metadata = createMetadataRouteTree(metadataVaryPath)\n  // Route structure is essentially static — it only changes on deploy.\n  // Always use the static stale time.\n  // NOTE: An exception is rewrites/redirects in middleware or proxy, which can\n  // change routes dynamically. We have other strategies for handling those.\n  fulfilledEntry.staleAt = now + STATIC_STALETIME_MS\n  fulfilledEntry.couldBeIntercepted = couldBeIntercepted\n  fulfilledEntry.canonicalUrl = canonicalUrl\n  fulfilledEntry.renderedSearch = renderedSearch\n  fulfilledEntry.supportsPerSegmentPrefetching = supportsPerSegmentPrefetching\n  fulfilledEntry.hasDynamicRewrite = false\n  pingBlockedTasks(entry)\n  return fulfilledEntry\n}\n\nexport function writeRouteIntoCache(\n  now: number,\n  pathname: NormalizedPathname,\n  nextUrl: string | null,\n  tree: RouteTree,\n  metadataVaryPath: PageVaryPath,\n  couldBeIntercepted: boolean,\n  canonicalUrl: string,\n  supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n  const pendingEntry = createDetachedRouteCacheEntry()\n  const fulfilledEntry = fulfillRouteCacheEntry(\n    now,\n    pendingEntry,\n    tree,\n    metadataVaryPath,\n    couldBeIntercepted,\n    canonicalUrl,\n    supportsPerSegmentPrefetching\n  )\n  const renderedSearch = fulfilledEntry.renderedSearch\n  const varyPath = getFulfilledRouteVaryPath(\n    pathname,\n    renderedSearch,\n    nextUrl as NormalizedNextUrl | null,\n    couldBeIntercepted\n  )\n  const isRevalidation = false\n  setInCacheMap(routeCacheMap, varyPath, fulfilledEntry, isRevalidation)\n  return fulfilledEntry\n}\n\n/**\n * Marks a route cache entry as having a dynamic rewrite. Called when we\n * discover that a route pattern has dynamic rewrite behavior - i.e., we used\n * an optimistic route tree for prediction, but the server responded with a\n * different rendered pathname.\n *\n * Once marked, attempts to use this entry as a template for prediction will\n * bail out to server resolution.\n */\nexport function markRouteEntryAsDynamicRewrite(\n  entry: FulfilledRouteCacheEntry\n): void {\n  entry.hasDynamicRewrite = true\n  // Note: The caller is responsible for also calling invalidateRouteCacheEntries\n  // to invalidate other entries that may have been derived from this template\n  // before we knew it had a dynamic rewrite.\n}\n\nfunction fulfillSegmentCacheEntry(\n  segmentCacheEntry: PendingSegmentCacheEntry,\n  rsc: React.ReactNode,\n  staleAt: number,\n  isPartial: boolean\n): FulfilledSegmentCacheEntry {\n  const fulfilledEntry: FulfilledSegmentCacheEntry = segmentCacheEntry as any\n  fulfilledEntry.status = EntryStatus.Fulfilled\n  fulfilledEntry.rsc = rsc\n  fulfilledEntry.staleAt = staleAt\n  fulfilledEntry.isPartial = isPartial\n  // Resolve any listeners that were waiting for this data.\n  if (segmentCacheEntry.promise !== null) {\n    segmentCacheEntry.promise.resolve(fulfilledEntry)\n    // Free the promise for garbage collection.\n    fulfilledEntry.promise = null\n  }\n  return fulfilledEntry\n}\n\nfunction rejectRouteCacheEntry(\n  entry: PendingRouteCacheEntry,\n  staleAt: number\n): void {\n  const rejectedEntry: RejectedRouteCacheEntry = entry as any\n  rejectedEntry.status = EntryStatus.Rejected\n  rejectedEntry.staleAt = staleAt\n  pingBlockedTasks(entry)\n}\n\nfunction rejectSegmentCacheEntry(\n  entry: PendingSegmentCacheEntry,\n  staleAt: number\n): void {\n  const rejectedEntry: RejectedSegmentCacheEntry = entry as any\n  rejectedEntry.status = EntryStatus.Rejected\n  rejectedEntry.staleAt = staleAt\n  if (entry.promise !== null) {\n    // NOTE: We don't currently propagate the reason the prefetch was canceled\n    // but we could by accepting a `reason` argument.\n    entry.promise.resolve(null)\n    entry.promise = null\n  }\n}\n\ntype RouteTreeAccumulator = {\n  metadataVaryPath: PageVaryPath | null\n}\n\nfunction convertRootTreePrefetchToRouteTree(\n  rootTree: RootTreePrefetch,\n  renderedPathname: string,\n  renderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n) {\n  // Remove trailing and leading slashes\n  const pathnameParts = renderedPathname.split('/').filter((p) => p !== '')\n  const index = 0\n  const rootSegment = ROOT_SEGMENT_REQUEST_KEY\n  return convertTreePrefetchToRouteTree(\n    rootTree.tree,\n    rootSegment,\n    null,\n    ROOT_SEGMENT_REQUEST_KEY,\n    pathnameParts,\n    index,\n    renderedSearch,\n    acc\n  )\n}\n\nfunction convertTreePrefetchToRouteTree(\n  prefetch: TreePrefetch,\n  segment: FlightRouterStateSegment,\n  partialVaryPath: PartialSegmentVaryPath | null,\n  requestKey: SegmentRequestKey,\n  pathnameParts: Array<string>,\n  pathnamePartsIndex: number,\n  renderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n): RouteTree {\n  // Converts the route tree sent by the server into the format used by the\n  // cache. The cached version of the tree includes additional fields, such as a\n  // cache key for each segment. Since this is frequently accessed, we compute\n  // it once instead of on every access. This same cache key is also used to\n  // request the segment from the server.\n\n  let slots: { [parallelRouteKey: string]: RouteTree } | null = null\n  let isPage: boolean\n  let varyPath: SegmentVaryPath\n  const prefetchSlots = prefetch.slots\n  if (prefetchSlots !== null) {\n    isPage = false\n    varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n\n    slots = {}\n    for (let parallelRouteKey in prefetchSlots) {\n      const childPrefetch = prefetchSlots[parallelRouteKey]\n      const childSegmentName = childPrefetch.name\n      const childParam = childPrefetch.param\n\n      let childDoesAppearInURL: boolean\n      let childSegment: FlightRouterStateSegment\n      let childPartialVaryPath: PartialSegmentVaryPath | null\n      if (childParam !== null) {\n        // This segment is parameterized. Get the param from the pathname.\n        const childParamValue = parseDynamicParamFromURLPart(\n          childParam.type,\n          pathnameParts,\n          pathnamePartsIndex\n        )\n\n        // Assign a cache key to the segment, based on the param value. In the\n        // pre-Segment Cache implementation, the server computes this and sends\n        // it in the body of the response. In the Segment Cache implementation,\n        // the server sends an empty string and we fill it in here.\n\n        // TODO: We're intentionally not adding the search param to page\n        // segments here; it's tracked separately and added back during a read.\n        // This would clearer if we waited to construct the segment until it's\n        // read from the cache, since that's effectively what we're\n        // doing anyway.\n        const childParamKey =\n          // The server omits this field from the prefetch response when\n          // cacheComponents is enabled.\n          childParam.key !== null\n            ? childParam.key\n            : // If no param key was sent, use the value parsed on the client.\n              getCacheKeyForDynamicParam(\n                childParamValue,\n                '' as NormalizedSearch\n              )\n\n        childPartialVaryPath = appendLayoutVaryPath(\n          partialVaryPath,\n          childParamKey,\n          childSegmentName\n        )\n        childSegment = [\n          childSegmentName,\n          childParamKey,\n          childParam.type,\n          childParam.siblings,\n        ]\n        childDoesAppearInURL = true\n      } else {\n        // This segment does not have a param. Inherit the partial vary path of\n        // the parent.\n        childPartialVaryPath = partialVaryPath\n        childSegment = childSegmentName\n        childDoesAppearInURL = doesStaticSegmentAppearInURL(childSegmentName)\n      }\n\n      // Only increment the index if the segment appears in the URL. If it's a\n      // \"virtual\" segment, like a route group, it remains the same.\n      const childPathnamePartsIndex = childDoesAppearInURL\n        ? pathnamePartsIndex + 1\n        : pathnamePartsIndex\n\n      const childRequestKeyPart = createSegmentRequestKeyPart(childSegment)\n      const childRequestKey = appendSegmentRequestKeyPart(\n        requestKey,\n        parallelRouteKey,\n        childRequestKeyPart\n      )\n      slots[parallelRouteKey] = convertTreePrefetchToRouteTree(\n        childPrefetch,\n        childSegment,\n        childPartialVaryPath,\n        childRequestKey,\n        pathnameParts,\n        childPathnamePartsIndex,\n        renderedSearch,\n        acc\n      )\n    }\n  } else {\n    if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n      // This is a page segment.\n      isPage = true\n      varyPath = finalizePageVaryPath(\n        requestKey,\n        renderedSearch,\n        partialVaryPath\n      )\n      // The metadata \"segment\" is not part the route tree, but it has the same\n      // conceptual params as a page segment. Write the vary path into the\n      // accumulator object. If there are multiple parallel pages, we use the\n      // first one. Which page we choose is arbitrary as long as it's\n      // consistently the same one every time every time. See\n      // finalizeMetadataVaryPath for more details.\n      if (acc.metadataVaryPath === null) {\n        acc.metadataVaryPath = finalizeMetadataVaryPath(\n          requestKey,\n          renderedSearch,\n          partialVaryPath\n        )\n      }\n    } else {\n      // This is a layout segment.\n      isPage = false\n      varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n    }\n  }\n\n  return {\n    requestKey,\n    segment,\n    refreshState: null,\n    // TODO: Cheating the type system here a bit because TypeScript can't tell\n    // that the type of isPage and varyPath are consistent. The fix would be to\n    // create separate constructors and call the appropriate one from each of\n    // the branches above. Just seems a bit overkill only for one field so I'll\n    // leave it as-is for now. If isPage were wrong it would break the behavior\n    // and we'd catch it quickly, anyway.\n    varyPath: varyPath as any,\n    isPage: isPage as boolean as any,\n    slots,\n    prefetchHints: prefetch.prefetchHints,\n  }\n}\n\nexport function convertRootFlightRouterStateToRouteTree(\n  flightRouterState: FlightRouterState,\n  renderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n): RouteTree {\n  return convertFlightRouterStateToRouteTree(\n    flightRouterState,\n    ROOT_SEGMENT_REQUEST_KEY,\n    null,\n    renderedSearch,\n    acc\n  )\n}\n\nexport function convertReusedFlightRouterStateToRouteTree(\n  parentRouteTree: RouteTree,\n  parallelRouteKey: string,\n  flightRouterState: FlightRouterState,\n  renderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n) {\n  // Create a RouteTree for a FlightRouterState that was reused from an older\n  // route. This happens during a navigation when a parallel route slot does not\n  // match the target route; we reuse whatever slot was already active.\n\n  // Unlike a FlightRouterState, the RouteTree type contains backreferences to\n  // the parent segments. Append the vary path to the parent's vary path.\n  const parentPartialVaryPath = parentRouteTree.isPage\n    ? getPartialPageVaryPath(parentRouteTree.varyPath)\n    : getPartialLayoutVaryPath(parentRouteTree.varyPath)\n  const segment = flightRouterState[0]\n  // And the request key.\n  const parentRequestKey = parentRouteTree.requestKey\n  const requestKeyPart = createSegmentRequestKeyPart(segment)\n  const requestKey = appendSegmentRequestKeyPart(\n    parentRequestKey,\n    parallelRouteKey,\n    requestKeyPart\n  )\n  return convertFlightRouterStateToRouteTree(\n    flightRouterState,\n    requestKey,\n    parentPartialVaryPath,\n    renderedSearch,\n    acc\n  )\n}\n\nfunction convertFlightRouterStateToRouteTree(\n  flightRouterState: FlightRouterState,\n  requestKey: SegmentRequestKey,\n  parentPartialVaryPath: PartialSegmentVaryPath | null,\n  parentRenderedSearch: NormalizedSearch,\n  acc: RouteTreeAccumulator\n): RouteTree {\n  const originalSegment = flightRouterState[0]\n\n  // If the FlightRouterState has a refresh state, then this segment is part of\n  // an inactive parallel route. It has a different rendered search query than\n  // the outer parent route. In order to construct the inactive route correctly,\n  // we must restore the query that was originally used to render it.\n  const compressedRefreshState = flightRouterState[2] ?? null\n  const refreshState =\n    compressedRefreshState !== null\n      ? {\n          canonicalUrl: compressedRefreshState[0] as string,\n          renderedSearch: compressedRefreshState[1] as NormalizedSearch,\n        }\n      : null\n  const renderedSearch =\n    refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch\n\n  let segment: FlightRouterStateSegment\n  let partialVaryPath: PartialSegmentVaryPath | null\n  let isPage: boolean\n  let varyPath: SegmentVaryPath\n  if (Array.isArray(originalSegment)) {\n    isPage = false\n    const paramCacheKey = originalSegment[1]\n    const paramName = originalSegment[0]\n    partialVaryPath = appendLayoutVaryPath(\n      parentPartialVaryPath,\n      paramCacheKey,\n      paramName\n    )\n    varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n    segment = originalSegment\n  } else {\n    // This segment does not have a param. Inherit the partial vary path of\n    // the parent.\n    partialVaryPath = parentPartialVaryPath\n    if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n      // This is a page segment.\n      isPage = true\n\n      // The navigation implementation expects the search params to be included\n      // in the segment. However, in the case of a static response, the search\n      // params are omitted. So the client needs to add them back in when reading\n      // from the Segment Cache.\n      //\n      // For consistency, we'll do this for dynamic responses, too.\n      //\n      // TODO: We should move search params out of FlightRouterState and handle\n      // them entirely on the client, similar to our plan for dynamic params.\n      segment = PAGE_SEGMENT_KEY\n      varyPath = finalizePageVaryPath(\n        requestKey,\n        renderedSearch,\n        partialVaryPath\n      )\n      // The metadata \"segment\" is not part the route tree, but it has the same\n      // conceptual params as a page segment. Write the vary path into the\n      // accumulator object. If there are multiple parallel pages, we use the\n      // first one. Which page we choose is arbitrary as long as it's\n      // consistently the same one every time every time. See\n      // finalizeMetadataVaryPath for more details.\n      if (acc.metadataVaryPath === null) {\n        acc.metadataVaryPath = finalizeMetadataVaryPath(\n          requestKey,\n          renderedSearch,\n          partialVaryPath\n        )\n      }\n    } else {\n      // This is a layout segment.\n      isPage = false\n      segment = originalSegment\n      varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n    }\n  }\n\n  let slots: { [parallelRouteKey: string]: RouteTree } | null = null\n\n  const parallelRoutes = flightRouterState[1]\n  for (let parallelRouteKey in parallelRoutes) {\n    const childRouterState = parallelRoutes[parallelRouteKey]\n    const childSegment = childRouterState[0]\n    // TODO: Eventually, the param values will not be included in the response\n    // from the server. We'll instead fill them in on the client by parsing\n    // the URL. This is where we'll do that.\n    const childRequestKeyPart = createSegmentRequestKeyPart(childSegment)\n    const childRequestKey = appendSegmentRequestKeyPart(\n      requestKey,\n      parallelRouteKey,\n      childRequestKeyPart\n    )\n    const childTree = convertFlightRouterStateToRouteTree(\n      childRouterState,\n      childRequestKey,\n      partialVaryPath,\n      renderedSearch,\n      acc\n    )\n    if (slots === null) {\n      slots = {\n        [parallelRouteKey]: childTree,\n      }\n    } else {\n      slots[parallelRouteKey] = childTree\n    }\n  }\n\n  return {\n    requestKey,\n    segment,\n    refreshState,\n    // TODO: Cheating the type system here a bit because TypeScript can't tell\n    // that the type of isPage and varyPath are consistent. The fix would be to\n    // create separate constructors and call the appropriate one from each of\n    // the branches above. Just seems a bit overkill only for one field so I'll\n    // leave it as-is for now. If isPage were wrong it would break the behavior\n    // and we'd catch it quickly, anyway.\n    varyPath: varyPath as any,\n    isPage: isPage as boolean as any,\n    slots,\n    prefetchHints: flightRouterState[4] ?? 0,\n  }\n}\n\nexport function convertRouteTreeToFlightRouterState(\n  routeTree: RouteTree\n): FlightRouterState {\n  const parallelRoutes: Record<string, FlightRouterState> = {}\n  if (routeTree.slots !== null) {\n    for (const parallelRouteKey in routeTree.slots) {\n      parallelRoutes[parallelRouteKey] = convertRouteTreeToFlightRouterState(\n        routeTree.slots[parallelRouteKey]\n      )\n    }\n  }\n  const flightRouterState: FlightRouterState = [\n    routeTree.segment,\n    parallelRoutes,\n    null,\n    null,\n  ]\n  return flightRouterState\n}\n\nexport async function fetchRouteOnCacheMiss(\n  entry: PendingRouteCacheEntry,\n  key: RouteCacheKey\n): Promise<PrefetchSubtaskResult<null> | null> {\n  // This function is allowed to use async/await because it contains the actual\n  // fetch that gets issued on a cache miss. Notice it writes the result to the\n  // cache entry directly, rather than return data that is then written by\n  // the caller.\n  const pathname = key.pathname\n  const search = key.search\n  const nextUrl = key.nextUrl\n  const segmentPath = '/_tree' as SegmentRequestKey\n\n  const headers: RequestHeaders = {\n    [RSC_HEADER]: '1',\n    [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n    [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: segmentPath,\n  }\n  if (nextUrl !== null) {\n    headers[NEXT_URL] = nextUrl\n  }\n  // Tell the server to perform a static pre-render for the Instant Navigation\n  // Testing API. Static pre-renders don't normally happen during development.\n  addInstantPrefetchHeaderIfLocked(headers)\n\n  try {\n    const url = new URL(pathname + search, location.origin)\n    let response\n    let urlAfterRedirects\n    if (isOutputExportMode) {\n      // In output: \"export\" mode, we can't use headers to request a particular\n      // segment. Instead, we encode the extra request information into the URL.\n      // This is not part of the \"public\" interface of the app; it's an internal\n      // Next.js implementation detail that the app developer should not need to\n      // concern themselves with.\n      //\n      // For example, to request a segment:\n      //\n      //   Path passed to <Link>:   /path/to/page\n      //   Path passed to fetch:    /path/to/page/__next-segments/_tree\n      //\n      //   (This is not the exact protocol, just an illustration.)\n      //\n      // Before we do that, though, we need to account for redirects. Even in\n      // output: \"export\" mode, a proxy might redirect the page to a different\n      // location, but we shouldn't assume or expect that they also redirect all\n      // the segment files, too.\n      //\n      // To check whether the page is redirected, previously we perform a range\n      // request of 64 bytes of the HTML document to check if the target page\n      // is part of this app (by checking if build id matches). Only if the target\n      // page is part of this app do we determine the final canonical URL.\n      //\n      // However, as mentioned in https://github.com/vercel/next.js/pull/85903,\n      // some popular static hosting providers (like Cloudflare Pages or Render.com)\n      // do not support range requests, in the worst case, the entire HTML instead\n      // of 64 bytes could be returned, which is wasteful.\n      //\n      // So instead, we drops the check for build id here, and simply perform\n      // a HEAD request to rejects 1xx/4xx/5xx responses, and then determine the\n      // final URL after redirects.\n      //\n      // NOTE: We could embed the route tree into the HTML document, to avoid\n      // a second request. We're not doing that currently because it would make\n      // the HTML document larger and affect normal page loads.\n      const headResponse = await fetch(url, {\n        method: 'HEAD',\n      })\n      if (headResponse.status < 200 || headResponse.status >= 400) {\n        // The target page responded w/o a successful status code\n        // Could be a WAF serving a 403, or a 5xx from a backend\n        //\n        // Note that we can't use headResponse.ok here, because\n        // Response#ok returns `false` with 3xx responses.\n        rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n        return null\n      }\n\n      urlAfterRedirects = headResponse.redirected\n        ? new URL(headResponse.url)\n        : url\n\n      response = await fetchPrefetchResponse(\n        addSegmentPathToUrlInOutputExportMode(urlAfterRedirects, segmentPath),\n        headers\n      )\n    } else {\n      // \"Server\" mode. We can use request headers instead of the pathname.\n      // TODO: The eventual plan is to get rid of our custom request headers and\n      // encode everything into the URL, using a similar strategy to the\n      // \"output: export\" block above.\n      response = await fetchPrefetchResponse(url, headers)\n      urlAfterRedirects =\n        response !== null && response.redirected ? new URL(response.url) : url\n    }\n\n    if (\n      !response ||\n      !response.ok ||\n      // 204 is a Cache miss. Though theoretically this shouldn't happen when\n      // PPR is enabled, because we always respond to route tree requests, even\n      // if it needs to be blockingly generated on demand.\n      response.status === 204 ||\n      !response.body\n    ) {\n      // Server responded with an error, or with a miss. We should still cache\n      // the response, but we can try again after 10 seconds.\n      rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n      return null\n    }\n\n    // TODO: The canonical URL is the href without the origin. I think\n    // historically the reason for this is because the initial canonical URL\n    // gets passed as a prop to the top-level React component, which means it\n    // needs to be computed during SSR. If it were to include the origin, it\n    // would need to always be same as location.origin on the client, to prevent\n    // a hydration mismatch. To sidestep this complexity, we omit the origin.\n    //\n    // However, since this is neither a native URL object nor a fully qualified\n    // URL string, we need to be careful about how we use it. To prevent subtle\n    // mistakes, we should create a special type for it, instead of just string.\n    // Or, we should just use a (readonly) URL object instead. The type of the\n    // prop that we pass to seed the initial state does not need to be the same\n    // type as the state itself.\n    const canonicalUrl = createHrefFromUrl(urlAfterRedirects)\n\n    // Check whether the response varies based on the Next-Url header.\n    const varyHeader = response.headers.get('vary')\n    const couldBeIntercepted =\n      varyHeader !== null && varyHeader.includes(NEXT_URL)\n\n    // TODO: The `closed` promise was originally used to track when a streaming\n    // network connection closes, so the scheduler could limit concurrent\n    // connections. Now that prefetch responses are buffered, `closed` is\n    // resolved immediately after buffering — before the outer function even\n    // returns. This mechanism is only still meaningful for dynamic (Full)\n    // prefetches, which use incremental streaming. Consider removing the\n    // `closed` plumbing for buffered prefetch paths.\n    const closed = createPromiseWithResolvers<void>()\n\n    // This checks whether the response was served from the per-segment cache,\n    // rather than the old prefetching flow. If it fails, it implies that PPR\n    // is disabled on this route.\n    const routeIsPPREnabled =\n      response.headers.get(NEXT_DID_POSTPONE_HEADER) === '2' ||\n      // In output: \"export\" mode, we can't rely on response headers. But if we\n      // receive a well-formed response, we can assume it's a static response,\n      // because all data is static in this mode.\n      isOutputExportMode\n\n    if (routeIsPPREnabled) {\n      const { stream: prefetchStream, size: responseSize } =\n        await createNonTaskyPrefetchResponseStream(response.body)\n      closed.resolve()\n      setSizeInCacheMap(entry, responseSize)\n      const serverData = await createFromNextReadableStream<RootTreePrefetch>(\n        prefetchStream,\n        headers,\n        { allowPartialStream: true }\n      )\n\n      if (\n        (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n          serverData.buildId) !== getNavigationBuildId()\n      ) {\n        // The server build does not match the client. Treat as a 404. During\n        // an actual navigation, the router will trigger an MPA navigation.\n        // TODO: We should cache the fact that this is an MPA navigation.\n        rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n        return null\n      }\n\n      // Get the params that were used to render the target page. These may\n      // be different from the params in the request URL, if the page\n      // was rewritten.\n      const renderedPathname = getRenderedPathname(response)\n      const renderedSearch = getRenderedSearch(response)\n\n      // Convert the server-sent data into the RouteTree format used by the\n      // client cache.\n      //\n      // During this traversal, we accumulate additional data into this\n      // \"accumulator\" object.\n      const acc: RouteTreeAccumulator = { metadataVaryPath: null }\n      const routeTree = convertRootTreePrefetchToRouteTree(\n        serverData,\n        renderedPathname,\n        renderedSearch,\n        acc\n      )\n      const metadataVaryPath = acc.metadataVaryPath\n      if (metadataVaryPath === null) {\n        rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n        return null\n      }\n\n      discoverKnownRoute(\n        Date.now(),\n        pathname,\n        nextUrl,\n        entry,\n        routeTree,\n        metadataVaryPath,\n        couldBeIntercepted,\n        canonicalUrl,\n        routeIsPPREnabled,\n        false // hasDynamicRewrite\n      )\n    } else {\n      // PPR is not enabled for this route. The server responds with a\n      // different format (FlightRouterState) that we need to convert.\n      // TODO: We will unify the responses eventually. I'm keeping the types\n      // separate for now because FlightRouterState has so many\n      // overloaded concerns.\n      const { stream: prefetchStream, size: responseSize } =\n        await createNonTaskyPrefetchResponseStream(response.body)\n      closed.resolve()\n      setSizeInCacheMap(entry, responseSize)\n      const serverData =\n        await createFromNextReadableStream<NavigationFlightResponse>(\n          prefetchStream,\n          headers,\n          { allowPartialStream: true }\n        )\n\n      if (\n        (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n          serverData.b) !== getNavigationBuildId()\n      ) {\n        // The server build does not match the client. Treat as a 404. During\n        // an actual navigation, the router will trigger an MPA navigation.\n        // TODO: We should cache the fact that this is an MPA navigation.\n        rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n        return null\n      }\n\n      // Read head vary params synchronously. Individual segments carry their\n      // own thenables in CacheNodeSeedData.\n      const headVaryParamsThenable = serverData.h\n      const headVaryParams =\n        headVaryParamsThenable !== null\n          ? readVaryParams(headVaryParamsThenable)\n          : null\n      writeDynamicTreeResponseIntoCache(\n        Date.now(),\n        // The non-PPR response format is what we'd get if we prefetched these segments\n        // using the LoadingBoundary fetch strategy, so mark their cache entries accordingly.\n        FetchStrategy.LoadingBoundary,\n        response as RSCResponse<NavigationFlightResponse>,\n        serverData,\n        entry,\n        couldBeIntercepted,\n        canonicalUrl,\n        routeIsPPREnabled,\n        headVaryParams,\n        pathname,\n        nextUrl\n      )\n    }\n\n    if (!couldBeIntercepted) {\n      // This route will never be intercepted. So we can use this entry for all\n      // requests to this route, regardless of the Next-Url header. This works\n      // because when reading the cache we always check for a valid\n      // non-intercepted entry first.\n\n      // Re-key the entry. The `set` implementation handles removing it from\n      // its previous position in the cache. We don't need to do anything to\n      // update the LRU, because the entry is already in it.\n      // TODO: Treat this as an upsert — should check if an entry already\n      // exists at the new keypath, and if so, whether we should keep that\n      // one instead.\n      const fulfilledVaryPath: RouteVaryPath = getFulfilledRouteVaryPath(\n        pathname,\n        search,\n        nextUrl,\n        couldBeIntercepted\n      )\n      const isRevalidation = false\n      setInCacheMap(routeCacheMap, fulfilledVaryPath, entry, isRevalidation)\n    }\n    // Return a promise that resolves when the network connection closes, so\n    // the scheduler can track the number of concurrent network connections.\n    return { value: null, closed: closed.promise }\n  } catch (error) {\n    // Either the connection itself failed, or something bad happened while\n    // decoding the response.\n    rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n    return null\n  }\n}\n\nexport async function fetchSegmentOnCacheMiss(\n  route: FulfilledRouteCacheEntry,\n  segmentCacheEntry: PendingSegmentCacheEntry,\n  routeKey: RouteCacheKey,\n  tree: RouteTree\n): Promise<PrefetchSubtaskResult<FulfilledSegmentCacheEntry> | null> {\n  // This function is allowed to use async/await because it contains the actual\n  // fetch that gets issued on a cache miss. Notice it writes the result to the\n  // cache entry directly, rather than return data that is then written by\n  // the caller.\n  //\n  // Segment fetches are non-blocking so we don't need to ping the scheduler\n  // on completion.\n\n  // Use the canonical URL to request the segment, not the original URL. These\n  // are usually the same, but the canonical URL will be different if the route\n  // tree response was redirected. To avoid an extra waterfall on every segment\n  // request, we pass the redirected URL instead of the original one.\n  const url = new URL(route.canonicalUrl, location.origin)\n  const nextUrl = routeKey.nextUrl\n\n  const requestKey = tree.requestKey\n  const normalizedRequestKey =\n    requestKey === ROOT_SEGMENT_REQUEST_KEY\n      ? // The root segment is a special case. To simplify the server-side\n        // handling of these requests, we encode the root segment path as\n        // `_index` instead of as an empty string. This should be treated as\n        // an implementation detail and not as a stable part of the protocol.\n        // It just needs to match the equivalent logic that happens when\n        // prerendering the responses. It should not leak outside of Next.js.\n        ('/_index' as SegmentRequestKey)\n      : requestKey\n\n  const headers: RequestHeaders = {\n    [RSC_HEADER]: '1',\n    [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n    [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: normalizedRequestKey,\n  }\n  if (nextUrl !== null) {\n    headers[NEXT_URL] = nextUrl\n  }\n  // Tell the server to perform a static pre-render for the Instant Navigation\n  // Testing API. Static pre-renders don't normally happen during development.\n  addInstantPrefetchHeaderIfLocked(headers)\n\n  const requestUrl = isOutputExportMode\n    ? // In output: \"export\" mode, we need to add the segment path to the URL.\n      addSegmentPathToUrlInOutputExportMode(url, normalizedRequestKey)\n    : url\n  try {\n    const response = await fetchPrefetchResponse(requestUrl, headers)\n    if (\n      !response ||\n      !response.ok ||\n      response.status === 204 || // Cache miss\n      // This checks whether the response was served from the per-segment cache,\n      // rather than the old prefetching flow. If it fails, it implies that PPR\n      // is disabled on this route. Theoretically this should never happen\n      // because we only issue requests for segments once we've verified that\n      // the route supports PPR.\n      (response.headers.get(NEXT_DID_POSTPONE_HEADER) !== '2' &&\n        // In output: \"export\" mode, we can't rely on response headers. But if\n        // we receive a well-formed response, we can assume it's a static\n        // response, because all data is static in this mode.\n        !isOutputExportMode) ||\n      !response.body\n    ) {\n      // Server responded with an error, or with a miss. We should still cache\n      // the response, but we can try again after 10 seconds.\n      rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n      return null\n    }\n\n    // See TODO in fetchRouteOnCacheMiss about removing `closed` for\n    // buffered prefetch paths.\n    const closed = createPromiseWithResolvers<void>()\n\n    const { stream: prefetchStream, size: responseSize } =\n      await createNonTaskyPrefetchResponseStream(response.body)\n    closed.resolve()\n    setSizeInCacheMap(segmentCacheEntry, responseSize)\n    const serverData = await createFromNextReadableStream<SegmentPrefetch>(\n      prefetchStream,\n      headers,\n      { allowPartialStream: true }\n    )\n    if (\n      (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n        serverData.buildId) !== getNavigationBuildId()\n    ) {\n      // The server build does not match the client. Treat as a 404. During\n      // an actual navigation, the router will trigger an MPA navigation.\n      rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n      return null\n    }\n    const now = Date.now()\n    const staleAt = now + getStaleTimeMs(serverData.staleTime)\n    const fulfilledEntry = fulfillSegmentCacheEntry(\n      segmentCacheEntry,\n      serverData.rsc,\n      staleAt,\n      serverData.isPartial\n    )\n\n    // If the server tells us which params the segment varies by, we can re-key\n    // the entry to a more generic vary path. This allows the entry to be reused\n    // across different param values for params that the segment doesn't\n    // actually depend on.\n    const varyParams = serverData.varyParams\n    const fulfilledVaryPath =\n      process.env.__NEXT_VARY_PARAMS && varyParams !== null\n        ? getFulfilledSegmentVaryPath(tree.varyPath, varyParams)\n        : getSegmentVaryPathForRequest(segmentCacheEntry.fetchStrategy, tree)\n    // Re-key and upsert the entry at the fulfilled vary path. This ensures\n    // the entry is stored at the most generic path possible based on which\n    // params the segment actually depends on.\n    upsertSegmentEntry(now, fulfilledVaryPath, fulfilledEntry)\n\n    return {\n      value: fulfilledEntry,\n      // Return a promise that resolves when the network connection closes, so\n      // the scheduler can track the number of concurrent network connections.\n      closed: closed.promise,\n    }\n  } catch (error) {\n    // Either the connection itself failed, or something bad happened while\n    // decoding the response.\n    rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n    return null\n  }\n}\n\n// TODO: The inlined prefetch flow below is temporary. Eventually, inlining\n// will be the default behavior controlled by a size heuristic rather than a\n// boolean flag. At that point, the per-segment and inlined fetch paths will\n// merge, and these separate functions will be removed.\n//\n// The call site in the scheduler is guarded by\n// process.env.__NEXT_PREFETCH_INLINING, so these functions are\n// dead-code-eliminated from the client bundle when the feature is disabled.\n\nexport async function fetchInlinedSegmentsOnCacheMiss(\n  route: FulfilledRouteCacheEntry,\n  routeKey: RouteCacheKey,\n  tree: RouteTree,\n  spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): Promise<PrefetchSubtaskResult<null> | null> {\n  // When prefetch inlining is enabled, all segment data for a route is bundled\n  // into a single /_inlined response instead of individual per-segment\n  // requests. This function fetches that response and walks the tree to fill\n  // all segment cache entries at once.\n  const url = new URL(route.canonicalUrl, location.origin)\n  const nextUrl = routeKey.nextUrl\n\n  const headers: RequestHeaders = {\n    [RSC_HEADER]: '1',\n    [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n    [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: '/' + PAGE_SEGMENT_KEY,\n  }\n  if (nextUrl !== null) {\n    headers[NEXT_URL] = nextUrl\n  }\n  addInstantPrefetchHeaderIfLocked(headers)\n\n  try {\n    const response = await fetchPrefetchResponse(url, headers)\n    if (\n      !response ||\n      !response.ok ||\n      response.status === 204 ||\n      (response.headers.get(NEXT_DID_POSTPONE_HEADER) !== '2' &&\n        !isOutputExportMode) ||\n      !response.body\n    ) {\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n      return null\n    }\n\n    // See TODO in fetchRouteOnCacheMiss about removing `closed` for\n    // buffered prefetch paths.\n    const closed = createPromiseWithResolvers<void>()\n\n    const { stream: prefetchStream } =\n      await createNonTaskyPrefetchResponseStream(response.body)\n    closed.resolve()\n    const serverData =\n      await createFromNextReadableStream<InlinedPrefetchResponse>(\n        prefetchStream,\n        headers,\n        { allowPartialStream: true }\n      )\n\n    if (\n      (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n        serverData.tree.segment.buildId) !== getNavigationBuildId()\n    ) {\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n      return null\n    }\n\n    const now = Date.now()\n\n    // Walk the inlined tree in parallel with the RouteTree and fill\n    // segment cache entries.\n    fillInlinedSegmentEntries(now, route, tree, serverData.tree, spawnedEntries)\n\n    // Fill the head entry.\n    const headStaleAt = now + getStaleTimeMs(serverData.head.staleTime)\n    const headKey = route.metadata.requestKey\n    const ownedHeadEntry = spawnedEntries.get(headKey)\n    if (ownedHeadEntry !== undefined) {\n      fulfillSegmentCacheEntry(\n        ownedHeadEntry,\n        serverData.head.rsc,\n        headStaleAt,\n        serverData.head.isPartial\n      )\n    } else {\n      // The head was already cached. Try to upsert if the entry is empty.\n      const existingEntry = readOrCreateSegmentCacheEntry(\n        now,\n        FetchStrategy.PPR,\n        route.metadata\n      )\n      if (existingEntry.status === EntryStatus.Empty) {\n        fulfillSegmentCacheEntry(\n          upgradeToPendingSegment(existingEntry, FetchStrategy.PPR),\n          serverData.head.rsc,\n          headStaleAt,\n          serverData.head.isPartial\n        )\n      }\n    }\n\n    // Reject any remaining entries that were not fulfilled by the response.\n    rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n\n    return { value: null, closed: closed.promise }\n  } catch (error) {\n    rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n    return null\n  }\n}\n\nfunction fillInlinedSegmentEntries(\n  now: number,\n  route: FulfilledRouteCacheEntry,\n  tree: RouteTree,\n  inlinedNode: InlinedSegmentPrefetch,\n  spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): void {\n  // Check if the spawned entries map has an entry for this segment's key.\n  const segment = inlinedNode.segment\n  const staleAt = now + getStaleTimeMs(segment.staleTime)\n  const ownedEntry = spawnedEntries.get(tree.requestKey)\n  if (ownedEntry !== undefined) {\n    // We own this entry. Fulfill it directly.\n    fulfillSegmentCacheEntry(\n      ownedEntry,\n      segment.rsc,\n      staleAt,\n      segment.isPartial\n    )\n  } else {\n    // Not owned by us — this is extra data from the inlined response for a\n    // segment that was already cached. Try to upsert if the entry is empty.\n    const existingEntry = readOrCreateSegmentCacheEntry(\n      now,\n      FetchStrategy.PPR,\n      tree\n    )\n    if (existingEntry.status === EntryStatus.Empty) {\n      fulfillSegmentCacheEntry(\n        upgradeToPendingSegment(existingEntry, FetchStrategy.PPR),\n        segment.rsc,\n        staleAt,\n        segment.isPartial\n      )\n    }\n  }\n\n  // Recurse into children.\n  if (tree.slots !== null && inlinedNode.slots !== null) {\n    for (const parallelRouteKey in tree.slots) {\n      const childTree = tree.slots[parallelRouteKey]\n      const childInlinedNode = inlinedNode.slots[parallelRouteKey]\n      if (childInlinedNode !== undefined) {\n        fillInlinedSegmentEntries(\n          now,\n          route,\n          childTree,\n          childInlinedNode,\n          spawnedEntries\n        )\n      }\n    }\n  }\n}\n\nexport async function fetchSegmentPrefetchesUsingDynamicRequest(\n  task: PrefetchTask,\n  route: FulfilledRouteCacheEntry,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.Full,\n  dynamicRequestTree: FlightRouterState,\n  spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): Promise<PrefetchSubtaskResult<null> | null> {\n  const key = task.key\n  const url = new URL(route.canonicalUrl, location.origin)\n  const nextUrl = key.nextUrl\n\n  if (\n    spawnedEntries.size === 1 &&\n    spawnedEntries.has(route.metadata.requestKey)\n  ) {\n    // The only thing pending is the head. Instruct the server to\n    // skip over everything else.\n    dynamicRequestTree = MetadataOnlyRequestTree\n  }\n\n  const headers: RequestHeaders = {\n    [RSC_HEADER]: '1',\n    [NEXT_ROUTER_STATE_TREE_HEADER]:\n      prepareFlightRouterStateForRequest(dynamicRequestTree),\n  }\n  if (nextUrl !== null) {\n    headers[NEXT_URL] = nextUrl\n  }\n  switch (fetchStrategy) {\n    case FetchStrategy.Full: {\n      // We omit the prefetch header from a full prefetch because it's essentially\n      // just a navigation request that happens ahead of time — it should include\n      // all the same data in the response.\n      break\n    }\n    case FetchStrategy.PPRRuntime: {\n      headers[NEXT_ROUTER_PREFETCH_HEADER] = '2'\n      break\n    }\n    case FetchStrategy.LoadingBoundary: {\n      headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n      break\n    }\n    default: {\n      fetchStrategy satisfies never\n    }\n  }\n\n  try {\n    const response = await fetchPrefetchResponse(url, headers)\n    if (!response || !response.ok || !response.body) {\n      // Server responded with an error, or with a miss. We should still cache\n      // the response, but we can try again after 10 seconds.\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n      return null\n    }\n\n    const renderedSearch = getRenderedSearch(response)\n    if (renderedSearch !== route.renderedSearch) {\n      // The search params that were used to render the target page are\n      // different from the search params in the request URL. This only happens\n      // when there's a dynamic rewrite in between the tree prefetch and the\n      // data prefetch.\n      // TODO: For now, since this is an edge case, we reject the prefetch, but\n      // the proper way to handle this is to evict the stale route tree entry\n      // then fill the cache with the new response.\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n      return null\n    }\n\n    // Track when the network connection closes. Only meaningful for Full\n    // (dynamic) prefetches which use incremental streaming. For buffered\n    // paths, this is resolved immediately — see TODO in fetchRouteOnCacheMiss.\n    const closed = createPromiseWithResolvers<void>()\n\n    let fulfilledEntries: Array<FulfilledSegmentCacheEntry> | null = null\n    let prefetchStream: ReadableStream<Uint8Array>\n    let bufferedResponseSize: number | null = null\n    if (fetchStrategy === FetchStrategy.Full) {\n      // Full prefetches are dynamic responses stored in the prefetch cache.\n      // They don't carry vary params or other cache metadata, so there's no\n      // need to buffer them. Use the incremental version to allow data to be\n      // processed as it arrives.\n      prefetchStream = createIncrementalPrefetchResponseStream(\n        response.body,\n        closed.resolve,\n        function onResponseSizeUpdate(totalBytesReceivedSoFar) {\n          // When processing a dynamic response, we don't know how large each\n          // individual segment is, so approximate by assigning each segment\n          // the average of the total response size.\n          if (fulfilledEntries === null) {\n            // Haven't received enough data yet to know which segments\n            // were included.\n            return\n          }\n          const averageSize = totalBytesReceivedSoFar / fulfilledEntries.length\n          for (const entry of fulfilledEntries) {\n            setSizeInCacheMap(entry, averageSize)\n          }\n        }\n      )\n    } else {\n      const { stream, size } = await createNonTaskyPrefetchResponseStream(\n        response.body\n      )\n      closed.resolve()\n      prefetchStream = stream\n      bufferedResponseSize = size\n    }\n\n    const [serverData, cacheData] = await Promise.all([\n      createFromNextReadableStream<NavigationFlightResponse>(\n        prefetchStream,\n        headers,\n        { allowPartialStream: true }\n      ),\n      response.cacheData,\n    ])\n\n    // Read head vary params synchronously. Individual segments carry their\n    // own thenables in CacheNodeSeedData.\n    const headVaryParamsThenable = serverData.h\n    const headVaryParams =\n      headVaryParamsThenable !== null\n        ? readVaryParams(headVaryParamsThenable)\n        : null\n\n    const now = Date.now()\n    const staleAt = await getStaleAt(now, serverData.s, response)\n    // PPRRuntime prefetches are partial when the server marks the response\n    // as '~' (Partial). Full/LoadingBoundary prefetches are always complete.\n    const isResponsePartial =\n      fetchStrategy === FetchStrategy.PPRRuntime &&\n      (cacheData?.isResponsePartial ?? false)\n\n    // Aside from writing the data into the cache, this function also returns\n    // the entries that were fulfilled, so we can streamingly update their sizes\n    // in the LRU as more data comes in.\n    const buildId =\n      response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b\n    const flightDatas = normalizeFlightData(serverData.f)\n    if (typeof flightDatas === 'string') {\n      rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n      return null\n    }\n    const navigationSeed = convertServerPatchToFullTree(\n      now,\n      dynamicRequestTree,\n      flightDatas,\n      renderedSearch,\n      // Not needed for prefetch responses; pass unknown to use the default.\n      UnknownDynamicStaleTime\n    )\n    fulfilledEntries = writeDynamicRenderResponseIntoCache(\n      now,\n      fetchStrategy,\n      flightDatas,\n      buildId,\n      isResponsePartial,\n      headVaryParams,\n      staleAt,\n      navigationSeed,\n      spawnedEntries\n    )\n\n    // For buffered responses, update LRU sizes now that we know which\n    // entries were fulfilled.\n    if (\n      bufferedResponseSize !== null &&\n      fulfilledEntries !== null &&\n      fulfilledEntries.length > 0\n    ) {\n      const averageSize = bufferedResponseSize / fulfilledEntries.length\n      for (const entry of fulfilledEntries) {\n        setSizeInCacheMap(entry, averageSize)\n      }\n    }\n\n    // Return a promise that resolves when the network connection closes, so\n    // the scheduler can track the number of concurrent network connections.\n    return { value: null, closed: closed.promise }\n  } catch (error) {\n    rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n    return null\n  }\n}\n\nfunction writeDynamicTreeResponseIntoCache(\n  now: number,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.Full,\n  response: RSCResponse<NavigationFlightResponse>,\n  serverData: NavigationFlightResponse,\n  entry: PendingRouteCacheEntry,\n  couldBeIntercepted: boolean,\n  canonicalUrl: string,\n  routeIsPPREnabled: boolean,\n  headVaryParams: VaryParams | null,\n  originalPathname: string,\n  nextUrl: string | null\n): void {\n  const renderedSearch = getRenderedSearch(response)\n\n  const normalizedFlightDataResult = normalizeFlightData(serverData.f)\n  if (\n    // A string result means navigating to this route will result in an\n    // MPA navigation.\n    typeof normalizedFlightDataResult === 'string' ||\n    normalizedFlightDataResult.length !== 1\n  ) {\n    rejectRouteCacheEntry(entry, now + 10 * 1000)\n    return\n  }\n  const flightData = normalizedFlightDataResult[0]\n  if (!flightData.isRootRender) {\n    // Unexpected response format.\n    rejectRouteCacheEntry(entry, now + 10 * 1000)\n    return\n  }\n\n  const flightRouterState = flightData.tree\n  // If the response was postponed, segments may contain dynamic holes.\n  // The head has its own partiality flag (flightDataEntry.isHeadPartial)\n  // which is handled separately in writeDynamicRenderResponseIntoCache.\n  const isResponsePartial =\n    response.headers.get(NEXT_DID_POSTPONE_HEADER) === '1'\n\n  // Convert the server-sent data into the RouteTree format used by the\n  // client cache.\n  //\n  // During this traversal, we accumulate additional data into this\n  // \"accumulator\" object.\n  const acc: RouteTreeAccumulator = { metadataVaryPath: null }\n  const routeTree = convertRootFlightRouterStateToRouteTree(\n    flightRouterState,\n    renderedSearch,\n    acc\n  )\n  const metadataVaryPath = acc.metadataVaryPath\n  if (metadataVaryPath === null) {\n    rejectRouteCacheEntry(entry, now + 10 * 1000)\n    return\n  }\n\n  discoverKnownRoute(\n    now,\n    originalPathname,\n    nextUrl,\n    entry,\n    routeTree,\n    metadataVaryPath,\n    couldBeIntercepted,\n    canonicalUrl,\n    routeIsPPREnabled,\n    false // hasDynamicRewrite\n  )\n\n  // If the server sent segment data as part of the response, we should write\n  // it into the cache to prevent a second, redundant prefetch request.\n  // TODO: This is a leftover branch from before Client Segment Cache was\n  // enabled everywhere. Tree prefetches should never include segment data.  We\n  // can delete it. Leaving for a subsequent PR.\n  const navigationSeed = convertServerPatchToFullTree(\n    now,\n    flightRouterState,\n    normalizedFlightDataResult,\n    renderedSearch,\n    UnknownDynamicStaleTime\n  )\n  const buildId =\n    response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b\n  writeDynamicRenderResponseIntoCache(\n    now,\n    fetchStrategy,\n    normalizedFlightDataResult,\n    buildId,\n    isResponsePartial,\n    headVaryParams,\n    getStaleAtFromHeader(now, response),\n    navigationSeed,\n    null\n  )\n}\n\nfunction rejectSegmentEntriesIfStillPending(\n  entries: Map<SegmentRequestKey, SegmentCacheEntry>,\n  staleAt: number\n): Array<FulfilledSegmentCacheEntry> {\n  const fulfilledEntries = []\n  for (const entry of entries.values()) {\n    if (entry.status === EntryStatus.Pending) {\n      rejectSegmentCacheEntry(entry, staleAt)\n    } else if (entry.status === EntryStatus.Fulfilled) {\n      fulfilledEntries.push(entry)\n    }\n  }\n  return fulfilledEntries\n}\n\nexport function writeDynamicRenderResponseIntoCache(\n  now: number,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPR\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.Full,\n  flightDatas: NormalizedFlightData[],\n  buildId: string | undefined,\n  isResponsePartial: boolean,\n  headVaryParams: VaryParams | null,\n  staleAt: number,\n  navigationSeed: NavigationSeed,\n  spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null\n): Array<FulfilledSegmentCacheEntry> | null {\n  if (buildId && buildId !== getNavigationBuildId()) {\n    // The server build does not match the client. Treat as a 404. During\n    // an actual navigation, the router will trigger an MPA navigation.\n    if (spawnedEntries !== null) {\n      rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)\n    }\n    return null\n  }\n\n  const routeTree = navigationSeed.routeTree\n  const metadataTree =\n    navigationSeed.metadataVaryPath !== null\n      ? createMetadataRouteTree(navigationSeed.metadataVaryPath)\n      : null\n\n  for (const flightDataEntry of flightDatas) {\n    const seedData = flightDataEntry.seedData\n    if (seedData !== null) {\n      // The data sent by the server represents only a subtree of the app. We\n      // need to find the part of the task tree that matches the response.\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      const segmentPath = flightDataEntry.segmentPath\n      let tree = routeTree\n      for (let i = 0; i < segmentPath.length; i += 2) {\n        const parallelRouteKey: string = segmentPath[i]\n        if (tree?.slots?.[parallelRouteKey] !== undefined) {\n          tree = tree.slots[parallelRouteKey]\n        } else {\n          if (spawnedEntries !== null) {\n            rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)\n          }\n          return null\n        }\n      }\n\n      writeSeedDataIntoCache(\n        now,\n        fetchStrategy,\n        tree,\n        staleAt,\n        seedData,\n        isResponsePartial,\n        spawnedEntries\n      )\n    }\n\n    const head = flightDataEntry.head\n    if (head !== null && metadataTree !== null) {\n      // When Cache Components is enabled, the server conservatively marks\n      // the head as partial during static generation (isPossiblyPartialHead\n      // in app-render.tsx), even for fully static pages where the head is\n      // actually complete. When the response is non-partial, we override\n      // this since the server confirmed no dynamic content exists.\n      //\n      // Without Cache Components, the server always sends the correct\n      // isHeadPartial value, so no override is needed.\n      const isHeadPartial =\n        !isResponsePartial && process.env.__NEXT_CACHE_COMPONENTS\n          ? false\n          : flightDataEntry.isHeadPartial\n\n      fulfillEntrySpawnedByRuntimePrefetch(\n        now,\n        fetchStrategy,\n        head,\n        isHeadPartial,\n        staleAt,\n        // For head entries, use the head-specific vary params passed as\n        // parameter.\n        headVaryParams,\n        metadataTree,\n        spawnedEntries\n      )\n    }\n  }\n  // Any entry that's still pending was intentionally not rendered by the\n  // server, because it was inside the loading boundary. Mark them as rejected\n  // so we know not to fetch them again.\n  // TODO: If PPR is enabled on some routes but not others, then it's possible\n  // that a different page is able to do a per-segment prefetch of one of the\n  // segments we're marking as rejected here. We should mark on the segment\n  // somehow that the reason for the rejection is because of a non-PPR prefetch.\n  // That way a per-segment prefetch knows to disregard the rejection.\n  if (spawnedEntries !== null) {\n    const fulfilledEntries = rejectSegmentEntriesIfStillPending(\n      spawnedEntries,\n      now + 10 * 1000\n    )\n    return fulfilledEntries\n  }\n  return null\n}\n\nfunction writeSeedDataIntoCache(\n  now: number,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPR\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.Full,\n  tree: RouteTree,\n  staleAt: number,\n  seedData: CacheNodeSeedData,\n  isResponsePartial: boolean,\n  entriesOwnedByCurrentTask: Map<\n    SegmentRequestKey,\n    PendingSegmentCacheEntry\n  > | null\n) {\n  // This function is used to write the result of a runtime server request\n  // (CacheNodeSeedData) into the prefetch cache.\n  const rsc = seedData[0]\n  const isPartial = rsc === null || isResponsePartial\n  const varyParamsThenable = seedData[4]\n  // Each segment carries its own vary params thenable in the seed data. The\n  // thenable resolves to the set of params the segment accessed during render.\n  // A null thenable means tracking was not enabled (not a prerender).\n  const varyParams =\n    varyParamsThenable !== null ? readVaryParams(varyParamsThenable) : null\n  fulfillEntrySpawnedByRuntimePrefetch(\n    now,\n    fetchStrategy,\n    rsc,\n    isPartial,\n    staleAt,\n    varyParams,\n    tree,\n    entriesOwnedByCurrentTask\n  )\n\n  // Recursively write the child data into the cache.\n  const slots = tree.slots\n  if (slots !== null) {\n    const seedDataChildren = seedData[1]\n    for (const parallelRouteKey in slots) {\n      const childTree = slots[parallelRouteKey]\n      const childSeedData: CacheNodeSeedData | null | void =\n        seedDataChildren[parallelRouteKey]\n      if (childSeedData !== null && childSeedData !== undefined) {\n        writeSeedDataIntoCache(\n          now,\n          fetchStrategy,\n          childTree,\n          staleAt,\n          childSeedData,\n          isResponsePartial,\n          entriesOwnedByCurrentTask\n        )\n      }\n    }\n  }\n}\n\nfunction fulfillEntrySpawnedByRuntimePrefetch(\n  now: number,\n  fetchStrategy:\n    | FetchStrategy.LoadingBoundary\n    | FetchStrategy.PPR\n    | FetchStrategy.PPRRuntime\n    | FetchStrategy.Full,\n  rsc: React.ReactNode,\n  isPartial: boolean,\n  staleAt: number,\n  segmentVaryParams: Set<string> | null,\n  tree: RouteTree,\n  entriesOwnedByCurrentTask: Map<\n    SegmentRequestKey,\n    PendingSegmentCacheEntry\n  > | null\n) {\n  // We should only write into cache entries that are owned by us. Or create\n  // a new one and write into that. We must never write over an entry that was\n  // created by a different task, because that causes data races.\n  const ownedEntry =\n    entriesOwnedByCurrentTask !== null\n      ? entriesOwnedByCurrentTask.get(tree.requestKey)\n      : undefined\n  if (ownedEntry !== undefined) {\n    const fulfilledEntry = fulfillSegmentCacheEntry(\n      ownedEntry,\n      rsc,\n      staleAt,\n      isPartial\n    )\n    // Re-key the entry based on which params the segment actually depends on.\n    if (process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null) {\n      const fulfilledVaryPath = getFulfilledSegmentVaryPath(\n        tree.varyPath,\n        segmentVaryParams\n      )\n      const isRevalidation = false\n      setInCacheMap(\n        segmentCacheMap,\n        fulfilledVaryPath,\n        fulfilledEntry,\n        isRevalidation\n      )\n    }\n  } else {\n    // There's no matching entry. Attempt to create a new one.\n    const possiblyNewEntry = readOrCreateSegmentCacheEntry(\n      now,\n      fetchStrategy,\n      tree\n    )\n    if (possiblyNewEntry.status === EntryStatus.Empty) {\n      // Confirmed this is a new entry. We can fulfill it.\n      const newEntry = possiblyNewEntry\n      const fulfilledEntry = fulfillSegmentCacheEntry(\n        upgradeToPendingSegment(newEntry, fetchStrategy),\n        rsc,\n        staleAt,\n        isPartial\n      )\n      // Re-key the entry based on which params the segment actually depends on.\n      if (process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null) {\n        const fulfilledVaryPath = getFulfilledSegmentVaryPath(\n          tree.varyPath,\n          segmentVaryParams\n        )\n        const isRevalidation = false\n        setInCacheMap(\n          segmentCacheMap,\n          fulfilledVaryPath,\n          fulfilledEntry,\n          isRevalidation\n        )\n      }\n    } else {\n      // There was already an entry in the cache. But we may be able to\n      // replace it with the new one from the server.\n      const newEntry = fulfillSegmentCacheEntry(\n        upgradeToPendingSegment(\n          createDetachedSegmentCacheEntry(now),\n          fetchStrategy\n        ),\n        rsc,\n        staleAt,\n        isPartial\n      )\n      // Use the fulfilled vary path if available, otherwise fall back to\n      // the request vary path.\n      const varyPath =\n        process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null\n          ? getFulfilledSegmentVaryPath(tree.varyPath, segmentVaryParams)\n          : getSegmentVaryPathForRequest(fetchStrategy, tree)\n      upsertSegmentEntry(now, varyPath, newEntry)\n    }\n  }\n}\n\nasync function fetchPrefetchResponse<T>(\n  url: URL,\n  headers: RequestHeaders\n): Promise<RSCResponse<T> | null> {\n  const fetchPriority = 'low'\n  // When issuing a prefetch request, don't immediately decode the response; we\n  // use the lower level `createFromResponse` API instead because we need to do\n  // some extra processing of the response stream. See\n  // `createNonTaskyPrefetchResponseStream` for more details.\n  const shouldImmediatelyDecode = false\n  const response = await createFetch<T>(\n    url,\n    headers,\n    fetchPriority,\n    shouldImmediatelyDecode\n  )\n  if (!response.ok) {\n    return null\n  }\n\n  // Check the content type\n  if (isOutputExportMode) {\n    // In output: \"export\" mode, we relaxed about the content type, since it's\n    // not Next.js that's serving the response. If the status is OK, assume the\n    // response is valid. If it's not a valid response, the Flight client won't\n    // be able to decode it, and we'll treat it as a miss.\n  } else {\n    const contentType = response.headers.get('content-type')\n    const isFlightResponse =\n      contentType && contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n    if (!isFlightResponse) {\n      return null\n    }\n  }\n  return response\n}\n\nasync function createNonTaskyPrefetchResponseStream(\n  body: ReadableStream<Uint8Array>\n): Promise<{ stream: ReadableStream<Uint8Array>; size: number }> {\n  // Buffer the entire response before passing it to the Flight client. This\n  // ensures that when Flight processes the stream, all model data is available\n  // synchronously. This is important for readVaryParams, which synchronously\n  // checks the thenable status — if data arrived in multiple network chunks,\n  // the thenables might not yet be fulfilled.\n  //\n  // TODO: There are too many intermediate stream transformations in the\n  // prefetch response pipeline (e.g. stripIsPartialByte, this function).\n  // These could all be consolidated into a single transformation. Refactor\n  // once the cached navigations experiment lands.\n  //\n  // Read the entire response from the network.\n  const reader = body.getReader()\n  const chunks: Uint8Array[] = []\n  let size = 0\n  while (true) {\n    const { done, value } = await reader.read()\n    if (done) break\n    chunks.push(value)\n    size += value.byteLength\n  }\n  // Concatenate into a single chunk so that Flight's processBinaryChunk\n  // processes all rows synchronously in one call. Multiple chunks would not\n  // be sufficient: even though reader.read() resolves as a microtask for\n  // already-enqueued data, the `await` continuation from\n  // createFromReadableStream can interleave between chunks. If the root\n  // model row isn't the first row (e.g. outlined values come first), the\n  // PromiseResolveThenableJob from `await` can cause the root to initialize\n  // eagerly, scheduling the continuation before remaining chunks (including\n  // promise value rows) are processed. A single chunk avoids this.\n  let buffer: Uint8Array\n  if (chunks.length === 1) {\n    buffer = chunks[0]\n  } else if (chunks.length > 1) {\n    buffer = new Uint8Array(size)\n    let offset = 0\n    for (const chunk of chunks) {\n      buffer.set(chunk, offset)\n      offset += chunk.byteLength\n    }\n  } else {\n    buffer = new Uint8Array(0)\n  }\n  const stream = new ReadableStream<Uint8Array>({\n    start(controller) {\n      controller.enqueue(buffer)\n      controller.close()\n    },\n  })\n  return { stream, size }\n}\n\n/**\n * Creates a streaming (non-buffered) prefetch response stream for dynamic/Full\n * prefetches. These are essentially dynamic responses that get stored in the\n * prefetch cache — they don't carry vary params or other cache metadata that\n * requires synchronous thenable resolution, so there's no need to buffer them.\n * They should continue to stream so consumers can process data as it arrives.\n */\nfunction createIncrementalPrefetchResponseStream(\n  originalFlightStream: ReadableStream<Uint8Array>,\n  onStreamClose: () => void,\n  onResponseSizeUpdate: (size: number) => void\n): ReadableStream<Uint8Array> {\n  // While processing the original stream, we incrementally update the size\n  // of the cache entry in the LRU.\n  let totalByteLength = 0\n  const reader = originalFlightStream.getReader()\n  return new ReadableStream({\n    async pull(controller) {\n      while (true) {\n        const { done, value } = await reader.read()\n        if (!done) {\n          // Pass to the target stream and keep consuming the Flight response\n          // from the server.\n          controller.enqueue(value)\n\n          // Incrementally update the size of the cache entry in the LRU.\n          totalByteLength += value.byteLength\n          onResponseSizeUpdate(totalByteLength)\n          continue\n        }\n        controller.close()\n        onStreamClose()\n        return\n      }\n    },\n  })\n}\n\nfunction addSegmentPathToUrlInOutputExportMode(\n  url: URL,\n  segmentPath: SegmentRequestKey\n): URL {\n  if (isOutputExportMode) {\n    // In output: \"export\" mode, we cannot use a header to encode the segment\n    // path. Instead, we append it to the end of the pathname.\n    const staticUrl = new URL(url)\n    const routeDir = staticUrl.pathname.endsWith('/')\n      ? staticUrl.pathname.slice(0, -1)\n      : staticUrl.pathname\n    const staticExportFilename =\n      convertSegmentPathToStaticExportFilename(segmentPath)\n    staticUrl.pathname = `${routeDir}/${staticExportFilename}`\n    return staticUrl\n  }\n  return url\n}\n\n/**\n * Checks whether the new fetch strategy is likely to provide more content than the old one.\n *\n * Generally, when an app uses dynamic data, a \"more specific\" fetch strategy is expected to provide more content:\n * - `LoadingBoundary` only provides static layouts\n * - `PPR` can provide shells for each segment (even for segments that use dynamic data)\n * - `PPRRuntime` can additionally include content that uses searchParams, params, or cookies\n * - `Full` includes all the content, even if it uses dynamic data\n *\n * However, it's possible that a more specific fetch strategy *won't* give us more content if:\n * - a segment is fully static\n *   (then, `PPR`/`PPRRuntime`/`Full` will all yield equivalent results)\n * - providing searchParams/params/cookies doesn't reveal any more content, e.g. because of an `await connection()`\n *   (then, `PPR` and `PPRRuntime` will yield equivalent results, only `Full` will give us more)\n * Because of this, when comparing two segments, we should also check if the existing segment is partial.\n * If it's not partial, then there's no need to prefetch it again, even using a \"more specific\" strategy.\n * There's currently no way to know if `PPRRuntime` will yield more data that `PPR`, so we have to assume it will.\n *\n * Also note that, in practice, we don't expect to be comparing `LoadingBoundary` to `PPR`/`PPRRuntime`,\n * because a non-PPR-enabled route wouldn't ever use the latter strategies. It might however use `Full`.\n */\nexport function canNewFetchStrategyProvideMoreContent(\n  currentStrategy: FetchStrategy,\n  newStrategy: FetchStrategy\n): boolean {\n  return currentStrategy < newStrategy\n}\n\n/**\n * Adds the instant prefetch header if the navigation lock is active.\n * Uses a lazy require to ensure dead code elimination.\n */\nfunction addInstantPrefetchHeaderIfLocked(\n  headers: Record<string, string>\n): void {\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      headers[NEXT_INSTANT_PREFETCH_HEADER] = '1'\n    }\n  }\n}\n\nfunction getStaleAtFromHeader(\n  now: number,\n  response: RSCResponse<unknown>\n): number {\n  const staleTimeSeconds = parseInt(\n    response.headers.get(NEXT_ROUTER_STALE_TIME_HEADER) ?? '',\n    10\n  )\n\n  const staleTimeMs = !isNaN(staleTimeSeconds)\n    ? getStaleTimeMs(staleTimeSeconds)\n    : STATIC_STALETIME_MS\n\n  return now + staleTimeMs\n}\n\n/**\n * Reads the stale time from an async iterable or a response header and\n * returns a staleAt timestamp.\n *\n * TODO: Buffer the response and then read the iterable values\n * synchronously, similar to readVaryParams. This would avoid the need to\n * make this async, and we could also use it in\n * writeDynamicTreeResponseIntoCache. This will also be needed when React\n * starts leaving async iterables hanging when the outer RSC stream is\n * aborted e.g. due to sync I/O (with unstable_allowPartialStream).\n */\nexport async function getStaleAt(\n  now: number,\n  staleTimeIterable: AsyncIterable<number> | undefined,\n  response?: RSCResponse<unknown>\n): Promise<number> {\n  if (staleTimeIterable !== undefined) {\n    // Iterate the async iterable and take the last yielded value. The server\n    // yields updated staleTime values during the render; the last one is the\n    // final staleTime.\n    let staleTimeSeconds: number | undefined\n    for await (const value of staleTimeIterable) {\n      staleTimeSeconds = value\n    }\n\n    if (staleTimeSeconds !== undefined) {\n      const staleTimeMs = isNaN(staleTimeSeconds)\n        ? STATIC_STALETIME_MS\n        : getStaleTimeMs(staleTimeSeconds)\n\n      return now + staleTimeMs\n    }\n  }\n\n  if (response !== undefined) {\n    return getStaleAtFromHeader(now, response)\n  }\n\n  return now + STATIC_STALETIME_MS\n}\n\n/**\n * Writes the static stage of a navigation response into the segment cache.\n * When `isResponsePartial` is false, segments are written as non-partial with\n * `FetchStrategy.Full` so no dynamic follow-up is needed. Default segments\n * are skipped (by `writeSeedDataIntoCache`) to avoid caching fallback content\n * that would block refreshes from overwriting with dynamic data.\n */\nexport function writeStaticStageResponseIntoCache(\n  now: number,\n  flightData: FlightData,\n  buildId: string | undefined,\n  headVaryParamsThenable: VaryParamsThenable | null,\n  staleAt: number,\n  baseTree: FlightRouterState,\n  renderedSearch: string,\n  isResponsePartial: boolean\n): void {\n  const fetchStrategy = isResponsePartial\n    ? FetchStrategy.PPR\n    : FetchStrategy.Full\n\n  const headVaryParams =\n    headVaryParamsThenable !== null\n      ? readVaryParams(headVaryParamsThenable)\n      : null\n\n  const flightDatas = normalizeFlightData(flightData)\n  if (typeof flightDatas === 'string') {\n    return\n  }\n  const navigationSeed = convertServerPatchToFullTree(\n    now,\n    baseTree,\n    flightDatas,\n    renderedSearch,\n    UnknownDynamicStaleTime\n  )\n  writeDynamicRenderResponseIntoCache(\n    now,\n    fetchStrategy,\n    flightDatas,\n    buildId,\n    isResponsePartial,\n    headVaryParams,\n    staleAt,\n    navigationSeed,\n    null // spawnedEntries — no pre-created entries; will create or upsert\n  )\n}\n\n/**\n * Decodes an embedded runtime prefetch Flight stream, normalizes the flight\n * data, and derives a `NavigationSeed` from the base tree.\n *\n * Returns `null` if the response triggers an MPA navigation.\n */\nexport async function processRuntimePrefetchStream(\n  now: number,\n  runtimePrefetchStream: ReadableStream<Uint8Array>,\n  baseTree: FlightRouterState,\n  renderedSearch: string\n): Promise<{\n  flightDatas: NormalizedFlightData[]\n  navigationSeed: NavigationSeed\n  buildId: string | undefined\n  isResponsePartial: boolean\n  headVaryParams: VaryParams | null\n  staleAt: number\n} | null> {\n  const { stream, isPartial } = await stripIsPartialByte(runtimePrefetchStream)\n\n  const serverData =\n    await createFromNextReadableStream<NavigationFlightResponse>(\n      stream,\n      undefined,\n      { allowPartialStream: true }\n    )\n\n  const headVaryParamsThenable = serverData.h\n  const headVaryParams =\n    headVaryParamsThenable !== null\n      ? readVaryParams(headVaryParamsThenable)\n      : null\n\n  const staleAt = await getStaleAt(now, serverData.s)\n\n  const flightDatas = normalizeFlightData(serverData.f)\n  if (typeof flightDatas === 'string') {\n    return null\n  }\n  const navigationSeed = convertServerPatchToFullTree(\n    now,\n    baseTree,\n    flightDatas,\n    renderedSearch,\n    UnknownDynamicStaleTime\n  )\n\n  return {\n    flightDatas,\n    navigationSeed,\n    buildId: serverData.b,\n    isResponsePartial: isPartial,\n    headVaryParams,\n    staleAt,\n  }\n}\n\n/**\n * Strips the leading isPartial byte from an RSC response stream.\n *\n * The server prepends a single byte: '~' (0x7e) for partial, '#' (0x23) for\n * complete. These bytes cannot appear as the first byte of a valid RSC Flight\n * response (Flight rows start with a hex digit or ':').\n *\n * If the first byte is not a recognized marker, the stream is returned intact\n * and `isPartial` is determined by the cachedNavigations experimental flag.\n */\nexport async function stripIsPartialByte(\n  stream: ReadableStream<Uint8Array>\n): Promise<{ stream: ReadableStream<Uint8Array>; isPartial: boolean }> {\n  // When there is no recognized marker byte, the fallback depends on whether\n  // Cached Navigations is enabled. When enabled, dynamic navigation responses\n  // don't have a marker but may contain dynamic holes, so they are treated as\n  // partial. When disabled, unmarked responses are treated as non-partial.\n  const defaultIsPartial = !!process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\n\n  const reader = stream.getReader()\n  const { done, value } = await reader.read()\n\n  if (done || !value || value.byteLength === 0) {\n    return {\n      stream: new ReadableStream({ start: (c) => c.close() }),\n      isPartial: defaultIsPartial,\n    }\n  }\n\n  const firstByte = value[0]\n  const hasMarker = firstByte === 0x23 || firstByte === 0x7e\n  const isPartial = hasMarker ? firstByte === 0x7e : defaultIsPartial\n\n  const remainder = hasMarker\n    ? value.byteLength > 1\n      ? value.subarray(1)\n      : null\n    : value\n\n  return {\n    isPartial,\n    stream: new ReadableStream<Uint8Array>({\n      start(controller) {\n        if (remainder) {\n          controller.enqueue(remainder)\n        }\n      },\n      async pull(controller) {\n        const result = await reader.read()\n        if (result.done) {\n          controller.close()\n        } else {\n          controller.enqueue(result.value)\n        }\n      },\n    }),\n  }\n}\n"],"names":["readVaryParams","NEXT_DID_POSTPONE_HEADER","NEXT_INSTANT_PREFETCH_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_ROUTER_STALE_TIME_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_URL","RSC_CONTENT_TYPE_HEADER","RSC_HEADER","createFetch","createFromNextReadableStream","pingPrefetchTask","isPrefetchTaskDirty","getRouteVaryPath","getFulfilledRouteVaryPath","getFulfilledSegmentVaryPath","getSegmentVaryPathForRequest","appendLayoutVaryPath","finalizeLayoutVaryPath","finalizePageVaryPath","clonePageVaryPathWithNewSearchParams","finalizeMetadataVaryPath","getPartialPageVaryPath","getPartialLayoutVaryPath","getRenderedSearchFromVaryPath","createHrefFromUrl","createCacheKey","createPrefetchRequestKey","doesStaticSegmentAppearInURL","getCacheKeyForDynamicParam","getRenderedPathname","getRenderedSearch","parseDynamicParamFromURLPart","createCacheMap","getFromCacheMap","setInCacheMap","setSizeInCacheMap","deleteFromCacheMap","isValueExpired","appendSegmentRequestKeyPart","convertSegmentPathToStaticExportFilename","createSegmentRequestKeyPart","HEAD_REQUEST_KEY","ROOT_SEGMENT_REQUEST_KEY","normalizeFlightData","prepareFlightRouterStateForRequest","STATIC_STALETIME_MS","pingVisibleLinks","PAGE_SEGMENT_KEY","FetchStrategy","createPromiseWithResolvers","readFromBFCache","UnknownDynamicStaleTime","discoverKnownRoute","matchKnownRoute","convertServerPatchToFullTree","getNavigationBuildId","NEXT_NAV_DEPLOYMENT_ID_HEADER","getStaleTimeMs","staleTimeSeconds","Math","max","EntryStatus","isOutputExportMode","process","env","NODE_ENV","__NEXT_CONFIG_OUTPUT","MetadataOnlyRequestTree","routeCacheMap","segmentCacheMap","invalidationListeners","currentRouteCacheVersion","currentSegmentCacheVersion","getCurrentRouteCacheVersion","getCurrentSegmentCacheVersion","invalidateEntirePrefetchCache","nextUrl","tree","pingInvalidationListeners","invalidateRouteCacheEntries","invalidateSegmentCacheEntries","attachInvalidationListener","task","onInvalidate","Set","add","notifyInvalidationListener","error","reportError","console","tasks","readRouteCacheEntry","now","key","varyPath","pathname","search","isRevalidation","existingEntry","__NEXT_OPTIMISTIC_ROUTING","readSegmentCacheEntry","readRevalidatingSegmentCacheEntry","waitForSegmentCacheEntry","pendingEntry","promiseWithResolvers","promise","createDetachedRouteCacheEntry","canonicalUrl","status","blockedTasks","metadata","couldBeIntercepted","supportsPerSegmentPrefetching","renderedSearch","ref","size","staleAt","Infinity","version","readOrCreateRouteCacheEntry","deprecated_requestOptimisticRouteCacheEntry","requestedUrl","requestedSearch","urlWithoutSearchParams","URL","routeWithNoSearchParams","href","canonicalUrlForRouteWithNoSearchParams","origin","optimisticCanonicalSearch","optimisticRenderedSearch","optimisticUrl","location","optimisticCanonicalUrl","optimisticRouteTree","deprecated_createOptimisticRouteTree","optimisticMetadataTree","optimisticEntry","hasDynamicRewrite","newRenderedSearch","clonedSlots","originalSlots","slots","parallelRouteKey","childTree","isPage","requestKey","segment","refreshState","prefetchHints","readOrCreateSegmentCacheEntry","fetchStrategy","varyPathForRequest","createDetachedSegmentCacheEntry","readOrCreateRevalidatingSegmentEntry","overwriteRevalidatingSegmentCacheEntry","upsertSegmentEntry","candidateEntry","canNewFetchStrategyProvideMoreContent","isPartial","rejectedEntry","rsc","emptyEntry","PPR","upgradeToPendingSegment","Full","attemptToFulfillDynamicSegmentFromBFCache","bfcacheEntry","dynamicPrefetchStaleAt","navigatedAt","pendingSegment","fulfillSegmentCacheEntry","attemptToUpgradeSegmentFromBFCache","newEntry","segmentVaryPath","upserted","pingBlockedTasks","entry","createMetadataRouteTree","metadataVaryPath","fulfillRouteCacheEntry","fulfilledEntry","writeRouteIntoCache","markRouteEntryAsDynamicRewrite","segmentCacheEntry","resolve","rejectRouteCacheEntry","rejectSegmentCacheEntry","convertRootTreePrefetchToRouteTree","rootTree","renderedPathname","acc","pathnameParts","split","filter","p","index","rootSegment","convertTreePrefetchToRouteTree","prefetch","partialVaryPath","pathnamePartsIndex","prefetchSlots","childPrefetch","childSegmentName","name","childParam","param","childDoesAppearInURL","childSegment","childPartialVaryPath","childParamValue","type","childParamKey","siblings","childPathnamePartsIndex","childRequestKeyPart","childRequestKey","endsWith","convertRootFlightRouterStateToRouteTree","flightRouterState","convertFlightRouterStateToRouteTree","convertReusedFlightRouterStateToRouteTree","parentRouteTree","parentPartialVaryPath","parentRequestKey","requestKeyPart","parentRenderedSearch","originalSegment","compressedRefreshState","Array","isArray","paramCacheKey","paramName","parallelRoutes","childRouterState","convertRouteTreeToFlightRouterState","routeTree","fetchRouteOnCacheMiss","segmentPath","headers","addInstantPrefetchHeaderIfLocked","url","response","urlAfterRedirects","headResponse","fetch","method","Date","redirected","fetchPrefetchResponse","addSegmentPathToUrlInOutputExportMode","ok","body","varyHeader","get","includes","closed","routeIsPPREnabled","stream","prefetchStream","responseSize","createNonTaskyPrefetchResponseStream","serverData","allowPartialStream","buildId","b","headVaryParamsThenable","h","headVaryParams","writeDynamicTreeResponseIntoCache","LoadingBoundary","fulfilledVaryPath","value","fetchSegmentOnCacheMiss","route","routeKey","normalizedRequestKey","requestUrl","staleTime","varyParams","__NEXT_VARY_PARAMS","fetchInlinedSegmentsOnCacheMiss","spawnedEntries","rejectSegmentEntriesIfStillPending","fillInlinedSegmentEntries","headStaleAt","head","headKey","ownedHeadEntry","undefined","inlinedNode","ownedEntry","childInlinedNode","fetchSegmentPrefetchesUsingDynamicRequest","dynamicRequestTree","has","PPRRuntime","fulfilledEntries","bufferedResponseSize","createIncrementalPrefetchResponseStream","onResponseSizeUpdate","totalBytesReceivedSoFar","averageSize","length","cacheData","Promise","all","getStaleAt","s","isResponsePartial","flightDatas","f","navigationSeed","writeDynamicRenderResponseIntoCache","originalPathname","normalizedFlightDataResult","flightData","isRootRender","getStaleAtFromHeader","entries","values","push","metadataTree","flightDataEntry","seedData","i","writeSeedDataIntoCache","isHeadPartial","__NEXT_CACHE_COMPONENTS","fulfillEntrySpawnedByRuntimePrefetch","entriesOwnedByCurrentTask","varyParamsThenable","seedDataChildren","childSeedData","segmentVaryParams","possiblyNewEntry","fetchPriority","shouldImmediatelyDecode","contentType","isFlightResponse","startsWith","reader","getReader","chunks","done","read","byteLength","buffer","Uint8Array","offset","chunk","set","ReadableStream","start","controller","enqueue","close","originalFlightStream","onStreamClose","totalByteLength","pull","staticUrl","routeDir","slice","staticExportFilename","currentStrategy","newStrategy","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","parseInt","staleTimeMs","isNaN","staleTimeIterable","writeStaticStageResponseIntoCache","baseTree","processRuntimePrefetchStream","runtimePrefetchStream","stripIsPartialByte","defaultIsPartial","__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS","c","firstByte","hasMarker","remainder","subarray","result"],"mappings":"AAYA,SACEA,cAAc,QAGT,yDAAwD;AAC/D,SACEC,wBAAwB,EACxBC,4BAA4B,EAC5BC,2BAA2B,EAC3BC,mCAAmC,EACnCC,6BAA6B,EAC7BC,6BAA6B,EAC7BC,QAAQ,EACRC,uBAAuB,EACvBC,UAAU,QACL,wBAAuB;A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