Unverified Commit 889d1814 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Delete old navigation response handling implementation (#87149)

Based on:

- #87128 
- #87147 
- #87134 
- #87135 

---

This completes the migration of navigation response handling to the new
Segment Cache and PPR-based implementation.

Most of this PR is just deleting vestigial code. No behavioral changes
are expected. The substance of the migration was completed in earlier
steps.
parent 80fb15ce
...@@ -341,10 +341,6 @@ export const publicAppRouterInstance: AppRouterInstance = { ...@@ -341,10 +341,6 @@ export const publicAppRouterInstance: AppRouterInstance = {
fetchStrategy = FetchStrategy.Full fetchStrategy = FetchStrategy.Full
break break
} }
case PrefetchKind.TEMPORARY: {
// This concept doesn't exist in the segment cache implementation.
return
}
default: { default: {
prefetchKind satisfies never prefetchKind satisfies never
// Despite typescript thinking that this can't happen, // Despite typescript thinking that this can't happen,
......
...@@ -105,19 +105,6 @@ function HistoryUpdater({ ...@@ -105,19 +105,6 @@ function HistoryUpdater({
return null return null
} }
export function createEmptyCacheNode(): CacheNode {
return {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
navigatedAt: -1,
}
}
function copyNextJsInternalHistoryState(data: any) { function copyNextJsInternalHistoryState(data: any) {
if (data == null) data = {} if (data == null) data = {}
const currentState = window.history.state const currentState = window.history.state
......
'use client' 'use client'
import type { import type { CacheNode } from '../../shared/lib/app-router-types'
CacheNode,
LazyCacheNode,
} from '../../shared/lib/app-router-types'
import type { LoadingModuleData } from '../../shared/lib/app-router-types' import type { LoadingModuleData } from '../../shared/lib/app-router-types'
import type { import type {
FlightRouterState, FlightRouterState,
...@@ -11,16 +8,12 @@ import type { ...@@ -11,16 +8,12 @@ import type {
Segment, Segment,
} from '../../shared/lib/app-router-types' } from '../../shared/lib/app-router-types'
import type { ErrorComponent } from './error-boundary' import type { ErrorComponent } from './error-boundary'
import { import type { FocusAndScrollRef } from './router-reducer/router-reducer-types'
ACTION_SERVER_PATCH,
type FocusAndScrollRef,
} from './router-reducer/router-reducer-types'
import React, { import React, {
Activity, Activity,
useContext, useContext,
use, use,
startTransition,
Suspense, Suspense,
useDeferredValue, useDeferredValue,
type JSX, type JSX,
...@@ -32,7 +25,6 @@ import { ...@@ -32,7 +25,6 @@ import {
GlobalLayoutRouterContext, GlobalLayoutRouterContext,
TemplateContext, TemplateContext,
} from '../../shared/lib/app-router-context.shared-runtime' } from '../../shared/lib/app-router-context.shared-runtime'
import { fetchServerResponse } from './router-reducer/fetch-server-response'
import { unresolvedThenable } from './unresolved-thenable' import { unresolvedThenable } from './unresolved-thenable'
import { ErrorBoundary } from './error-boundary' import { ErrorBoundary } from './error-boundary'
import { matchSegment } from './match-segments' import { matchSegment } from './match-segments'
...@@ -40,8 +32,6 @@ import { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/route ...@@ -40,8 +32,6 @@ import { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/route
import { RedirectBoundary } from './redirect-boundary' import { RedirectBoundary } from './redirect-boundary'
import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary' import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'
import { createRouterCacheKey } from './router-reducer/create-router-cache-key' import { createRouterCacheKey } from './router-reducer/create-router-cache-key'
import { hasInterceptionRouteInCurrentTree } from './router-reducer/reducers/has-interception-route-in-current-tree'
import { dispatchAppRouterAction } from './use-action-queue'
import { useRouterBFCache, type RouterBFCacheEntry } from './bfcache' import { useRouterBFCache, type RouterBFCacheEntry } from './bfcache'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { import {
...@@ -52,56 +42,6 @@ import { getParamValueFromCacheKey } from '../route-params' ...@@ -52,56 +42,6 @@ import { getParamValueFromCacheKey } from '../route-params'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { isDeferredRsc } from './router-reducer/ppr-navigations' import { isDeferredRsc } from './router-reducer/ppr-navigations'
/**
* Add refetch marker to router state at the point of the current layout segment.
* This ensures the response returned is not further down than the current layout segment.
*/
function walkAddRefetch(
segmentPathToWalk: FlightSegmentPath | undefined,
treeToRecreate: FlightRouterState
): FlightRouterState {
if (segmentPathToWalk) {
const [segment, parallelRouteKey] = segmentPathToWalk
const isLast = segmentPathToWalk.length === 2
if (matchSegment(treeToRecreate[0], segment)) {
if (treeToRecreate[1].hasOwnProperty(parallelRouteKey)) {
if (isLast) {
const subTree = walkAddRefetch(
undefined,
treeToRecreate[1][parallelRouteKey]
)
return [
treeToRecreate[0],
{
...treeToRecreate[1],
[parallelRouteKey]: [
subTree[0],
subTree[1],
subTree[2],
'refetch',
],
},
]
}
return [
treeToRecreate[0],
{
...treeToRecreate[1],
[parallelRouteKey]: walkAddRefetch(
segmentPathToWalk.slice(2),
treeToRecreate[1][parallelRouteKey]
),
},
]
}
}
}
return treeToRecreate
}
const __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ( const __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = (
ReactDOM as any ReactDOM as any
).__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE ).__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE
...@@ -335,7 +275,7 @@ function InnerLayoutRouter({ ...@@ -335,7 +275,7 @@ function InnerLayoutRouter({
tree, tree,
segmentPath, segmentPath,
debugNameContext, debugNameContext,
cacheNode, cacheNode: maybeCacheNode,
params, params,
url, url,
isActive, isActive,
...@@ -343,7 +283,7 @@ function InnerLayoutRouter({ ...@@ -343,7 +283,7 @@ function InnerLayoutRouter({
tree: FlightRouterState tree: FlightRouterState
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
debugNameContext: string debugNameContext: string
cacheNode: CacheNode cacheNode: CacheNode | null
params: Params params: Params
url: string url: string
isActive: boolean isActive: boolean
...@@ -355,7 +295,18 @@ function InnerLayoutRouter({ ...@@ -355,7 +295,18 @@ function InnerLayoutRouter({
throw new Error('invariant global layout router not mounted') throw new Error('invariant global layout router not mounted')
} }
const { tree: fullTree } = context const cacheNode =
maybeCacheNode !== null
? maybeCacheNode
: // This segment is not in the cache. Suspend indefinitely.
//
// This should only be reachable for inactive/hidden segments, during
// prerendering The active segment should always be consistent with the
// CacheNode tree. Regardless, if we don't have a matching CacheNode, we
// must suspend rather than render nothing, to prevent showing an
// inconsistent route.
(use(unresolvedThenable) as never)
// `rsc` represents the renderable node for this segment. // `rsc` represents the renderable node for this segment.
...@@ -389,71 +340,12 @@ function InnerLayoutRouter({ ...@@ -389,71 +340,12 @@ function InnerLayoutRouter({
resolvedRsc = unwrappedRsc resolvedRsc = unwrappedRsc
} else { } else {
// This is not a deferred RSC promise. Don't need to unwrap it. // This is not a deferred RSC promise. Don't need to unwrap it.
resolvedRsc = rsc if (rsc === null) {
} use(unresolvedThenable) as never
// TODO: At this point, the only reason `resolvedRsc` would be null is if the
// data for this segment was fetched by a reducer that hasn't been migrated
// yet to the Segment Cache implementation. It shouldn't happen for regular
// navigations. Once we convert the remaining reducers, we can delete the
// lazy fetching block below.
if (!resolvedRsc) {
// The data for this segment is not available, and there's no pending
// navigation that will be able to fulfill it. We need to fetch more from
// the server and patch the cache.
// Only fetch data for the active segment. Inactive segments (rendered
// offscreen for bfcache) should not trigger fetches.
if (isActive) {
// Check if there's already a pending request.
let lazyData = cacheNode.lazyData
if (lazyData === null) {
/**
* Router state with refetch marker added
*/
// TODO-APP: remove ''
const refetchTree = walkAddRefetch(['', ...segmentPath], fullTree)
const includeNextUrl = hasInterceptionRouteInCurrentTree(fullTree)
const navigatedAt = Date.now()
cacheNode.lazyData = lazyData = fetchServerResponse(
new URL(url, location.origin),
{
flightRouterState: refetchTree,
nextUrl: includeNextUrl
? // We always send the last next-url, not the current when
// performing a dynamic request. This is because we update
// the next-url after a navigation, but we want the same
// interception route to be matched that used the last
// next-url.
context.previousNextUrl || context.nextUrl
: null,
}
).then((serverResponse) => {
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_SERVER_PATCH,
previousTree: fullTree,
serverResponse,
navigatedAt,
retry: null,
})
})
return serverResponse
})
// Suspend while waiting for lazyData to resolve
use(lazyData)
}
} }
// Suspend infinitely as `changeByServerResponse` will cause a different part of the tree to be rendered. resolvedRsc = rsc
// A falsey `resolvedRsc` indicates missing data -- we should not commit that branch, and we need to wait for the data to arrive.
use(unresolvedThenable) as never
} }
// If we get to this point, then we know we have something we can render.
let content = resolvedRsc
// In dev, we create a NavigationPromisesContext containing the instrumented promises that provide // In dev, we create a NavigationPromisesContext containing the instrumented promises that provide
// `useSelectedLayoutSegment` and `useSelectedLayoutSegments`. // `useSelectedLayoutSegment` and `useSelectedLayoutSegments`.
// Promises are cached outside of render to survive suspense retries. // Promises are cached outside of render to survive suspense retries.
...@@ -468,15 +360,17 @@ function InnerLayoutRouter({ ...@@ -468,15 +360,17 @@ function InnerLayoutRouter({
) )
} }
let children = resolvedRsc
if (navigationPromises) { if (navigationPromises) {
content = ( children = (
<NavigationPromisesContext.Provider value={navigationPromises}> <NavigationPromisesContext.Provider value={navigationPromises}>
{resolvedRsc} {resolvedRsc}
</NavigationPromisesContext.Provider> </NavigationPromisesContext.Provider>
) )
} }
const subtree = ( children = (
// The layout router context narrows down tree and childNodes at each level. // The layout router context narrows down tree and childNodes at each level.
<LayoutRouterContext.Provider <LayoutRouterContext.Provider
value={{ value={{
...@@ -491,11 +385,11 @@ function InnerLayoutRouter({ ...@@ -491,11 +385,11 @@ function InnerLayoutRouter({
isActive: isActive, isActive: isActive,
}} }}
> >
{content} {children}
</LayoutRouterContext.Provider> </LayoutRouterContext.Provider>
) )
// Ensure root layout is not wrapped in a div as the root layout renders `<html>`
return subtree return children
} }
/** /**
...@@ -657,25 +551,7 @@ export default function OuterLayoutRouter({ ...@@ -657,25 +551,7 @@ export default function OuterLayoutRouter({
const cacheKey = createRouterCacheKey(segment) const cacheKey = createRouterCacheKey(segment)
// Read segment path from the parallel router cache node. // Read segment path from the parallel router cache node.
let cacheNode = segmentMap.get(cacheKey) const cacheNode = segmentMap.get(cacheKey) ?? null
if (cacheNode === undefined) {
// When data is not available during rendering client-side we need to fetch
// it from the server.
const newLazyCacheNode: LazyCacheNode = {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
navigatedAt: -1,
}
// Flight data fetch kicked off during render and put into the cache.
cacheNode = newLazyCacheNode
segmentMap.set(cacheKey, newLazyCacheNode)
}
/* /*
- Error boundary - Error boundary
......
import type {
CacheNodeSeedData,
FlightRouterState,
FlightSegmentPath,
} from '../../../shared/lib/app-router-types'
import type { CacheNode } from '../../../shared/lib/app-router-types'
import {
addSearchParamsIfPageSegment,
DEFAULT_SEGMENT_KEY,
PAGE_SEGMENT_KEY,
} from '../../../shared/lib/segment'
import type { NormalizedFlightData } from '../../flight-data-helpers'
import { createEmptyCacheNode } from '../app-router'
import { applyRouterStatePatchToTree } from './apply-router-state-patch-to-tree'
import { createHrefFromUrl } from './create-href-from-url'
import { createRouterCacheKey } from './create-router-cache-key'
import { fillCacheWithNewSubTreeDataButOnlyLoading } from './fill-cache-with-new-subtree-data'
import { handleMutable } from './handle-mutable'
import { generateSegmentsFromPatch } from './reducers/navigate-reducer'
import type { Mutable, ReadonlyReducerState } from './router-reducer-types'
/**
* This is a stop-gap until per-segment caching is implemented. It leverages the `aliased` flag that is added
* to prefetch entries when it's determined that the loading state from that entry should be used for this navigation.
* This function takes the aliased entry and only applies the loading state to the updated cache node.
* We should remove this once per-segment fetching is implemented as ideally the prefetch cache will contain a
* more granular segment map and so the router will be able to simply re-use the loading segment for the new navigation.
*/
export function handleAliasedPrefetchEntry(
navigatedAt: number,
state: ReadonlyReducerState,
flightData: string | NormalizedFlightData[],
url: URL,
renderedSearch: string,
mutable: Mutable
) {
let currentTree = state.tree
let currentCache = state.cache
const href = createHrefFromUrl(url)
let applied
let scrollableSegments: FlightSegmentPath[] = []
if (typeof flightData === 'string') {
return false
}
for (const normalizedFlightData of flightData) {
// If the segment doesn't have a loading component, we don't need to do anything.
if (!hasLoadingComponentInSeedData(normalizedFlightData.seedData)) {
continue
}
let treePatch = normalizedFlightData.tree
// Segments are keyed by searchParams (e.g. __PAGE__?{"foo":"bar"}). We might return a less specific, param-less entry,
// so we ensure that the final tree contains the correct searchParams (reflected in the URL) are provided in the updated FlightRouterState tree.
// We only do this on the first read, as otherwise we'd be overwriting the searchParams that may have already been set
treePatch = addSearchParamsToPageSegments(
treePatch,
Object.fromEntries(url.searchParams)
)
const { seedData, isRootRender, pathToSegment } = normalizedFlightData
// TODO-APP: remove ''
const flightSegmentPathWithLeadingEmpty = ['', ...pathToSegment]
// Segments are keyed by searchParams (e.g. __PAGE__?{"foo":"bar"}). We might return a less specific, param-less entry,
// so we ensure that the final tree contains the correct searchParams (reflected in the URL) are provided in the updated FlightRouterState tree.
// We only do this on the first read, as otherwise we'd be overwriting the searchParams that may have already been set
treePatch = addSearchParamsToPageSegments(
treePatch,
Object.fromEntries(url.searchParams)
)
let newTree = applyRouterStatePatchToTree(
flightSegmentPathWithLeadingEmpty,
currentTree,
treePatch,
href
)
const newCache = createEmptyCacheNode()
// The prefetch cache entry was aliased -- this signals that we only fill in the cache with the
// loading state and not the actual parallel route seed data.
if (isRootRender && seedData) {
// Fill in the cache with the new loading / rsc data
const rsc = seedData[0]
const loading = seedData[2]
newCache.loading = loading
newCache.rsc = rsc
// Construct a new tree and apply the aliased loading state for each parallel route
fillNewTreeWithOnlyLoadingSegments(
navigatedAt,
newCache,
currentCache,
treePatch,
seedData
)
} else {
// Copy rsc for the root node of the cache.
newCache.rsc = currentCache.rsc
newCache.prefetchRsc = currentCache.prefetchRsc
newCache.loading = currentCache.loading
newCache.parallelRoutes = new Map(currentCache.parallelRoutes)
// copy the loading state only into the leaf node (the part that changed)
fillCacheWithNewSubTreeDataButOnlyLoading(
navigatedAt,
newCache,
currentCache,
normalizedFlightData
)
}
// If we don't have an updated tree, there's no reason to update the cache, as the tree
// dictates what cache nodes to render.
if (newTree) {
currentTree = newTree
currentCache = newCache
applied = true
}
for (const subSegment of generateSegmentsFromPatch(treePatch)) {
const scrollableSegmentPath = [
...normalizedFlightData.pathToSegment,
...subSegment,
]
// Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.
if (
scrollableSegmentPath[scrollableSegmentPath.length - 1] !==
DEFAULT_SEGMENT_KEY
) {
scrollableSegments.push(scrollableSegmentPath)
}
}
}
if (!applied) {
return false
}
mutable.patchedTree = currentTree
mutable.renderedSearch = renderedSearch
mutable.cache = currentCache
mutable.canonicalUrl = href
mutable.hashFragment = url.hash
mutable.scrollableSegments = scrollableSegments
return handleMutable(state, mutable)
}
function hasLoadingComponentInSeedData(seedData: CacheNodeSeedData | null) {
if (!seedData) return false
const parallelRoutes = seedData[1]
const loading = seedData[2]
if (loading) {
return true
}
for (const key in parallelRoutes) {
if (hasLoadingComponentInSeedData(parallelRoutes[key])) {
return true
}
}
return false
}
function fillNewTreeWithOnlyLoadingSegments(
navigatedAt: number,
newCache: CacheNode,
existingCache: CacheNode,
routerState: FlightRouterState,
cacheNodeSeedData: CacheNodeSeedData | null
) {
const isLastSegment = Object.keys(routerState[1]).length === 0
if (isLastSegment) {
return
}
for (const key in routerState[1]) {
const parallelRouteState = routerState[1][key]
const segmentForParallelRoute = parallelRouteState[0]
const cacheKey = createRouterCacheKey(segmentForParallelRoute)
const parallelSeedData =
cacheNodeSeedData !== null && cacheNodeSeedData[1][key] !== undefined
? cacheNodeSeedData[1][key]
: null
let newCacheNode: CacheNode
if (parallelSeedData !== null) {
// New data was sent from the server.
const rsc = parallelSeedData[0]
const loading = parallelSeedData[2]
newCacheNode = {
lazyData: null,
// copy the layout but null the page segment as that's not meant to be used
rsc: segmentForParallelRoute.includes(PAGE_SEGMENT_KEY) ? null : rsc,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading,
navigatedAt,
}
} else {
// No data available for this node. This will trigger a lazy fetch
// during render.
newCacheNode = {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
navigatedAt: -1,
}
}
const existingParallelRoutes = newCache.parallelRoutes.get(key)
if (existingParallelRoutes) {
existingParallelRoutes.set(cacheKey, newCacheNode)
} else {
newCache.parallelRoutes.set(key, new Map([[cacheKey, newCacheNode]]))
}
fillNewTreeWithOnlyLoadingSegments(
navigatedAt,
newCacheNode,
existingCache,
parallelRouteState,
parallelSeedData
)
}
}
/**
* Add search params to the page segments in the flight router state
* Page segments that are associated with search params have a page segment key
* followed by a query string. This function will add those params to the page segment.
* This is useful if we return an aliased prefetch entry (ie, won't have search params)
* but the canonical router URL has search params.
*/
export function addSearchParamsToPageSegments(
flightRouterState: FlightRouterState,
searchParams: Record<string, string | string[] | undefined>
): FlightRouterState {
const [segment, parallelRoutes, ...rest] = flightRouterState
// If it's a page segment, modify the segment by adding search params
if (segment.includes(PAGE_SEGMENT_KEY)) {
const newSegment = addSearchParamsIfPageSegment(segment, searchParams)
return [newSegment, parallelRoutes, ...rest]
}
// Otherwise, recurse through the parallel routes and return a new tree
const updatedParallelRoutes: { [key: string]: FlightRouterState } = {}
for (const [key, parallelRoute] of Object.entries(parallelRoutes)) {
updatedParallelRoutes[key] = addSearchParamsToPageSegments(
parallelRoute,
searchParams
)
}
return [segment, updatedParallelRoutes, ...rest]
}
import type { CacheNode } from '../../../shared/lib/app-router-types'
import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'
import { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data'
import type { NormalizedFlightData } from '../../flight-data-helpers'
export function applyFlightData(
navigatedAt: number,
existingCache: CacheNode,
cache: CacheNode,
flightData: NormalizedFlightData
): boolean {
// The one before last item is the router state tree patch
const { tree: treePatch, seedData, head, isRootRender } = flightData
// Handles case where prefetch only returns the router tree patch without rendered components.
if (seedData === null) {
return false
}
if (isRootRender) {
const rsc = seedData[0]
const loading = seedData[2]
cache.loading = loading
cache.rsc = rsc
// This is a PPR-only field. When PPR is enabled, we shouldn't hit
// this path during a navigation, but until PPR is fully implemented
// yet it's possible the existing node does have a non-null
// `prefetchRsc`. As an incremental step, we'll just de-opt to the
// old behavior — no PPR value.
cache.prefetchRsc = null
fillLazyItemsTillLeafWithHead(
navigatedAt,
cache,
existingCache,
treePatch,
seedData,
head
)
} else {
// Copy rsc for the root node of the cache.
cache.rsc = existingCache.rsc
// This is a PPR-only field. Unlike the previous branch, since we're
// just cloning the existing cache node, we might as well keep the
// PPR value, if it exists.
cache.prefetchRsc = existingCache.prefetchRsc
cache.parallelRoutes = new Map(existingCache.parallelRoutes)
cache.loading = existingCache.loading
// Create a copy of the existing cache with the rsc applied.
fillCacheWithNewSubTreeData(navigatedAt, cache, existingCache, flightData)
}
return true
}
import React from 'react'
import type {
FlightData,
FlightRouterState,
} from '../../../shared/lib/app-router-types'
import { applyRouterStatePatchToTree } from './apply-router-state-patch-to-tree'
const getInitialRouterStateTree = (): FlightRouterState => [
'',
{
children: [
'linking',
{
children: ['', {}],
},
],
},
undefined,
undefined,
true,
]
const getFlightData = (): FlightData => {
return [
[
'children',
'linking',
'children',
'about',
[
'about',
{
children: ['', {}],
},
],
['about', {}, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
false,
],
]
}
describe('applyRouterStatePatchToTree', () => {
it('should apply a patch to the tree', () => {
const initialRouterStateTree = getInitialRouterStateTree()
const flightData = getFlightData()
if (typeof flightData === 'string') {
throw new Error('invalid flight data')
}
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const [treePatch /*, cacheNodeSeedData, head, isHeadPartial*/] =
flightDataPath.slice(-4)
const flightSegmentPath = flightDataPath.slice(0, -4)
const newRouterStateTree = applyRouterStatePatchToTree(
['', ...flightSegmentPath],
initialRouterStateTree,
treePatch,
''
)
expect(newRouterStateTree).toMatchObject([
'',
{
children: [
'linking',
{
children: [
'about',
{
children: ['', {}],
},
],
},
],
},
undefined,
undefined,
true,
])
})
})
import type {
FlightRouterState,
FlightSegmentPath,
} from '../../../shared/lib/app-router-types'
import { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/segment'
import { getNextFlightSegmentPath } from '../../flight-data-helpers'
import { matchSegment } from '../match-segments'
import { addRefreshMarkerToActiveParallelSegments } from './refetch-inactive-parallel-segments'
/**
* Deep merge of the two router states. Parallel route keys are preserved if the patch doesn't have them.
*/
function applyPatch(
initialTree: FlightRouterState,
patchTree: FlightRouterState
): FlightRouterState {
const [initialSegment, initialParallelRoutes] = initialTree
const [patchSegment, patchParallelRoutes] = patchTree
// if the applied patch segment is __DEFAULT__ then it can be ignored in favor of the initial tree
// this is because the __DEFAULT__ segment is used as a placeholder on navigation
if (
patchSegment === DEFAULT_SEGMENT_KEY &&
initialSegment !== DEFAULT_SEGMENT_KEY
) {
return initialTree
}
if (matchSegment(initialSegment, patchSegment)) {
const newParallelRoutes: FlightRouterState[1] = {}
for (const key in initialParallelRoutes) {
const isInPatchTreeParallelRoutes =
typeof patchParallelRoutes[key] !== 'undefined'
if (isInPatchTreeParallelRoutes) {
newParallelRoutes[key] = applyPatch(
initialParallelRoutes[key],
patchParallelRoutes[key]
)
} else {
newParallelRoutes[key] = initialParallelRoutes[key]
}
}
for (const key in patchParallelRoutes) {
if (newParallelRoutes[key]) {
continue
}
newParallelRoutes[key] = patchParallelRoutes[key]
}
const tree: FlightRouterState = [initialSegment, newParallelRoutes]
// Copy over the existing tree
if (initialTree[2]) {
tree[2] = initialTree[2]
}
if (initialTree[3]) {
tree[3] = initialTree[3]
}
if (initialTree[4]) {
tree[4] = initialTree[4]
}
return tree
}
return patchTree
}
/**
* Apply the router state from the Flight response, but skip patching default segments.
* Useful for patching the router cache when navigating, where we persist the existing default segment if there isn't a new one.
* Creates a new router state tree.
*/
export function applyRouterStatePatchToTree(
flightSegmentPath: FlightSegmentPath,
flightRouterState: FlightRouterState,
treePatch: FlightRouterState,
path: string
): FlightRouterState | null {
const [segment, parallelRoutes, url, refetch, isRootLayout] =
flightRouterState
// Root refresh
if (flightSegmentPath.length === 1) {
const tree: FlightRouterState = applyPatch(flightRouterState, treePatch)
addRefreshMarkerToActiveParallelSegments(tree, path)
return tree
}
const [currentSegment, parallelRouteKey] = flightSegmentPath
// Tree path returned from the server should always match up with the current tree in the browser
if (!matchSegment(currentSegment, segment)) {
return null
}
const lastSegment = flightSegmentPath.length === 2
let parallelRoutePatch
if (lastSegment) {
parallelRoutePatch = applyPatch(parallelRoutes[parallelRouteKey], treePatch)
} else {
parallelRoutePatch = applyRouterStatePatchToTree(
getNextFlightSegmentPath(flightSegmentPath),
parallelRoutes[parallelRouteKey],
treePatch,
path
)
if (parallelRoutePatch === null) {
return null
}
}
const tree: FlightRouterState = [
flightSegmentPath[0],
{
...parallelRoutes,
[parallelRouteKey]: parallelRoutePatch,
},
url,
refetch,
]
// Current segment is the root layout
if (isRootLayout) {
tree[4] = true
}
addRefreshMarkerToActiveParallelSegments(tree, path)
return tree
}
import React from 'react'
import { clearCacheNodeDataForSegmentPath } from './clear-cache-node-data-for-segment-path'
import type { CacheNode } from '../../../shared/lib/app-router-types'
const navigatedAt = -1
describe('clearCacheNodeDataForSegmentPath', () => {
it('should clear the data property', () => {
const pathname = '/dashboard/settings'
const segments = pathname.split('/')
const flightSegmentPath = segments
.slice(1)
.map((segment) => ['children', segment])
.flat()
const cache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
}
const existingCache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
navigatedAt,
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
navigatedAt,
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
},
],
]),
],
]),
},
],
]),
],
]),
}
clearCacheNodeDataForSegmentPath(cache, existingCache, flightSegmentPath)
expect(cache).toMatchInlineSnapshot(`
{
"head": null,
"lazyData": null,
"loading": null,
"navigatedAt": -1,
"parallelRoutes": Map {
"children" => Map {
"linking" => {
"head": null,
"lazyData": null,
"loading": null,
"navigatedAt": -1,
"parallelRoutes": Map {
"children" => Map {
"" => {
"head": null,
"lazyData": null,
"loading": null,
"navigatedAt": -1,
"parallelRoutes": Map {},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": <React.Fragment>
Page
</React.Fragment>,
},
},
},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": <React.Fragment>
Linking
</React.Fragment>,
},
"dashboard" => {
"head": null,
"lazyData": null,
"loading": null,
"navigatedAt": -1,
"parallelRoutes": Map {},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": null,
},
},
},
"prefetchHead": null,
"prefetchRsc": null,
"rsc": null,
}
`)
})
})
import type {
FlightSegmentPath,
CacheNode,
} from '../../../shared/lib/app-router-types'
import { getNextFlightSegmentPath } from '../../flight-data-helpers'
import { createRouterCacheKey } from './create-router-cache-key'
/**
* This will clear the CacheNode data for a particular segment path. This will cause a lazy-fetch in layout router to fill in new data.
*/
export function clearCacheNodeDataForSegmentPath(
newCache: CacheNode,
existingCache: CacheNode,
flightSegmentPath: FlightSegmentPath
): void {
const isLastEntry = flightSegmentPath.length <= 2
const [parallelRouteKey, segment] = flightSegmentPath
const cacheKey = createRouterCacheKey(segment)
const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey)
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap)
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
}
const existingChildCacheNode = existingChildSegmentMap?.get(cacheKey)
let childCacheNode = childSegmentMap.get(cacheKey)
// In case of last segment start off the fetch at this level and don't copy further down.
if (isLastEntry) {
if (
!childCacheNode ||
!childCacheNode.lazyData ||
childCacheNode === existingChildCacheNode
) {
childSegmentMap.set(cacheKey, {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
navigatedAt: -1,
})
}
return
}
if (!childCacheNode || !existingChildCacheNode) {
// Start fetch in the place where the existing cache doesn't have the data yet.
if (!childCacheNode) {
childSegmentMap.set(cacheKey, {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
navigatedAt: -1,
})
}
return
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
lazyData: childCacheNode.lazyData,
rsc: childCacheNode.rsc,
prefetchRsc: childCacheNode.prefetchRsc,
head: childCacheNode.head,
prefetchHead: childCacheNode.prefetchHead,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
loading: childCacheNode.loading,
} as CacheNode
childSegmentMap.set(cacheKey, childCacheNode)
}
return clearCacheNodeDataForSegmentPath(
childCacheNode,
existingChildCacheNode,
getNextFlightSegmentPath(flightSegmentPath)
)
}
...@@ -12,9 +12,9 @@ import type { ...@@ -12,9 +12,9 @@ import type {
NavigationFlightResponse, NavigationFlightResponse,
} from '../../../shared/lib/app-router-types' } from '../../../shared/lib/app-router-types'
import type { NEXT_ROUTER_SEGMENT_PREFETCH_HEADER } from '../app-router-headers'
import { import {
NEXT_ROUTER_PREFETCH_HEADER, type NEXT_ROUTER_PREFETCH_HEADER,
type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER, NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_RSC_UNION_QUERY, NEXT_RSC_UNION_QUERY,
NEXT_URL, NEXT_URL,
...@@ -28,7 +28,6 @@ import { ...@@ -28,7 +28,6 @@ import {
} from '../app-router-headers' } from '../app-router-headers'
import { callServer } from '../../app-call-server' import { callServer } from '../../app-call-server'
import { findSourceMapURL } from '../../app-find-source-map-url' import { findSourceMapURL } from '../../app-find-source-map-url'
import { PrefetchKind } from './router-reducer-types'
import { import {
normalizeFlightData, normalizeFlightData,
prepareFlightRouterStateForRequest, prepareFlightRouterStateForRequest,
...@@ -64,7 +63,6 @@ if ( ...@@ -64,7 +63,6 @@ if (
export interface FetchServerResponseOptions { export interface FetchServerResponseOptions {
readonly flightRouterState: FlightRouterState readonly flightRouterState: FlightRouterState
readonly nextUrl: string | null readonly nextUrl: string | null
readonly prefetchKind?: PrefetchKind
readonly isHmrRefresh?: boolean readonly isHmrRefresh?: boolean
} }
...@@ -128,7 +126,7 @@ export async function fetchServerResponse( ...@@ -128,7 +126,7 @@ export async function fetchServerResponse(
url: URL, url: URL,
options: FetchServerResponseOptions options: FetchServerResponseOptions
): Promise<FetchServerResponseResult> { ): Promise<FetchServerResponseResult> {
const { flightRouterState, nextUrl, prefetchKind } = options const { flightRouterState, nextUrl } = options
const headers: RequestHeaders = { const headers: RequestHeaders = {
// Enable flight response // Enable flight response
...@@ -140,16 +138,6 @@ export async function fetchServerResponse( ...@@ -140,16 +138,6 @@ export async function fetchServerResponse(
), ),
} }
/**
* Three cases:
* - `prefetchKind` is `undefined`, it means it's a normal navigation, so we want to prefetch the page data fully
* - `prefetchKind` is `full` - we want to prefetch the whole page so same as above
* - `prefetchKind` is `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully
*/
if (prefetchKind === PrefetchKind.AUTO) {
headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'
}
if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) { if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) {
headers[NEXT_HMR_REFRESH_HEADER] = '1' headers[NEXT_HMR_REFRESH_HEADER] = '1'
} }
...@@ -163,16 +151,6 @@ export async function fetchServerResponse( ...@@ -163,16 +151,6 @@ export async function fetchServerResponse(
const originalUrl = url const originalUrl = url
try { try {
// When creating a "temporary" prefetch (the "on-demand" prefetch that gets created on navigation, if one doesn't exist)
// we send the request with a "high" priority as it's in response to a user interaction that could be blocking a transition.
// Otherwise, all other prefetches are sent with a "low" priority.
// We use "auto" for in all other cases to match the existing default, as this function is shared outside of prefetching.
const fetchPriority = prefetchKind
? prefetchKind === PrefetchKind.TEMPORARY
? 'high'
: 'low'
: 'auto'
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
if (process.env.__NEXT_CONFIG_OUTPUT === 'export') { if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {
// In "output: export" mode, we can't rely on headers to distinguish // In "output: export" mode, we can't rely on headers to distinguish
...@@ -196,7 +174,7 @@ export async function fetchServerResponse( ...@@ -196,7 +174,7 @@ export async function fetchServerResponse(
const res = await createFetch<NavigationFlightResponse>( const res = await createFetch<NavigationFlightResponse>(
url, url,
headers, headers,
fetchPriority, 'auto',
shouldImmediatelyDecode shouldImmediatelyDecode
) )
......
import { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data'
import type { CacheNode } from '../../../shared/lib/app-router-types'
import type { NormalizedFlightData } from '../../flight-data-helpers'
const getFlightData = (): NormalizedFlightData[] => {
return [
{
pathToSegment: ['children', 'linking', 'children'],
segmentPath: ['children', 'linking', 'children', 'about'],
segment: 'about',
tree: ['about', { children: ['', {}] }],
seedData: [<h1>SubTreeData Injected!</h1>, {}, null, false, false],
head: null,
isHeadPartial: false,
isRootRender: false,
},
]
}
describe('fillCacheWithNewSubtreeData', () => {
it('should apply rsc and head property', () => {
const cache: CacheNode = {
navigatedAt: -1,
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
}
const existingCache: CacheNode = {
navigatedAt: -1,
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
navigatedAt: -1,
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
navigatedAt: -1,
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
},
],
]),
],
]),
},
],
]),
],
]),
}
const flightData = getFlightData()
if (typeof flightData === 'string') {
throw new Error('invalid flight data')
}
// Mirrors the way router-reducer values are passed in.
const normalizedFlightData = flightData[0]
const navigatedAt = -1
fillCacheWithNewSubTreeData(
navigatedAt,
cache,
existingCache,
normalizedFlightData
)
const expectedCache: CacheNode = {
navigatedAt: -1,
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
navigatedAt: -1,
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
// TODO-APP: this segment should be preserved when creating the new cache
[
'',
{
navigatedAt: -1,
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
},
],
[
'about',
{
navigatedAt: -1,
lazyData: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
lazyData: null,
rsc: null,
prefetchRsc: null,
parallelRoutes: new Map(),
prefetchHead: null,
loading: null,
head: null,
},
],
]),
],
]),
rsc: <h1>SubTreeData Injected!</h1>,
prefetchRsc: null,
},
],
]),
],
]),
},
],
]),
],
]),
}
expect(cache).toMatchObject(expectedCache)
})
})
import type { CacheNode, Segment } from '../../../shared/lib/app-router-types'
import { invalidateCacheByRouterState } from './invalidate-cache-by-router-state'
import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'
import { createRouterCacheKey } from './create-router-cache-key'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
import type { NormalizedFlightData } from '../../flight-data-helpers'
/**
* Common logic for filling cache with new sub tree data.
*/
function fillCacheHelper(
navigatedAt: number,
newCache: CacheNode,
existingCache: CacheNode,
flightData: NormalizedFlightData,
fillLazyItems: boolean
): void {
const {
segmentPath,
seedData: cacheNodeSeedData,
tree: treePatch,
head,
} = flightData
let newCacheNode = newCache
let existingCacheNode = existingCache
for (let i = 0; i < segmentPath.length; i += 2) {
const parallelRouteKey: string = segmentPath[i]
const segment: Segment = segmentPath[i + 1]
// segmentPath is a repeating tuple of parallelRouteKey and segment
// we know we've hit the last entry we've reached our final pair
const isLastEntry = i === segmentPath.length - 2
const cacheKey = createRouterCacheKey(segment)
const existingChildSegmentMap =
existingCacheNode.parallelRoutes.get(parallelRouteKey)
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
continue
}
let childSegmentMap = newCacheNode.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap)
newCacheNode.parallelRoutes.set(parallelRouteKey, childSegmentMap)
}
const existingChildCacheNode = existingChildSegmentMap.get(cacheKey)
let childCacheNode = childSegmentMap.get(cacheKey)
if (isLastEntry) {
if (
cacheNodeSeedData &&
(!childCacheNode ||
!childCacheNode.lazyData ||
childCacheNode === existingChildCacheNode)
) {
const rsc = cacheNodeSeedData[0]
const loading = cacheNodeSeedData[2]
childCacheNode = {
lazyData: null,
// When `fillLazyItems` is false, we only want to fill the RSC data for the layout,
// not the page segment.
rsc: fillLazyItems || segment !== PAGE_SEGMENT_KEY ? rsc : null,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading,
parallelRoutes:
fillLazyItems && existingChildCacheNode
? new Map(existingChildCacheNode.parallelRoutes)
: new Map(),
navigatedAt,
}
if (existingChildCacheNode && fillLazyItems) {
invalidateCacheByRouterState(
childCacheNode,
existingChildCacheNode,
treePatch
)
}
if (fillLazyItems) {
fillLazyItemsTillLeafWithHead(
navigatedAt,
childCacheNode,
existingChildCacheNode,
treePatch,
cacheNodeSeedData,
head
)
}
childSegmentMap.set(cacheKey, childCacheNode)
}
continue
}
if (!childCacheNode || !existingChildCacheNode) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
continue
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
lazyData: childCacheNode.lazyData,
rsc: childCacheNode.rsc,
prefetchRsc: childCacheNode.prefetchRsc,
head: childCacheNode.head,
prefetchHead: childCacheNode.prefetchHead,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
loading: childCacheNode.loading,
} as CacheNode
childSegmentMap.set(cacheKey, childCacheNode)
}
// Move deeper into the cache nodes
newCacheNode = childCacheNode
existingCacheNode = existingChildCacheNode
}
}
/**
* Fill cache with rsc based on flightDataPath
*/
export function fillCacheWithNewSubTreeData(
navigatedAt: number,
newCache: CacheNode,
existingCache: CacheNode,
flightData: NormalizedFlightData
): void {
fillCacheHelper(navigatedAt, newCache, existingCache, flightData, true)
}
export function fillCacheWithNewSubTreeDataButOnlyLoading(
navigatedAt: number,
newCache: CacheNode,
existingCache: CacheNode,
flightData: NormalizedFlightData
): void {
fillCacheHelper(navigatedAt, newCache, existingCache, flightData, false)
}
import React from 'react'
import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'
import type {
CacheNode,
FlightData,
} from '../../../shared/lib/app-router-types'
const getFlightData = (): FlightData => {
return [
[
[
'',
{
children: [
'linking',
{
children: [
'about',
{
children: ['', {}],
},
],
},
],
},
null,
null,
true,
],
['', {}, <h1>About Page!</h1>],
<>
<title>About page!</title>
</>,
],
]
}
const navigatedAt = Date.now()
describe('fillLazyItemsTillLeafWithHead', () => {
it('should fill lazy items till leaf with head', () => {
const cache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
}
const existingCache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
navigatedAt,
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
navigatedAt,
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
},
],
]),
],
]),
},
],
]),
],
]),
}
const flightData = getFlightData()
if (typeof flightData === 'string') {
throw new Error('invalid flight data')
}
// Mirrors the way router-reducer values are passed in.
const flightDataPath = flightData[0]
const [treePatch, cacheNodeSeedData, head /*, isHeadPartial */] =
flightDataPath.slice(-4)
fillLazyItemsTillLeafWithHead(
navigatedAt,
cache,
existingCache,
treePatch,
cacheNodeSeedData,
head
)
const expectedCache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
navigatedAt,
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'about',
{
navigatedAt,
lazyData: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
navigatedAt,
lazyData: null,
rsc: null,
prefetchRsc: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
head: null,
},
],
]),
],
]),
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
},
],
[
'',
{
navigatedAt,
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
},
],
]),
],
]),
},
],
]),
],
]),
}
expect(cache).toMatchObject(expectedCache)
})
})
import type { CacheNode } from '../../../shared/lib/app-router-types'
import type {
FlightRouterState,
CacheNodeSeedData,
} from '../../../shared/lib/app-router-types'
import { createRouterCacheKey } from './create-router-cache-key'
export function fillLazyItemsTillLeafWithHead(
navigatedAt: number,
newCache: CacheNode,
existingCache: CacheNode | undefined,
routerState: FlightRouterState,
cacheNodeSeedData: CacheNodeSeedData | null,
head: React.ReactNode
): void {
const isLastSegment = Object.keys(routerState[1]).length === 0
if (isLastSegment) {
newCache.head = head
return
}
// Remove segment that we got data for so that it is filled in during rendering of rsc.
for (const key in routerState[1]) {
const parallelRouteState = routerState[1][key]
const segmentForParallelRoute = parallelRouteState[0]
const cacheKey = createRouterCacheKey(segmentForParallelRoute)
// TODO: We should traverse the cacheNodeSeedData tree instead of the router
// state tree. Ideally, they would always be the same shape, but because of
// the loading.js pattern, cacheNodeSeedData sometimes only represents a
// partial tree. That's why this node is sometimes null. Once PPR lands,
// loading.js will no longer have special behavior and we can traverse the
// data tree instead.
//
// We should also consider merging the router state tree and the data tree
// in the response format, so that we don't have to send the keys twice.
// Then the client can convert them into separate representations.
const parallelSeedData =
cacheNodeSeedData !== null && cacheNodeSeedData[1][key] !== undefined
? cacheNodeSeedData[1][key]
: null
if (existingCache) {
const existingParallelRoutesCacheNode =
existingCache.parallelRoutes.get(key)
if (existingParallelRoutesCacheNode) {
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)
const existingCacheNode = parallelRouteCacheNode.get(cacheKey)
let newCacheNode: CacheNode
if (parallelSeedData !== null) {
// New data was sent from the server.
const seedNode = parallelSeedData[0]
const loading = parallelSeedData[2]
newCacheNode = {
lazyData: null,
rsc: seedNode,
// This is a PPR-only field. When PPR is enabled, we shouldn't hit
// this path during a navigation, but until PPR is fully implemented
// yet it's possible the existing node does have a non-null
// `prefetchRsc`. As an incremental step, we'll just de-opt to the
// old behavior — no PPR value.
prefetchRsc: null,
head: null,
prefetchHead: null,
loading,
parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
navigatedAt,
}
} else {
// No data available for this node. This will trigger a lazy fetch
// during render.
newCacheNode = {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
loading: null,
navigatedAt,
}
}
// Overrides the cache key with the new cache node.
parallelRouteCacheNode.set(cacheKey, newCacheNode)
// Traverse deeper to apply the head / fill lazy items till the head.
fillLazyItemsTillLeafWithHead(
navigatedAt,
newCacheNode,
existingCacheNode,
parallelRouteState,
parallelSeedData ? parallelSeedData : null,
head
)
newCache.parallelRoutes.set(key, parallelRouteCacheNode)
continue
}
}
let newCacheNode: CacheNode
if (parallelSeedData !== null) {
// New data was sent from the server.
const seedNode = parallelSeedData[0]
const loading = parallelSeedData[2]
newCacheNode = {
lazyData: null,
rsc: seedNode,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading,
navigatedAt,
}
} else {
// No data available for this node. This will trigger a lazy fetch
// during render.
newCacheNode = {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
navigatedAt,
}
}
const existingParallelRoutes = newCache.parallelRoutes.get(key)
if (existingParallelRoutes) {
existingParallelRoutes.set(cacheKey, newCacheNode)
} else {
newCache.parallelRoutes.set(key, new Map([[cacheKey, newCacheNode]]))
}
fillLazyItemsTillLeafWithHead(
navigatedAt,
newCacheNode,
undefined,
parallelRouteState,
parallelSeedData,
head
)
}
}
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import { handleExternalUrl } from './reducers/navigate-reducer'
import type {
ReadonlyReducerState,
ReducerActions,
} from './router-reducer-types'
/**
* Handles the case where the client router attempted to patch the tree but, due to a mismatch, the patch failed.
* This will perform an MPA navigation to return the router to a valid state.
*/
export function handleSegmentMismatch(
state: ReadonlyReducerState,
action: ReducerActions,
treePatch: FlightRouterState
) {
if (process.env.NODE_ENV === 'development') {
console.warn(
'Performing hard navigation because your application experienced an unrecoverable error. If this keeps occurring, please file a Next.js issue.\n\n' +
'Reason: Segment mismatch\n' +
`Last Action: ${action.type}\n\n` +
`Current Tree: ${JSON.stringify(state.tree)}\n\n` +
`Tree Patch Payload: ${JSON.stringify(treePatch)}`
)
}
return handleExternalUrl(state, {}, state.canonicalUrl, true)
}
import React from 'react'
import { invalidateCacheBelowFlightSegmentPath } from './invalidate-cache-below-flight-segmentpath'
import type { CacheNode } from '../../../shared/lib/app-router-types'
import { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data'
import type { NormalizedFlightData } from '../../flight-data-helpers'
const getFlightData = (): NormalizedFlightData[] => {
return [
{
pathToSegment: ['children', 'linking', 'children'],
segmentPath: ['children', 'linking', 'children', 'about'],
segment: 'about',
tree: ['about', { children: ['', {}] }],
seedData: [<h1>About Page!</h1>, {}, null, false, false],
head: null,
isHeadPartial: false,
isRootRender: false,
},
]
}
const navigatedAt = Date.now()
describe('invalidateCacheBelowFlightSegmentPath', () => {
it('should invalidate cache below flight segment path', () => {
const cache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
}
const existingCache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
navigatedAt,
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
navigatedAt,
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
},
],
]),
],
]),
},
],
]),
],
]),
}
const flightData = getFlightData()
if (typeof flightData === 'string') {
throw new Error('invalid flight data')
}
// Mirrors the way router-reducer values are passed in.
const normalizedFlightData = flightData[0]
// Copy rsc for the root node of the cache.
cache.rsc = existingCache.rsc
cache.prefetchRsc = existingCache.prefetchRsc
// Create a copy of the existing cache with the rsc applied.
fillCacheWithNewSubTreeData(
navigatedAt,
cache,
existingCache,
normalizedFlightData
)
// Invalidate the cache below the flight segment path. This should remove the 'about' node.
invalidateCacheBelowFlightSegmentPath(
cache,
existingCache,
normalizedFlightData.segmentPath
)
const expectedCache: CacheNode = {
navigatedAt,
lazyData: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
navigatedAt,
lazyData: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
navigatedAt,
lazyData: null,
loading: null,
parallelRoutes: new Map(),
rsc: <React.Fragment>Page</React.Fragment>,
prefetchRsc: null,
head: null,
prefetchHead: null,
},
],
]),
],
]),
rsc: <React.Fragment>Linking</React.Fragment>,
prefetchRsc: null,
},
],
]),
],
]),
rsc: <>Root layout</>,
prefetchRsc: null,
}
expect(cache).toMatchObject(expectedCache)
})
})
import type {
CacheNode,
FlightSegmentPath,
} from '../../../shared/lib/app-router-types'
import { createRouterCacheKey } from './create-router-cache-key'
import { getNextFlightSegmentPath } from '../../flight-data-helpers'
/**
* Fill cache up to the end of the flightSegmentPath, invalidating anything below it.
*/
export function invalidateCacheBelowFlightSegmentPath(
newCache: CacheNode,
existingCache: CacheNode,
flightSegmentPath: FlightSegmentPath
): void {
const isLastEntry = flightSegmentPath.length <= 2
const [parallelRouteKey, segment] = flightSegmentPath
const cacheKey = createRouterCacheKey(segment)
const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey)
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap)
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
}
// In case of last entry don't copy further down.
if (isLastEntry) {
childSegmentMap.delete(cacheKey)
return
}
const existingChildCacheNode = existingChildSegmentMap.get(cacheKey)
let childCacheNode = childSegmentMap.get(cacheKey)
if (!childCacheNode || !existingChildCacheNode) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
lazyData: childCacheNode.lazyData,
rsc: childCacheNode.rsc,
prefetchRsc: childCacheNode.prefetchRsc,
head: childCacheNode.head,
prefetchHead: childCacheNode.prefetchHead,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
} as CacheNode
childSegmentMap.set(cacheKey, childCacheNode)
}
invalidateCacheBelowFlightSegmentPath(
childCacheNode,
existingChildCacheNode,
getNextFlightSegmentPath(flightSegmentPath)
)
}
import { invalidateCacheByRouterState } from './invalidate-cache-by-router-state'
import type {
CacheNode,
FlightRouterState,
} from '../../../shared/lib/app-router-types'
const navigatedAt = -1
describe('invalidateCacheByRouterState', () => {
it('should invalidate the cache by router state', () => {
const cache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
}
const existingCache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: <>Root layout</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
navigatedAt,
lazyData: null,
rsc: <>Linking</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
navigatedAt,
lazyData: null,
rsc: <>Page</>,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map(),
},
],
]),
],
]),
},
],
]),
],
]),
}
const routerState: FlightRouterState = [
'',
{
children: [
'linking',
{
children: [
'about',
{
children: ['', {}],
},
],
},
],
},
null,
null,
true,
]
invalidateCacheByRouterState(cache, existingCache, routerState)
const expectedCache: CacheNode = {
navigatedAt,
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading: null,
parallelRoutes: new Map([['children', new Map()]]),
}
expect(cache).toMatchObject(expectedCache)
})
})
import type {
CacheNode,
FlightRouterState,
} from '../../../shared/lib/app-router-types'
import { createRouterCacheKey } from './create-router-cache-key'
/**
* Invalidate cache one level down from the router state.
*/
export function invalidateCacheByRouterState(
newCache: CacheNode,
existingCache: CacheNode,
routerState: FlightRouterState
): void {
// Remove segment that we got data for so that it is filled in during rendering of rsc.
for (const key in routerState[1]) {
const segmentForParallelRoute = routerState[1][key][0]
const cacheKey = createRouterCacheKey(segmentForParallelRoute)
const existingParallelRoutesCacheNode =
existingCache.parallelRoutes.get(key)
if (existingParallelRoutesCacheNode) {
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)
parallelRouteCacheNode.delete(cacheKey)
newCache.parallelRoutes.set(key, parallelRouteCacheNode)
}
}
}
...@@ -4,9 +4,8 @@ import type { ...@@ -4,9 +4,8 @@ import type {
FlightSegmentPath, FlightSegmentPath,
} from '../../../shared/lib/app-router-types' } from '../../../shared/lib/app-router-types'
import type { import type {
CacheNode,
ChildSegmentMap, ChildSegmentMap,
ReadyCacheNode, CacheNode,
} from '../../../shared/lib/app-router-types' } from '../../../shared/lib/app-router-types'
import type { import type {
HeadData, HeadData,
...@@ -371,7 +370,7 @@ function updateCacheNodeOnNavigation( ...@@ -371,7 +370,7 @@ function updateCacheNodeOnNavigation(
// usually we just clone the data from the old CacheNode. However, during a // usually we just clone the data from the old CacheNode. However, during a
// refresh or a revalidation, there won't be any existing CacheNode. So we // refresh or a revalidation, there won't be any existing CacheNode. So we
// may need to consult the prefetch cache, like we would for a new segment. // may need to consult the prefetch cache, like we would for a new segment.
let newCacheNode: ReadyCacheNode let newCacheNode: CacheNode
let needsDynamicRequest: boolean let needsDynamicRequest: boolean
if ( if (
oldCacheNode !== undefined && oldCacheNode !== undefined &&
...@@ -748,7 +747,7 @@ function createCacheNodeOnNavigation( ...@@ -748,7 +747,7 @@ function createCacheNodeOnNavigation(
accumulation.scrollableSegments.push(segmentPath) accumulation.scrollableSegments.push(segmentPath)
} }
let newCacheNode: ReadyCacheNode let newCacheNode: CacheNode
let needsDynamicRequest: boolean let needsDynamicRequest: boolean
if (!shouldRefreshDynamicData && oldCacheNode !== undefined) { if (!shouldRefreshDynamicData && oldCacheNode !== undefined) {
// Reuse the existing CacheNode // Reuse the existing CacheNode
...@@ -1045,10 +1044,9 @@ function reuseDynamicCacheNode( ...@@ -1045,10 +1044,9 @@ function reuseDynamicCacheNode(
dropPrefetchRsc: boolean, dropPrefetchRsc: boolean,
existingCacheNode: CacheNode, existingCacheNode: CacheNode,
parallelRoutes: Map<string, ChildSegmentMap> parallelRoutes: Map<string, ChildSegmentMap>
): ReadyCacheNode { ): CacheNode {
// Clone an existing CacheNode's data, with (possibly) new children. // Clone an existing CacheNode's data, with (possibly) new children.
const cacheNode: ReadyCacheNode = { const cacheNode: CacheNode = {
lazyData: null,
rsc: existingCacheNode.rsc, rsc: existingCacheNode.rsc,
prefetchRsc: dropPrefetchRsc ? null : existingCacheNode.prefetchRsc, prefetchRsc: dropPrefetchRsc ? null : existingCacheNode.prefetchRsc,
head: existingCacheNode.head, head: existingCacheNode.head,
...@@ -1073,7 +1071,7 @@ function readCacheNodeFromSeedData( ...@@ -1073,7 +1071,7 @@ function readCacheNodeFromSeedData(
isPageSegment: boolean, isPageSegment: boolean,
parallelRoutes: Map<string, ChildSegmentMap>, parallelRoutes: Map<string, ChildSegmentMap>,
navigatedAt: number navigatedAt: number
): ReadyCacheNode { ): CacheNode {
// TODO: Currently this is threaded through the navigation logic using the // TODO: Currently this is threaded through the navigation logic using the
// CacheNodeSeedData type, but in the future this will read directly from // CacheNodeSeedData type, but in the future this will read directly from
// the Segment Cache. See readRenderSnapshotFromCache. // the Segment Cache. See readRenderSnapshotFromCache.
...@@ -1107,8 +1105,7 @@ function readCacheNodeFromSeedData( ...@@ -1107,8 +1105,7 @@ function readCacheNodeFromSeedData(
head = null head = null
} }
const cacheNode: ReadyCacheNode = { const cacheNode: CacheNode = {
lazyData: null,
rsc, rsc,
prefetchRsc, prefetchRsc,
head, head,
...@@ -1129,7 +1126,7 @@ function spawnNewCacheNode( ...@@ -1129,7 +1126,7 @@ function spawnNewCacheNode(
isLeafSegment: boolean, isLeafSegment: boolean,
navigatedAt: number, navigatedAt: number,
freshness: FreshnessPolicy freshness: FreshnessPolicy
): ReadyCacheNode { ): CacheNode {
// We should never spawn network requests during hydration. We must treat the // We should never spawn network requests during hydration. We must treat the
// initial payload as authoritative, because the initial page load is used // initial payload as authoritative, because the initial page load is used
// as a last-ditch mechanism for recovering the app. // as a last-ditch mechanism for recovering the app.
...@@ -1146,8 +1143,7 @@ function spawnNewCacheNode( ...@@ -1146,8 +1143,7 @@ function spawnNewCacheNode(
// case in updateCacheNodeOnNavigation. // case in updateCacheNodeOnNavigation.
const isHydration = freshness === FreshnessPolicy.Hydration const isHydration = freshness === FreshnessPolicy.Hydration
const cacheNode: ReadyCacheNode = { const cacheNode: CacheNode = {
lazyData: null,
rsc: !isHydration ? createDeferredRsc() : null, rsc: !isHydration ? createDeferredRsc() : null,
prefetchRsc: null, prefetchRsc: null,
head: !isHydration && isLeafSegment ? createDeferredRsc() : null, head: !isHydration && isLeafSegment ? createDeferredRsc() : null,
...@@ -1412,15 +1408,11 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1412,15 +1408,11 @@ function dispatchRetryDueToTreeMismatch(
previousNavigationDidMismatch = true previousNavigationDidMismatch = true
const retryAction: ServerPatchAction = { const retryAction: ServerPatchAction = {
type: ACTION_SERVER_PATCH, type: ACTION_SERVER_PATCH,
navigatedAt: Date.now(),
previousTree: baseTree, previousTree: baseTree,
serverResponse: null, url: retryUrl,
retry: { nextUrl: retryNextUrl,
url: retryUrl, seed,
nextUrl: retryNextUrl, mpa: isHardRetry,
seed,
mpa: isHardRetry,
},
} }
dispatchAppRouterAction(retryAction) dispatchAppRouterAction(retryAction)
} }
......
...@@ -30,7 +30,6 @@ describe('findHeadInCache', () => { ...@@ -30,7 +30,6 @@ describe('findHeadInCache', () => {
const cache: CacheNode = { const cache: CacheNode = {
navigatedAt, navigatedAt,
lazyData: null,
rsc: null, rsc: null,
prefetchRsc: null, prefetchRsc: null,
head: null, head: null,
...@@ -44,7 +43,6 @@ describe('findHeadInCache', () => { ...@@ -44,7 +43,6 @@ describe('findHeadInCache', () => {
'linking', 'linking',
{ {
navigatedAt, navigatedAt,
lazyData: null,
rsc: null, rsc: null,
prefetchRsc: null, prefetchRsc: null,
head: null, head: null,
...@@ -58,7 +56,6 @@ describe('findHeadInCache', () => { ...@@ -58,7 +56,6 @@ describe('findHeadInCache', () => {
'about', 'about',
{ {
navigatedAt, navigatedAt,
lazyData: null,
head: null, head: null,
prefetchHead: null, prefetchHead: null,
loading: null, loading: null,
...@@ -70,7 +67,6 @@ describe('findHeadInCache', () => { ...@@ -70,7 +67,6 @@ describe('findHeadInCache', () => {
'', '',
{ {
navigatedAt, navigatedAt,
lazyData: null,
rsc: null, rsc: null,
prefetchRsc: null, prefetchRsc: null,
prefetchHead: null, prefetchHead: null,
...@@ -90,7 +86,6 @@ describe('findHeadInCache', () => { ...@@ -90,7 +86,6 @@ describe('findHeadInCache', () => {
// [ // [
// '', // '',
// { // {
// lazyData: null,
// rsc: <>Page</>, // rsc: <>Page</>,
// prefetchRsc: null, // prefetchRsc: null,
// parallelRoutes: new Map(), // parallelRoutes: new Map(),
......
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
import type { import type {
ServerPatchAction, ServerPatchAction,
ReducerState, ReducerState,
...@@ -8,10 +6,6 @@ import type { ...@@ -8,10 +6,6 @@ import type {
Mutable, Mutable,
} from '../router-reducer-types' } from '../router-reducer-types'
import { handleExternalUrl, handleNavigationResult } from './navigate-reducer' import { handleExternalUrl, handleNavigationResult } from './navigate-reducer'
import { applyFlightData } from '../apply-flight-data'
import { handleMutable } from '../handle-mutable'
import type { CacheNode } from '../../../../shared/lib/app-router-types'
import { createEmptyCacheNode } from '../../app-router'
import { navigateToSeededRoute } from '../../segment-cache/navigation' import { navigateToSeededRoute } from '../../segment-cache/navigation'
import { refreshReducer } from './refresh-reducer' import { refreshReducer } from './refresh-reducer'
import { FreshnessPolicy } from '../ppr-navigations' import { FreshnessPolicy } from '../ppr-navigations'
...@@ -20,126 +14,47 @@ export function serverPatchReducer( ...@@ -20,126 +14,47 @@ export function serverPatchReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: ServerPatchAction action: ServerPatchAction
): ReducerState { ): ReducerState {
const { serverResponse, navigatedAt, retry, previousTree } = action
const mutable: Mutable = {} const mutable: Mutable = {}
mutable.preserveCustomHistoryState = false mutable.preserveCustomHistoryState = false
if (retry !== null) { // A "retry" is a navigation that happens due to a route mismatch. It's
// A "retry" is a navigation that happens due to a route mismatch. It's // similar to a refresh, because we will omit any existing dynamic data on
// similar to a refresh, because we will omit any existing dynamic data on // the page. But we seed the retry navigation with the exact tree that the
// the page. But we seed the retry navigation with the exact tree that the // server just responded with.
// server just responded with. const retryMpa = action.mpa
const retryMpa = retry.mpa const retryUrl = new URL(action.url, location.origin)
const retryUrl = new URL(retry.url, location.origin) const retrySeed = action.seed
const retrySeed = retry.seed if (retryMpa || retrySeed === null) {
if (retryMpa || retrySeed === null) { // If the server did not send back data during the mismatch, fall back to
// If the server did not send back data during the mismatch, fall back to // an MPA navigation.
// an MPA navigation. return handleExternalUrl(state, mutable, retryUrl.href, false)
return handleExternalUrl(state, mutable, retryUrl.href, false)
}
const currentUrl = new URL(state.canonicalUrl, location.origin)
if (previousTree !== state.tree) {
// There was another, more recent navigation since the once that
// mismatched. We can abort the retry, but we still need to refresh the
// page to evict any stale dynamic data.
return refreshReducer(state)
}
// There have been no new navigations since the mismatched one. Refresh,
// using the tree we just received from the server.
const retryCanonicalUrl = createHrefFromUrl(retryUrl)
const retryNextUrl = retry.nextUrl
// A retry should not create a new history entry.
const pendingPush = false
const shouldScroll = true
const now = Date.now()
const result = navigateToSeededRoute(
now,
retryUrl,
retryCanonicalUrl,
retrySeed,
currentUrl,
state.cache,
state.tree,
FreshnessPolicy.RefreshAll,
retryNextUrl,
shouldScroll
)
return handleNavigationResult(retryUrl, state, mutable, pendingPush, result)
}
// TODO: The rest of this reducer will be deleted once we migrate the
// remaining to reducers to no longer rely on the lazy data fetch that happens
// on mismatch in LayoutRouter.
if (serverResponse === null) {
// No data provided. Fall back to a hard refresh.
return handleExternalUrl(
state,
mutable,
state.canonicalUrl,
state.pushRef.pendingPush
)
} }
const currentUrl = new URL(state.canonicalUrl, location.origin)
// Handle case when navigating to page in `pages` from `app` if (action.previousTree !== state.tree) {
if (typeof serverResponse === 'string') { // There was another, more recent navigation since the once that
return handleExternalUrl( // mismatched. We can abort the retry, but we still need to refresh the
state, // page to evict any stale dynamic data.
mutable, return refreshReducer(state)
serverResponse,
state.pushRef.pendingPush
)
}
const { flightData, canonicalUrl, renderedSearch } = serverResponse
let currentTree = state.tree
let currentCache = state.cache
for (const normalizedFlightData of flightData) {
const { segmentPath: flightSegmentPath, tree: treePatch } =
normalizedFlightData
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
['', ...flightSegmentPath],
currentTree,
treePatch,
state.canonicalUrl
)
// `applyRouterStatePatchToTree` returns `null` when it determined that the server response is not applicable to the current tree.
// In other words, the server responded with a tree that doesn't match what the client is currently rendering.
// This can happen if the server patch action took longer to resolve than a subsequent navigation which would have changed the tree.
// Previously this case triggered an MPA navigation but it should be safe to simply discard the server response rather than forcing
// the entire page to reload.
if (newTree === null) {
return state
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(
state,
mutable,
state.canonicalUrl,
state.pushRef.pendingPush
)
}
mutable.canonicalUrl = createHrefFromUrl(canonicalUrl)
const cache: CacheNode = createEmptyCacheNode()
applyFlightData(navigatedAt, currentCache, cache, normalizedFlightData)
mutable.patchedTree = newTree
mutable.renderedSearch = renderedSearch
mutable.cache = cache
currentCache = cache
currentTree = newTree
} }
// There have been no new navigations since the mismatched one. Refresh,
return handleMutable(state, mutable) // using the tree we just received from the server.
const retryCanonicalUrl = createHrefFromUrl(retryUrl)
const retryNextUrl = action.nextUrl
// A retry should not create a new history entry.
const pendingPush = false
const shouldScroll = true
const now = Date.now()
const result = navigateToSeededRoute(
now,
retryUrl,
retryCanonicalUrl,
retrySeed,
currentUrl,
state.cache,
state.tree,
FreshnessPolicy.RefreshAll,
retryNextUrl,
shouldScroll
)
return handleNavigationResult(retryUrl, state, mutable, pendingPush, result)
} }
import type {
FlightRouterState,
CacheNode,
} from '../../../shared/lib/app-router-types'
import type { AppRouterState } from './router-reducer-types'
import { applyFlightData } from './apply-flight-data'
import { fetchServerResponse } from './fetch-server-response'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
interface RefreshInactiveParallelSegments {
navigatedAt: number
state: AppRouterState
updatedTree: FlightRouterState
updatedCache: CacheNode
includeNextUrl: boolean
canonicalUrl: string
}
/**
* Refreshes inactive segments that are still in the current FlightRouterState.
* A segment is considered "inactive" when the server response indicates it didn't match to a page component.
* This happens during a soft-navigation, where the server will want to patch in the segment
* with the "default" component, but we explicitly ignore the server in this case
* and keep the existing state for that segment. New data for inactive segments are inherently
* not part of the server response when we patch the tree, because they were associated with a response
* from an earlier navigation/request. For each segment, once it becomes "active", we encode the URL that provided
* the data for it. This function traverses parallel routes looking for these markers so that it can re-fetch
* and patch the new data into the tree.
*/
export async function refreshInactiveParallelSegments(
options: RefreshInactiveParallelSegments
) {
const fetchedSegments = new Set<string>()
await refreshInactiveParallelSegmentsImpl({
...options,
rootTree: options.updatedTree,
fetchedSegments,
})
}
async function refreshInactiveParallelSegmentsImpl({
navigatedAt,
state,
updatedTree,
updatedCache,
includeNextUrl,
fetchedSegments,
rootTree = updatedTree,
canonicalUrl,
}: RefreshInactiveParallelSegments & {
fetchedSegments: Set<string>
rootTree: FlightRouterState
}) {
const [, parallelRoutes, refetchPath, refetchMarker] = updatedTree
const fetchPromises = []
if (
refetchPath &&
refetchPath !== canonicalUrl &&
refetchMarker === 'refresh' &&
// it's possible for the tree to contain multiple segments that contain data at the same URL
// we keep track of them so we can dedupe the requests
!fetchedSegments.has(refetchPath)
) {
fetchedSegments.add(refetchPath) // Mark this URL as fetched
// Eagerly kick off the fetch for the refetch path & the parallel routes. This should be fine to do as they each operate
// independently on their own cache nodes, and `applyFlightData` will copy anything it doesn't care about from the existing cache.
const fetchPromise = fetchServerResponse(
new URL(refetchPath, location.origin),
{
// refetch from the root of the updated tree, otherwise it will be scoped to the current segment
// and might not contain the data we need to patch in interception route data (such as dynamic params from a previous segment)
flightRouterState: [rootTree[0], rootTree[1], rootTree[2], 'refetch'],
nextUrl: includeNextUrl ? state.nextUrl : null,
}
).then((result) => {
if (typeof result !== 'string') {
const { flightData } = result
for (const flightDataPath of flightData) {
// we only pass the new cache as this function is called after clearing the router cache
// and filling in the new page data from the server. Meaning the existing cache is actually the cache that's
// just been created & has been written to, but hasn't been "committed" yet.
applyFlightData(
navigatedAt,
updatedCache,
updatedCache,
flightDataPath
)
}
} else {
// When result is a string, it suggests that the server response should have triggered an MPA navigation
// I'm not 100% sure of this decision, but it seems unlikely that we'd want to introduce a redirect side effect
// when refreshing on-screen data, so handling this has been ommitted.
}
})
fetchPromises.push(fetchPromise)
}
for (const key in parallelRoutes) {
const parallelFetchPromise = refreshInactiveParallelSegmentsImpl({
navigatedAt,
state,
updatedTree: parallelRoutes[key],
updatedCache,
includeNextUrl,
fetchedSegments,
rootTree,
canonicalUrl,
})
fetchPromises.push(parallelFetchPromise)
}
await Promise.all(fetchPromises)
}
/**
* Walks the current parallel segments to determine if they are "active".
* An active parallel route will have a `__PAGE__` segment in the FlightRouterState.
* As opposed to a `__DEFAULT__` segment, which means there was no match for that parallel route.
* We add a special marker here so that we know how to refresh its data when the router is revalidated.
*/
export function addRefreshMarkerToActiveParallelSegments(
tree: FlightRouterState,
path: string
) {
const [segment, parallelRoutes, , refetchMarker] = tree
// a page segment might also contain concatenated search params, so we do a partial match on the key
if (segment.includes(PAGE_SEGMENT_KEY) && refetchMarker !== 'refresh') {
tree[2] = path
tree[3] = 'refresh'
}
for (const key in parallelRoutes) {
addRefreshMarkerToActiveParallelSegments(parallelRoutes[key], path)
}
}
...@@ -132,33 +132,25 @@ export type AppHistoryState = { ...@@ -132,33 +132,25 @@ export type AppHistoryState = {
/** /**
* Server-patch applies the provided Flight data to the cache and router tree. * Server-patch applies the provided Flight data to the cache and router tree.
* - Only triggered in layout-router.
* - Creates a new cache and router state with the Flight data applied.
*/ */
export interface ServerPatchAction { export interface ServerPatchAction {
type: typeof ACTION_SERVER_PATCH type: typeof ACTION_SERVER_PATCH
navigatedAt: number
serverResponse: FetchServerResponseResult | null
previousTree: FlightRouterState previousTree: FlightRouterState
retry: null | { url: URL
url: URL nextUrl: string | null
nextUrl: string | null seed: NavigationSeed | null
seed: NavigationSeed | null mpa: boolean
mpa: boolean
}
} }
/** /**
* PrefetchKind defines the type of prefetching that should be done. * PrefetchKind defines the type of prefetching that should be done.
* - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully. * - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.
* - `full` - prefetch the page data fully. * - `full` - prefetch the page data fully.
* - `temporary` - a temporary prefetch entry is added to the cache, this is used when prefetch={false} is used in next/link or when you push a route programmatically.
*/ */
export enum PrefetchKind { export enum PrefetchKind {
AUTO = 'auto', AUTO = 'auto',
FULL = 'full', FULL = 'full',
TEMPORARY = 'temporary',
} }
/** /**
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* This file contains type definitions that can be safely imported * This file contains type definitions that can be safely imported
* by both client-side and server-side code without circular dependencies. * by both client-side and server-side code without circular dependencies.
*/ */
import type { FetchServerResponseResult } from '../../client/components/router-reducer/fetch-server-response'
import type React from 'react' import type React from 'react'
export type LoadingModuleData = export type LoadingModuleData =
...@@ -19,68 +19,15 @@ export type ChildSegmentMap = Map<string, CacheNode> ...@@ -19,68 +19,15 @@ export type ChildSegmentMap = Map<string, CacheNode>
/** /**
* Cache node used in app-router / layout-router. * Cache node used in app-router / layout-router.
*/ */
export type CacheNode = ReadyCacheNode | LazyCacheNode
export type LazyCacheNode = {
/**
* When rsc is null, this is a lazily-initialized cache node.
*
* If the app attempts to render it, it triggers a lazy data fetch,
* postpones the render, and schedules an update to a new tree.
*
* TODO: This mechanism should not be used when PPR is enabled, though it
* currently is in some cases until we've implemented partial
* segment fetching.
*/
rsc: null
/**
* A prefetched version of the segment data. See explanation in corresponding
* field of ReadyCacheNode (below).
*
* Since LazyCacheNode mostly only exists in the non-PPR implementation, this
* will usually be null, but it could have been cloned from a previous
* CacheNode that was created by the PPR implementation. Eventually we want
* to migrate everything away from LazyCacheNode entirely.
*/
prefetchRsc: React.ReactNode
/**
* A pending response for the lazy data fetch. If this is not present
* during render, it is lazily created.
*/
lazyData: Promise<FetchServerResponseResult> | null
prefetchHead: HeadData | null
head: HeadData
loading: LoadingModuleData | Promise<LoadingModuleData>
/** export type CacheNode = {
* Child parallel routes.
*/
parallelRoutes: Map<string, ChildSegmentMap>
/**
* The timestamp of the navigation that last updated the CacheNode's data. If
* a CacheNode is reused from a previous navigation, this value is not
* updated. Used to track the staleness of the data.
*/
navigatedAt: number
}
export type ReadyCacheNode = {
/** /**
* When rsc is not null, it represents the RSC data for the * When rsc is not null, it represents the RSC data for the
* corresponding segment. * corresponding segment.
* *
* `null` is a valid React Node but because segment data is always a * `null` is a valid React Node but because segment data is always a
* <LayoutRouter> component, we can use `null` to represent empty. * <LayoutRouter> component, we can use `null` to represent empty. When it is
* * null, it represents missing data, and rendering should suspend.
* TODO: For additional type safety, update this type to
* Exclude<React.ReactNode, null>. Need to update createEmptyCacheNode to
* accept rsc as an argument, or just inline the callers.
*/ */
rsc: React.ReactNode rsc: React.ReactNode
...@@ -97,10 +44,6 @@ export type ReadyCacheNode = { ...@@ -97,10 +44,6 @@ export type ReadyCacheNode = {
*/ */
prefetchRsc: React.ReactNode prefetchRsc: React.ReactNode
/**
* There should never be a lazy data request in this case.
*/
lazyData: null
prefetchHead: HeadData | null prefetchHead: HeadData | null
head: HeadData head: HeadData
...@@ -109,6 +52,11 @@ export type ReadyCacheNode = { ...@@ -109,6 +52,11 @@ export type ReadyCacheNode = {
parallelRoutes: Map<string, ChildSegmentMap> parallelRoutes: Map<string, ChildSegmentMap>
/**
* The timestamp of the navigation that last updated the CacheNode's data. If
* a CacheNode is reused from a previous navigation, this value is not
* updated. Used to track the staleness of the data.
*/
navigatedAt: number navigatedAt: number
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment