Unverified Commit e1131ee7 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Separate tracking of runtime data accesses for shells and prefetches (#98129)

Expands the static tracking from #96095 to track shells and prefetches
separately. We split the `ShouldAttemptStaticPrefetch` hint into
`ShouldAttemptStaticShell` and `ShouldAttemptStaticPrefetch`, which the
client router considers separately depending on whether we need a shell
or a prefetch.

The server-side tracking of `needsRuntimeRequest` becomes a bit more
subtle.

First, a runtime data access should only affect the shell if we're in
the `ShellStatic` render stage. If we're already in the `PrefetchStatic`
stage, then that content is not conceptually part of the shell, and
should not deopt the shell to runtime, so we only unset
`shouldAttemptStaticShell` if we're still in the shell stage.

Second, accessing data that would only resolve in the prefetch (params,
search params, short-stale caches) should **not** affect whether the
shell can be static. `makeRuntimeDataHangingPromise` has been split into
variants that match this:
- `makeSessionDataHangingPromise` - data that affects the shell (and the
prefetch), e.g. `cookies()`
- `makeURLDataHangingPromise` - data that only affects the prefetch,
e.g. `params`
- `makeUnknownRuntimeDataHangingPromise`, used for private caches -- we
omit these during build so we don't know whether they should affect the
shell or only the prefetch, so we conservatively affect both (unless a
private cache is only used in the prefetch stage)
  
The server-side `needsRuntimeRequest` promise is now resolved such that
data that only resolves in the prefetch does not affect the shell. If
we're accessing data that only resolves in the prefetch, we will delay
the promise's resolution to the `PrefetchStatic` stage, which means that
when the client rewinds the static response to a shell, it will see an
unresolved promise and consider the response as not having used runtime
data. (see `markRuntimeDataAccessWhenStageReached`)
parent 51603630
import type React from 'react' import type React from 'react'
import type { Segment as FlightRouterStateSegment } from '../../../shared/lib/app-router-types' import type { Segment as FlightRouterStateSegment } from '../../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types' import {
PrefetchHint,
StaticAttemptHints,
} from '../../../shared/lib/app-router-types'
import type { VaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding' import type { VaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding'
import { readFulfilledValue } from '../../../shared/lib/rsc-transport' import { readFulfilledValue } from '../../../shared/lib/rsc-transport'
import { import {
...@@ -1443,13 +1446,13 @@ export function createMetadataRouteTree( ...@@ -1443,13 +1446,13 @@ export function createMetadataRouteTree(
// one. If this logic ever gets more complex we can change this to an enum. // one. If this logic ever gets more complex we can change this to an enum.
isPage: true, isPage: true,
slots: null, slots: null,
// Only the static-attempt bit applies to the head: it's a route-level // Only the static-attempt bits apply to the head: it's a route-level
// fact ("static per-segment responses may exist for this route"), and // fact ("static per-segment responses may exist for this route"), and
// it's what lets a shell-tier cached head attempt a static head fetch // it's what lets a shell-tier cached head attempt a static head fetch
// before deopting to a runtime request (see the shell-tier eligibility // before deopting to a runtime request (see the shell-tier eligibility
// check in pingSegmentBundle). The other bits describe tree structure // check in pingSegmentBundle). The other bits describe tree structure
// the head doesn't participate in. // the head doesn't participate in.
prefetchHints: rootPrefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch, prefetchHints: rootPrefetchHints & StaticAttemptHints,
} }
return metadata return metadata
} }
......
...@@ -1100,10 +1100,9 @@ function pingStaticHead( ...@@ -1100,10 +1100,9 @@ function pingStaticHead(
if ( if (
headRequiresRuntimeCompleteness && headRequiresRuntimeCompleteness &&
// The head is not a tree node — it hangs off the route root — so the // The head is not a tree node — it hangs off the route root — so the
// static-attempt hint is read from the root's node. (Segments read the // static-attempt hints are read from the root's node. (Segments read the
// bit from their own node; see the decision point in // hints from their own node; see `pingNewPartOfCacheComponentsTree.`)
// pingNewPartOfCacheComponentsTree.) !shouldSegmentAttemptStaticRequest(fetchStrategy, route.tree)
(route.tree.prefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch) === 0
) { ) {
// No static attempt: the head arrives via the runtime request instead. // No static attempt: the head arrives via the runtime request instead.
addSpawnedRuntimePrefetch(task, route.metadata.requestKey) addSpawnedRuntimePrefetch(task, route.metadata.requestKey)
...@@ -1170,7 +1169,7 @@ function pingStaticHead( ...@@ -1170,7 +1169,7 @@ function pingStaticHead(
* dynamic holes are filled by the navigation-time request. * dynamic holes are filled by the navigation-time request.
* *
* Note: The runtime contract is affordable because most * Note: The runtime contract is affordable because most
* routes carry the ShouldAttemptStaticPrefetch hint: their segments are * routes carry the ShouldAttemptStatic{Shell,Prefetch} hints: their segments are
* prefetched statically and the responses' own sufficiency signal makes a * prefetched statically and the responses' own sufficiency signal makes a
* runtime request rare. On a hint-unset route, a walked segment deopts * runtime request rare. On a hint-unset route, a walked segment deopts
* directly to the batched runtime request. * directly to the batched runtime request.
...@@ -1184,12 +1183,40 @@ function walkRequiresRuntimeCompleteness( ...@@ -1184,12 +1183,40 @@ function walkRequiresRuntimeCompleteness(
staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell, staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell,
route: FulfilledRouteCacheEntry route: FulfilledRouteCacheEntry
): boolean { ): boolean {
if (staticWalkStrategy === FetchStrategy.StaticShell) {
// `FetchStrategy.StaticShell` is only used on PPF routes.
return true
}
// `FetchStrategy.PPR` can only use runtime requests if PPF is enabled on the route.
return ( return (
staticWalkStrategy === FetchStrategy.StaticShell ||
(route.tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 (route.tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0
) )
} }
/**
* Whether a static request for this segment should be attempted.
* This may vary on the static walk's strategy, because we might e.g.
* have a shell that's static, but a prefetch that requires runtime requests.
*
* NOTE: Should only be used on Partial Prefetching routes, where
* `walkCanUseRuntimeRequests` is true.
* */
function shouldSegmentAttemptStaticRequest(
staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell,
tree: RouteTree<any>
): boolean {
const { prefetchHints } = tree
switch (staticWalkStrategy) {
case FetchStrategy.StaticShell:
return (prefetchHints & PrefetchHint.ShouldAttemptStaticShell) !== 0
case FetchStrategy.PPR:
return (prefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch) !== 0
default:
staticWalkStrategy satisfies never
return false
}
}
/** /**
* The runtime counterpart of a pass's static walk strategy: the strategy the * The runtime counterpart of a pass's static walk strategy: the strategy the
* batched runtime request uses if this walk deopts. Each phase has exactly one * batched runtime request uses if this walk deopts. Each phase has exactly one
...@@ -1256,9 +1283,9 @@ function isShellEntryEligibleForStaticAttempt( ...@@ -1256,9 +1283,9 @@ function isShellEntryEligibleForStaticAttempt(
!( !(
(entry.fetchStrategy === FetchStrategy.StaticShell || (entry.fetchStrategy === FetchStrategy.StaticShell ||
entry.fetchStrategy === FetchStrategy.RuntimeShell) && entry.fetchStrategy === FetchStrategy.RuntimeShell) &&
(tree.prefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch) !== 0 && shouldSegmentAttemptStaticRequest(fetchStrategy, tree) &&
// A StaticShell walk's static attempt is the shell tier itself, so it // if the `fetchStrategy` is `FetchStrategy.PPR`, it might provide more content
// only applies when the walk's static strategy outranks the entry. // (e.g. static params that this shell doesn't have)
canNewFetchStrategyProvideMoreContent(entry.fetchStrategy, fetchStrategy) canNewFetchStrategyProvideMoreContent(entry.fetchStrategy, fetchStrategy)
) )
) { ) {
...@@ -1455,7 +1482,7 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1455,7 +1482,7 @@ function pingNewPartOfCacheComponentsTree(
// complete as a runtime response for every segment before the prefetch // complete as a runtime response for every segment before the prefetch
// can complete (see walkRequiresRuntimeCompleteness) — this function is // can complete (see walkRequiresRuntimeCompleteness) — this function is
// also the per-segment decision point. If the segment's node carries the // also the per-segment decision point. If the segment's node carries the
// ShouldAttemptStaticPrefetch hint (the build-time prerender accessed no // ShouldAttemptStatic{Shell,Prefetch} hints (the build-time prerender accessed no
// runtime data), its subtree is prefetched statically first, // runtime data), its subtree is prefetched statically first,
// and the responses themselves decide whether that was enough: every // and the responses themselves decide whether that was enough: every
// fulfilled entry carries a needsRuntimeRequest signal. Pending responses // fulfilled entry carries a needsRuntimeRequest signal. Pending responses
...@@ -1482,27 +1509,21 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1482,27 +1509,21 @@ function pingNewPartOfCacheComponentsTree(
// Constant for the whole pass; recomputed here only because the walk is // Constant for the whole pass; recomputed here only because the walk is
// recursive and the check is cheap. // recursive and the check is cheap.
const segmentRequiresRuntimeCompleteness = walkRequiresRuntimeCompleteness( const requiresRuntimeCompleteness = walkRequiresRuntimeCompleteness(
fetchStrategy, fetchStrategy,
route route
) )
// TODO: The static-attempt hint reflects the build-time prerender's whole
// runtime-data tracking, so a page that always accesses
// runtime data after the shell stage never attempts a static prefetch —
// even though its shell variant is rewindable at the shell boundary and
// perfectly reusable. The server could emit a second bit derived from the
// shell-stage value ("a static SHELL attempt is worthwhile even though
// the page accesses runtime data post-shell") to let such pages attempt
// static, too.
// A force-disabled segment deliberately does NOT deopt here: disabling // A force-disabled segment deliberately does NOT deopt here: disabling
// prefetch is passive. It never initiates a request — its accumulation // prefetch is passive. It never initiates a request — its accumulation
// below contributes nothing — and must never be the reason a runtime // below contributes nothing — and must never be the reason a runtime
// prefetch spawns, though it may ride along in a runtime response issued // prefetch spawns, though it may ride along in a runtime response issued
// on another segment's behalf. // on another segment's behalf.
const attemptStaticPrefetchOfSegment =
(tree.prefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch) !== 0
if (segmentRequiresRuntimeCompleteness && !attemptStaticPrefetchOfSegment) { if (
requiresRuntimeCompleteness &&
!shouldSegmentAttemptStaticRequest(fetchStrategy, tree)
) {
// Deopt directly to a runtime prefetch, without a static attempt. // Deopt directly to a runtime prefetch, without a static attempt.
addSpawnedRuntimePrefetch(task, tree.requestKey) addSpawnedRuntimePrefetch(task, tree.requestKey)
// If there's a pending static bundle from a parent, we need to finish // If there's a pending static bundle from a parent, we need to finish
...@@ -1533,7 +1554,7 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1533,7 +1554,7 @@ function pingNewPartOfCacheComponentsTree(
) )
const bundleInProgress = accumulation.bundle const bundleInProgress = accumulation.bundle
if (segmentRequiresRuntimeCompleteness && accumulation.needsRuntimeRequest) { if (requiresRuntimeCompleteness && accumulation.needsRuntimeRequest) {
// The static attempt for this segment was insufficient. Stop the walk // The static attempt for this segment was insufficient. Stop the walk
// and deopt — the runtime prefetch covers the whole subtree. (Unlike the // and deopt — the runtime prefetch covers the whole subtree. (Unlike the
// direct deopt above, any open bundle is dropped rather than finished: a // direct deopt above, any open bundle is dropped rather than finished: a
......
...@@ -337,6 +337,8 @@ import { isInstantValidationError } from './instant-validation/instant-validatio ...@@ -337,6 +337,8 @@ import { isInstantValidationError } from './instant-validation/instant-validatio
import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers' import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'
import { import {
RENDER_STAGES_BY_DATA_KIND, RENDER_STAGES_BY_DATA_KIND,
createPrerenderDataTracking,
finishPrerenderDataTracking,
trackIncompatibleShellContent, trackIncompatibleShellContent,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import type { import type {
...@@ -8893,8 +8895,7 @@ async function prerenderToStream( ...@@ -8893,8 +8895,7 @@ async function prerenderToStream(
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one // We don't track vary params during initial prerender, only the final one
varyParamsAccumulator: null, varyParamsAccumulator: null,
runtimeDataAccessed: null, prerenderDataTracking: null,
shouldAttemptStaticPrefetch: null,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
} }
...@@ -8930,8 +8931,7 @@ async function prerenderToStream( ...@@ -8930,8 +8931,7 @@ async function prerenderToStream(
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one // We don't track vary params during initial prerender, only the final one
varyParamsAccumulator: null, varyParamsAccumulator: null,
runtimeDataAccessed: null, prerenderDataTracking: null,
shouldAttemptStaticPrefetch: null,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
}) })
...@@ -9157,25 +9157,7 @@ async function prerenderToStream( ...@@ -9157,25 +9157,7 @@ async function prerenderToStream(
finalStage: RenderStage.Static, finalStage: RenderStage.Static,
}) })
// Records runtime data accesses from the payload and render stores const prerenderDataTracking = createPrerenderDataTracking()
// below into the RSC payload (as `u`), resolved `true` at the moment
// of first access so the fulfillment row is serialized at the stream
// position where it happened. Used when generating per-segment
// prefetch responses. Request data props (params, searchParams) are
// created while the RSC payload is constructed, under the payload
// store; both stores share the same promise so it observes accesses
// from both.
const runtimeDataAccessed = createPromiseWithResolvers<boolean>()
// Companion cell holding this prerender's static-prefetch measurement
// directly — the value that becomes the route's build-constant hint:
// starts true, and a disqualifying runtime-data access flips it false
// — fallback-param accesses on an upgradeable route don't (see
// trackRuntimeDataAccessed, which applies the rule at access time).
// Read after the prerender settles by
// collectSegmentData below. Shared between both stores for the same
// reason as the promise.
const shouldAttemptStaticPrefetch = { current: true }
const finalServerPayloadPrerenderStore: PrerenderStoreModernServer = { const finalServerPayloadPrerenderStore: PrerenderStoreModernServer = {
type: 'prerender', type: 'prerender',
...@@ -9203,8 +9185,7 @@ async function prerenderToStream( ...@@ -9203,8 +9185,7 @@ async function prerenderToStream(
resumeDataCache, resumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator, varyParamsAccumulator,
runtimeDataAccessed, prerenderDataTracking,
shouldAttemptStaticPrefetch,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
} }
...@@ -9233,7 +9214,7 @@ async function prerenderToStream( ...@@ -9233,7 +9214,7 @@ async function prerenderToStream(
// Embed the runtime data access tracking in the payload so // Embed the runtime data access tracking in the payload so
// collectSegmentData can replay it per stage. Only needed when the // collectSegmentData can replay it per stage. Only needed when the
// Flight data will be decomposed into segment prefetches below. // Flight data will be decomposed into segment prefetches below.
finalServerPayload.u = runtimeDataAccessed.promise finalServerPayload.u = prerenderDataTracking.runtimeDataAccessed.promise
const serverDynamicTracking = createDynamicTrackingState( const serverDynamicTracking = createDynamicTrackingState(
isDebugDynamicAccesses isDebugDynamicAccesses
...@@ -9259,8 +9240,7 @@ async function prerenderToStream( ...@@ -9259,8 +9240,7 @@ async function prerenderToStream(
resumeDataCache, resumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator, varyParamsAccumulator,
runtimeDataAccessed, prerenderDataTracking,
shouldAttemptStaticPrefetch,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
}) })
...@@ -9317,7 +9297,6 @@ async function prerenderToStream( ...@@ -9317,7 +9297,6 @@ async function prerenderToStream(
if (staleTimeIterable !== undefined) { if (staleTimeIterable !== undefined) {
staleTimeIterable.close() staleTimeIterable.close()
} }
runtimeDataAccessed.resolve(false)
finishAccumulatingVaryParams(varyParamsAccumulator) finishAccumulatingVaryParams(varyParamsAccumulator)
} }
} }
...@@ -9410,9 +9389,7 @@ async function prerenderToStream( ...@@ -9410,9 +9389,7 @@ async function prerenderToStream(
if (staleTimeIterable !== undefined) { if (staleTimeIterable !== undefined) {
staleTimeIterable.close() staleTimeIterable.close()
} }
// Idempotent: a no-op if a runtime data access already resolved it finishPrerenderDataTracking(prerenderDataTracking)
// `true`. The `false` row lands here, after all stage content.
runtimeDataAccessed.resolve(false)
finishAccumulatingVaryParams(varyParamsAccumulator) finishAccumulatingVaryParams(varyParamsAccumulator)
shellByteLengthDeferred.resolve( shellByteLengthDeferred.resolve(
...@@ -9467,6 +9444,16 @@ async function prerenderToStream( ...@@ -9467,6 +9444,16 @@ async function prerenderToStream(
? metadata.flightData.subarray(1) ? metadata.flightData.subarray(1)
: metadata.flightData : metadata.flightData
if (process.env.NEXT_PRIVATE_DEBUG_RUNTIME_DATA) {
const {
shouldAttemptStaticShell: shellIsStatic,
shouldAttemptStaticPrefetch: prefetchIsStatic,
} = prerenderDataTracking
const label = (isStatic: boolean) => (isStatic ? 'static' : 'runtime')
console.log(
`Route ${workStore.route} :: hints: shell=${label(shellIsStatic)}, prefetch=${label(prefetchIsStatic)}`
)
}
await collectSegmentData( await collectSegmentData(
flightData, flightData,
finalServerPrerenderStore, finalServerPrerenderStore,
...@@ -9979,8 +9966,7 @@ async function prerenderToStream( ...@@ -9979,8 +9966,7 @@ async function prerenderToStream(
resumeDataCache: originalResumeDataCache, resumeDataCache: originalResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator: null, varyParamsAccumulator: null,
runtimeDataAccessed: null, prerenderDataTracking: null,
shouldAttemptStaticPrefetch: null,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
} }
...@@ -10642,20 +10628,22 @@ async function collectSegmentData( ...@@ -10642,20 +10628,22 @@ async function collectSegmentData(
let hints: PrefetchHints | null let hints: PrefetchHints | null
const prefetchInlining = renderOpts.experimental.prefetchInlining const prefetchInlining = renderOpts.experimental.prefetchInlining
if (renderOpts.isBuildTimePrerendering) { if (renderOpts.isBuildTimePrerendering) {
// Whether the client should attempt a static prefetch for this route // Whether the client should attempt to use static requests for
// (PrefetchHint.ShouldAttemptStaticPrefetch): the prerender store's // shells and prefetches. Only applies in routes with Partial Prefetching.
// cell holds the hint value directly — true iff the build-time const prerenderDataTracking =
// prerender accessed no runtime data that disqualifies a static
// attempt. The fallback-param upgradeability rule is applied at access
// time — see trackRuntimeDataAccessed — so only the settled value is
// read here. Only the modern (cacheComponents) prerender tracks
// accesses; legacy prerenders conservatively never set the hint.
const hintCell =
prerenderStore.type === 'prerender' prerenderStore.type === 'prerender'
? prerenderStore.shouldAttemptStaticPrefetch ? prerenderStore.prerenderDataTracking
: null : null
const shouldAttemptStaticPrefetch = hintCell !== null && hintCell.current const {
if (prefetchInlining || shouldAttemptStaticPrefetch) { shouldAttemptStaticShell = false,
shouldAttemptStaticPrefetch = false,
} = prerenderDataTracking ?? {}
if (
prefetchInlining ||
shouldAttemptStaticShell ||
shouldAttemptStaticPrefetch
) {
// Build time: compute fresh hints and store in metadata for the // Build time: compute fresh hints and store in metadata for the
// manifest. When prefetch inlining is disabled there are no sizes to // manifest. When prefetch inlining is disabled there are no sizes to
// measure, but the static-prefetch hint still rides the manifest — // measure, but the static-prefetch hint still rides the manifest —
...@@ -10667,6 +10655,7 @@ async function collectSegmentData( ...@@ -10667,6 +10655,7 @@ async function collectSegmentData(
clientModules, clientModules,
serverConsumerManifest, serverConsumerManifest,
prefetchInlining, prefetchInlining,
shouldAttemptStaticShell,
shouldAttemptStaticPrefetch shouldAttemptStaticPrefetch
) )
metadata.prefetchHints = hints metadata.prefetchHints = hints
......
...@@ -364,7 +364,7 @@ export async function collectSegmentData( ...@@ -364,7 +364,7 @@ export async function collectSegmentData(
* decisions can be fed back into collectSegmentData to control which segments * decisions can be fed back into collectSegmentData to control which segments
* are output as separate entries vs. inlined into their parent. * are output as separate entries vs. inlined into their parent.
* *
* `shouldAttemptStaticPrefetch` (computed by the caller from the prerender's * `shouldAttemptStatic{Shell,Prefetch}` (computed by the caller from the prerender's
* runtime-data tracking) is folded onto every node of the result, so the * runtime-data tracking) is folded onto every node of the result, so the
* manifest delivers it to every response like the other hint bits. It's * manifest delivers it to every response like the other hint bits. It's
* independent of the inlining feature: when `inlining` is false the sizing * independent of the inlining feature: when `inlining` is false the sizing
...@@ -384,6 +384,7 @@ export async function collectPrefetchHints( ...@@ -384,6 +384,7 @@ export async function collectPrefetchHints(
clientModules: ManifestNode, clientModules: ManifestNode,
serverConsumerManifest: any, serverConsumerManifest: any,
inlining: { maxSize: number; maxBundleSize: number } | false, inlining: { maxSize: number; maxBundleSize: number } | false,
shouldAttemptStaticShell: boolean,
shouldAttemptStaticPrefetch: boolean shouldAttemptStaticPrefetch: boolean
): Promise<PrefetchHints> { ): Promise<PrefetchHints> {
// Warm up the module cache, same as collectSegmentData. // Warm up the module cache, same as collectSegmentData.
...@@ -409,13 +410,18 @@ export async function collectPrefetchHints( ...@@ -409,13 +410,18 @@ export async function collectPrefetchHints(
const buildId = initialRSCPayload.b const buildId = initialRSCPayload.b
const head = transportData.h.r const head = transportData.h.r
// The hints every node starts from. The static-prefetch-attempt hint is // The hints every node starts from. The static-prefetch-attempt hints are
// page-global (the tracking that feeds it is), so it goes on every node, // page-global (the tracking that creates them is), so they go on every node,
// non-propagating — the client reads it per segment, and the runtime // non-propagating — the client reads it per segment, and the runtime
// hint merging walks the manifest tree node-by-node. // hint merging walks the manifest tree node-by-node.
const baseHints = shouldAttemptStaticPrefetch // (NOTE: if the prefetch is static, then the shell must be as well)
? PrefetchHint.ShouldAttemptStaticPrefetch let baseHints = 0
: 0 if (shouldAttemptStaticShell) {
baseHints |= PrefetchHint.ShouldAttemptStaticShell
}
if (shouldAttemptStaticPrefetch) {
baseHints |= PrefetchHint.ShouldAttemptStaticPrefetch
}
if (inlining === false) { if (inlining === false) {
// Prefetch inlining is disabled: nothing to measure, and no inlining // Prefetch inlining is disabled: nothing to measure, and no inlining
...@@ -1030,11 +1036,10 @@ function collectSegmentDataImpl( ...@@ -1030,11 +1036,10 @@ function collectSegmentDataImpl(
// response as-is. Root params are forwarded separately, once per response. // response as-is. Root params are forwarded separately, once per response.
const varyParams = node.d.v const varyParams = node.d.v
// If static prefetching is disabled for this segment // If static prefetching is disabled for this segment (prefetch: 'force-disabled'),
// (prefetch: 'force-disabled' / instant = false), it still participates in // it still participates in the bundle chain but with null data.
// the bundle chain but with null data. Its node in the response tree // Its node in the response tree carries identity only, so the client skips
// carries identity only, so the client skips creating a cache entry // creating a cache entry for it.
// for it.
// //
// Partial Prefetching segments are NOT disabled even though they may need // Partial Prefetching segments are NOT disabled even though they may need
// a runtime prefetch: their static data is emitted UNCONDITIONALLY, so the // a runtime prefetch: their static data is emitted UNCONDITIONALLY, so the
......
...@@ -35,10 +35,7 @@ import React from 'react' ...@@ -35,10 +35,7 @@ import React from 'react'
import { DynamicServerError } from '../../client/components/hooks-server-context' import { DynamicServerError } from '../../client/components/hooks-server-context'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { getStagedRenderingController } from './work-unit-async-storage.external' import { getStagedRenderingController } from './work-unit-async-storage.external'
import { import { isClientHookDynamicError } from '../dynamic-rendering-utils'
isClientHookDynamicError,
trackRuntimeDataAccessed,
} from '../dynamic-rendering-utils'
import { import {
METADATA_BOUNDARY_NAME, METADATA_BOUNDARY_NAME,
VIEWPORT_BOUNDARY_NAME, VIEWPORT_BOUNDARY_NAME,
...@@ -348,15 +345,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess( ...@@ -348,15 +345,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
errorWithStack: Error, errorWithStack: Error,
prerenderStore: PrerenderStoreModern prerenderStore: PrerenderStoreModern
): never { ): never {
// The synchronously accessed request data would have been available during
// a runtime prerender, which would have rendered past this point instead of
// aborting — so a runtime prefetch would produce more content than this
// render. Record that, same as when request data access creates a hanging
// promise (see makeRuntimeHangingPromise). Unlike
// `abortOnSynchronousPlatformIOAccess`, which aborts a runtime prerender
// all the same and therefore must not record anything.
trackRuntimeDataAccessed(prerenderStore, expression)
const prerenderSignal = prerenderStore.controller.signal const prerenderSignal = prerenderStore.controller.signal
if (prerenderSignal.aborted === false) { if (prerenderSignal.aborted === false) {
// TODO it would be better to move this aborted check into the callsite so we can avoid making // TODO it would be better to move this aborted check into the callsite so we can avoid making
......
...@@ -113,6 +113,11 @@ export class StagedRenderingController { ...@@ -113,6 +113,11 @@ export class StagedRenderingController {
} }
} }
/**
* Schedules a callback that will execute synchronously when the controller is advanced
* to `stage` or past it, before any promises for that stage are resolved.
* If the controller is already past `stage`, the callback is executed immediately.
* */
onStage(stage: AdvanceableRenderStage, callback: () => void) { onStage(stage: AdvanceableRenderStage, callback: () => void) {
addSyncTriggerListener(this.triggers[stage], callback) addSyncTriggerListener(this.triggers[stage], callback)
} }
......
...@@ -22,6 +22,7 @@ import type { ...@@ -22,6 +22,7 @@ import type {
} from './staged-rendering' } from './staged-rendering'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking' import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples' import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
import type { PrerenderDataTracking } from '../dynamic-rendering-utils'
export type WorkUnitPhase = 'action' | 'render' | 'after' export type WorkUnitPhase = 'action' | 'render' | 'after'
...@@ -177,53 +178,23 @@ export interface PrerenderStoreModernServer ...@@ -177,53 +178,23 @@ export interface PrerenderStoreModernServer
readonly stagedRendering: StagedRenderingController | null readonly stagedRendering: StagedRenderingController | null
/** /*
* When not null, records whether the render has accessed a data source * Records usages of non-static data during a prerender to determine
* that hangs during a static prerender but would resolve during a runtime * whether it should be statically optimized.
* prerender — cookies, headers, fallback params, searchParams, and cache * Includes:
* entries excluded only from static prerenders. Call sites go through * - session data (`cookies()`, `headers()`)
* `trackRuntimeDataAccessed`, which resolves the promise `true` on the * - URL data (`params`, `searchParams`)
* first access; it's resolved `false` when the prerender completes without
* one. Promise resolution is idempotent, so the flag is monotonic with no
* extra state.
* *
* The promise is embedded in the RSC payload (`InitialRSCPayload['u']`) * Only intended to be used during the final prerender of a page.
* so the fulfillment row's stream position records the stage the access * */
* happened in; the per-segment prefetch encoding (`collectSegmentData`) readonly prerenderDataTracking: PrerenderDataTracking | null
* extracts it from the page data to tell the client whether a runtime
* prefetch request could be skipped. Tracking is page-global: an access
* anywhere in the page poisons all segments (per-segment granularity is
* recovered downstream for segments whose content is provably complete).
* Shared between the payload prerender store and the render store because
* request-data props are created during payload construction, before the
* render store exists. Null for warmup, route-handler, and error prerender
* stores.
*/
readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null
/**
* Mutable single-boolean companion to `runtimeDataAccessed`, holding this
* prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement
* directly — the value that becomes the route's build-constant hint:
* starts `true`, and a disqualifying runtime-data access flips it to
* `false`. Not every access that resolves the promise disqualifies —
* fallback-param accesses on a fallback-upgradeable route are transient
* and leave the hint intact (see `trackRuntimeDataAccessed`, which applies
* the rule at access time using `isFallbackUpgradeable` below). A plain
* boolean suffices because the hint needs no stream positioning: unlike
* `runtimeDataAccessed`, whose fulfillment position encodes which stage
* the access happened in, this is read once after the prerender settles.
* Held in a cell so it can be shared. Same sharing and null rules as
* `runtimeDataAccessed`.
*/
readonly shouldAttemptStaticPrefetch: { current: boolean } | null
/** /**
* Whether a fallback shell produced by this prerender could later be * Whether a fallback shell produced by this prerender could later be
* upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`: * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:
* at least one fallback param is a `generateStaticParams` candidate). * at least one fallback param is a `generateStaticParams` candidate).
* Consulted by `trackRuntimeDataAccessed` to decide whether a * Used to decide whether a fallback-param access indicates that a
* fallback-param access disqualifies the static-prefetch hint. * runtime prefetch should be used.
*/ */
readonly isFallbackUpgradeable: boolean readonly isFallbackUpgradeable: boolean
} }
......
...@@ -21,7 +21,7 @@ import { ...@@ -21,7 +21,7 @@ import {
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { import {
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeRuntimeHangingPromise, makeSessionDataHangingPromise,
RENDER_STAGES_BY_DATA_KIND, RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
...@@ -165,7 +165,7 @@ function makeHangingCookies( ...@@ -165,7 +165,7 @@ function makeHangingCookies(
return cachedPromise return cachedPromise
} }
const promise = makeRuntimeHangingPromise<ReadonlyRequestCookies>( const promise = makeSessionDataHangingPromise<ReadonlyRequestCookies>(
prerenderStore.renderSignal, prerenderStore.renderSignal,
workStore.route, workStore.route,
'`cookies()`', '`cookies()`',
......
...@@ -19,7 +19,7 @@ import { ...@@ -19,7 +19,7 @@ import {
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { import {
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeRuntimeHangingPromise, makeSessionDataHangingPromise,
RENDER_STAGES_BY_DATA_KIND, RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
...@@ -169,7 +169,7 @@ function makeHangingHeaders( ...@@ -169,7 +169,7 @@ function makeHangingHeaders(
return cachedHeaders return cachedHeaders
} }
const promise = makeRuntimeHangingPromise<ReadonlyHeaders>( const promise = makeSessionDataHangingPromise<ReadonlyHeaders>(
prerenderStore.renderSignal, prerenderStore.renderSignal,
workStore.route, workStore.route,
'`headers()`', '`headers()`',
......
...@@ -95,9 +95,7 @@ function createPrerenderPathname( ...@@ -95,9 +95,7 @@ function createPrerenderPathname(
case 'prerender': { case 'prerender': {
const fallbackParams = prerenderStore.fallbackRouteParams const fallbackParams = prerenderStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) { if (fallbackParams && fallbackParams.size > 0) {
// The pathname only hangs when there are fallback params, and a // The pathname depends on params, so we track it like a fallback params access.
// concrete (ISR-upgraded) prerender resolves it — so this access is
// fallback-param data for the static-prefetch hint.
return makeFallbackParamsHangingPromise<string>( return makeFallbackParamsHangingPromise<string>(
prerenderStore.renderSignal, prerenderStore.renderSignal,
workStore.route, workStore.route,
......
...@@ -28,9 +28,9 @@ import { ...@@ -28,9 +28,9 @@ import {
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { import {
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeRuntimeHangingPromise, makeURLDataHangingPromise,
makePromiseFromTrigger, makePromiseFromTrigger,
trackRuntimeDataAccessed, trackURLDataAccessed,
RENDER_STAGES_BY_DATA_KIND, RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
...@@ -175,7 +175,7 @@ export function createPrerenderSearchParamsForClientPage(): Promise<SearchParams ...@@ -175,7 +175,7 @@ export function createPrerenderSearchParamsForClientPage(): Promise<SearchParams
case 'prerender-client': case 'prerender-client':
// We're prerendering in a mode that aborts (cacheComponents) and should stall // We're prerendering in a mode that aborts (cacheComponents) and should stall
// the promise to ensure the RSC side is considered dynamic // the promise to ensure the RSC side is considered dynamic
return makeRuntimeHangingPromise( return makeURLDataHangingPromise(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
'`searchParams`', '`searchParams`',
...@@ -221,9 +221,10 @@ function createStaticPrerenderSearchParams( ...@@ -221,9 +221,10 @@ function createStaticPrerenderSearchParams(
switch (prerenderStore.type) { switch (prerenderStore.type) {
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client': {
// We are in a cacheComponents (PPR or otherwise) prerender // We are in a cacheComponents (PPR or otherwise) prerender
return makeHangingSearchParams(workStore, prerenderStore) return makeHangingSearchParams(workStore, prerenderStore)
}
case 'prerender-legacy': case 'prerender-legacy':
// We are in a legacy static generation and need to interrupt the // We are in a legacy static generation and need to interrupt the
// prerender when search params are accessed. // prerender when search params are accessed.
...@@ -382,7 +383,7 @@ function makeHangingSearchParams( ...@@ -382,7 +383,7 @@ function makeHangingSearchParams(
return cachedSearchParams return cachedSearchParams
} }
const promise = makeRuntimeHangingPromise<SearchParams>( const promise = makeURLDataHangingPromise<SearchParams>(
prerenderStore.renderSignal, prerenderStore.renderSignal,
workStore.route, workStore.route,
'`searchParams`', '`searchParams`',
...@@ -397,7 +398,7 @@ function makeHangingSearchParams( ...@@ -397,7 +398,7 @@ function makeHangingSearchParams(
// created while the RSC payload is constructed, but typically accessed // created while the RSC payload is constructed, but typically accessed
// later, during the render, under a different store. // later, during the render, under a different store.
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
trackRuntimeDataAccessed(workUnitStore ?? prerenderStore, '`searchParams`') trackURLDataAccessed(workUnitStore ?? prerenderStore, '`searchParams`')
} }
const proxyHandler: ProxyHandler<Promise<SearchParams>> = { const proxyHandler: ProxyHandler<Promise<SearchParams>> = {
......
...@@ -597,8 +597,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -597,8 +597,7 @@ export class AppRouteRouteModule extends RouteModule<
resumeDataCache: prerenderResumeDataCache, resumeDataCache: prerenderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator: null, varyParamsAccumulator: null,
runtimeDataAccessed: null, prerenderDataTracking: null,
shouldAttemptStaticPrefetch: null,
isFallbackUpgradeable: false, isFallbackUpgradeable: false,
}) })
...@@ -696,8 +695,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -696,8 +695,7 @@ export class AppRouteRouteModule extends RouteModule<
resumeDataCache: prerenderResumeDataCache, resumeDataCache: prerenderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator: null, varyParamsAccumulator: null,
runtimeDataAccessed: null, prerenderDataTracking: null,
shouldAttemptStaticPrefetch: null,
isFallbackUpgradeable: false, isFallbackUpgradeable: false,
}) })
......
...@@ -42,9 +42,11 @@ import { ...@@ -42,9 +42,11 @@ import {
applyOwnerStack, applyOwnerStack,
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeDynamicHangingPromise, makeDynamicHangingPromise,
makeRuntimeHangingPromise,
makePrefetchHangingPromise,
makeUntrackedHangingPromise, makeUntrackedHangingPromise,
makeSessionDataHangingPromise,
makeURLDataHangingPromise,
makePrefetchHangingPromise,
makeUnknownRuntimeDataHangingPromise,
RENDER_STAGES_BY_DATA_KIND, RENDER_STAGES_BY_DATA_KIND,
trackIncompatibleShellContent, trackIncompatibleShellContent,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
...@@ -1457,8 +1459,9 @@ async function generateCacheEntryImpl( ...@@ -1457,8 +1459,9 @@ async function generateCacheEntryImpl(
// If the prerender is aborted because of dynamic access (e.g. reading // If the prerender is aborted because of dynamic access (e.g. reading
// fallback params), we return a hanging promise. This essentially makes // fallback params), we return a hanging promise. This essentially makes
// the "use cache" function dynamic. // the "use cache" function dynamic.
// The dynamic access is a fallback params read, which is runtime data. // The dynamic access means reading either params or searchParams,
const hangingPromise = makeRuntimeHangingPromise<never>( // both of which are URL data.
const hangingPromise = makeURLDataHangingPromise<never>(
outerWorkUnitStore.renderSignal, outerWorkUnitStore.renderSignal,
workStore.route, workStore.route,
'dynamic "use cache"', 'dynamic "use cache"',
...@@ -1883,8 +1886,11 @@ export async function cache( ...@@ -1883,8 +1886,11 @@ export async function cache(
switch (workUnitStore.type) { switch (workUnitStore.type) {
// "use cache: private" is dynamic in prerendering contexts. // "use cache: private" is dynamic in prerendering contexts.
case 'prerender': case 'prerender':
// Private caches can read request data, which is runtime data. // Private caches can read request data. At this point we don't know
return makeRuntimeHangingPromise( // Whether it's going to use session data or URL data.
// TODO(app-shells): This could be narrowed (and thus optimized) if we checked whether URL data
// is included in the cache key, because it can only be passed in as arguments.
return makeUnknownRuntimeDataHangingPromise(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
expression, expression,
...@@ -2194,9 +2200,9 @@ export async function cache( ...@@ -2194,9 +2200,9 @@ export async function cache(
) )
if (dynamicAccessAbortController.signal.aborted) { if (dynamicAccessAbortController.signal.aborted) {
// The dynamic access is a fallback params read, which is runtime // The dynamic access is means the arguments contain either
// data. // params or searchParams, which are URL data.
return makeRuntimeHangingPromise( return makeURLDataHangingPromise(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
'dynamic "use cache"', 'dynamic "use cache"',
...@@ -2340,8 +2346,10 @@ export async function cache( ...@@ -2340,8 +2346,10 @@ export async function cache(
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
// The cache key was marked dynamic because it depends on fallback // The cache key was marked dynamic because it depends on fallback
// params, which are runtime data. // params or search params, which are URL data.
return makeRuntimeHangingPromise( // (Note that this can still occur in a runtime prerender for a runtime shell,
// which does not have access to params or searchParams)
return makeURLDataHangingPromise(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
'dynamic "use cache"', 'dynamic "use cache"',
...@@ -2462,9 +2470,9 @@ export async function cache( ...@@ -2462,9 +2470,9 @@ export async function cache(
cacheSignal.endRead() cacheSignal.endRead()
} }
// The entry is only excluded from *static* prerenders — the // The entry is only excluded from *static* prerenders — the
// 'prerender-runtime' case below serves it — so a runtime // 'prerender-runtime' case below serves it.
// prefetch would include this content. // TODO(app-shells): Does this handle the MIN_SHELL_STALE case below correctly?
return makeRuntimeHangingPromise( return makeSessionDataHangingPromise(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
'dynamic "use cache"', 'dynamic "use cache"',
...@@ -2762,9 +2770,8 @@ export async function cache( ...@@ -2762,9 +2770,8 @@ export async function cache(
// also do here, this covers the case where params are transformed // also do here, this covers the case where params are transformed
// with an async function before being passed into the "use cache" // with an async function before being passed into the "use cache"
// function, which escapes the instrumentation. // function, which escapes the instrumentation.
// The cache key depends on fallback params, which are runtime // The cache key depends on fallback params, which are URL data.
// data. return makeURLDataHangingPromise(
return makeRuntimeHangingPromise(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
'dynamic "use cache"', 'dynamic "use cache"',
...@@ -2784,10 +2791,8 @@ export async function cache( ...@@ -2784,10 +2791,8 @@ export async function cache(
// broken cache entry that gets aborted. // broken cache entry that gets aborted.
console.warn(new UnexpectedCacheMissError(workStore.route)) console.warn(new UnexpectedCacheMissError(workStore.route))
// This is an anomaly (non-deterministic cache key), so we can't // This is an anomaly (non-deterministic cache key), so we can't
// know whether a runtime prerender would resolve it. Treat it as // know whether a runtime prerender would resolve it.
// runtime data, conservatively: the cost is at most a redundant return makeUnknownRuntimeDataHangingPromise(
// runtime prefetch request.
return makeRuntimeHangingPromise(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
'dynamic "use cache"', 'dynamic "use cache"',
...@@ -3197,10 +3202,10 @@ export async function cache( ...@@ -3197,10 +3202,10 @@ export async function cache(
cacheSignal.endRead() cacheSignal.endRead()
} }
// The entry is only excluded from *static* prerenders — the // The entry is only excluded from *static* prerenders. A runtime
// 'prerender-runtime' case below serves it — so a runtime // shell or prefetch would include this content.
// prefetch would include this content. // TODO(app-shells): Does this handle the MIN_SHELL_STALE case below correctly?
const hangingPromise = makeRuntimeHangingPromise<never>( const hangingPromise = makeSessionDataHangingPromise<never>(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
'dynamic "use cache"', 'dynamic "use cache"',
......
...@@ -277,15 +277,16 @@ export const enum PrefetchHint { ...@@ -277,15 +277,16 @@ export const enum PrefetchHint {
// navigations alike. (Routes missing from the manifest — see the #91407 // navigations alike. (Routes missing from the manifest — see the #91407
// fallbacks — simply never carry it.) Set on every node of the tree, but // fallbacks — simply never carry it.) Set on every node of the tree, but
// does not propagate. // does not propagate.
ShouldAttemptStaticPrefetch = 0b100000000000000, ShouldAttemptStaticShell = 0b100000000000000,
ShouldAttemptStaticPrefetch = 0b1000000000000000,
// This dynamic segment only accepts build-time parameter values. Kept on // This dynamic segment only accepts build-time parameter values. Kept on
// the affected node, without propagating or copying it to other segments. // the affected node, without propagating or copying it to other segments.
// Until the client knows the allowed values, any such node prevents route // Until the client knows the allowed values, any such node prevents route
// prediction, even when the route's components never read the parameter. // prediction, even when the route's components never read the parameter.
IsClosedParam = 0b1000000000000000, IsClosedParam = 0b10000000000000000,
// A descendant segment (but not this one) has a closed parameter. Propagates // A descendant segment (but not this one) has a closed parameter. Propagates
// upward so route prediction can check the root instead of walking the tree. // upward so route prediction can check the root instead of walking the tree.
SubtreeHasClosedParams = 0b10000000000000000, SubtreeHasClosedParams = 0b100000000000000000,
} }
/** /**
...@@ -297,17 +298,21 @@ export const enum PrefetchHint { ...@@ -297,17 +298,21 @@ export const enum PrefetchHint {
* Static prefetching is disabled ONLY by `prefetch: 'force-disabled'` * Static prefetching is disabled ONLY by `prefetch: 'force-disabled'`
* (PrefetchDisabled). Notably, Partial Prefetching segments DO have static * (PrefetchDisabled). Notably, Partial Prefetching segments DO have static
* data even though they require runtime completeness: the server emits it * data even though they require runtime completeness: the server emits it
* unconditionally — it can't be gated on the ShouldAttemptStaticPrefetch * unconditionally — it can't be gated on the ShouldAttemptStatic{Shell,Prefetch}
* hint, because which segments carry static data must be deterministic * hints, because which segments carry static data must be deterministic
* from build-time config. A runtime request may still be needed for the * from build-time config. A runtime request may still be needed for the
* segment, but the scheduler may attempt a static prefetch first (per the * segment, but the scheduler may attempt a static prefetch first (per the
* ShouldAttemptStaticPrefetch hint) and skip the runtime request if the * ShouldAttemptStatic{Shell,Prefetch} hints) and skip the runtime request if the
* static response proves sufficient. * static response proves sufficient.
* *
* Usage: `(hints & StaticPrefetchDisabled) !== 0` * Usage: `(hints & StaticPrefetchDisabled) !== 0`
*/ */
export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled
export const StaticAttemptHints =
PrefetchHint.ShouldAttemptStaticShell |
PrefetchHint.ShouldAttemptStaticPrefetch
/** /**
* The subset of PrefetchHint bits that propagate upward from a child segment to * The subset of PrefetchHint bits that propagate upward from a child segment to
* its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary * its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary
...@@ -438,11 +443,9 @@ export type InitialRSCPayload = { ...@@ -438,11 +443,9 @@ export type InitialRSCPayload = {
* Unlike an async iterable, a pending promise costs Flight no abort * Unlike an async iterable, a pending promise costs Flight no abort
* listener on the render. Used when generating per-segment prefetch * listener on the render. Used when generating per-segment prefetch
* responses (forwarded as each response's own `u`). * responses (forwarded as each response's own `u`).
* The build-constant `PrefetchHint.ShouldAttemptStaticPrefetch` is * The build-time constant `PrefetchHint.ShouldAttemptStatic{Shell,Prefetch}`
* tracked directly on the prerender store instead (its * hint is tracked separately.
* `shouldAttemptStaticPrefetch` cell) — it needs neither stream * Only present for static prerenders when Cache Components is enabled.
* positioning nor this flag's param/non-param blindness. Only present
* for static prerenders when Cache Components is enabled.
*/ */
u?: Promise<boolean> u?: Promise<boolean>
/** staticStageByteLength - Resolves when the static stage ends. */ /** staticStageByteLength - Resolves when the static stage ends. */
......
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import type { PrerenderManifest } from 'next/dist/build' import type { PrerenderManifest } from 'next/dist/build'
import type { FlightRouterState } from 'next/dist/shared/lib/app-router-types' import {
type FlightRouterState,
PrefetchHint,
} from 'next/dist/shared/lib/app-router-types'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
describe('segment cache closed params (dynamicParams = false)', () => { describe('segment cache closed params (dynamicParams = false)', () => {
...@@ -14,33 +17,43 @@ describe('segment cache closed params (dynamicParams = false)', () => { ...@@ -14,33 +17,43 @@ describe('segment cache closed params (dynamicParams = false)', () => {
) { ) {
// If this private tree representation changes, reconstruct the regression // If this private tree representation changes, reconstruct the regression
// rather than preserving or exposing router internals just for this test. // rather than preserving or exposing router internals just for this test.
return browser.eval(() => { return browser.eval(
const closedSegments: string[] = [] (IsClosedParam: number) => {
function visit(tree: FlightRouterState) { const closedSegments: string[] = []
// PrefetchHint.IsClosedParam is a const enum bit. Check every node so function visit(tree: FlightRouterState) {
// stamping the root, static segments, or page nodes also fails. // PrefetchHint.IsClosedParam is a const enum bit. Check every node so
if (((tree[4] ?? 0) & 0b1000000000000000) !== 0) { // stamping the root, static segments, or page nodes also fails.
const segment = tree[0] if (((tree[4] ?? 0) & IsClosedParam) !== 0) {
closedSegments.push( const segment = tree[0]
typeof segment === 'string' ? segment : `[${segment[0]}]` closedSegments.push(
) typeof segment === 'string' ? segment : `[${segment[0]}]`
)
}
for (const child of Object.values(tree[1])) visit(child)
} }
for (const child of Object.values(tree[1])) visit(child) visit(window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE.tree)
} return closedSegments
visit(window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE.tree) },
return closedSegments // Client code in the closure cannot access this imported value,
}) // so we have to pass it in
PrefetchHint.IsClosedParam
)
} }
async function hasClosedParamDescendants( async function hasClosedParamDescendants(
browser: Awaited<ReturnType<typeof next.browser>> browser: Awaited<ReturnType<typeof next.browser>>
) { ) {
return browser.eval(() => { return browser.eval(
const tree: FlightRouterState = (SubtreeHasClosedParams: number) => {
window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE.tree const tree: FlightRouterState =
// PrefetchHint.SubtreeHasClosedParams summarizes descendants at the root. window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE.tree
return ((tree[4] ?? 0) & 0b10000000000000000) !== 0 // PrefetchHint.SubtreeHasClosedParams summarizes descendants at the root.
}) return ((tree[4] ?? 0) & SubtreeHasClosedParams) !== 0
},
// Client code in the closure cannot access this imported value,
// so we have to pass it in
PrefetchHint.SubtreeHasClosedParams
)
} }
// @force-gate prefetching // @force-gate prefetching
......
...@@ -47,6 +47,44 @@ export default async function Page() { ...@@ -47,6 +47,44 @@ export default async function Page() {
</LinkAccordion> </LinkAccordion>
</li> </li>
</ul> </ul>
<h2>First cookies only used in the prefetch, then also in the shell</h2>
<ul>
<li data-prefetch="auto">
<LinkAccordion href="/partial-conditional-cookies-in-both/first-prefetch-then-shell">
/partial-conditional-cookies-in-both/first-prefetch-then-shell (auto
prefetch)
</LinkAccordion>
</li>
<li data-prefetch="true">
<LinkAccordion
href="/partial-conditional-cookies-in-both/first-prefetch-then-shell"
prefetch={true}
>
/partial-conditional-cookies-in-both/first-prefetch-then-shell
(prefetch=true)
</LinkAccordion>
</li>
</ul>
<h2>First cookies used in the shell, then also in the prefetch</h2>
<ul>
<li data-prefetch="auto">
<LinkAccordion href="/partial-conditional-cookies-in-both/first-shell-then-prefetch">
/partial-conditional-cookies-in-both/first-shell-then-prefetch (auto
prefetch)
</LinkAccordion>
</li>
<li data-prefetch="true">
<LinkAccordion
href="/partial-conditional-cookies-in-both/first-shell-then-prefetch"
prefetch={true}
>
/partial-conditional-cookies-in-both/first-shell-then-prefetch
(prefetch=true)
</LinkAccordion>
</li>
</ul>
</main> </main>
) )
} }
import { getCachedValue, CookieData } from '../../../cached-value'
import { Suspense } from 'react'
import { connection } from 'next/server'
import { unstable_prefetch } from 'next/cache'
export default async function Page() {
const cachedValue = await getCachedValue()
// The tag is "original" during build and switches to "updated" after revalidation.
const shouldUseCookiesInShell = cachedValue.tag !== 'original'
return (
<main>
<h1>
Partial page that uses cookies in the prefetch at build, but starts
using them in the shell after a revalidation (which makes the shell
become not static)
</h1>
<p>{`Cached value: ${cachedValue.tag}, cookies used in ${shouldUseCookiesInShell ? 'shell' : 'prefetch'}`}</p>
{shouldUseCookiesInShell ? (
<CookieData label="in shell" />
) : (
<p>No cookies used in the shell</p>
)}
<Suspense
fallback={
<div id="prefetch-data-fallback">Loading prefetch data...</div>
}
>
<PrefetchOnly>
<div id="prefetch-data">Prefetch data</div>
{!shouldUseCookiesInShell && <CookieData label="in prefetch" />}
</PrefetchOnly>
</Suspense>
<Suspense
fallback={<div id="dynamic-data-fallback">Loading dynamic data...</div>}
>
<DynamicData />
</Suspense>
</main>
)
}
async function PrefetchOnly({ children }) {
await unstable_prefetch()
return children
}
async function DynamicData() {
await connection()
return <div id="dynamic-data">Dynamic data</div>
}
import { getCachedValue, CookieData } from '../../../cached-value'
import { Suspense } from 'react'
import { connection } from 'next/server'
import { unstable_prefetch } from 'next/cache'
export default async function Page() {
const cachedValue = await getCachedValue()
// The tag is "original" during build and switches to "updated" after revalidation.
const shouldUseCookiesInShell = cachedValue.tag === 'original'
return (
<main>
<h1>
Partial page that uses cookies in the shell at build, but starts using
them only the prefetch after a revalidation (which makes the shell
become static)
</h1>
<p>{`Cached value: ${cachedValue.tag}, cookies used in ${shouldUseCookiesInShell ? 'shell' : 'prefetch'}`}</p>
{shouldUseCookiesInShell ? (
<CookieData label="in shell" />
) : (
<p>No cookies used in the shell</p>
)}
<Suspense
fallback={
<div id="prefetch-data-fallback">Loading prefetch data...</div>
}
>
<PrefetchOnly>
<div id="prefetch-data">Prefetch data</div>
{!shouldUseCookiesInShell && <CookieData label="in prefetch" />}
</PrefetchOnly>
</Suspense>
<Suspense
fallback={<div id="dynamic-data-fallback">Loading dynamic data...</div>}
>
<DynamicData />
</Suspense>
</main>
)
}
async function PrefetchOnly({ children }) {
await unstable_prefetch()
return children
}
async function DynamicData() {
await connection()
return <div id="dynamic-data">Dynamic data</div>
}
...@@ -58,22 +58,26 @@ export async function ConditionalCookies() { ...@@ -58,22 +58,26 @@ export async function ConditionalCookies() {
return ( return (
<div> <div>
<p>{`Cached value: ${cachedValue.tag}, cookies used: ${shouldUseCookies}`}</p> <p>{`Cached value: ${cachedValue.tag}, cookies used: ${shouldUseCookies}`}</p>
{shouldUseCookies && ( {shouldUseCookies && <CookieData />}
<Suspense
fallback={<div id="cookie-data-fallback">Loading cookie data...</div>}
>
<CookieData />
</Suspense>
)}
</div> </div>
) )
} }
async function CookieData() { export async function CookieData({ label }: { label?: string }) {
return (
<Suspense
fallback={<div id="cookie-data-fallback">Loading cookie data...</div>}
>
<CookieDataImpl label={label} />
</Suspense>
)
}
async function CookieDataImpl({ label }: { label?: string }) {
await cookies() await cookies()
return ( return (
<> <>
<div id="cookie-data">Cookie data</div> <div id="cookie-data">{`Cookie data${label ? ' ' + label : ''}`}</div>
<Suspense <Suspense
fallback={ fallback={
<div id="cookies-runtime-prefetch-data-fallback"> <div id="cookies-runtime-prefetch-data-fallback">
......
'use client' 'use client'
import Link from 'next/link' import Link, { type LinkProps } from 'next/link'
import { useState } from 'react' import { useState } from 'react'
export function LinkAccordion({ export function LinkAccordion({
href, href,
children, children,
prefetch, prefetch = 'auto',
}: { }: {
href: string href: string
children: React.ReactNode children: React.ReactNode
prefetch?: boolean prefetch?: LinkProps['prefetch']
}) { }) {
const [isVisible, setIsVisible] = useState(false) const [isVisible, setIsVisible] = useState(false)
const prefetchAttr = prefetch === null ? 'auto' : `${prefetch}`
return ( return (
<> <>
<input <input
type="checkbox" type="checkbox"
checked={isVisible} checked={isVisible}
onChange={() => setIsVisible(!isVisible)} onChange={() => setIsVisible(!isVisible)}
data-prefetch={prefetchAttr}
data-link-accordion={href} data-link-accordion={href}
/> />
{isVisible ? ( {isVisible ? (
...@@ -25,7 +27,7 @@ export function LinkAccordion({ ...@@ -25,7 +27,7 @@ export function LinkAccordion({
{children} {children}
</Link> </Link>
) : ( ) : (
`${children} (link is hidden)` <>{children} (link is hidden)</>
)} )}
</> </>
) )
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
import { connection } from 'next/server' import { connection } from 'next/server'
import { cookies } from 'next/headers'
type Params = { id: string } type Params = { id: string }
...@@ -14,6 +15,8 @@ export const prefetch = 'partial' ...@@ -14,6 +15,8 @@ export const prefetch = 'partial'
export default function Page({ params }: { params: Promise<Params> }) { export default function Page({ params }: { params: Promise<Params> }) {
return ( return (
<main> <main>
{/* This page is meant to test a runtime shell, so we add a cookies access. */}
<ForceRuntimeShell />
{/* stale: 5 minutes (the App Shell threshold) — included in the {/* stale: 5 minutes (the App Shell threshold) — included in the
App Shell. */} App Shell. */}
<Suspense <Suspense
...@@ -39,6 +42,18 @@ export default function Page({ params }: { params: Promise<Params> }) { ...@@ -39,6 +42,18 @@ export default function Page({ params }: { params: Promise<Params> }) {
) )
} }
function ForceRuntimeShell() {
return (
<Suspense>
<ForceRuntimeShellInner />
</Suspense>
)
}
async function ForceRuntimeShellInner() {
await cookies()
return null
}
async function LongStaleCached() { async function LongStaleCached() {
'use cache' 'use cache'
cacheLife('hours') // stale: 5 minutes cacheLife('hours') // stale: 5 minutes
......
...@@ -144,7 +144,7 @@ describe('App Shell prefetching', () => { ...@@ -144,7 +144,7 @@ describe('App Shell prefetching', () => {
) )
}) })
it('skips the per-link Speculative prefetch for a route with prefetch = "partial"', async () => { it('skips the per-link Speculative prefetch for a link without prefetch={true}', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) { beforePageLoad(p: Playwright.Page) {
...@@ -180,7 +180,7 @@ describe('App Shell prefetching', () => { ...@@ -180,7 +180,7 @@ describe('App Shell prefetching', () => {
}, 'no-requests') }, 'no-requests')
}) })
it('does NOT skip the Speculative prefetch for a prefetch={true} link, even on a partial route', async () => { it('does NOT skip the Speculative prefetch for a link with prefetch={true}', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) { beforePageLoad(p: Playwright.Page) {
...@@ -277,8 +277,9 @@ describe('App Shell prefetching', () => { ...@@ -277,8 +277,9 @@ describe('App Shell prefetching', () => {
.elementByCss('input[data-link-accordion="/short-stale/1"]') .elementByCss('input[data-link-accordion="/short-stale/1"]')
.click() .click()
}, [ }, [
// The route reads request data, so its static-attempt hint is unset // The route deliberately accesses cookies to force using a runtime shell.
// and the prefetch deopts to a runtime request. // Note that the short-stale cache is omitted from both static and runtime shells,
// and thus is not counted as a runtime access.
{ includes: 'App shell for short-stale', kind: 'runtime' }, { includes: 'App shell for short-stale', kind: 'runtime' },
]) ])
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { DebugLinkAccordion } from '../components/link-accordion'
export default function Page() {
const linkForSlug = (slug: string) => `/static-for-some-params/${slug}`
return (
<main>
<h2>Prerendered, did not use cookies</h2>
<ul>
<li>
<DebugLinkAccordion
href={linkForSlug('no-cookies')}
prefetch={true}
/>
</li>
</ul>
<h2>Prerendered, did use cookies</h2>
<ul>
<li>
<DebugLinkAccordion
href={linkForSlug('yes-cookies')}
prefetch="auto"
/>
</li>
<li>
<DebugLinkAccordion
href={linkForSlug('yes-cookies')}
prefetch={true}
/>
</li>
</ul>
<h2>Not prerendered, did not use cookies</h2>
<ul>
<li>
<DebugLinkAccordion
href={linkForSlug('not-prerendered-1-no-cookies-prefetch-auto')}
prefetch="auto"
/>
</li>
<li>
<DebugLinkAccordion
href={linkForSlug('not-prerendered-1-no-cookies-prefetch-true')}
prefetch={true}
/>
</li>
</ul>
<h2>Not prerendered, did use cookies</h2>
<ul>
<li>
<DebugLinkAccordion
href={linkForSlug('not-prerendered-2-yes-cookies-prefetch-auto')}
prefetch="auto"
/>
</li>
<li>
<DebugLinkAccordion
href={linkForSlug('not-prerendered-2-yes-cookies-prefetch-true')}
prefetch={true}
/>
</li>
</ul>
</main>
)
}
import { unstable_navigation } from 'next/cache'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export async function generateStaticParams() {
return [{ slug: 'no-cookies' }, { slug: 'yes-cookies' }]
}
function shouldUseRuntimeDataForSlug(slug: string) {
return !slug.includes('no-cookies')
}
export default function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<main>
<p>This page only accesses runtime data for some param values.</p>
<Suspense fallback={<div>Loading param content...</div>}>
<ParamsDependent params={params} />
</Suspense>
</main>
)
}
async function ParamsDependent({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
console.log(`rendering page for slug ${slug}`)
if (slug.includes('not-prerendered')) {
// TODO(isr-fallbacks): it seems like in `next start` the initial /_tree request
// already kicks off an ISR prerender. We're trying to test the client router's
// handling of ISR fallbacks, so we need to make sure that the prerender does not finish
// before the page itself is requested (because then we'd serve a concrete
// prerender instead of a fallback)
await cachedDelay(500, slug)
}
return (
<div>
<div id="param-value">{`Slug: ${slug}`}</div>
<ConditionalCookiesUse slug={slug} />
<NavigationContent slug={slug} />
</div>
)
}
async function cachedDelay(durationMs: number, key: string) {
'use cache'
await new Promise((resolve) => setTimeout(resolve, durationMs))
return key
}
async function ConditionalCookiesUse({ slug }: { slug: string }) {
const shouldUseRuntimeData = shouldUseRuntimeDataForSlug(slug)
if (shouldUseRuntimeData) {
await cookies()
}
return (
<div>{`Runtime data accessed on ${slug}: ${shouldUseRuntimeData}'`}</div>
)
}
async function NavigationContent({ slug }: { slug: string }) {
await unstable_navigation()
return <div>{`Navigation content on ${slug}`}</div>
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
const prefetchAttr = prefetch === null ? 'auto' : `${prefetch}`
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
data-prefetch={prefetchAttr}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
export function DebugLinkAccordion({
href,
prefetch = 'auto',
}: {
href: string
prefetch?: LinkProps['prefetch']
}) {
const prefetchDisplay = prefetch === null ? 'auto' : `${prefetch}`
return (
<LinkAccordion href={href} prefetch={prefetch}>
{href} (prefetch={prefetchDisplay})
</LinkAccordion>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
...@@ -2,13 +2,11 @@ import type * as Playwright from 'playwright' ...@@ -2,13 +2,11 @@ import type * as Playwright from 'playwright'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
import { PrefetchHint } from 'next/src/shared/lib/app-router-types'
// Bit values from PrefetchHint enum (const enum, so we duplicate values here) import {
const ParentInlinedIntoSelf = 0b100000 // 32 type HintsManifest,
const InlinedIntoChild = 0b1000000 // 64 getHumanReadablePrefetchHints,
const HeadInlinedIntoSelf = 0b10000000 // 128 } from '../../../../lib/prefetch-hints'
const HeadOutlined = 0b100000000 // 256
const PrefetchDisabled = 0b10000000000 // 1024
// The subset of the FlightRouterState tuple the assertions below read (see // The subset of the FlightRouterState tuple the assertions below read (see
// FlightRouterState in shared/lib/app-router-types.ts). The segment is // FlightRouterState in shared/lib/app-router-types.ts). The segment is
...@@ -44,7 +42,7 @@ const DYNAMIC_TAG = 'dynamic \u25FB'.padStart(OUTLINED_TAG.length) ...@@ -44,7 +42,7 @@ const DYNAMIC_TAG = 'dynamic \u25FB'.padStart(OUTLINED_TAG.length)
function renderInliningTree(tree: FlightRouterStateLike): string { function renderInliningTree(tree: FlightRouterStateLike): string {
const lines: string[] = [] const lines: string[] = []
const isHeadOutlined = ((tree[4] ?? 0) & HeadOutlined) !== 0 const isHeadOutlined = ((tree[4] ?? 0) & PrefetchHint.HeadOutlined) !== 0
collectNodes(tree, '', !isHeadOutlined, false, lines) collectNodes(tree, '', !isHeadOutlined, false, lines)
if (isHeadOutlined) { if (isHeadOutlined) {
// Metadata is not inlined into any page — render as a standalone sibling. // Metadata is not inlined into any page — render as a standalone sibling.
...@@ -62,9 +60,9 @@ function collectNodes( ...@@ -62,9 +60,9 @@ function collectNodes(
slotKey?: string slotKey?: string
): void { ): void {
const prefetchHints = node[4] ?? 0 const prefetchHints = node[4] ?? 0
const prefetchDisabled = (prefetchHints & PrefetchDisabled) !== 0 const prefetchDisabled = (prefetchHints & PrefetchHint.PrefetchDisabled) !== 0
const inlinedIntoChild = (prefetchHints & InlinedIntoChild) !== 0 const inlinedIntoChild = (prefetchHints & PrefetchHint.InlinedIntoChild) !== 0
const headInlined = (prefetchHints & HeadInlinedIntoSelf) !== 0 const headInlined = (prefetchHints & PrefetchHint.HeadInlinedIntoSelf) !== 0
const slotPrefix = const slotPrefix =
slotKey !== undefined && slotKey !== 'children' ? `@${slotKey}/` : '' slotKey !== undefined && slotKey !== 'children' ? `@${slotKey}/` : ''
...@@ -94,7 +92,7 @@ function collectNodes( ...@@ -94,7 +92,7 @@ function collectNodes(
if (keys.length > 0) { if (keys.length > 0) {
const children = Object.values(slots) const children = Object.values(slots)
const childrenWithParentInlined = children.filter( const childrenWithParentInlined = children.filter(
(c) => ((c[4] ?? 0) & ParentInlinedIntoSelf) !== 0 (c) => ((c[4] ?? 0) & PrefetchHint.ParentInlinedIntoSelf) !== 0
) )
if (inlinedIntoChild && childrenWithParentInlined.length === 0) { if (inlinedIntoChild && childrenWithParentInlined.length === 0) {
throw new Error( throw new Error(
...@@ -535,25 +533,34 @@ describe('prefetch inlining', () => { ...@@ -535,25 +533,34 @@ describe('prefetch inlining', () => {
if (isNextStart) { if (isNextStart) {
it('partially generated dynamic route: build hints use the most specific shell', async () => { it('partially generated dynamic route: build hints use the most specific shell', async () => {
const hints = await next.readJSON('.next/server/prefetch-hints.json') const hintsManifest: HintsManifest = await next.readJSON(
'.next/server/prefetch-hints.json'
expect(hints['/test-dynamic-partial/[top]/[bottom]']) )
.toMatchInlineSnapshot(`
{ // The page awaits fallback params (and no other runtime data), so:
"hints": 64, // - the shell can be static (ShouldAttemptStaticShell hint set),
"slots": { // - the prefetch is runtime (ShouldAttemptStaticPrefetch hint is NOT set).
"children": { expect(
"hints": 96, getHumanReadablePrefetchHints(
"slots": { hintsManifest['/test-dynamic-partial/[top]/[bottom]']
"children": { )
"hints": 32, ).toMatchInlineSnapshot(`
"slots": { {
"children": { "hints": "InlinedIntoChild | ShouldAttemptStaticShell",
"hints": 64, "slots": {
"slots": { "children": {
"children": { "hints": "ParentInlinedIntoSelf | InlinedIntoChild | ShouldAttemptStaticShell",
"hints": 160, "slots": {
"slots": null, "children": {
"hints": "ParentInlinedIntoSelf | ShouldAttemptStaticShell",
"slots": {
"children": {
"hints": "InlinedIntoChild | ShouldAttemptStaticShell",
"slots": {
"children": {
"hints": "ParentInlinedIntoSelf | HeadInlinedIntoSelf | ShouldAttemptStaticShell",
"slots": null,
},
}, },
}, },
}, },
...@@ -561,9 +568,8 @@ describe('prefetch inlining', () => { ...@@ -561,9 +568,8 @@ describe('prefetch inlining', () => {
}, },
}, },
}, },
}, }
} `)
`)
}) })
} }
......
...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared' ...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
export const instant = true export const instant = true
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared' ...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
export const instant = true export const instant = true
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared' ...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
export const instant = true export const instant = true
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared' ...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
export const instant = true export const instant = true
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared' ...@@ -3,7 +3,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
export const instant = true export const instant = true
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { DebugRenderKind } from '../../../../../shared' import { DebugRenderKind } from '../../../../../shared'
import { ForceRuntimeShell } from '../../../../../../components/force-runtime-shell'
type Params = { id: string } type Params = { id: string }
...@@ -14,6 +15,7 @@ export const prefetch = 'partial' ...@@ -14,6 +15,7 @@ export const prefetch = 'partial'
export default async function Page({ params }: { params: Promise<Params> }) { export default async function Page({ params }: { params: Promise<Params> }) {
return ( return (
<main> <main>
<ForceRuntimeShell />
<DebugRenderKind /> <DebugRenderKind />
<p id="intro"> <p id="intro">
This page performs sync IO after awaiting params, so we should only see This page performs sync IO after awaiting params, so we should only see
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { DebugRenderKind } from '../../../../shared' import { DebugRenderKind } from '../../../../shared'
import { ForceRuntimeShell } from '../../../../../components/force-runtime-shell'
type AnySearchParams = { [key: string]: string | string[] | undefined } type AnySearchParams = { [key: string]: string | string[] | undefined }
...@@ -18,6 +19,7 @@ export default async function Page({ ...@@ -18,6 +19,7 @@ export default async function Page({
}) { }) {
return ( return (
<main> <main>
<ForceRuntimeShell />
<DebugRenderKind /> <DebugRenderKind />
<p id="intro"> <p id="intro">
This page performs sync IO after awaiting searchParams, so we should This page performs sync IO after awaiting searchParams, so we should
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
// In the future, this test can be used to check whether we correctly // In the future, this test can be used to check whether we correctly
// *skip* a runtime prefetch if a page was prerendered as static. // *skip* a runtime prefetch if a page was prerendered as static.
export const instant = true export const instant = true
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -5,7 +5,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared' ...@@ -5,7 +5,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
export const instant = { export const instant = {
unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }], unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -6,7 +6,6 @@ import { connection } from 'next/server' ...@@ -6,7 +6,6 @@ import { connection } from 'next/server'
export const instant = { export const instant = {
unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }], unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { ForceRuntimeShell } from '../../../../../components/force-runtime-shell'
export const instant = { export const instant = {
unstable_samples: [{ params: { id: 'test' } }], unstable_samples: [{ params: { id: 'test' } }],
} }
export const prefetch = 'partial'
type Params = { id: string } type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) { export default async function Page({ params }: { params: Promise<Params> }) {
return ( return (
<main> <main>
{/* Params are URL data and don't force a runtime shell on their own. */}
<ForceRuntimeShell />
<DebugRenderKind /> <DebugRenderKind />
<p> <p>
This page uses params and some uncached IO, so parts of it should be This page uses params and some uncached IO, so parts of it should be
......
...@@ -6,7 +6,6 @@ import { connection } from 'next/server' ...@@ -6,7 +6,6 @@ import { connection } from 'next/server'
export const instant = { export const instant = {
unstable_samples: [{ headers: [['host', 'test-host']] }], unstable_samples: [{ headers: [['host', 'test-host']] }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { ForceRuntimeShell } from '../../../../components/force-runtime-shell'
export const instant = { export const instant = {
unstable_samples: [{ searchParams: { searchParam: 'value' } }], unstable_samples: [{ searchParams: { searchParam: 'value' } }],
} }
export const prefetch = 'partial'
type AnySearchParams = { [key: string]: string | string[] | undefined } type AnySearchParams = { [key: string]: string | string[] | undefined }
...@@ -16,6 +16,8 @@ export default async function Page({ ...@@ -16,6 +16,8 @@ export default async function Page({
}) { }) {
return ( return (
<main> <main>
{/* Search params are URL data and don't force a runtime shell on their own. */}
<ForceRuntimeShell />
<DebugRenderKind /> <DebugRenderKind />
<p> <p>
This page uses search params and some uncached IO, so parts of it should This page uses search params and some uncached IO, so parts of it should
......
...@@ -5,7 +5,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared' ...@@ -5,7 +5,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
export const instant = { export const instant = {
unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }], unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -6,7 +6,6 @@ import { connection } from 'next/server' ...@@ -6,7 +6,6 @@ import { connection } from 'next/server'
export const instant = { export const instant = {
unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }], unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { PrefetchContent } from '../../../../components/prefetch-content'
export const instant = true export const instant = true
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
...@@ -25,6 +25,7 @@ async function RuntimePrefetchable() { ...@@ -25,6 +25,7 @@ async function RuntimePrefetchable() {
return ( return (
<div style={{ border: '1px solid blue', padding: '1em' }}> <div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="timestamp">{`Timestamp: ${now}`}</div> <div id="timestamp">{`Timestamp: ${now}`}</div>
<PrefetchContent text={`Timestamp (in prefetch): ${now}`} />
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic /> <Dynamic />
</Suspense> </Suspense>
......
...@@ -5,7 +5,6 @@ import { connection } from 'next/server' ...@@ -5,7 +5,6 @@ import { connection } from 'next/server'
export const instant = { export const instant = {
unstable_samples: [{ params: { id: 'test' } }], unstable_samples: [{ params: { id: 'test' } }],
} }
export const prefetch = 'partial'
type Params = { id: string } type Params = { id: string }
......
...@@ -6,7 +6,6 @@ import { connection } from 'next/server' ...@@ -6,7 +6,6 @@ import { connection } from 'next/server'
export const instant = { export const instant = {
unstable_samples: [{ headers: [['host', 'test-host']] }], unstable_samples: [{ headers: [['host', 'test-host']] }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -5,7 +5,6 @@ import { connection } from 'next/server' ...@@ -5,7 +5,6 @@ import { connection } from 'next/server'
export const instant = { export const instant = {
unstable_samples: [{ searchParams: { searchParam: 'value' } }], unstable_samples: [{ searchParams: { searchParam: 'value' } }],
} }
export const prefetch = 'partial'
type AnySearchParams = { [key: string]: string | string[] | undefined } type AnySearchParams = { [key: string]: string | string[] | undefined }
......
...@@ -5,7 +5,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared' ...@@ -5,7 +5,6 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
export const instant = { export const instant = {
unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }], unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -6,7 +6,6 @@ import { connection } from 'next/server' ...@@ -6,7 +6,6 @@ import { connection } from 'next/server'
export const instant = { export const instant = {
unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }], unstable_samples: [{ cookies: [{ name: 'testCookie', value: 'testValue' }] }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -6,7 +6,6 @@ import { cookies } from 'next/headers' ...@@ -6,7 +6,6 @@ import { cookies } from 'next/headers'
export const instant = { export const instant = {
unstable_samples: [{ params: { id: 'test' } }], unstable_samples: [{ params: { id: 'test' } }],
} }
export const prefetch = 'partial'
type Params = { id: string } type Params = { id: string }
......
...@@ -6,7 +6,6 @@ import { connection } from 'next/server' ...@@ -6,7 +6,6 @@ import { connection } from 'next/server'
export const instant = { export const instant = {
unstable_samples: [{ headers: [['host', 'test-host']] }], unstable_samples: [{ headers: [['host', 'test-host']] }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
......
...@@ -6,7 +6,6 @@ import { cookies } from 'next/headers' ...@@ -6,7 +6,6 @@ import { cookies } from 'next/headers'
export const instant = { export const instant = {
unstable_samples: [{ searchParams: { searchParam: 'value' } }], unstable_samples: [{ searchParams: { searchParam: 'value' } }],
} }
export const prefetch = 'partial'
type AnySearchParams = { [key: string]: string | string[] | undefined } type AnySearchParams = { [key: string]: string | string[] | undefined }
...@@ -19,8 +18,9 @@ export default async function Page({ ...@@ -19,8 +18,9 @@ export default async function Page({
<main> <main>
<DebugRenderKind /> <DebugRenderKind />
<p> <p>
This page passes search params to a public cache, and uses some uncached This page uses search params (passed to a public cache), and uses some
IO, so parts of it should be prefetchable with a runtime prefetch. uncached IO, so parts of it should be prefetchable with a runtime
prefetch.
</p> </p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable searchParams={searchParams} /> <RuntimePrefetchable searchParams={searchParams} />
......
...@@ -3,15 +3,17 @@ import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared' ...@@ -3,15 +3,17 @@ import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { lang } from 'next/root-params' import { lang } from 'next/root-params'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
import { ForceRuntimeShell } from '../../../../../components/force-runtime-shell'
import { PrefetchContent } from '../../../../../components/prefetch-content'
export const instant = { export const instant = {
unstable_samples: [{ params: { lang: 'en' } }], unstable_samples: [{ params: { lang: 'en' } }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
<ForceRuntimeShell />
<DebugRenderKind /> <DebugRenderKind />
<p> <p>
This page uses root params and some uncached IO. Root params should This page uses root params and some uncached IO. Root params should
...@@ -33,6 +35,7 @@ async function RuntimePrefetchable() { ...@@ -33,6 +35,7 @@ async function RuntimePrefetchable() {
return ( return (
<div style={{ border: '1px solid blue', padding: '1em' }}> <div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="root-param-value">{`Lang: ${currentLang}`}</div> <div id="root-param-value">{`Lang: ${currentLang}`}</div>
<PrefetchContent text={`Lang (in prefetch): ${currentLang}`} />
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic /> <Dynamic />
</Suspense> </Suspense>
......
...@@ -2,11 +2,11 @@ import { Suspense } from 'react' ...@@ -2,11 +2,11 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { lang } from 'next/root-params' import { lang } from 'next/root-params'
import { PrefetchContent } from '../../../../../components/prefetch-content'
export const instant = { export const instant = {
unstable_samples: [{ params: { lang: 'en' } }], unstable_samples: [{ params: { lang: 'en' } }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
...@@ -30,6 +30,7 @@ async function RuntimePrefetchable() { ...@@ -30,6 +30,7 @@ async function RuntimePrefetchable() {
return ( return (
<div style={{ border: '1px solid blue', padding: '1em' }}> <div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="root-param-value">{`Lang: ${currentLang}`}</div> <div id="root-param-value">{`Lang: ${currentLang}`}</div>
<PrefetchContent text={`Lang (in prefetch): ${currentLang}`} />
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic /> <Dynamic />
</Suspense> </Suspense>
......
...@@ -2,15 +2,17 @@ import { Suspense } from 'react' ...@@ -2,15 +2,17 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared' import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server' import { connection } from 'next/server'
import { lang } from 'next/root-params' import { lang } from 'next/root-params'
import { ForceRuntimeShell } from '../../../../../components/force-runtime-shell'
import { PrefetchContent } from '../../../../../components/prefetch-content'
export const instant = { export const instant = {
unstable_samples: [{ params: { lang: 'en' } }], unstable_samples: [{ params: { lang: 'en' } }],
} }
export const prefetch = 'partial'
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
<ForceRuntimeShell />
<DebugRenderKind /> <DebugRenderKind />
<p> <p>
This page uses root params (passed to a private cache) and some uncached This page uses root params (passed to a private cache) and some uncached
...@@ -30,6 +32,7 @@ async function RuntimePrefetchable() { ...@@ -30,6 +32,7 @@ async function RuntimePrefetchable() {
return ( return (
<div style={{ border: '1px solid blue', padding: '1em' }}> <div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="root-param-value">{`Lang: ${currentLang}`}</div> <div id="root-param-value">{`Lang: ${currentLang}`}</div>
<PrefetchContent text={`Lang (in prefetch): ${currentLang}`} />
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic /> <Dynamic />
</Suspense> </Suspense>
......
import { unstable_prefetch } from 'next/cache'
import { Suspense } from 'react'
/**
* Only renders `text` when requested with a prefetch (i.e. it's excluded from the app shell)
*
* Exists mostly because of `createRouterAct`'s requirement
* that the text in the `includes` assertion is unique:
*
* ```
* The same expected substring was sent multiple times by the server
* [...]
* Choose a more specific substring to assert on.
* ```
* This component lets us concisely add a second string that will only
* appear in the prefetch:
*
* ```tsx
* <div>{`Foo: ${foo}`}</div>
* <PrefetchContent text={`Foo (in prefetch): ${foo}`}} />
* ```
* Which lets us assert separately on `{ includes: "Foo: ..." }` and
* `{ includes: "Foo (in prefetch): ..." }`
* */
export function PrefetchContent({ text }: { text: string }) {
return (
<Suspense
fallback={
<div id="prefetch-content-fallback">Not included in the shell</div>
}
>
<Inner text={text} />
</Suspense>
)
}
async function Inner({ text }: { text: string }) {
await unstable_prefetch()
return <div id="prefetch-content">{text}</div>
}
...@@ -2,6 +2,7 @@ import type { NextConfig } from 'next' ...@@ -2,6 +2,7 @@ import type { NextConfig } from 'next'
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
cacheComponents: true, cacheComponents: true,
partialPrefetching: true,
productionBrowserSourceMaps: true, productionBrowserSourceMaps: true,
experimental: { experimental: {
// TODO: This test asserts on the pre-`varyParams` cache-keying behavior // TODO: This test asserts on the pre-`varyParams` cache-keying behavior
......
...@@ -46,6 +46,14 @@ export default function Page() { ...@@ -46,6 +46,14 @@ export default function Page() {
Param 1 Param 1
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion
href="/params-used-after-navigation/1"
prefetch={true}
>
Param 1 (prefetch=true)
</LinkAccordion>
</li>
<li> <li>
<Link href="/params-used-after-navigation/2" prefetch={false}> <Link href="/params-used-after-navigation/2" prefetch={false}>
Param 2 (unprefetched) Param 2 (unprefetched)
...@@ -61,6 +69,11 @@ export default function Page() { ...@@ -61,6 +69,11 @@ export default function Page() {
Param 1 Param 1
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion href="/params-used-in-icon/1" prefetch={true}>
Param 1 (prefetch=true)
</LinkAccordion>
</li>
<li> <li>
<Link href="/params-used-in-icon/2" prefetch={false}> <Link href="/params-used-in-icon/2" prefetch={false}>
Params 2 Params 2
...@@ -73,9 +86,19 @@ export default function Page() { ...@@ -73,9 +86,19 @@ export default function Page() {
Uses search params Uses search params
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion href="/uses-search-params?q=test" prefetch={true}>
Uses search params (prefetch=true)
</LinkAccordion>
</li>
<li> <li>
<LinkAccordion href="/uses-connection">Uses connection</LinkAccordion> <LinkAccordion href="/uses-connection">Uses connection</LinkAccordion>
</li> </li>
<li>
<LinkAccordion href="/uses-connection" prefetch={true}>
Uses connection (prefetch=true)
</LinkAccordion>
</li>
<li> <li>
<LinkAccordion href="/uses-runtime-after-navigation"> <LinkAccordion href="/uses-runtime-after-navigation">
Uses runtime APIs after navigation() Uses runtime APIs after navigation()
...@@ -91,6 +114,11 @@ export default function Page() { ...@@ -91,6 +114,11 @@ export default function Page() {
Uses runtime APIs after prefetch() Uses runtime APIs after prefetch()
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion href="/uses-runtime-after-prefetch" prefetch={true}>
Uses runtime APIs after prefetch() (prefetch=true)
</LinkAccordion>
</li>
<li> <li>
<LinkAccordion href="/uses-prefetch-static"> <LinkAccordion href="/uses-prefetch-static">
Uses prefetch() on a static page Uses prefetch() on a static page
......
...@@ -25,12 +25,14 @@ async function NavigationOnly(props: Props) { ...@@ -25,12 +25,14 @@ async function NavigationOnly(props: Props) {
return ( return (
<> <>
<div id="navigation-content">Navigation content</div> <div id="navigation-content">Navigation content</div>
<ParamsDependent {...props} /> <Suspense fallback={<p id="param-loading">Loading param content...</p>}>
<ParamsDependent {...props} />
</Suspense>
</> </>
) )
} }
async function ParamsDependent(props: Props) { async function ParamsDependent(props: Props) {
const { id } = await props.params const { id } = await props.params
return <p id="param-value">Post: {id}</p> return <p id="param-value">{`Post: ${id}`}</p>
} }
import {
PrefetchHint,
type PrefetchHints,
} from 'next/src/shared/lib/app-router-types'
const hintsEnumAsObject = Object.fromEntries(
Object.entries(
// @ts-expect-error - const enum (which jest ignores)
PrefetchHint
)
)
const prefetchHintsByName = Object.fromEntries(
Object.entries(hintsEnumAsObject)
.filter(([, value]) => typeof value === 'number')
.map((entry) => entry as [string, PrefetchHint])
)
export function prefetchHintsValuesToHumanReadableString(
hintsValue: number,
mask?: number
): string {
const names: string[] = []
let hasMaskedValues = false
for (const [name, bit] of Object.entries(prefetchHintsByName)) {
if ((hintsValue & bit) !== 0) {
if (mask !== undefined) {
if (bit & mask) {
names.push(name)
} else {
// if the value is not included in the mask, omit it.
hasMaskedValues = true
}
} else {
names.push(name)
}
}
}
// indicate if we've omitted some values due to a mask.
if (hasMaskedValues) {
names.push('...')
}
return names.join(' | ')
}
export type HintsManifest = { [route: string]: PrefetchHints }
export type HumanReadableHints = {
hints: string
slots: null | Record<string, HumanReadableHints>
}
export function getHumanReadablePrefetchHints(
tree: PrefetchHints,
mask?: number
): HumanReadableHints {
return {
hints: prefetchHintsValuesToHumanReadableString(tree.hints, mask),
slots:
tree.slots === null
? null
: Object.fromEntries(
Object.entries(tree.slots).map(([name, slot]) => [
name,
getHumanReadablePrefetchHints(slot, mask),
])
),
}
}
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