Unverified Commit b3512c2e authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Separate route structure comparison from param comparison (#98974)

Changing a page’s search params doesn’t change which page it is, but it
may change the data that page needs. The router currently mixes these
concerns by appending search params to `__PAGE__` segments. Remove that
encoding so we can compare which route is being rendered separately from
the param values used to render it.

Param values are now compared through the existing VaryPath data
structure, while route structure is compared during the existing tree
traversals. Each traversal can decide which comparisons matter for the
work it’s doing.

Client-side comparisons and history restoration still need the search
params, so store them in a separate FlightRouterState slot for now. As
before, previous-page search params are stripped from normal request
headers. This is a temporary step that lets us migrate incrementally.
Eventually, FlightRouterState will be replaced by a type that represents
the route and its params more directly.

This is mostly a refactor, though it fixes an accidental inconsistency
in search-param handling compared with regular route params, avoiding
some redundant prefetch work.

Fully cached pages already track their vary params correctly. This
separation prepares us to do the same for partially dynamic segments
during navigation, so changing an unrelated param won’t require
rendering their dynamic content again.
parent aa8e252f
...@@ -563,10 +563,8 @@ export default function OuterLayoutRouter({ ...@@ -563,10 +563,8 @@ export default function OuterLayoutRouter({
// On the server, the key describes the segment's structure instead, so it // On the server, the key describes the segment's structure instead, so it
// stays the same when unknown params become known during HTML resume. // stays the same when unknown params become known during HTML resume.
// //
// The "cache" key of a segment, however, *does* include the search params, if // Whether the data can be reused is tracked separately, by the segment
// it's possible that the segment accessed the search params on the server. // cache's vary paths.
// (This only applies to page segments; layout segments cannot access search
// params on the server.)
const activeTree = parentTree[1][parallelRouterKey] const activeTree = parentTree[1][parallelRouterKey]
const activeRenderTree = parentRenderTree.slots?.get(parallelRouterKey) const activeRenderTree = parentRenderTree.slots?.get(parallelRouterKey)
if (activeTree === undefined || activeRenderTree === undefined) { if (activeTree === undefined || activeRenderTree === undefined) {
...@@ -583,7 +581,7 @@ export default function OuterLayoutRouter({ ...@@ -583,7 +581,7 @@ export default function OuterLayoutRouter({
} }
const activeSegment = activeTree[0] const activeSegment = activeTree[0]
const activeStateKey = createSegmentKey(activeSegment, true) // no search params const activeStateKey = createSegmentKey(activeSegment)
// At each level of the route tree, not only do we render the currently // At each level of the route tree, not only do we render the currently
// active segment — we also render the last N segments that were active at // active segment — we also render the last N segments that were active at
......
import type { Segment } from '../../shared/lib/app-router-types'
export const matchSegment = (
existingSegment: Segment,
segment: Segment
): boolean => {
// segment is either Array or string
if (typeof existingSegment === 'string') {
if (typeof segment === 'string') {
// Common case: segment is just a string
return existingSegment === segment
}
return false
}
if (typeof segment === 'string') {
return false
}
return existingSegment[0] === segment[0] && existingSegment[1] === segment[1]
}
...@@ -9,7 +9,6 @@ import { ...@@ -9,7 +9,6 @@ import {
DEFAULT_SEGMENT_KEY, DEFAULT_SEGMENT_KEY,
PAGE_SEGMENT_KEY, PAGE_SEGMENT_KEY,
} from '../../../shared/lib/segment' } from '../../../shared/lib/segment'
import { matchSegment } from '../match-segments'
const removeLeadingSlash = (segment: string): string => { const removeLeadingSlash = (segment: string): string => {
return segment[0] === '/' ? segment.slice(1) : segment return segment[0] === '/' ? segment.slice(1) : segment
...@@ -30,7 +29,7 @@ const segmentToPathname = (segment: Segment): string => { ...@@ -30,7 +29,7 @@ const segmentToPathname = (segment: Segment): string => {
export const segmentToSourcePagePathname = (segment: Segment): string => { export const segmentToSourcePagePathname = (segment: Segment): string => {
if (typeof segment === 'string') { if (typeof segment === 'string') {
if (segment === 'children') return '' if (segment === 'children') return ''
if (segment.startsWith(PAGE_SEGMENT_KEY)) return 'page' if (segment === PAGE_SEGMENT_KEY) return 'page'
return segment return segment
} }
...@@ -91,7 +90,7 @@ export function extractPathFromFlightRouterState( ...@@ -91,7 +90,7 @@ export function extractPathFromFlightRouterState(
) )
return undefined return undefined
if (segment.startsWith(PAGE_SEGMENT_KEY)) return '' if (segment === PAGE_SEGMENT_KEY) return ''
const segments = [segmentToPathname(segment)] const segments = [segmentToPathname(segment)]
const parallelRoutes = flightRouterState[1] ?? {} const parallelRoutes = flightRouterState[1] ?? {}
...@@ -185,7 +184,22 @@ function computeChangedPathImpl( ...@@ -185,7 +184,22 @@ function computeChangedPathImpl(
return '' return ''
} }
if (!matchSegment(segmentA, segmentB)) { // Param types and static sibling hints don't affect the resulting pathname,
// so only compare the segment name and param value.
// TODO: computeChangedPath is only used to compute the Next-Url header.
// We should refactor this data structure to be lower cardinality. For example
// it doesn't need to include any of the concrete param values, just the
// route structure.
const didPathChange =
typeof segmentA === 'string' || typeof segmentB === 'string'
? segmentA !== segmentB
: segmentA[0] !== segmentB[0] || segmentA[1] !== segmentB[1]
if (
didPathChange ||
// A change to the page's search params counts, too. (They used to be part
// of the page segment string.)
(segmentA === PAGE_SEGMENT_KEY && treeA[5] !== treeB[5])
) {
// once we find where the tree changed, we compute the rest of the path by traversing the tree // once we find where the tree changed, we compute the rest of the path by traversing the tree
return extractPathFromFlightRouterState(treeB) ?? '' return extractPathFromFlightRouterState(treeB) ?? ''
} }
...@@ -232,7 +246,7 @@ export function getSelectedParams( ...@@ -232,7 +246,7 @@ export function getSelectedParams(
const segment = parallelRoute[0] const segment = parallelRoute[0]
const isDynamicParameter = Array.isArray(segment) const isDynamicParameter = Array.isArray(segment)
const segmentValue = isDynamicParameter ? segment[1] : segment const segmentValue = isDynamicParameter ? segment[1] : segment
if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) continue if (!segmentValue || segmentValue === PAGE_SEGMENT_KEY) continue
// Ensure catchAll and optional catchall are turned into an array // Ensure catchAll and optional catchall are turned into an array
const isCatchAll = const isCatchAll =
......
...@@ -49,10 +49,11 @@ export function createInitialRouterState({ ...@@ -49,10 +49,11 @@ export function createInitialRouterState({
// as a URL that should be crawled. // as a URL that should be crawled.
const initialCanonicalUrl = initialCanonicalUrlParts.join('/') const initialCanonicalUrl = initialCanonicalUrlParts.join('/')
// The initial router state tree, derived from the transport tree. Page // The initial router state tree, derived from the transport tree.
// segments keep their search params, which travel inside the segment const initialTree = transportNodeToFlightRouterState(
// string. initialTransportData.t,
const initialTree = transportNodeToFlightRouterState(initialTransportData.t) initialRenderedSearch
)
const canonicalUrl = const canonicalUrl =
// location.href is read as the initial value for canonicalUrl in the browser // location.href is read as the initial value for canonicalUrl in the browser
......
import type { Segment } from '../../../shared/lib/app-router-types' import type { Segment } from '../../../shared/lib/app-router-types'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
export function createRouterCacheKey( export function createRouterCacheKey(segment: Segment) {
segment: Segment,
withoutSearchParameters: boolean = false
) {
// if the segment is an array, it means it's a dynamic segment // if the segment is an array, it means it's a dynamic segment
// for example, ['lang', 'en', 'd']. We need to convert it to a string to store it as a cache node key. // for example, ['lang', 'en', 'd']. We need to convert it to a string to store it as a cache node key.
if (Array.isArray(segment)) { if (Array.isArray(segment)) {
return `${segment[0]}|${segment[1]}|${segment[2]}` return `${segment[0]}|${segment[1]}|${segment[2]}`
} }
// Page segments might have search parameters, ie __PAGE__?foo=bar
// When `withoutSearchParameters` is true, we only want to return the page segment
if (withoutSearchParameters && segment.startsWith(PAGE_SEGMENT_KEY)) {
return PAGE_SEGMENT_KEY
}
return segment return segment
} }
import { createRouterCacheKey } from './create-router-cache-key'
import { createSegmentKey } from './create-segment-key'
import { createSegmentKey as createBrowserSegmentKey } from './create-segment-key.browser'
describe('createSegmentKey on the server', () => {
it.each(['d', 'c', 'oc', 'di(.)', 'ci(.)'] as const)(
'keeps %s keys stable between prerendering and resuming',
(paramType) => {
const fallbackKey = createSegmentKey([
'slug',
'%%drp:slug:abc123%%',
paramType,
null,
])
expect(fallbackKey).toBe(`slug|${paramType}`)
expect(createSegmentKey(['slug', 'first', paramType, null])).toBe(
fallbackKey
)
expect(createSegmentKey(['slug', 'second/third', paramType, null])).toBe(
fallbackKey
)
}
)
it('distinguishes param names and segment types', () => {
const keys = [
createSegmentKey(['slug', 'value', 'd', null]),
createSegmentKey(['other', 'value', 'd', null]),
createSegmentKey(['slug', 'value', 'c', null]),
createSegmentKey(['slug', 'value', 'oc', null]),
createSegmentKey(['slug', 'value', 'di(.)', null]),
createSegmentKey(['slug', 'value', 'ci(.)', null]),
]
expect(new Set(keys).size).toBe(keys.length)
})
it.each(['', 'catalog', '__DEFAULT__', '__PAGE__'])(
'preserves the static segment %j',
(segment) => {
expect(createSegmentKey(segment)).toBe(segment)
}
)
it.each([undefined, false, true])(
'always omits search params, even with withoutSearchParameters=%s',
(withoutSearchParameters) => {
expect(
createSegmentKey('__PAGE__?{"q":"first"}', withoutSearchParameters)
).toBe('__PAGE__')
expect(
createSegmentKey('__PAGE__?{"q":"second"}', withoutSearchParameters)
).toBe('__PAGE__')
}
)
})
describe('createSegmentKey in the browser', () => {
it('re-exports the router cache key implementation', () => {
expect(createBrowserSegmentKey).toBe(createRouterCacheKey)
})
it.each(['d', 'c', 'oc', 'di(.)', 'ci(.)'] as const)(
'includes concrete param values in %s keys',
(paramType) => {
expect(createBrowserSegmentKey(['slug', 'first', paramType, null])).toBe(
`slug|first|${paramType}`
)
expect(
createBrowserSegmentKey(['slug', 'second/third', paramType, null])
).toBe(`slug|second/third|${paramType}`)
}
)
it.each([undefined, false, true])(
'respects withoutSearchParameters=%s',
(withoutSearchParameters) => {
const segment = '__PAGE__?{"q":"first"}'
expect(createBrowserSegmentKey(segment, withoutSearchParameters)).toBe(
withoutSearchParameters ? '__PAGE__' : segment
)
}
)
})
...@@ -7,16 +7,12 @@ import { createRouterCacheKey } from './create-router-cache-key' ...@@ -7,16 +7,12 @@ import { createRouterCacheKey } from './create-router-cache-key'
// The browser uses the concrete keys instead, so navigation still resets or // The browser uses the concrete keys instead, so navigation still resets or
// preserves state as appropriate. Its bundle uses create-segment-key.browser.ts. // preserves state as appropriate. Its bundle uses create-segment-key.browser.ts.
// React keys are not embedded in the HTML. // React keys are not embedded in the HTML.
export function createSegmentKey( export function createSegmentKey(segment: Segment): string {
segment: Segment,
// Server keys always omit search params, regardless of this browser option.
_withoutSearchParameters?: boolean
): string {
if (Array.isArray(segment)) { if (Array.isArray(segment)) {
return `${segment[0]}|${segment[2]}` return `${segment[0]}|${segment[2]}`
} }
return createRouterCacheKey(segment, true) return createRouterCacheKey(segment)
} }
// TODO: To model this more accurately, we should use React.optimisticKey // TODO: To model this more accurately, we should use React.optimisticKey
......
...@@ -60,6 +60,7 @@ import { ...@@ -60,6 +60,7 @@ import {
getPathnameFromRequestURL, getPathnameFromRequestURL,
getRenderedPathname, getRenderedPathname,
getRenderedSearch, getRenderedSearch,
normalizeRenderedSearch,
} from '../../route-params' } from '../../route-params'
import { import {
createCacheMap, createCacheMap,
...@@ -244,6 +245,22 @@ export function createRootRouteTree<TData>( ...@@ -244,6 +245,22 @@ export function createRootRouteTree<TData>(
return { tree, head } return { tree, head }
} }
export function doesRouteStructureMatch<TCurrent, TNext>(
currentTree: RouteTree<TCurrent>,
nextTree: RouteTree<TNext>
): boolean {
// The request key includes the param names and types, but not the values.
if (currentTree.requestKey !== nextTree.requestKey) {
return false
}
// The root request key is always empty (even for global Not Found), so we
// have to compare the root segment directly.
return (
nextTree.requestKey !== ROOT_SEGMENT_REQUEST_KEY ||
currentTree.segment === nextTree.segment
)
}
type RouteCacheEntryShared = { type RouteCacheEntryShared = {
// This is false only if we're certain the route cannot be intercepted. It's // This is false only if we're certain the route cannot be intercepted. It's
// true in all other cases, including on initialization when we haven't yet // true in all other cases, including on initialization when we haven't yet
...@@ -813,7 +830,7 @@ export function deprecated_requestOptimisticRouteCacheEntry( ...@@ -813,7 +830,7 @@ export function deprecated_requestOptimisticRouteCacheEntry(
routeWithNoSearchParams.renderedSearch !== '' routeWithNoSearchParams.renderedSearch !== ''
? // Base route was rewritten. Reuse the same rewritten search string. ? // Base route was rewritten. Reuse the same rewritten search string.
routeWithNoSearchParams.renderedSearch routeWithNoSearchParams.renderedSearch
: requestedSearch : normalizeRenderedSearch(requestedSearch)
const optimisticUrl = new URL( const optimisticUrl = new URL(
routeWithNoSearchParams.canonicalUrl, routeWithNoSearchParams.canonicalUrl,
...@@ -1418,11 +1435,11 @@ function pingBlockedTasks(entry: { ...@@ -1418,11 +1435,11 @@ function pingBlockedTasks(entry: {
* The head's request key on the client. The server's own key for the head, * The head's request key on the client. The server's own key for the head,
* HEAD_REQUEST_KEY, carries no path information: there is only one head per * HEAD_REQUEST_KEY, carries no path information: there is only one head per
* URL, so the server has no need to distinguish parallel pages. On the client * URL, so the server has no need to distinguish parallel pages. On the client
* the request key is the head's cache identity, so the head takes its page's * the request key is the head's cache identity and what doesRouteStructureMatch
* request key with HEAD_REQUEST_KEY appended — the key the server would have * compares, so the head takes its page's request key with HEAD_REQUEST_KEY
* assigned had the head been a segment below the page — and two pages' heads * appended — the key the server would have assigned had the head been a
* never share a key. The head varies on the same params as its page, so the * segment below the page — and two pages' heads never match. The head varies
* rest of its vary path is the page's. * on the same params as its page, so the rest of its vary path is the page's.
* The page must be the route's own: a page in a slot retained from another * The page must be the route's own: a page in a slot retained from another
* URL (one with a refresh state) belongs to that URL's head. When a route has * URL (one with a refresh state) belongs to that URL's head. When a route has
* multiple parallel pages of its own, the first one is used; the keys only * multiple parallel pages of its own, the first one is used; the keys only
...@@ -1732,6 +1749,9 @@ export function convertFlightRouterStateToRouteTree( ...@@ -1732,6 +1749,9 @@ export function convertFlightRouterStateToRouteTree(
renderedSearch: compressedRefreshState[1] as NormalizedSearch, renderedSearch: compressedRefreshState[1] as NormalizedSearch,
} }
: null : null
// Use the incoming search params, even if the response has no new data for
// this segment. The base tree may still have the previous URL's. History
// restores pass in their saved search params instead.
const renderedSearch = const renderedSearch =
refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch
......
...@@ -32,7 +32,6 @@ import { ...@@ -32,7 +32,6 @@ import {
DEFAULT_SEGMENT_KEY, DEFAULT_SEGMENT_KEY,
PAGE_SEGMENT_KEY, PAGE_SEGMENT_KEY,
} from '../../../shared/lib/segment' } from '../../../shared/lib/segment'
import { matchSegment } from '../match-segments'
import { InvariantError } from '../../../shared/lib/invariant-error' import { InvariantError } from '../../../shared/lib/invariant-error'
import { import {
doesStaticSegmentAppearInURL, doesStaticSegmentAppearInURL,
...@@ -268,16 +267,6 @@ export function createRouteTreeNode<TData>( ...@@ -268,16 +267,6 @@ export function createRouteTreeNode<TData>(
partialVaryPath = parentPartialVaryPath partialVaryPath = parentPartialVaryPath
if (requestKey.endsWith(PAGE_SEGMENT_KEY)) { if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {
// This is a page segment. // This is a page segment.
// The navigation implementation expects the search params to be included
// in the segment. However, in the case of a static response, the search
// params are omitted. So the client needs to add them back in when reading
// from the Segment Cache.
//
// For consistency, we'll do this for live-render responses, too.
//
// TODO: We should move search params out of FlightRouterState and handle
// them entirely on the client, similar to our plan for dynamic params.
segment = PAGE_SEGMENT_KEY segment = PAGE_SEGMENT_KEY
varyPath = finalizeVaryPath(requestKey, renderedSearch, partialVaryPath) varyPath = finalizeVaryPath(requestKey, renderedSearch, partialVaryPath)
// The head is keyed under the route's own first page and varies on the // The head is keyed under the route's own first page and varies on the
...@@ -405,17 +394,33 @@ function resolveTransportSegment( ...@@ -405,17 +394,33 @@ function resolveTransportSegment(
pathnameParts, pathnameParts,
pathnamePartsIndex pathnamePartsIndex
) )
// TODO: We're intentionally not adding the search param to page segments
// here; it's tracked separately and added back during a read from the
// Segment Cache.
return [ return [
transportSegment.n, transportSegment.n,
getCacheKeyForDynamicParam(paramValue, '' as NormalizedSearch), getCacheKeyForDynamicParam(paramValue),
transportSegment.t, transportSegment.t,
transportSegment.s, transportSegment.s,
] ]
} }
function doSegmentsMatch(
baseSegment: FlightRouterStateSegment,
segment: FlightRouterStateSegment
): boolean {
if (typeof baseSegment === 'string' || typeof segment === 'string') {
// Static segments have to match exactly.
return baseSegment === segment
}
// Both segments are dynamic. The static sibling hints aren't part of the
// segment's identity, so only compare the param name, type, and value.
const [baseParamName, baseParamValue, baseParamType] = baseSegment
const [paramName, paramValue, paramType] = segment
return (
baseParamName === paramName &&
baseParamType === paramType &&
baseParamValue === paramValue
)
}
function decodeTransportNode( function decodeTransportNode(
node: PartialTransportNode, node: PartialTransportNode,
// The node's identity, already resolved by the caller (the parent's child // The node's identity, already resolved by the caller (the parent's child
...@@ -453,18 +458,10 @@ function decodeTransportNode( ...@@ -453,18 +458,10 @@ function decodeTransportNode(
// are still checked. // are still checked.
} else { } else {
const baseSegment = compareBase[0] const baseSegment = compareBase[0]
if ( if (originalSegment === DEFAULT_SEGMENT_KEY) {
typeof originalSegment === 'string' &&
typeof baseSegment === 'string' &&
originalSegment.startsWith(PAGE_SEGMENT_KEY) &&
baseSegment.startsWith(PAGE_SEGMENT_KEY)
) {
// Page segments match modulo embedded search params, which are
// validated separately (see getRenderedSearch).
} else if (originalSegment === DEFAULT_SEGMENT_KEY) {
// A default filled in by the server is not a claim about the // A default filled in by the server is not a claim about the
// position's identity. // position's identity.
} else if (!matchSegment(baseSegment, originalSegment)) { } else if (!doSegmentsMatch(baseSegment, originalSegment)) {
acc.treeDivergedFromBase = true acc.treeDivergedFromBase = true
} }
} }
......
...@@ -65,6 +65,7 @@ import { ...@@ -65,6 +65,7 @@ import {
import { isValueExpired } from './cache-map' import { isValueExpired } from './cache-map'
import { import {
canonicalizeURLPart, canonicalizeURLPart,
normalizeRenderedSearch,
doesStaticSegmentAppearInURL, doesStaticSegmentAppearInURL,
} from '../../route-params' } from '../../route-params'
import type { NormalizedPathname, NormalizedSearch } from './cache-key' import type { NormalizedPathname, NormalizedSearch } from './cache-key'
...@@ -785,11 +786,12 @@ export function matchKnownRoute( ...@@ -785,11 +786,12 @@ export function matchKnownRoute(
// "Reify" the pattern: clone the template tree with concrete param values. // "Reify" the pattern: clone the template tree with concrete param values.
// This substitutes resolved params (e.g., slug: "hello") into dynamic // This substitutes resolved params (e.g., slug: "hello") into dynamic
// segments and recomputes vary paths for correct segment cache keying. // segments and recomputes vary paths for correct segment cache keying.
const renderedSearch = normalizeRenderedSearch(search)
const acc: ReifyAccumulator = { metadataVaryPath: null } const acc: ReifyAccumulator = { metadataVaryPath: null }
const reifiedTree = reifyRouteTree( const reifiedTree = reifyRouteTree(
pattern.root.tree, pattern.root.tree,
resolvedParams, resolvedParams,
search, renderedSearch,
null, // Start with null partial vary path at the root null, // Start with null partial vary path at the root
acc acc
) )
...@@ -822,7 +824,7 @@ export function matchKnownRoute( ...@@ -822,7 +824,7 @@ export function matchKnownRoute(
couldBeIntercepted: pattern.couldBeIntercepted, couldBeIntercepted: pattern.couldBeIntercepted,
supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching, supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,
predictedFrom: matchedPart, predictedFrom: matchedPart,
renderedSearch: search, renderedSearch,
ref: null, ref: null,
size: pattern.size, size: pattern.size,
staleAt: pattern.staleAt, staleAt: pattern.staleAt,
......
import { matchSegment } from '../match-segments' import { compareParams, ParamsChange } from './vary-path'
import { getRenderedSearchFromVaryPath } from './vary-path'
import type { import type {
FlightRouterState, FlightRouterState,
CacheNode, CacheNode,
...@@ -23,6 +22,7 @@ import { ...@@ -23,6 +22,7 @@ import {
type PendingSegmentCacheEntry, type PendingSegmentCacheEntry,
type SegmentCacheEntry, type SegmentCacheEntry,
convertRouteTreeToFlightRouterState, convertRouteTreeToFlightRouterState,
doesRouteStructureMatch,
readOrCreateRevalidatingSegmentEntry, readOrCreateRevalidatingSegmentEntry,
upgradeToPendingSegment, upgradeToPendingSegment,
overwriteRevalidatingSegmentCacheEntry, overwriteRevalidatingSegmentCacheEntry,
...@@ -30,7 +30,7 @@ import { ...@@ -30,7 +30,7 @@ import {
attemptToFulfillDynamicSegmentFromBFCache, attemptToFulfillDynamicSegmentFromBFCache,
attemptToUpgradeSegmentFromBFCache, attemptToUpgradeSegmentFromBFCache,
} from './cache' } from './cache'
import type { NormalizedSearch, RouteCacheKey } from './cache-key' import type { RouteCacheKey } from './cache-key'
import { createCacheKey } from './cache-key' import { createCacheKey } from './cache-key'
import { import {
FetchStrategy, FetchStrategy,
...@@ -44,7 +44,6 @@ import { ...@@ -44,7 +44,6 @@ import {
} from './cache' } from './cache'
import type { CacheMap } from './cache-map' import type { CacheMap } from './cache-map'
import type { NavigationLockPrefetch } from './navigation-testing-lock' import type { NavigationLockPrefetch } from './navigation-testing-lock'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
import { import {
HEAD_REQUEST_KEY, HEAD_REQUEST_KEY,
type SegmentRequestKey, type SegmentRequestKey,
...@@ -1382,7 +1381,9 @@ function pingSharedPartOfCacheComponentsTree( ...@@ -1382,7 +1381,9 @@ function pingSharedPartOfCacheComponentsTree(
let childExitStatus let childExitStatus
if ( if (
oldTreeChild !== undefined && oldTreeChild !== undefined &&
doesCurrentSegmentMatchCachedSegment(route, oldTreeChild, newTreeChild) doesRouteStructureMatch(oldTreeChild, newTreeChild) &&
compareParams(oldTreeChild.varyPath, newTreeChild.varyPath) ===
ParamsChange.None
) { ) {
// We're still in the "shared" part of the tree. // We're still in the "shared" part of the tree.
childExitStatus = pingSharedPartOfCacheComponentsTree( childExitStatus = pingSharedPartOfCacheComponentsTree(
...@@ -1592,7 +1593,9 @@ function diffRouteTreeAgainstCurrent( ...@@ -1592,7 +1593,9 @@ function diffRouteTreeAgainstCurrent(
const oldTreeChild = oldSlots?.get(parallelRouteKey) const oldTreeChild = oldSlots?.get(parallelRouteKey)
if ( if (
oldTreeChild !== undefined && oldTreeChild !== undefined &&
doesCurrentSegmentMatchCachedSegment(route, oldTreeChild, newTreeChild) doesRouteStructureMatch(oldTreeChild, newTreeChild) &&
compareParams(oldTreeChild.varyPath, newTreeChild.varyPath) ===
ParamsChange.None
) { ) {
// This segment is already part of the current route. Keep traversing. // This segment is already part of the current route. Keep traversing.
const requestTreeChild = diffRouteTreeAgainstCurrent( const requestTreeChild = diffRouteTreeAgainstCurrent(
...@@ -2610,27 +2613,6 @@ function pingFullSegmentRevalidation( ...@@ -2610,27 +2613,6 @@ function pingFullSegmentRevalidation(
} }
} }
// TODO: Removed in a later change, which compares route structure by
// request key.
function doesCurrentSegmentMatchCachedSegment(
route: FulfilledRouteCacheEntry,
currentTree: RouteTree<CacheNode>,
cachedTree: RouteTree<null>
): boolean {
if (!matchSegment(currentTree.segment, cachedTree.segment)) {
return false
}
if (cachedTree.segment === PAGE_SEGMENT_KEY) {
// The render tree stores the page's rendered search on its vary path; the
// route cache stores it on the route entry.
const currentSearch =
getRenderedSearchFromVaryPath(currentTree.varyPath) ??
('' as NormalizedSearch)
return currentSearch === route.renderedSearch
}
return true
}
/** /**
* Decides whether to speculatively prefetch a subtree. Under Partial * Decides whether to speculatively prefetch a subtree. Under Partial
* Prefetching we only do this if the Link's prefetch prop is set to true — * Prefetching we only do this if the Link's prefetch prop is set to true —
......
...@@ -8,8 +8,10 @@ import type { RouteTree } from './cache' ...@@ -8,8 +8,10 @@ import type { RouteTree } from './cache'
import { Fallback, type FallbackType } from './cache-map' import { Fallback, type FallbackType } from './cache-map'
import type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding' import type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'
import { import {
readVaryParams,
SEARCH_PARAMS_VARY_ID, SEARCH_PARAMS_VARY_ID,
type VaryParamId, type VaryParamId,
type VaryParams,
} from '../../../shared/lib/segment-cache/vary-params-decoding' } from '../../../shared/lib/segment-cache/vary-params-decoding'
type Opaque<T, K> = T & { __brand: K } type Opaque<T, K> = T & { __brand: K }
...@@ -324,6 +326,88 @@ export function getRenderedSearchFromVaryPath( ...@@ -324,6 +326,88 @@ export function getRenderedSearchFromVaryPath(
return null return null
} }
/**
* The kind of param change between two vary paths for the same segment. A path
* param change takes precedence, because path params are part of
* LayoutRouter's React key: the segment remounts either way.
*/
export const enum ParamsChange {
None,
SearchParams,
PathParam,
}
export function compareParams(
currentVaryPath: VaryPath,
nextVaryPath: VaryPath
): ParamsChange {
// Both vary paths are for the same segment, so they list the same params in
// the same order. Walk them together. This includes params inherited from
// parent layouts, since those may have changed, too.
let current: VaryPathNode | null = currentVaryPath
let next: VaryPathNode | null = nextVaryPath
let change = ParamsChange.None
while (current !== null && next !== null) {
if (current.value !== next.value) {
const id = current.id
if (id === null) {
// The request key. Callers check that the route structure matches
// first, so it's always the same.
} else if (id === SEARCH_PARAMS_VARY_ID) {
change = ParamsChange.SearchParams
} else {
return ParamsChange.PathParam
}
}
current = current.parent
next = next.parent
}
return change
}
export function didReadChangedParam(
currentVaryPath: VaryPath,
nextVaryPath: VaryPath,
varyParams: VaryParams | null
): boolean {
// Returns true if the output rendered with `currentVaryPath` read a param
// whose value is different in `nextVaryPath`. `varyParams` is the set of
// params the output read, or null if we don't know.
//
// Same traversal as compareParams. Only read the set if a param changed.
let current: VaryPathNode | null = currentVaryPath
let next: VaryPathNode | null = nextVaryPath
let total: Set<VaryParamId> | null = null
while (current !== null && next !== null) {
if (current.value !== next.value) {
const id = current.id
if (id === null) {
// The request key. Callers check that the route structure matches
// first, so it's always the same.
} else {
if (total === null) {
if (varyParams === null) {
// We don't know. Assume it read the param.
return true
}
total = readVaryParams(varyParams)
if (total === null) {
// The render hasn't finished, or it aborted. Assume it read the
// param.
return true
}
}
if (total.has(id)) {
return true
}
}
}
current = current.parent
next = next.parent
}
return false
}
export function getFulfilledSegmentVaryPath( export function getFulfilledSegmentVaryPath(
original: VaryPathNode, original: VaryPathNode,
varyParams: Set<VaryParamId> varyParams: Set<VaryParamId>
......
...@@ -8,11 +8,12 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -8,11 +8,12 @@ describe('prepareFlightRouterStateForRequest', () => {
describe('HMR refresh handling', () => { describe('HMR refresh handling', () => {
it('should preserve complete state for HMR refresh requests', () => { it('should preserve complete state for HMR refresh requests', () => {
const flightRouterState: FlightRouterState = [ const flightRouterState: FlightRouterState = [
'__PAGE__?{"sensitive":"data"}', '__PAGE__',
{}, {},
['/some/url', ''], ['/some/url', ''],
'refetch', 'refetch',
PrefetchHint.IsRootLayoutOrAbove | 1, PrefetchHint.IsRootLayoutOrAbove | 1,
'?sensitive=data',
] ]
const result = prepareFlightRouterStateForRequest(flightRouterState, true) const result = prepareFlightRouterStateForRequest(flightRouterState, true)
...@@ -22,19 +23,28 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -22,19 +23,28 @@ describe('prepareFlightRouterStateForRequest', () => {
}) })
}) })
describe('__PAGE__ segment handling', () => { describe('page search handling', () => {
it('should strip search params from __PAGE__ segments', () => { it('should strip the page search (index 5)', () => {
const flightRouterState: FlightRouterState = [ const flightRouterState: FlightRouterState = [
'__PAGE__?{"param":"value","foo":"bar"}', '__PAGE__',
{}, {},
['/some/url', ''],
'refetch',
PrefetchHint.IsRootLayoutOrAbove | 1,
'?sensitive=data',
] ]
const result = prepareFlightRouterStateForRequest(flightRouterState) const result = prepareFlightRouterStateForRequest(
flightRouterState,
false
)
const decoded = JSON.parse(decodeURIComponent(result)) const decoded = JSON.parse(decodeURIComponent(result))
expect(decoded[0]).toBe('__PAGE__') expect(decoded[5]).toBeUndefined()
})
}) })
describe('__PAGE__ segment handling', () => {
it('should preserve non-page segments', () => { it('should preserve non-page segments', () => {
const flightRouterState: FlightRouterState = ['regular-segment', {}] const flightRouterState: FlightRouterState = ['regular-segment', {}]
...@@ -174,7 +184,7 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -174,7 +184,7 @@ describe('prepareFlightRouterStateForRequest', () => {
const flightRouterState: FlightRouterState = [ const flightRouterState: FlightRouterState = [
'parent', 'parent',
{ {
children: ['__PAGE__?{"nested":"param"}', {}, ['/nested/url', '']], children: ['__PAGE__', {}, ['/nested/url', '']],
modal: ['modal-segment', {}, ['/modal/url', ''], 'refetch'], modal: ['modal-segment', {}, ['/modal/url', ''], 'refetch'],
}, },
['/parent/url', ''], ['/parent/url', ''],
...@@ -188,7 +198,7 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -188,7 +198,7 @@ describe('prepareFlightRouterStateForRequest', () => {
'parent', 'parent',
{ {
children: [ children: [
'__PAGE__', // search params stripped '__PAGE__',
{}, {},
// URL stripped // URL stripped
// 'refresh' marker stripped // 'refresh' marker stripped
...@@ -212,12 +222,7 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -212,12 +222,7 @@ describe('prepareFlightRouterStateForRequest', () => {
children: [ children: [
'level1', 'level1',
{ {
children: [ children: ['__PAGE__', {}, ['/deep/url', ''], 'refetch'],
'__PAGE__?{"deep":"nesting"}',
{},
['/deep/url', ''],
'refetch',
],
}, },
], ],
}, },
...@@ -235,13 +240,13 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -235,13 +240,13 @@ describe('prepareFlightRouterStateForRequest', () => {
describe('real-world scenarios', () => { describe('real-world scenarios', () => {
it('should handle complex FlightRouterState with all features', () => { it('should handle complex FlightRouterState with all features', () => {
const complexState: FlightRouterState = [ const complexState: FlightRouterState = [
'__PAGE__?{"userId":"123"}', '__PAGE__',
{ {
children: [ children: [
'dashboard', 'dashboard',
{ {
modal: [ modal: [
'__PAGE__?{"modalParam":"data"}', '__PAGE__',
{}, {},
['/modal/path', ''], ['/modal/path', ''],
null, null,
...@@ -270,7 +275,7 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -270,7 +275,7 @@ describe('prepareFlightRouterStateForRequest', () => {
const decoded = JSON.parse(decodeURIComponent(result)) const decoded = JSON.parse(decodeURIComponent(result))
// Root level checks // Root level checks
expect(decoded[0]).toBe('__PAGE__') // search params stripped expect(decoded[0]).toBe('__PAGE__')
expect(decoded[2]).toBeNull() // URL stripped expect(decoded[2]).toBeNull() // URL stripped
expect(decoded[3]).toBe('inside-shared-layout') // server marker preserved expect(decoded[3]).toBe('inside-shared-layout') // server marker preserved
expect(decoded[4]).toBe( expect(decoded[4]).toBe(
...@@ -289,7 +294,7 @@ describe('prepareFlightRouterStateForRequest', () => { ...@@ -289,7 +294,7 @@ describe('prepareFlightRouterStateForRequest', () => {
// Modal route checks // Modal route checks
const modalRoute = childrenRoute[1].modal const modalRoute = childrenRoute[1].modal
expect(modalRoute[0]).toBe('__PAGE__') // search params stripped expect(modalRoute[0]).toBe('__PAGE__')
expect(modalRoute[2]).toBeNull() // URL stripped expect(modalRoute[2]).toBeNull() // URL stripped
expect(modalRoute[3]).toBeNull() // 'refresh' marker stripped expect(modalRoute[3]).toBeNull() // 'refresh' marker stripped
expect(modalRoute[4]).toBe(PrefetchHint.SegmentHasLoadingBoundary) // prefetchHints preserved expect(modalRoute[4]).toBe(PrefetchHint.SegmentHasLoadingBoundary) // prefetchHints preserved
......
...@@ -8,8 +8,6 @@ import type { ...@@ -8,8 +8,6 @@ import type {
FullTransportNode, FullTransportNode,
TransportSegment, TransportSegment,
} from '../shared/lib/rsc-transport' } from '../shared/lib/rsc-transport'
import { PAGE_SEGMENT_KEY } from '../shared/lib/segment'
import type { NormalizedSearch } from './components/segment-cache/cache-key'
import { import {
getCacheKeyForDynamicParam, getCacheKeyForDynamicParam,
parseDynamicParamFromURLPart, parseDynamicParamFromURLPart,
...@@ -57,8 +55,7 @@ export function createInitialRSCPayloadFromFallbackPrerender( ...@@ -57,8 +55,7 @@ export function createInitialRSCPayloadFromFallbackPrerender(
t: fillInFallbackTransportTree( t: fillInFallbackTransportTree(
fallbackTransportData.t, fallbackTransportData.t,
renderedPathname.split('/').filter((part) => part !== ''), renderedPathname.split('/').filter((part) => part !== ''),
0, 0
renderedSearch as NormalizedSearch
), ),
h: fallbackTransportData.h, h: fallbackTransportData.h,
}, },
...@@ -80,8 +77,7 @@ export function createInitialRSCPayloadFromFallbackPrerender( ...@@ -80,8 +77,7 @@ export function createInitialRSCPayloadFromFallbackPrerender(
function fillInFallbackTransportTree( function fillInFallbackTransportTree(
node: FullTransportNode, node: FullTransportNode,
pathnameParts: Array<string>, pathnameParts: Array<string>,
pathnamePartsIndex: number, pathnamePartsIndex: number
renderedSearch: NormalizedSearch
): FullTransportNode { ): FullTransportNode {
const originalSegment = node.s const originalSegment = node.s
let newSegment: TransportSegment let newSegment: TransportSegment
...@@ -98,7 +94,7 @@ function fillInFallbackTransportTree( ...@@ -98,7 +94,7 @@ function fillInFallbackTransportTree(
newSegment = { newSegment = {
n: originalSegment.n, n: originalSegment.n,
t: originalSegment.t, t: originalSegment.t,
k: getCacheKeyForDynamicParam(paramValue, renderedSearch), k: getCacheKeyForDynamicParam(paramValue),
s: originalSegment.s, s: originalSegment.s,
} }
doesAppearInURL = true doesAppearInURL = true
...@@ -120,8 +116,7 @@ function fillInFallbackTransportTree( ...@@ -120,8 +116,7 @@ function fillInFallbackTransportTree(
fillInFallbackTransportTree( fillInFallbackTransportTree(
childNode, childNode,
pathnameParts, pathnameParts,
childPathnamePartsIndex, childPathnamePartsIndex
renderedSearch
) )
) )
} }
...@@ -206,22 +201,18 @@ function stripClientOnlyDataFromFlightRouterState( ...@@ -206,22 +201,18 @@ function stripClientOnlyDataFromFlightRouterState(
result[4] = prefetchHints result[4] = prefetchHints
} }
// Everything else is used only by the client and is not needed for requests. // Leave out the page's search params. They're only used by the client, and
// request headers may be forwarded through redirects.
return result return result
} }
/** /**
* Strips client-only data from segments: * Strips client-only data from segments:
* - Search parameters from __PAGE__ segments
* - staticSiblings from dynamic segment tuples (only needed for client-side * - staticSiblings from dynamic segment tuples (only needed for client-side
* prefetch reuse decisions) * prefetch reuse decisions)
*/ */
function stripClientOnlyDataFromSegment(segment: Segment): Segment { function stripClientOnlyDataFromSegment(segment: Segment): Segment {
if (typeof segment === 'string') { if (typeof segment === 'string') {
// Strip search params from __PAGE__ segments
if (segment.startsWith(PAGE_SEGMENT_KEY + '?')) {
return PAGE_SEGMENT_KEY
}
return segment return segment
} }
// Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings] // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]
......
import type { DynamicParamTypesShort } from '../shared/lib/app-router-types' import type { DynamicParamTypesShort } from '../shared/lib/app-router-types'
import { import { DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../shared/lib/segment'
addSearchParamsIfPageSegment,
DEFAULT_SEGMENT_KEY,
PAGE_SEGMENT_KEY,
} from '../shared/lib/segment'
import { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding' import { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'
import { import {
NEXT_REWRITTEN_PATH_HEADER, NEXT_REWRITTEN_PATH_HEADER,
...@@ -19,9 +15,19 @@ import type { ...@@ -19,9 +15,19 @@ import type {
} from './components/segment-cache/cache-key' } from './components/segment-cache/cache-key'
import type { RSCResponse } from './components/router-reducer/fetch-server-response' import type { RSCResponse } from './components/router-reducer/fetch-server-response'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import { getRenderedSearch as getRenderedSearchFromQuery } from '../shared/lib/router/utils/querystring'
export type RouteParamValue = string | Array<string> | null export type RouteParamValue = string | Array<string> | null
export function normalizeRenderedSearch(search: string): NormalizedSearch {
// The same search params should produce the same string whether they came
// from the URL, a rewrite header, or the response (e.g. '+' vs '%20'). Only
// used for the rendered search. Request URLs keep their original form,
// since middleware and rewrites may depend on it.
const query = urlSearchParamsToParsedUrlQuery(new URLSearchParams(search))
return getRenderedSearchFromQuery(query) as NormalizedSearch
}
export function getRenderedSearch( export function getRenderedSearch(
response: RSCResponse<unknown> | Response response: RSCResponse<unknown> | Response
): NormalizedSearch { ): NormalizedSearch {
...@@ -30,14 +36,13 @@ export function getRenderedSearch( ...@@ -30,14 +36,13 @@ export function getRenderedSearch(
// the response will include a header that gives the rewritten search query. // the response will include a header that gives the rewritten search query.
const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER) const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)
if (rewrittenQuery !== null) { if (rewrittenQuery !== null) {
return ( return normalizeRenderedSearch(rewrittenQuery)
rewrittenQuery === '' ? '' : '?' + rewrittenQuery
) as NormalizedSearch
} }
// If the header is not present, there was no rewrite, so we use the search // If the header is not present, there was no rewrite, so we use the search
// query of the response URL. // query of the response URL.
return urlToUrlWithoutFlightMarker(new URL(response.url)) return normalizeRenderedSearch(
.search as NormalizedSearch urlToUrlWithoutFlightMarker(new URL(response.url)).search
)
} }
export function getRenderedPathname( export function getRenderedPathname(
...@@ -181,7 +186,7 @@ export function doesStaticSegmentAppearInURL(segment: string): boolean { ...@@ -181,7 +186,7 @@ export function doesStaticSegmentAppearInURL(segment: string): boolean {
// Otherwise, we wouldn't need this special case because pages are // Otherwise, we wouldn't need this special case because pages are
// always leaf nodes. // always leaf nodes.
// TODO: Investigate why the loader produces these fake page segments. // TODO: Investigate why the loader produces these fake page segments.
segment.startsWith(PAGE_SEGMENT_KEY) || segment === PAGE_SEGMENT_KEY ||
// Route groups. // Route groups.
(segment[0] === '(' && segment.endsWith(')')) || (segment[0] === '(' && segment.endsWith(')')) ||
segment === DEFAULT_SEGMENT_KEY || segment === DEFAULT_SEGMENT_KEY ||
...@@ -195,21 +200,13 @@ export function doesStaticSegmentAppearInURL(segment: string): boolean { ...@@ -195,21 +200,13 @@ export function doesStaticSegmentAppearInURL(segment: string): boolean {
} }
export function getCacheKeyForDynamicParam( export function getCacheKeyForDynamicParam(
paramValue: RouteParamValue, paramValue: RouteParamValue
renderedSearch: NormalizedSearch
): string { ): string {
// This needs to match the logic in get-dynamic-param.ts, until we're able to // This needs to match the logic in get-dynamic-param.ts, until we're able to
// unify the various implementations so that these are always computed on // unify the various implementations so that these are always computed on
// the client. // the client.
if (typeof paramValue === 'string') { if (typeof paramValue === 'string') {
// TODO: Refactor or remove this helper function to accept a string rather return paramValue
// than the whole segment type. Also we can probably just append the
// search string instead of turning it into JSON.
const pageSegmentWithSearchParams = addSearchParamsIfPageSegment(
paramValue,
urlSearchParamsToParsedUrlQuery(new URLSearchParams(renderedSearch))
) as string
return pageSegmentWithSearchParams
} else if (paramValue === null) { } else if (paramValue === null) {
return '' return ''
} else { } else {
......
...@@ -50,7 +50,7 @@ export function formatRoutePattern(tree: FlightRouterState): string { ...@@ -50,7 +50,7 @@ export function formatRoutePattern(tree: FlightRouterState): string {
// and route groups (parenthesized segments like "(marketing)") // and route groups (parenthesized segments like "(marketing)")
if ( if (
segment !== '' && segment !== '' &&
!segment.startsWith('__PAGE__') && segment !== '__PAGE__' &&
segment !== '__DEFAULT__' && segment !== '__DEFAULT__' &&
!(segment.startsWith('(') && segment.endsWith(')')) !(segment.startsWith('(') && segment.endsWith(')'))
) { ) {
......
...@@ -73,6 +73,7 @@ import type { AnyStream } from './stream-ops' ...@@ -73,6 +73,7 @@ import type { AnyStream } from './stream-ops'
import { createRenderInBrowserAbortSignal } from './render-in-browser' import { createRenderInBrowserAbortSignal } from './render-in-browser'
import { getInstantTestBootstrapScriptContent } from './instant-test-bootstrap' import { getInstantTestBootstrapScriptContent } from './instant-test-bootstrap'
import { stripInternalQueries } from '../internal-utils' import { stripInternalQueries } from '../internal-utils'
import { getRenderedSearch } from '../../shared/lib/router/utils/querystring'
import { import {
NEXT_HMR_REFRESH_HEADER, NEXT_HMR_REFRESH_HEADER,
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
...@@ -2157,39 +2158,6 @@ function prepareInitialCanonicalUrl(url: RequestStore['url']) { ...@@ -2157,39 +2158,6 @@ function prepareInitialCanonicalUrl(url: RequestStore['url']) {
return (url.pathname + url.search).split('/') return (url.pathname + url.search).split('/')
} }
function getRenderedSearch(query: NextParsedUrlQuery): string {
// Inlined implementation of querystring.encode, which is not available in
// the Edge runtime.
const pairs = []
for (const key in query) {
const value = query[key]
if (value == null) continue
if (Array.isArray(value)) {
for (const v of value) {
pairs.push(
`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`
)
}
} else {
pairs.push(
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
)
}
}
// The result should match the format of a web URL's `search` property, since
// this is the format that's stored in the App Router state.
// TODO: We're a bit inconsistent about this. The x-nextjs-rewritten-query
// header omits the leading question mark. Should refactor to always do
// that instead.
if (pairs.length === 0) {
// If the search string is empty, return an empty string.
return ''
}
// Prepend '?' to the search params string.
return '?' + pairs.join('&')
}
// This is the data necessary to render <AppRouter /> when no SSR errors are encountered // This is the data necessary to render <AppRouter /> when no SSR errors are encountered
async function getRSCPayload( async function getRSCPayload(
tree: LoaderTree, tree: LoaderTree,
...@@ -2456,7 +2424,6 @@ async function getErrorRSCPayload( ...@@ -2456,7 +2424,6 @@ async function getErrorRSCPayload(
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query,
ctx.renderOpts.notFoundParams ctx.renderOpts.notFoundParams
) )
// Attach the error shell as the root's render output. Vary params are not // Attach the error shell as the root's render output. Vary params are not
...@@ -7818,7 +7785,6 @@ async function validateInstantConfigs( ...@@ -7818,7 +7785,6 @@ async function validateInstantConfigs(
cache, cache,
loaderTree, loaderTree,
ctx.getDynamicParamFromSegment, ctx.getDynamicParamFromSegment,
ctx.query,
depth, depth,
groupDepthForValidation, groupDepthForValidation,
extraChunksSignal, extraChunksSignal,
......
...@@ -47,10 +47,7 @@ import type { ...@@ -47,10 +47,7 @@ import type {
UseCacheLayoutProps, UseCacheLayoutProps,
UseCachePageProps, UseCachePageProps,
} from '../use-cache/use-cache-wrapper' } from '../use-cache/use-cache-wrapper'
import { import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
addSearchParamsIfPageSegment,
DEFAULT_SEGMENT_KEY,
} from '../../shared/lib/segment'
import { import {
BOUNDARY_PREFIX, BOUNDARY_PREFIX,
BOUNDARY_SUFFIX, BOUNDARY_SUFFIX,
...@@ -470,10 +467,7 @@ async function createComponentTreeInternal( ...@@ -470,10 +467,7 @@ async function createComponentTreeInternal(
// The segment's identity on the wire. // The segment's identity on the wire.
const transportSegment = segmentToTransportSegment( const transportSegment = segmentToTransportSegment(
addSearchParamsIfPageSegment( segmentParam ? segmentParam.treeSegment : segment
segmentParam ? segmentParam.treeSegment : segment,
query
)
) )
// Create object holding the parent params and current params // Create object holding the parent params and current params
...@@ -600,7 +594,6 @@ async function createComponentTreeInternal( ...@@ -600,7 +594,6 @@ async function createComponentTreeInternal(
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query,
ctx.renderOpts.notFoundParams, ctx.renderOpts.notFoundParams,
rootLayoutIncludedAtThisLevelOrAbove rootLayoutIncludedAtThisLevelOrAbove
) )
......
...@@ -13,7 +13,6 @@ import { ...@@ -13,7 +13,6 @@ import {
segmentToTransportSegment, segmentToTransportSegment,
} from '../../shared/lib/rsc-transport' } from '../../shared/lib/rsc-transport'
import type { GetDynamicParamFromSegment } from './app-render' import type { GetDynamicParamFromSegment } from './app-render'
import { addSearchParamsIfPageSegment } from '../../shared/lib/segment'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config' import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param' import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param'
...@@ -168,7 +167,6 @@ async function createTransportTreeFromLoaderTreeImpl( ...@@ -168,7 +167,6 @@ async function createTransportTreeFromLoaderTreeImpl(
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
didFindRootLayout: boolean, didFindRootLayout: boolean,
notFoundParams: readonly string[] | undefined notFoundParams: readonly string[] | undefined
): Promise<PartialTransportNode> { ): Promise<PartialTransportNode> {
...@@ -205,7 +203,6 @@ async function createTransportTreeFromLoaderTreeImpl( ...@@ -205,7 +203,6 @@ async function createTransportTreeFromLoaderTreeImpl(
missingPrefetchHintPolicy, missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams,
didFindRootLayout, didFindRootLayout,
notFoundParams notFoundParams
) )
...@@ -220,9 +217,7 @@ async function createTransportTreeFromLoaderTreeImpl( ...@@ -220,9 +217,7 @@ async function createTransportTreeFromLoaderTreeImpl(
} }
const node: PartialTransportNode = { const node: PartialTransportNode = {
s: segmentToTransportSegment( s: segmentToTransportSegment(treeSegment),
addSearchParamsIfPageSegment(treeSegment, searchParams)
),
} }
if (prefetchHints !== 0) { if (prefetchHints !== 0) {
node.h = prefetchHints node.h = prefetchHints
...@@ -249,7 +244,6 @@ export async function createTransportTreeFromLoaderTree( ...@@ -249,7 +244,6 @@ export async function createTransportTreeFromLoaderTree(
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
notFoundParams: readonly string[] | undefined, notFoundParams: readonly string[] | undefined,
// Whether a root layout was already found above this loader tree slice, so a // Whether a root layout was already found above this loader tree slice, so a
// slice that starts below the root layout doesn't mark a sub-layout as the // slice that starts below the root layout doesn't mark a sub-layout as the
...@@ -264,7 +258,6 @@ export async function createTransportTreeFromLoaderTree( ...@@ -264,7 +258,6 @@ export async function createTransportTreeFromLoaderTree(
missingPrefetchHintPolicy, missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams,
didFindRootLayout, didFindRootLayout,
notFoundParams notFoundParams
) )
...@@ -282,7 +275,6 @@ export async function createFullTransportTreeFromLoaderTree( ...@@ -282,7 +275,6 @@ export async function createFullTransportTreeFromLoaderTree(
missingPrefetchHintPolicy: MissingPrefetchHintPolicy, missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
partialPrefetching: boolean, partialPrefetching: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
notFoundParams: readonly string[] | undefined notFoundParams: readonly string[] | undefined
): Promise<FullTransportNode> { ): Promise<FullTransportNode> {
// With emitSkippedData, every node carries data, which is what // With emitSkippedData, every node carries data, which is what
...@@ -296,7 +288,6 @@ export async function createFullTransportTreeFromLoaderTree( ...@@ -296,7 +288,6 @@ export async function createFullTransportTreeFromLoaderTree(
missingPrefetchHintPolicy, missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams,
false, false,
notFoundParams notFoundParams
) as Promise<FullTransportNode> ) as Promise<FullTransportNode>
...@@ -317,10 +308,6 @@ export async function createRouteTreePrefetch( ...@@ -317,10 +308,6 @@ export async function createRouteTreePrefetch(
// See note on createTransportTreeFromLoaderTree's didFindRootLayout. // See note on createTransportTreeFromLoaderTree's didFindRootLayout.
didFindRootLayout: boolean = false didFindRootLayout: boolean = false
): Promise<PartialTransportNode> { ): Promise<PartialTransportNode> {
// Search params should not be added to page segment's cache key during a
// route tree prefetch request, because they do not affect the structure of
// the route. The client cache has its own logic to handle search params.
const searchParams = {}
return createTransportTreeFromLoaderTreeImpl( return createTransportTreeFromLoaderTreeImpl(
loaderTree, loaderTree,
false, false,
...@@ -329,7 +316,6 @@ export async function createRouteTreePrefetch( ...@@ -329,7 +316,6 @@ export async function createRouteTreePrefetch(
missingPrefetchHintPolicy, missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams,
didFindRootLayout, didFindRootLayout,
notFoundParams notFoundParams
) )
......
...@@ -27,11 +27,7 @@ import { InvariantError } from '../../../shared/lib/invariant-error' ...@@ -27,11 +27,7 @@ import { InvariantError } from '../../../shared/lib/invariant-error'
*/ */
export function isImplicitValidationSegment(segment: Segment): boolean { export function isImplicitValidationSegment(segment: Segment): boolean {
const key = typeof segment === 'string' ? segment : segment[0] const key = typeof segment === 'string' ? segment : segment[0]
return ( return key === PAGE_SEGMENT_KEY || key === DEFAULT_SEGMENT_KEY
key === PAGE_SEGMENT_KEY ||
key.startsWith(PAGE_SEGMENT_KEY) ||
key === DEFAULT_SEGMENT_KEY
)
} }
/** /**
......
...@@ -54,7 +54,6 @@ import type { FlightComponentMod } from '../stream-ops' ...@@ -54,7 +54,6 @@ import type { FlightComponentMod } from '../stream-ops'
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import { createFromNodeStream } from 'react-server-dom-webpack/client' import { createFromNodeStream } from 'react-server-dom-webpack/client'
import { import {
addSearchParamsIfPageSegment,
isGroupSegment, isGroupSegment,
PAGE_SEGMENT_KEY, PAGE_SEGMENT_KEY,
DEFAULT_SEGMENT_KEY, DEFAULT_SEGMENT_KEY,
...@@ -64,7 +63,6 @@ import { ...@@ -64,7 +63,6 @@ import {
isFrameworkErrorRoute, isFrameworkErrorRoute,
isImplicitValidationSegment, isImplicitValidationSegment,
} from './instant-config' } from './instant-config'
import type { NextParsedUrlQuery } from '../../request-meta'
const filterStackFrame = const filterStackFrame =
process.env.NODE_ENV !== 'production' process.env.NODE_ENV !== 'production'
...@@ -134,8 +132,6 @@ function traverseTransportNodeSegments( ...@@ -134,8 +132,6 @@ function traverseTransportNodeSegments(
return return
} }
for (const [parallelRouteKey, childNode] of children) { for (const [parallelRouteKey, childNode] of children) {
// NOTE: if this is a __PAGE__ segment, it might have search params appended.
// Whoever reads from the cache needs to append them as well.
const childPath = createChildSegmentPath( const childPath = createChildSegmentPath(
path, path,
parallelRouteKey, parallelRouteKey,
...@@ -893,7 +889,7 @@ function segmentConsumesURLDepth(segment: Segment): boolean { ...@@ -893,7 +889,7 @@ function segmentConsumesURLDepth(segment: Segment): boolean {
if (typeof segment !== 'string') return true if (typeof segment !== 'string') return true
// Route groups, pages, defaults, and not-found don't consume a depth. // Route groups, pages, defaults, and not-found don't consume a depth.
if ( if (
segment.startsWith(PAGE_SEGMENT_KEY) || segment === PAGE_SEGMENT_KEY ||
isGroupSegment(segment) || isGroupSegment(segment) ||
segment === DEFAULT_SEGMENT_KEY || segment === DEFAULT_SEGMENT_KEY ||
segment === NOT_FOUND_SEGMENT_KEY segment === NOT_FOUND_SEGMENT_KEY
...@@ -1021,7 +1017,6 @@ export async function createCombinedPayloadAtDepth( ...@@ -1021,7 +1017,6 @@ export async function createCombinedPayloadAtDepth(
cache: SegmentCache, cache: SegmentCache,
initialLoaderTree: LoaderTree, initialLoaderTree: LoaderTree,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
query: NextParsedUrlQuery | null,
depth: number, depth: number,
groupDepth: number, groupDepth: number,
releaseSignal: AbortSignal, releaseSignal: AbortSignal,
...@@ -1074,8 +1069,7 @@ export async function createCombinedPayloadAtDepth( ...@@ -1074,8 +1069,7 @@ export async function createCombinedPayloadAtDepth(
if (dynamicParam) { if (dynamicParam) {
return dynamicParam.treeSegment return dynamicParam.treeSegment
} }
const segment = loaderTree[0] return loaderTree[0]
return query ? addSearchParamsIfPageSegment(segment, query) : segment
} }
async function buildSharedTransportTree( async function buildSharedTransportTree(
......
...@@ -79,7 +79,8 @@ export const flightRouterStateSchema: s.Describe<any> = s.tuple([ ...@@ -79,7 +79,8 @@ export const flightRouterStateSchema: s.Describe<any> = s.tuple([
]) ])
) )
), ),
s.optional(s.number()), s.optional(s.nullable(s.number())),
s.optional(s.string()),
]) ])
export type ServerOnInstrumentationRequestError = ( export type ServerOnInstrumentationRequestError = (
......
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import { getRenderedSearch } from '../../shared/lib/router/utils/querystring'
import type { import type {
FlightRouterState, FlightRouterState,
PrefetchHints, PrefetchHints,
...@@ -10,7 +12,6 @@ import { ...@@ -10,7 +12,6 @@ import {
segmentToTransportSegment, segmentToTransportSegment,
} from '../../shared/lib/rsc-transport' } from '../../shared/lib/rsc-transport'
import type { PreloadCallbacks } from './types' import type { PreloadCallbacks } from './types'
import { matchSegment } from '../../client/components/match-segments'
import type { LoaderTree } from '../lib/app-dir-module' import type { LoaderTree } from '../lib/app-dir-module'
import { getLinkAndScriptTags } from './get-css-inlined-link-tags' import { getLinkAndScriptTags } from './get-css-inlined-link-tags'
import { getPreloadableFonts } from './get-preloadable-fonts' import { getPreloadableFonts } from './get-preloadable-fonts'
...@@ -21,7 +22,6 @@ import { ...@@ -21,7 +22,6 @@ import {
} from './create-transport-tree-from-loader-tree' } from './create-transport-tree-from-loader-tree'
import type { AppRenderContext } from './app-render' import type { AppRenderContext } from './app-render'
import { hasLoadingComponentInTree } from './has-loading-component-in-tree' import { hasLoadingComponentInTree } from './has-loading-component-in-tree'
import { addSearchParamsIfPageSegment } from '../../shared/lib/segment'
import { createComponentTree } from './create-component-tree' import { createComponentTree } from './create-component-tree'
/** /**
...@@ -37,6 +37,28 @@ export type NavigationResponseTree = { ...@@ -37,6 +37,28 @@ export type NavigationResponseTree = {
isHeadPartial: boolean isHeadPartial: boolean
} }
function didRouteOrPathParamChange(
actualSegment: Segment,
requestedSegment: Segment
): boolean {
// The caller handles the page's search params separately.
if (
typeof actualSegment === 'string' ||
typeof requestedSegment === 'string'
) {
// Static segments have to match exactly.
return actualSegment !== requestedSegment
}
// Both segments are dynamic. Compare the param name, type, and value. The
// static sibling hints (index 3) aren't part of the segment's identity.
return (
actualSegment[0] !== requestedSegment[0] ||
actualSegment[2] !== requestedSegment[2] ||
actualSegment[1] !== requestedSegment[1]
)
}
/** /**
* Use router state to decide at what common layout to render the page. * Use router state to decide at what common layout to render the page.
* This can either be the common layout between two pages or a specific place to start rendering from using the "refetch" marker in the tree. * This can either be the common layout between two pages or a specific place to start rendering from using the "refetch" marker in the tree.
...@@ -111,10 +133,9 @@ export async function walkTreeWithFlightRouterState({ ...@@ -111,10 +133,9 @@ export async function walkTreeWithFlightRouterState({
[segmentParam.param]: segmentParam.value, [segmentParam.param]: segmentParam.value,
} }
: parentParams : parentParams
const actualSegment: Segment = addSearchParamsIfPageSegment( const actualSegment: Segment = segmentParam
segmentParam ? segmentParam.treeSegment : segment, ? segmentParam.treeSegment
query : segment
)
/** /**
* Decide if the current segment is where rendering has to start. * Decide if the current segment is where rendering has to start.
...@@ -122,8 +143,13 @@ export async function walkTreeWithFlightRouterState({ ...@@ -122,8 +143,13 @@ export async function walkTreeWithFlightRouterState({
const renderComponentsOnThisLevel = const renderComponentsOnThisLevel =
// No further router state available // No further router state available
!flightRouterState || !flightRouterState ||
// Segment in router state does not match current segment // Route structure or path param changed
!matchSegment(actualSegment, flightRouterState[0]) || didRouteOrPathParamChange(actualSegment, flightRouterState[0]) ||
// Normal requests leave out the page's search params, so treat a missing
// value as empty. HMR requests include them.
(actualSegment === PAGE_SEGMENT_KEY &&
getRenderedSearch(query) !==
(flightRouterState[5] === undefined ? '' : flightRouterState[5])) ||
// Explicit refresh // Explicit refresh
flightRouterState[3] === 'refetch' flightRouterState[3] === 'refetch'
...@@ -182,7 +208,6 @@ export async function walkTreeWithFlightRouterState({ ...@@ -182,7 +208,6 @@ export async function walkTreeWithFlightRouterState({
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query,
ctx.renderOpts.notFoundParams, ctx.renderOpts.notFoundParams,
rootLayoutIncluded rootLayoutIncluded
) )
...@@ -214,7 +239,6 @@ export async function walkTreeWithFlightRouterState({ ...@@ -214,7 +239,6 @@ export async function walkTreeWithFlightRouterState({
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
partialPrefetching, partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query,
ctx.renderOpts.notFoundParams, ctx.renderOpts.notFoundParams,
rootLayoutIncluded rootLayoutIncluded
) )
......
...@@ -147,7 +147,7 @@ function getEntrypointsFromTree( ...@@ -147,7 +147,7 @@ function getEntrypointsFromTree(
? convertDynamicParamTypeToSyntax(segment[2], segment[0]) ? convertDynamicParamTypeToSyntax(segment[2], segment[0])
: segment : segment
const isPageSegment = currentSegment.startsWith(PAGE_SEGMENT_KEY) const isPageSegment = currentSegment === PAGE_SEGMENT_KEY
const currentPath = [...parentPath, isPageSegment ? '' : currentSegment] const currentPath = [...parentPath, isPageSegment ? '' : currentSegment]
......
...@@ -170,9 +170,16 @@ export type FlightRouterState = [ ...@@ -170,9 +170,16 @@ export type FlightRouterState = [
/** /**
* Bitmask of PrefetchHint flags. Encodes route structure metadata: * Bitmask of PrefetchHint flags. Encodes route structure metadata:
* root layout, loading boundaries, instant configs, and prefetch strategy * root layout, loading boundaries, instant configs, and prefetch strategy
* hints. Only set when non-zero. * hints. Only set when non-zero. JSON encodes an omitted slot as null when
* a later slot is present.
*/ */
prefetchHints?: number, prefetchHints?: number | null,
/**
* The rendered search params of a page segment. An empty string means there
* are none. Only set on page nodes, and left out of request headers.
* TODO: Revisit this as part of the larger FlightRouterState refactor.
*/
renderedSearch?: string,
] ]
/** /**
......
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
export function getRenderedSearch(query: ParsedUrlQuery): string {
// Inlined implementation of querystring.encode, which is not available in
// the Edge runtime.
const pairs = []
for (const key in query) {
const value = query[key]
if (value == null) continue
if (Array.isArray(value)) {
for (const v of value) {
pairs.push(
`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`
)
}
} else {
pairs.push(
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
)
}
}
// The result should match the format of a web URL's `search` property, since
// this is the format that's stored in the App Router state.
// TODO: We're a bit inconsistent about this. The x-nextjs-rewritten-query
// header omits the leading question mark. Should refactor to always do
// that instead.
if (pairs.length === 0) {
// If the search string is empty, return an empty string.
return ''
}
// Prepend '?' to the search params string.
return '?' + pairs.join('&')
}
export function searchParamsToUrlQuery( export function searchParamsToUrlQuery(
searchParams: URLSearchParams searchParams: URLSearchParams
): ParsedUrlQuery { ): ParsedUrlQuery {
......
import { PAGE_SEGMENT_KEY } from './segment'
/** /**
* The transport format for RSC responses. * The transport format for RSC responses.
* *
...@@ -26,11 +27,8 @@ import type { VaryParamsIterable } from './segment-cache/vary-params-decoding' ...@@ -26,11 +27,8 @@ import type { VaryParamsIterable } from './segment-cache/vary-params-decoding'
* Segment identity on the wire. A string for static segments; an object for * Segment identity on the wire. A string for static segments; an object for
* dynamic (parameterized) segments. * dynamic (parameterized) segments.
* *
* TODO: Page segments currently smuggle search params inside the string * Page segments are always `__PAGE__`. The search params are sent separately,
* (`__PAGE__?{...}`, see addSearchParamsIfPageSegment). This convention is * in the response's `q` field.
* carried over as-is for now. Consider giving search params a dedicated
* field (or removing them from the response entirely, since the client
* already knows the rendered search from the response-level `q`).
*/ */
export type TransportSegment = string | TransportDynamicSegment export type TransportSegment = string | TransportDynamicSegment
...@@ -300,18 +298,20 @@ export function transportSegmentToSegment( ...@@ -300,18 +298,20 @@ export function transportSegmentToSegment(
/** /**
* Derives a FlightRouterState from a transport tree. Used where the client * Derives a FlightRouterState from a transport tree. Used where the client
* needs a router-state representation of a full response (e.g. the initial * needs a router-state representation of a full response (e.g. the initial
* hydration payload). Render output (`d`) is not carried over; page segments * hydration payload). Render output (`d`) is not carried over.
* keep their search params, which travel inside the segment string.
*/ */
export function transportNodeToFlightRouterState( export function transportNodeToFlightRouterState(
node: TransportNode node: TransportNode,
renderedSearch: string
): FlightRouterState { ): FlightRouterState {
const parallelRoutes: Record<string, FlightRouterState> = {} const parallelRoutes: Record<string, FlightRouterState> = {}
const children = node.c const children = node.c
if (children !== undefined) { if (children !== undefined) {
for (const [parallelRouteKey, childNode] of children) { for (const [parallelRouteKey, childNode] of children) {
parallelRoutes[parallelRouteKey] = parallelRoutes[parallelRouteKey] = transportNodeToFlightRouterState(
transportNodeToFlightRouterState(childNode) childNode,
renderedSearch
)
} }
} }
const flightRouterState: FlightRouterState = [ const flightRouterState: FlightRouterState = [
...@@ -321,5 +321,8 @@ export function transportNodeToFlightRouterState( ...@@ -321,5 +321,8 @@ export function transportNodeToFlightRouterState(
if (node.h !== undefined) { if (node.h !== undefined) {
flightRouterState[4] = node.h flightRouterState[4] = node.h
} }
if (flightRouterState[0] === PAGE_SEGMENT_KEY) {
flightRouterState[5] = renderedSearch
}
return flightRouterState return flightRouterState
} }
import { PAGE_SEGMENT_KEY } from '../segment'
import type { Segment as FlightRouterStateSegment } from '../app-router-types' import type { Segment as FlightRouterStateSegment } from '../app-router-types'
// TypeScript trick to simulate opaque types, like in Flow. // TypeScript trick to simulate opaque types, like in Flow.
...@@ -15,18 +14,6 @@ export function createSegmentRequestKeyPart( ...@@ -15,18 +14,6 @@ export function createSegmentRequestKeyPart(
segment: FlightRouterStateSegment segment: FlightRouterStateSegment
): SegmentRequestKeyPart { ): SegmentRequestKeyPart {
if (typeof segment === 'string') { if (typeof segment === 'string') {
if (segment.startsWith(PAGE_SEGMENT_KEY)) {
// The Flight Router State type sometimes includes the search params in
// the page segment. However, the Segment Cache tracks this as a separate
// key. So, we strip the search params here, and then add them back when
// the cache entry is turned back into a FlightRouterState. This is an
// unfortunate consequence of the FlightRouteState being used both as a
// transport type and as a cache key; we'll address this once more of the
// Segment Cache implementation has settled.
// TODO: We should hoist the search params out of the FlightRouterState
// type entirely, This is our plan for dynamic route params, too.
return PAGE_SEGMENT_KEY as SegmentRequestKeyPart
}
const safeName = const safeName =
// TODO: FlightRouterState encodes Not Found routes as "/_not-found". // TODO: FlightRouterState encodes Not Found routes as "/_not-found".
// But params typically don't include the leading slash. We should use // But params typically don't include the leading slash. We should use
......
...@@ -13,22 +13,6 @@ export function isParallelRouteSegment(segment: string) { ...@@ -13,22 +13,6 @@ export function isParallelRouteSegment(segment: string) {
return segment.startsWith('@') && segment !== '@children' return segment.startsWith('@') && segment !== '@children'
} }
export function addSearchParamsIfPageSegment(
segment: Segment,
searchParams: Record<string, string | string[] | undefined>
) {
const isPageSegment = segment.includes(PAGE_SEGMENT_KEY)
if (isPageSegment) {
const stringifiedQuery = JSON.stringify(searchParams)
return stringifiedQuery !== '{}'
? PAGE_SEGMENT_KEY + '?' + stringifiedQuery
: PAGE_SEGMENT_KEY
}
return segment
}
export function computeSelectedLayoutSegment( export function computeSelectedLayoutSegment(
segments: string[] | null, segments: string[] | null,
parallelRouteKey: string parallelRouteKey: string
...@@ -70,7 +54,7 @@ export function getSelectedLayoutSegmentPath( ...@@ -70,7 +54,7 @@ export function getSelectedLayoutSegmentPath(
let segmentValue = getSegmentValue(segment) let segmentValue = getSegmentValue(segment)
if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) { if (!segmentValue || segmentValue === PAGE_SEGMENT_KEY) {
return segmentPath return segmentPath
} }
......
...@@ -785,10 +785,8 @@ describe('app-dir static/dynamic handling', () => { ...@@ -785,10 +785,8 @@ describe('app-dir static/dynamic handling', () => {
? await next.readFile('.next/server/app/blog/seb.prefetch.rsc') ? await next.readFile('.next/server/app/blog/seb.prefetch.rsc')
: await next.readFile('.next/server/app/blog/seb.rsc') : await next.readFile('.next/server/app/blog/seb.rsc')
// During SSG, pages that correspond with dynamic routes shouldn't have any search // Page segments contain only structural identity. Search params are
// parameters in the `__PAGE__` segment string. The only time we expect to see // carried separately, including in responses for dynamic routes.
// search parameters in the `__PAGE__` segment string is when the RSC data is
// requested from the client with search parameters.
expect(data).not.toContain('__PAGE__?') expect(data).not.toContain('__PAGE__?')
expect(data).toContain('__PAGE__') expect(data).toContain('__PAGE__')
}) })
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { LinkAccordion } from '../../../components/link-accordion'
async function Content({ searchParams }) { async function Content({ searchParams }) {
const { searchParam } = await searchParams const { searchParam } = await searchParams
...@@ -11,6 +12,15 @@ export default async function Target({ searchParams }) { ...@@ -11,6 +12,15 @@ export default async function Target({ searchParams }) {
<div id="target-page-with-search-param"> <div id="target-page-with-search-param">
<Content searchParams={searchParams} /> <Content searchParams={searchParams} />
</div> </div>
<LinkAccordion
prefetch={true}
href="/search-params/target-page?searchParam=query_only"
>
Change search params
</LinkAccordion>
<LinkAccordion href="/search-params/target-page?searchParam=hello+world,/x&unused&searchParam=another%20value">
Navigate with encoded and repeated search params
</LinkAccordion>
</Suspense> </Suspense>
) )
} }
...@@ -11,6 +11,79 @@ describe('segment cache (search params)', () => { ...@@ -11,6 +11,79 @@ describe('segment cache (search params)', () => {
return return
} }
it('prefetches new vary data for a query-only navigation from the active page', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser(
'/search-params/target-page?searchParam=initial',
{
beforePageLoad(page) {
act = createRouterAct(page)
},
}
)
expect(
await browser.elementById('target-page-with-search-param').text()
).toContain('Search param: initial')
await act(
async () => {
await browser
.elementByCss(
'input[data-link-accordion="/search-params/target-page?searchParam=query_only"]'
)
.click()
},
{ includes: 'Search param: query_only' }
)
await act(async () => {
await browser
.elementByCss(
'a[href="/search-params/target-page?searchParam=query_only"]'
)
.click()
}, 'no-requests')
expect(
await browser.elementById('target-page-with-search-param').text()
).toContain('Search param: query_only')
})
it('navigates to a prefetched page with encoded and repeated search params', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser(
'/search-params/target-page?searchParam=initial',
{
beforePageLoad(page) {
act = createRouterAct(page)
},
}
)
// Prefetch the shell before navigating. This URL uses both space encodings,
// unescaped punctuation, a bare key, and interleaved repeated values.
await act(async () => {
await browser
.elementByCss(
'input[data-link-accordion="/search-params/target-page?searchParam=hello+world,/x&unused&searchParam=another%20value"]'
)
.click()
})
await act(
async () => {
await browser
.elementByCss(
'a[href="/search-params/target-page?searchParam=hello+world,/x&unused&searchParam=another%20value"]'
)
.click()
},
{ includes: 'Search param: hello world,/x,another value' }
)
expect(
await browser.elementById('target-page-with-search-param').text()
).toBe('Search param: hello world,/x,another value')
expect(new URL(await browser.url()).search).toBe(
'?searchParam=hello+world,/x&unused&searchParam=another%20value'
)
})
it('when fetching with PPR, does not include search params in the cache key', async () => { it('when fetching with PPR, does not include search params in the cache key', async () => {
let act: ReturnType<typeof createRouterAct> let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/search-params', { const browser = await next.browser('/search-params', {
......
import { LinkAccordion } from '../../../../components/link-accordion'
/**
* Navigation reuse: the page does not read searchParams but its metadata
* does. A query-only navigation must still fetch the head, because it depends
* on the query.
*/
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
<ul>
<li>
<LinkAccordion href="/navigation-reuse/metadata-query?x=2">
x=2
</LinkAccordion>
</li>
</ul>
{children}
</>
)
}
export default function Loading() {
return <div data-loading="true">Loading metadata-query page...</div>
}
import { connection } from 'next/server'
type SearchParams = { x?: string }
export async function generateMetadata({
searchParams,
}: {
searchParams: Promise<SearchParams>
}) {
const { x } = await searchParams
return { title: `Query title: ${x}` }
}
export default async function Page() {
await connection()
return <p id="server-token">{`Server token: ${Math.random()}`}</p>
}
...@@ -888,4 +888,39 @@ describe('segment cache - vary params', () => { ...@@ -888,4 +888,39 @@ describe('segment cache - vary params', () => {
) )
} }
) )
it('still fetches the head on a query-only navigation when the metadata read searchParams', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/navigation-reuse/metadata-query?x=1', {
beforePageLoad(page: Playwright.Page) {
act = createRouterAct(page)
},
})
expect(await browser.eval('document.title')).toBe('Query title: 1')
const initialToken = await browser.elementById('server-token').text()
await act(async () => {
await browser
.elementByCss(
'input[data-link-accordion="/navigation-reuse/metadata-query?x=2"]'
)
.click()
}, 'no-requests')
// The head read the query, so it's fetched again.
await act(
async () => {
await browser
.elementByCss('a[href="/navigation-reuse/metadata-query?x=2"]')
.click()
},
{ includes: 'Query title: 2' }
)
expect(await browser.eval('document.title')).toBe('Query title: 2')
// A dynamic render reports no dependency information, so the page is
// re-rendered along with the head.
expect(await browser.elementById('server-token').text()).not.toBe(
initialToken
)
})
}) })
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