Unverified Commit c2bba0ea authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Revert legacy PPR removal (#90948)

This caused regressions. Apparently it was not a clean removal.
parent 2544467b
......@@ -2125,7 +2125,7 @@ export async function handleBuildComplete({
onMatchHeaders: [],
rewrites,
restrictedRedirectPaths: [],
isAppCacheComponentsEnabled: config.cacheComponents,
isAppPPREnabled: config.cacheComponents,
}).routesManifest.rsc,
},
outputs,
......
......@@ -13,6 +13,7 @@ import { discoverRoutes } from '../route-discovery'
import { findPagesDir } from '../../lib/find-pages-dir'
import loadCustomRoutes from '../../lib/load-custom-routes'
import { generateRoutesManifest } from '../generate-routes-manifest'
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import http from 'node:http'
......@@ -166,7 +167,7 @@ async function collectRoutesForAnalyze(
config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix
)
const isAppCacheComponentsEnabled = !!config.cacheComponents
const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
// Generate routes manifest
const { routesManifest } = generateRoutesManifest({
......@@ -178,7 +179,7 @@ async function collectRoutesForAnalyze(
onMatchHeaders,
rewrites,
restrictedRedirectPaths,
isAppCacheComponentsEnabled,
isAppPPREnabled,
})
return routesManifest.dynamicRoutes
......
......@@ -7,6 +7,7 @@ import type { ProxyMatcher } from './analysis/get-page-static-info'
import type { Rewrite } from '../lib/load-custom-routes'
import path from 'node:path'
import { needsExperimentalReact } from '../lib/needs-experimental-react'
import { checkIsAppPPREnabled } from '../server/lib/experimental/ppr'
import {
getNextConfigEnv,
getNextPublicEnvironmentVariables,
......@@ -119,6 +120,7 @@ export function getDefineEnv({
const nextPublicEnv = getNextPublicEnvironmentVariables()
const nextConfigEnv = getNextConfigEnv(config)
const isPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
const isCacheComponentsEnabled = !!config.cacheComponents
const isUseCacheEnabled = !!config.experimental.useCache
......@@ -168,6 +170,7 @@ export function getDefineEnv({
'process.env.__NEXT_APP_NEW_SCROLL_HANDLER': Boolean(
config.experimental.appNewScrollHandler
),
'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_INSTANT_NAV_TOGGLE':
!!config.experimental.instantNavigationDevToolsToggle,
......
......@@ -34,7 +34,7 @@ export interface GenerateRoutesManifestOptions {
onMatchHeaders: CustomRoutes['headers']
rewrites: CustomRoutes['rewrites']
restrictedRedirectPaths: string[]
isAppCacheComponentsEnabled: boolean
isAppPPREnabled: boolean
appType: 'pages' | 'app' | 'hybrid'
deploymentId?: string
}
......@@ -61,7 +61,7 @@ export function generateRoutesManifest(
onMatchHeaders,
rewrites,
restrictedRedirectPaths,
isAppCacheComponentsEnabled,
isAppPPREnabled,
appType,
deploymentId,
} = options
......@@ -132,8 +132,7 @@ export function generateRoutesManifest(
prefetchSegmentDirSuffix: RSC_SEGMENTS_DIR_SUFFIX,
clientParamParsing: config.cacheComponents ?? false,
clientParamParsingOrigins: config.experimental.clientParamParsingOrigins,
dynamicRSCPrerender:
isAppCacheComponentsEnabled && config.cacheComponents === true,
dynamicRSCPrerender: isAppPPREnabled && config.cacheComponents === true,
},
rewriteHeaders: {
pathHeader: NEXT_REWRITTEN_PATH_HEADER,
......@@ -141,7 +140,7 @@ export function generateRoutesManifest(
},
skipProxyUrlNormalize: config.skipProxyUrlNormalize,
deploymentId: deploymentId || undefined,
ppr: isAppCacheComponentsEnabled
ppr: isAppPPREnabled
? {
chain: {
headers: {
......
......@@ -185,6 +185,10 @@ import { traceMemoryUsage } from '../lib/memory/trace'
import { generateEncryptionKeyBase64 } from '../server/app-render/encryption-utils-server'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import uploadTrace from '../trace/upload-trace'
import {
checkIsAppPPREnabled,
checkIsRoutePPREnabled,
} from '../server/lib/experimental/ppr'
import { FallbackMode, fallbackModeToFallbackField } from '../lib/fallback'
import { RenderingMode } from './rendering-mode'
import { InvariantError } from '../shared/lib/invariant-error'
......@@ -1488,6 +1492,8 @@ export default async function build(
const isAuthInterruptsEnabled = Boolean(
config.experimental.authInterrupts
)
const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr)
const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
// Generate the routes manifest using the extracted helper
......@@ -1503,7 +1509,7 @@ export default async function build(
onMatchHeaders,
rewrites,
restrictedRedirectPaths,
isAppCacheComponentsEnabled,
isAppPPREnabled,
deploymentId: config.deploymentId,
})
)
......@@ -2056,6 +2062,7 @@ export default async function build(
locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale,
nextConfigOutput: config.output,
pprConfig: config.experimental.ppr,
cacheLifeProfiles: config.cacheLife,
buildId,
clientAssetToken:
......@@ -2282,6 +2289,7 @@ export default async function build(
: config.experimental.isrFlushToDisk,
cacheMaxMemorySize: config.cacheMaxMemorySize,
nextConfigOutput: config.output,
pprConfig: config.experimental.ppr,
cacheLifeProfiles: config.cacheLife,
buildId,
clientAssetToken:
......@@ -2686,7 +2694,7 @@ export default async function build(
},
{
featureName: 'experimental/ppr',
invocationCount: config.cacheComponents ? 1 : 0,
invocationCount: config.experimental.ppr ? 1 : 0,
},
{
featureName: 'turbopackFileSystemCache',
......@@ -2872,6 +2880,10 @@ export default async function build(
const appConfig = appDefaultConfigs.get(originalAppPath)
const isDynamicError = appConfig?.dynamic === 'error'
const isRoutePPREnabled: boolean = appConfig
? checkIsRoutePPREnabled(config.experimental.ppr)
: false
routes.forEach((route) => {
// If the route has any dynamic root segments, we need to skip
// rendering the route. This is because we don't support
......@@ -2896,6 +2908,7 @@ export default async function build(
_fallbackRouteParams: route.fallbackRouteParams,
_isDynamicError: isDynamicError,
_isAppDir: true,
_isRoutePPREnabled: isRoutePPREnabled,
_allowEmptyStaticShell: !route.throwOnEmptyStaticShell,
}
})
......@@ -3063,7 +3076,8 @@ export default async function build(
// When this is an app page and PPR is enabled, the route supports
// partial pre-rendering.
const isRoutePPREnabled: true | undefined =
!isAppRouteHandler && isAppCacheComponentsEnabled
!isAppRouteHandler &&
checkIsRoutePPREnabled(config.experimental.ppr)
? true
: undefined
......@@ -3203,7 +3217,7 @@ export default async function build(
prerenderManifest.routes[route.pathname] = {
initialStatus: status,
initialHeaders: meta.headers,
renderingMode: isAppCacheComponentsEnabled
renderingMode: isAppPPREnabled
? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC
: RenderingMode.STATIC
......@@ -3287,7 +3301,7 @@ export default async function build(
let dynamicRoute = routesManifest.dynamicRoutes.find(
(r) => r.page === route.pathname
)
if (!isAppRouteHandler && isAppCacheComponentsEnabled) {
if (!isAppRouteHandler && isAppPPREnabled) {
// If the dynamic route wasn't found, then we need to create
// it. This ensures that for each fallback shell there's an
// entry in the app routes manifest which enables routing for
......@@ -3390,7 +3404,7 @@ export default async function build(
prerenderManifest.dynamicRoutes[route.pathname] = {
experimentalPPR: isRoutePPREnabled,
renderingMode: isAppCacheComponentsEnabled
renderingMode: isAppPPREnabled
? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC
: RenderingMode.STATIC
......
......@@ -20,6 +20,7 @@ import { BaseServerSpan } from '../../server/lib/trace/constants'
import { interopDefault } from '../../server/app-render/interop-default'
import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers'
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'
import {
getFallbackRouteParams,
createOpaqueFallbackRouteParams,
......@@ -99,6 +100,7 @@ import * as entryBase from '../../server/app-render/entry-base' with { 'turbopac
import { RedirectStatusCode } from '../../client/components/redirect-status-code'
import { InvariantError } from '../../shared/lib/invariant-error'
import { scheduleOnNextTick } from '../../lib/scheduler'
import { isInterceptionRouteAppPath } from '../../shared/lib/router/utils/interception-routes'
export * from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' }
......@@ -193,8 +195,16 @@ export async function handler(
// We use the resolvedPathname instead of the parsedUrl.pathname because it
// is not rewritten as resolvedPathname is. This will ensure that the correct
// prerender info is used instead of using the original pathname as the
// source.
const prerenderInfo = routeModule.match(resolvedPathname, prerenderManifest)
// source. If however PPR is enabled and cacheComponents is disabled, we
// treat the pathname as dynamic. Currently, there's a bug in the PPR
// implementation that incorrectly leaves %%drp placeholders in the output of
// parallel routes. This is addressed with cacheComponents.
const prerenderInfo =
nextConfig.experimental.ppr &&
!nextConfig.cacheComponents &&
isInterceptionRouteAppPath(resolvedPathname)
? null
: routeModule.match(resolvedPathname, prerenderManifest)
const isPrerendered = !!prerenderManifest.routes[resolvedPathname]
......@@ -218,10 +228,12 @@ export async function handler(
const isPossibleServerAction = getIsPossibleServerAction(req)
/**
* If the route being rendered is an app page, and the cacheComponents feature
* has been enabled, then the given route _could_ support PPR.
* If the route being rendered is an app page, and the ppr feature has been
* enabled, then the given route _could_ support PPR.
*/
const isAppCacheComponentsEnabled: boolean = !!nextConfig.cacheComponents
const couldSupportPPR: boolean = checkIsAppPPREnabled(
nextConfig.experimental.ppr
)
// Stash postponed state for server actions when in minimal mode.
// We extract it here so the RDC is available for the re-render after the action completes.
......@@ -229,7 +241,7 @@ export async function handler(
if (
!getRequestMeta(req, 'postponed') &&
isMinimalMode &&
isAppCacheComponentsEnabled &&
couldSupportPPR &&
isPossibleServerAction &&
resumeStateLengthHeader &&
typeof resumeStateLengthHeader === 'string'
......@@ -293,7 +305,7 @@ export async function handler(
if (
!getRequestMeta(req, 'postponed') &&
isAppCacheComponentsEnabled &&
couldSupportPPR &&
req.headers[NEXT_RESUME_HEADER] === '1' &&
req.method === 'POST'
) {
......@@ -320,7 +332,7 @@ export async function handler(
const hasDebugStaticShellQuery =
process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1' &&
typeof query.__nextppronly !== 'undefined' &&
isAppCacheComponentsEnabled
couldSupportPPR
// When enabled, this will allow the use of the `?__nextppronly` query
// to enable debugging of the fallback shell.
......@@ -342,7 +354,7 @@ export async function handler(
// with blocking happening on the client side.
const isInstantNavigationTest =
exposeTestingApi &&
isAppCacheComponentsEnabled &&
couldSupportPPR &&
(req.headers[NEXT_INSTANT_PREFETCH_HEADER] === '1' ||
(req.headers[RSC_HEADER] === undefined &&
typeof req.headers.cookie === 'string' &&
......@@ -351,7 +363,7 @@ export async function handler(
// This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the
// prerender manifest and this is an app page.
const isRoutePPREnabled: boolean =
isAppCacheComponentsEnabled &&
couldSupportPPR &&
((
prerenderManifest.routes[normalizedSrcPage] ??
prerenderManifest.dynamicRoutes[normalizedSrcPage]
......@@ -715,6 +727,7 @@ export async function handler(
: {}),
cacheComponents: Boolean(nextConfig.cacheComponents),
experimental: {
isRoutePPREnabled,
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
......
......@@ -157,6 +157,7 @@ async function requestHandler(
Boolean(nextConfig.logging.serverFunctions),
cacheComponents: Boolean(nextConfig.cacheComponents),
experimental: {
isRoutePPREnabled: false,
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
......
......@@ -2,6 +2,8 @@ import type {
NextConfigComplete,
NextConfigRuntime,
} from '../server/config-shared'
import type { ExperimentalPPRConfig } from '../server/lib/experimental/ppr'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
import type { AssetBinding } from './webpack/loaders/get-module-build-info'
import type { ServerRuntime } from '../types'
import type { BuildManifest } from '../server/get-page-files'
......@@ -664,6 +666,7 @@ export async function isPageStatic({
cacheHandler,
cacheHandlers,
cacheLifeProfiles,
pprConfig,
buildId,
clientAssetToken,
sriEnabled,
......@@ -690,6 +693,7 @@ export async function isPageStatic({
[profile: string]: import('../server/use-cache/cache-life').CacheLife
}
nextConfigOutput: 'standalone' | 'export' | undefined
pprConfig: ExperimentalPPRConfig | undefined
buildId: string
clientAssetToken: string
sriEnabled: boolean
......@@ -816,10 +820,12 @@ export async function isPageStatic({
rootParamKeys = collectRootParamKeys(routeModule)
// A page supports partial prerendering if it is an app page and
// cacheComponents is enabled.
// A page supports partial prerendering if it is an app page and either
// the whole app has PPR enabled or this page has PPR enabled when we're
// in incremental mode.
isRoutePPREnabled =
routeModule.definition.kind === RouteKind.APP_PAGE && cacheComponents
routeModule.definition.kind === RouteKind.APP_PAGE &&
checkIsRoutePPREnabled(pprConfig)
// If force dynamic was set and we don't have PPR enabled, then set the
// revalidate to 0.
......
......@@ -20,6 +20,7 @@ function hasFallbackRouteParams(): boolean {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
const fallbackParams = workUnitStore.fallbackRouteParams
return fallbackParams ? fallbackParams.size > 0 : false
case 'validation-client':
......
......@@ -179,11 +179,15 @@ export async function fetchServerResponse(
// Typically, during a navigation, we decode the response using Flight's
// `createFromFetch` API, which accepts a `fetch` promise.
// TODO: Remove this check once the old PPR flag is removed
const isLegacyPPR =
process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS
const shouldImmediatelyDecode = !isLegacyPPR
const res = await createFetch<NavigationFlightResponse>(
url,
headers,
'auto',
true
shouldImmediatelyDecode
)
const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))
......
......@@ -2,7 +2,10 @@ import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-u
import { isPostpone } from '../../server/lib/router-utils/is-postpone'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { isNextRouterError } from './is-next-router-error'
import { isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering'
import {
isDynamicPostpone,
isPrerenderInterruptedError,
} from '../../server/app-render/dynamic-rendering'
import { isDynamicServerError } from './hooks-server-context'
export function unstable_rethrow(error: unknown): void {
......@@ -10,6 +13,7 @@ export function unstable_rethrow(error: unknown): void {
isNextRouterError(error) ||
isBailoutToCSRError(error) ||
isDynamicServerError(error) ||
isDynamicPostpone(error) ||
isPostpone(error) ||
isHangingPromiseRejectionError(error) ||
isPrerenderInterruptedError(error)
......
import { isDynamicServerError } from '../../client/components/hooks-server-context'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { isNextRouterError } from '../../client/components/is-next-router-error'
import { isDynamicPostpone } from '../../server/app-render/dynamic-rendering'
export const isDynamicUsageError = (err: unknown) =>
isDynamicServerError(err) ||
isBailoutToCSRError(err) ||
isNextRouterError(err)
isNextRouterError(err) ||
isDynamicPostpone(err)
......@@ -856,7 +856,7 @@ async function exportAppImpl(
}
// Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.cacheComponents) {
if (!options.buildExport && nextConfig.experimental.ppr) {
// TODO: add message
throw new Error('Invariant: PPR cannot be enabled in export mode')
}
......
......@@ -104,7 +104,7 @@ export async function exportAppPage(
} = metadata
// Ensure we don't postpone without having PPR enabled.
if (postponed && !renderOpts.cacheComponents) {
if (postponed && !renderOpts.experimental.isRoutePPREnabled) {
throw new Error('Invariant: page postponed without PPR being enabled')
}
......@@ -144,7 +144,8 @@ export async function exportAppPage(
const hasFallbackParams =
fallbackRouteParams != null && fallbackRouteParams.size > 0
const shouldWriteRsc =
!renderOpts.cacheComponents || (!postponed && !hasFallbackParams)
!renderOpts.experimental.isRoutePPREnabled ||
(!postponed && !hasFallbackParams)
hasStaticRsc = shouldWriteRsc
// With PPR enabled, we normally skip writing .rsc because it may contain
......@@ -196,7 +197,7 @@ export async function exportAppPage(
// When PPR is enabled, we don't always send 200 for routes that have been
// pregenerated, so we should grab the status code from the mocked
// response.
let status: number | undefined = renderOpts.cacheComponents
let status: number | undefined = renderOpts.experimental.isRoutePPREnabled
? res.statusCode
: undefined
......
......@@ -109,6 +109,10 @@ async function exportPageImpl(
// Check if this should error when dynamic usage is detected.
_isDynamicError: isDynamicError = false,
// If this page supports partial prerendering, then we need to pass that to
// the renderOpts.
_isRoutePPREnabled: isRoutePPREnabled,
// Configure the rendering of the page to allow that an empty static shell
// is generated while rendering using PPR and Cache Components.
_allowEmptyStaticShell: allowEmptyStaticShell = false,
......@@ -267,6 +271,7 @@ async function exportPageImpl(
allowEmptyStaticShell,
experimental: {
...commonRenderOpts.experimental,
isRoutePPREnabled,
},
renderResumeDataCache,
}
......
......@@ -117,7 +117,7 @@ async function createComponentTreeInternal(
isRoot: boolean
): Promise<CacheNodeSeedData> {
const {
renderOpts: { nextConfigOutput, cacheComponents },
renderOpts: { nextConfigOutput, experimental, cacheComponents },
workStore,
componentMod: {
createElement,
......@@ -133,6 +133,7 @@ async function createComponentTreeInternal(
createServerParamsForServerSegment,
createPrerenderParamsForClientSegment,
serverHooks: { DynamicServerError },
Postpone,
},
pagePath,
getDynamicParamFromSegment,
......@@ -286,7 +287,7 @@ async function createComponentTreeInternal(
workStore.forceDynamic = true
// TODO: (PPR) remove this bailout once PPR is the default
if (workStore.isStaticGeneration && !cacheComponents) {
if (workStore.isStaticGeneration && !experimental.isRoutePPREnabled) {
// If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
const err = new DynamicServerError(
......@@ -320,6 +321,7 @@ async function createComponentTreeInternal(
case 'prerender':
case 'prerender-runtime':
case 'prerender-legacy':
case 'prerender-ppr':
if (workUnitStore.revalidate > defaultRevalidate) {
workUnitStore.revalidate = defaultRevalidate
}
......@@ -345,7 +347,7 @@ async function createComponentTreeInternal(
defaultRevalidate === 0 &&
// If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
!cacheComponents
!experimental.isRoutePPREnabled
) {
const dynamicUsageDescription = `revalidate: 0 configured ${segment}`
workStore.dynamicUsageDescription = dynamicUsageDescription
......@@ -370,7 +372,7 @@ async function createComponentTreeInternal(
// For dynamic requests, this must always be `false` because dynamic responses
// are never partial.
const isPossiblyPartialResponse =
isStaticGeneration && cacheComponents === true
isStaticGeneration && experimental.isRoutePPREnabled === true
const LayoutOrPage: ComponentType<any> | undefined = layoutOrPageMod
? interopDefault(layoutOrPageMod)
......@@ -532,7 +534,7 @@ async function createComponentTreeInternal(
// possible during both prefetches and dynamic navigations. But during
// the beta period, we should be clear about this trade off in our
// communications.
!cacheComponents
!experimental.isRoutePPREnabled
) {
// Don't prefetch this child. This will trigger a lazy fetch by the
// client router.
......@@ -724,6 +726,46 @@ async function createComponentTreeInternal(
}
const Component = MaybeComponent
// If force-dynamic is used and the current render supports postponing, we
// replace it with a node that will postpone the render. This ensures that the
// postpone is invoked during the react render phase and not during the next
// render phase.
// @TODO this does not actually do what it seems like it would or should do. The idea is that
// if we are rendering in a force-dynamic mode and we can postpone we should only make the segments
// that ask for force-dynamic to be dynamic, allowing other segments to still prerender. However
// because this comes after the children traversal and the static generation store is mutated every segment
// along the parent path of a force-dynamic segment will hit this condition effectively making the entire
// render force-dynamic. We should refactor this function so that we can correctly track which segments
// need to be dynamic
if (
workStore.isStaticGeneration &&
workStore.forceDynamic &&
experimental.isRoutePPREnabled
) {
return createSeedData(
ctx,
createElement(
Fragment,
{
key: cacheNodeKey,
},
createElement(Postpone, {
reason: 'dynamic = "force-dynamic" was used',
route: workStore.route,
}),
layerAssets
),
parallelRouteCacheNodeSeedData,
loadingData,
true,
isRuntimePrefetchable,
// force-dynamic postpones without rendering the component, so no params
// are accessed. The vary params are empty.
emptyVaryParamsAccumulator
)
}
const isClientComponent = isClientReference(layoutOrPageMod)
const varyParamsAccumulator =
......@@ -1243,6 +1285,7 @@ function createSeedData(
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......
......@@ -28,6 +28,7 @@ import type {
ValidationStoreClient,
} from '../app-render/work-unit-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly
import React from 'react'
import { DynamicServerError } from '../../client/components/hooks-server-context'
......@@ -50,6 +51,8 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
const hasPostpone = typeof React.unstable_postpone === 'function'
export type DynamicAccess = {
/**
* If debugging, this will contain the stack trace of where the dynamic access
......@@ -141,6 +144,7 @@ export function markCurrentScopeAsDynamic(
// A private cache scope is already dynamic by definition.
return
case 'prerender-legacy':
case 'prerender-ppr':
case 'request':
break
default:
......@@ -161,6 +165,12 @@ export function markCurrentScopeAsDynamic(
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender-ppr':
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
workUnitStore.revalidate = 0
......@@ -230,6 +240,7 @@ export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {
case 'prerender':
case 'prerender-runtime':
case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client':
case 'validation-client':
break
......@@ -326,6 +337,78 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
)
}
/**
* This component will call `React.postpone` that throws the postponed error.
*/
type PostponeProps = {
reason: string
route: string
}
export function Postpone({ reason, route }: PostponeProps): never {
const prerenderStore = workUnitAsyncStorage.getStore()
const dynamicTracking =
prerenderStore && prerenderStore.type === 'prerender-ppr'
? prerenderStore.dynamicTracking
: null
postponeWithTracking(route, reason, dynamicTracking)
}
export function postponeWithTracking(
route: string,
expression: string,
dynamicTracking: null | DynamicTrackingState
): never {
assertPostpone()
if (dynamicTracking) {
dynamicTracking.dynamicAccesses.push({
// When we aren't debugging, we don't need to create another error for the
// stack trace.
stack: dynamicTracking.isDebugDynamicAccesses
? new Error().stack
: undefined,
expression,
})
}
React.unstable_postpone(createPostponeReason(route, expression))
}
function createPostponeReason(route: string, expression: string) {
return (
`Route ${route} needs to bail out of prerendering at this point because it used ${expression}. ` +
`React throws this special object to indicate where. It should not be caught by ` +
`your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`
)
}
export function isDynamicPostpone(err: unknown) {
if (
typeof err === 'object' &&
err !== null &&
typeof (err as any).message === 'string'
) {
return isDynamicPostponeReason((err as any).message)
}
return false
}
function isDynamicPostponeReason(reason: string) {
return (
reason.includes(
'needs to bail out of prerendering at this point because it used'
) &&
reason.includes(
'Learn more: https://nextjs.org/docs/messages/ppr-caught-error'
)
)
}
if (isDynamicPostponeReason(createPostponeReason('%%%', '^^^')) === false) {
throw new Error(
'Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js'
)
}
const NEXT_PRERENDER_INTERRUPTED = 'NEXT_PRERENDER_INTERRUPTED'
function createPrerenderInterruptedError(message: string): Error {
......@@ -406,9 +489,17 @@ export function formatDynamicAPIAccesses(
})
}
function assertPostpone() {
if (!hasPostpone) {
throw new Error(
`Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`
)
}
}
/**
* Abort with a dedicated CSR bailout reason so resumption can reliably switch
* postponed boundaries to client rendering.
* This is a bit of a hack to allow us to abort a render using a Postpone instance instead of an Error which changes React's
* abort semantics slightly.
*/
export function createRenderInBrowserAbortSignal(): AbortSignal {
const controller = new AbortController()
......@@ -466,6 +557,7 @@ export function createHangingInputAbortSignal(
return controller.signal
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......@@ -515,6 +607,17 @@ export function useDynamicRouteParams(expression: string) {
}
break
}
case 'prerender-ppr': {
const fallbackParams = workUnitStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) {
return postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
}
break
}
case 'prerender-runtime':
throw new InvariantError(
`\`${expression}\` was called during a runtime prerender. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`
......@@ -564,7 +667,8 @@ export function useDynamicSearchParams(expression: string) {
)
break
}
case 'prerender-legacy': {
case 'prerender-legacy':
case 'prerender-ppr': {
if (workStore.forceStatic) {
return
}
......
......@@ -299,6 +299,7 @@ export async function decryptActionBoundArgs(
break
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......
......@@ -38,6 +38,7 @@ export { createMetadataComponents } from '../../lib/metadata/metadata'
export { RootLayoutBoundary } from '../../lib/framework/boundary-components'
export { preloadStyle, preloadFont, preconnect } from './rsc/preloads'
export { Postpone } from './rsc/postpone'
export { taintObjectReference } from './rsc/taint'
export { collectSegmentData } from './collect-segment-data'
......
......@@ -15,6 +15,7 @@ function getValidationBoundaryTracking(): ValidationBoundaryTracking | null {
return store.boundaryState
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
case 'request':
......
/*
Files in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader.
*/
// When postpone is available in canary React we can switch to importing it directly
export { Postpone } from '../dynamic-rendering'
......@@ -142,6 +142,11 @@ export interface RenderOptsPartial {
isPrefetch?: boolean
htmlLimitedBots: string | undefined
experimental: {
/**
* When true, it indicates that the current page supports partial
* prerendering.
*/
isRoutePPREnabled?: boolean
expireTime: number | undefined
staleTimes: ExperimentalConfig['staleTimes'] | undefined
clientTraceMetadata: string[] | undefined
......
......@@ -124,6 +124,7 @@ export function getFlightStream<T>(
return responseOnNextTick
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......
......@@ -126,6 +126,7 @@ export function createVaryParamsAccumulator(): VaryParamsAccumulator | null {
}
return null
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......@@ -153,6 +154,7 @@ export function getMetadataVaryParamsAccumulator(): VaryParamsAccumulator | null
}
return null
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......@@ -199,6 +201,7 @@ export function getRootParamsVaryParamsAccumulator(): VaryParamsAccumulator | nu
}
return null
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......
......@@ -52,7 +52,7 @@ export async function walkTreeWithFlightRouterState({
MetadataOutlet: React.ComponentType
}): Promise<FlightDataPath[]> {
const {
renderOpts: { nextFontManifest, experimental, cacheComponents },
renderOpts: { nextFontManifest, experimental },
query,
isPrefetch,
getDynamicParamFromSegment,
......@@ -124,7 +124,7 @@ export async function walkTreeWithFlightRouterState({
if (
isInsideSharedLayout &&
!cacheComponents &&
!experimental.isRoutePPREnabled &&
// If PPR is disabled, and this is a request for the route tree, then we
// never render any components. Only send the router state.
(parsedRequestHeaders.isRouteTreePrefetchRequest ||
......
......@@ -267,6 +267,25 @@ interface StaticPrerenderStoreCommon {
readonly allowEmptyStaticShell: boolean
}
export interface PrerenderStorePPR
extends CommonWorkUnitStore,
RevalidateStore {
readonly type: 'prerender-ppr'
readonly rootParams: Params
readonly dynamicTracking: null | DynamicTrackingState
/**
* The set of unknown route parameters. Accessing these will be tracked as
* a dynamic access.
*/
readonly fallbackRouteParams: OpaqueFallbackRouteParams | null
/**
* The resume data cache for this prerender.
*/
prerenderResumeDataCache: PrerenderResumeDataCache
}
export interface PrerenderStoreLegacy
extends CommonWorkUnitStore,
RevalidateStore {
......@@ -274,7 +293,10 @@ export interface PrerenderStoreLegacy
readonly rootParams: Params
}
export type PrerenderStore = PrerenderStoreLegacy | PrerenderStoreModern
export type PrerenderStore =
| PrerenderStoreLegacy
| PrerenderStorePPR
| PrerenderStoreModern
// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */
export type StaticPrerenderStore = Exclude<
......@@ -363,6 +385,7 @@ export function getPrerenderResumeDataCache(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
return workUnitStore.prerenderResumeDataCache
case 'prerender-client':
case 'validation-client':
......@@ -400,6 +423,8 @@ export function getRenderResumeDataCache(
// that is used to read from prefilled caches.
return workUnitStore.renderResumeDataCache
}
// fallthrough
case 'prerender-ppr':
// Otherwise we return the mutable resume data cache here as an immutable
// version of the cache as it can also be used for reading.
return workUnitStore.prerenderResumeDataCache ?? null
......@@ -427,6 +452,7 @@ export function getHmrRefreshHash(
return workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
......@@ -449,6 +475,7 @@ export function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
......@@ -473,6 +500,7 @@ export function getServerComponentsHmrCache(
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
......@@ -502,6 +530,7 @@ export function getDraftModeProviderForCacheScope(
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
break
default:
......@@ -522,6 +551,7 @@ export function getStagedRenderingController(
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -548,6 +578,7 @@ export function getCacheSignal(
}
// fallthrough
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......
......@@ -29,7 +29,10 @@ export type WorkStoreContext = {
fetchCache?: AppSegmentConfig['fetchCache']
isPossibleServerAction?: boolean
pendingWaitUntil?: Promise<any>
experimental: Pick<RenderOpts['experimental'], 'authInterrupts'>
experimental: Pick<
RenderOpts['experimental'],
'isRoutePPREnabled' | 'authInterrupts'
>
/**
* Fetch metrics attached in patch-fetch.ts
......
......@@ -132,6 +132,7 @@ import { toRoute } from './lib/to-route'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers'
import { patchSetHeaderWithCookieSupport } from './lib/patch-set-header'
import { checkIsAppPPREnabled } from './lib/experimental/ppr'
import {
getBuiltinRequestContext,
type WaitUntil,
......@@ -426,7 +427,7 @@ export default abstract class Server<
readonly data: NextDataPathnameNormalizer | undefined
}
private readonly isCacheComponentsEnabled: boolean
private readonly isAppPPREnabled: boolean
/**
* This is used to persist cache scopes across
......@@ -512,8 +513,9 @@ export default abstract class Server<
this.enabledDirectories = this.getEnabledDirectories(dev)
this.isCacheComponentsEnabled =
this.enabledDirectories.app && !!this.nextConfig.cacheComponents
this.isAppPPREnabled =
this.enabledDirectories.app &&
checkIsAppPPREnabled(this.nextConfig.experimental.ppr)
this.normalizers = {
// We should normalize the pathname from the RSC prefix only in minimal
......@@ -1081,7 +1083,7 @@ export default abstract class Server<
// It's important to execute the following block even it the request
// matches a pages data route from above.
if (
this.isCacheComponentsEnabled &&
this.isAppPPREnabled &&
this.minimalMode &&
req.headers[NEXT_RESUME_HEADER] === '1' &&
req.method === 'POST'
......@@ -2192,7 +2194,7 @@ export default abstract class Server<
* enabled, then the given route _could_ support PPR.
*/
const couldSupportPPR: boolean =
this.isCacheComponentsEnabled &&
this.isAppPPREnabled &&
typeof routeModule !== 'undefined' &&
isAppPageRouteModule(routeModule)
......
......@@ -40,6 +40,7 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record(
_fallbackRouteParams: z.array(z.any()).optional(),
_isAppDir: z.boolean().optional(),
_isDynamicError: z.boolean().optional(),
_isRoutePPREnabled: z.boolean().optional(),
_allowEmptyStaticShell: z.boolean().optional(),
})
)
......
......@@ -11,6 +11,7 @@ import type { WEB_VITALS } from '../shared/lib/utils'
import type { NextParsedUrlQuery } from './request-meta'
import type { SizeLimit } from '../types'
import type { SupportedTestRunners } from '../cli/next-test'
import type { ExperimentalPPRConfig } from './lib/experimental/ppr'
import { INFINITE_CACHE } from '../lib/constants'
import { isStableBuild } from '../shared/lib/errors/canary-only-config-error'
import type { FallbackRouteParam } from '../build/static-paths/types'
......@@ -691,7 +692,7 @@ export interface ExperimentalConfig {
* @deprecated This configuration option has been merged into `cacheComponents`.
* The Partial Prerendering feature is still available via `cacheComponents`.
*/
ppr?: boolean | 'incremental'
ppr?: ExperimentalPPRConfig
/**
* Enables experimental taint APIs in React.
......@@ -1039,6 +1040,11 @@ export type ExportPathMap = {
*/
_isDynamicError?: boolean
/**
* @internal
*/
_isRoutePPREnabled?: boolean
/**
* When true, the page is prerendered as a fallback shell, while allowing
* any dynamic accesses to result in an empty shell. This is the case when
......
......@@ -1396,6 +1396,9 @@ function assignDefaultsAndValidate(
}
if (result.cacheComponents) {
// TODO: remove once we've finished migrating internally to cacheComponents.
result.experimental.ppr = true
// Prerender sourcemaps are enabled by default when using cacheComponents, unless explicitly disabled.
if (result.enablePrerenderSourceMaps === undefined) {
result.enablePrerenderSourceMaps = true
......
......@@ -798,6 +798,7 @@ export default class DevServer extends Server {
distDir: this.distDir,
pathname,
config: {
pprConfig: this.nextConfig.experimental.ppr,
configFileName,
cacheComponents: Boolean(this.nextConfig.cacheComponents),
},
......
......@@ -17,6 +17,10 @@ import { loadComponents } from '../load-components'
import { setHttpClientAndAgentOptions } from '../setup-http-agent-env'
import type { IncrementalCache } from '../lib/incremental-cache'
import { isAppPageRouteModule } from '../route-modules/checks'
import {
checkIsRoutePPREnabled,
type ExperimentalPPRConfig,
} from '../lib/experimental/ppr'
import { InvariantError } from '../../shared/lib/invariant-error'
import { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys'
import { buildAppStaticPaths } from '../../build/static-paths/app'
......@@ -25,6 +29,7 @@ import { createIncrementalCache } from '../../export/helpers/create-incremental-
import { parseAppRoute } from '../../shared/lib/router/routes/app'
type RuntimeConfig = {
pprConfig: ExperimentalPPRConfig | undefined
configFileName: string
cacheComponents: boolean
}
......@@ -121,7 +126,8 @@ export async function loadStaticPaths({
}
const isRoutePPREnabled =
isAppPageRouteModule(routeModule) && config.cacheComponents
isAppPageRouteModule(routeModule) &&
checkIsRoutePPREnabled(config.pprConfig)
const rootParamKeys = collectRootParamKeys(routeModule)
......
/**
* If set to `incremental`, only those leaf pages that export
* `experimental_ppr = true` will have partial prerendering enabled. If any
* page exports this value as `false` or does not export it at all will not
* have partial prerendering enabled. If set to a boolean, the options for
* `experimental_ppr` will be ignored.
*/
export type ExperimentalPPRConfig = boolean | 'incremental'
/**
* Returns true if partial prerendering is enabled for the application. It does
* not tell you if a given route has PPR enabled, as that requires analysis of
* the route's configuration.
*
* @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.
*/
export function checkIsAppPPREnabled(
config: ExperimentalPPRConfig | undefined
): boolean {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config
// If the config is a string, it must be 'incremental' to enable partial
// prerendering.
if (config === 'incremental') return true
return false
}
/**
* Returns true if partial prerendering is supported for the current page with
* the provided app configuration. If the application doesn't have partial
* prerendering enabled, this function will always return false. If you want to
* check if the application has partial prerendering enabled
*
* @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.
*/
export function checkIsRoutePPREnabled(
config: ExperimentalPPRConfig | undefined
): boolean {
// If the config is undefined, partial prerendering is disabled.
if (typeof config === 'undefined') return false
// If the config is a boolean, use it directly.
if (typeof config === 'boolean') return config
return false
}
......@@ -365,6 +365,7 @@ export function createPatchedFetcher(
// TODO: Stop accumulating tags in client prerender. (fallthrough)
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -406,6 +407,7 @@ export function createPatchedFetcher(
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......@@ -576,6 +578,7 @@ export function createPatchedFetcher(
)
}
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -707,6 +710,7 @@ export function createPatchedFetcher(
)
}
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -752,6 +756,7 @@ export function createPatchedFetcher(
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
......@@ -903,6 +908,7 @@ export function createPatchedFetcher(
)
}
// fallthrough
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -985,6 +991,7 @@ export function createPatchedFetcher(
)
}
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -1113,6 +1120,7 @@ export function createPatchedFetcher(
)
}
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -1163,6 +1171,7 @@ export function createPatchedFetcher(
case 'private-cache':
case 'unstable-cache':
case 'prerender-legacy':
case 'prerender-ppr':
break
default:
workUnitStore satisfies never
......
......@@ -246,6 +246,7 @@ function patchConsoleMethod(methodName: InterceptableConsoleMethod): void {
}
// intentional fallthrough
case 'prerender-legacy':
case 'prerender-ppr':
case 'cache':
case 'unstable-cache':
case 'private-cache':
......
......@@ -146,6 +146,7 @@ export function io(expression: string, type: ApiType) {
}
break
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......
......@@ -614,6 +614,7 @@ function filteringUnhandledRejectionHandler(
}
break
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......
......@@ -4,6 +4,7 @@ import {
workUnitAsyncStorage,
} from '../app-render/work-unit-async-storage.external'
import {
postponeWithTracking,
throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
......@@ -92,6 +93,14 @@ export function connection(): Promise<void> {
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
)
}
case 'prerender-ppr':
// We use React's postpone API to interrupt rendering here to create a
// dynamic hole
return postponeWithTracking(
workStore.route,
'connection',
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
// We throw an error here to interrupt prerendering to mark the route
// as dynamic
......
......@@ -16,6 +16,7 @@ import {
isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external'
import {
postponeWithTracking,
throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
......@@ -81,6 +82,14 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
)
case 'prerender-ppr':
// We need track dynamic access here eagerly to keep continuity with
// how cookies has worked in PPR without cacheComponents.
return postponeWithTracking(
workStore.route,
callingExpression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
// We track dynamic access here so we don't need to wrap the cookies
// in individual property access tracking.
......
......@@ -12,6 +12,7 @@ import {
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import {
abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
......@@ -58,6 +59,7 @@ export function draftMode(): Promise<DraftMode> {
// Otherwise, we fall through to providing an empty draft mode.
// eslint-disable-next-line no-fallthrough
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
// Return empty draft mode
return createOrGetCachedDraftMode(null, workStore)
......@@ -226,6 +228,12 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
)
case 'prerender-ppr':
return postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
workUnitStore.revalidate = 0
......
......@@ -14,6 +14,7 @@ import {
isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external'
import {
postponeWithTracking,
throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
......@@ -79,6 +80,7 @@ export function headers(): Promise<ReadonlyHeaders> {
case 'validation-client':
case 'private-cache':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
break
......@@ -103,6 +105,16 @@ export function headers(): Promise<ReadonlyHeaders> {
throw new InvariantError(
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
)
case 'prerender-ppr':
// PPR Prerender (no cacheComponents)
// We are prerendering with PPR. We need track dynamic access here eagerly
// to keep continuity with how headers has worked in PPR without cacheComponents.
// TODO consider switching the semantic to throw on property access instead
return postponeWithTracking(
workStore.route,
callingExpression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
// Legacy Prerender
// We are in a legacy static generation mode while prerendering
......
......@@ -10,9 +10,15 @@ import {
} from '../app-render/vary-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
throwToInterruptStaticGeneration,
postponeWithTracking,
} from '../app-render/dynamic-rendering'
import {
workUnitAsyncStorage,
type PrerenderStorePPR,
type PrerenderStoreLegacy,
type StaticPrerenderStoreModern,
type StaticPrerenderStore,
throwInvariantForMissingStore,
......@@ -47,6 +53,7 @@ export function createParamsFromClient(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
// Client params don't need additional vary tracking because by the
// time they reach the client, the access would have already been
......@@ -126,6 +133,7 @@ export function createServerParamsForRoute(
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
return createStaticPrerenderParams(
underlyingParams,
......@@ -196,6 +204,7 @@ export function createServerParamsForServerSegment(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
return createStaticPrerenderParams(
underlyingParams,
......@@ -294,6 +303,7 @@ export function createPrerenderParamsForClientSegment(
throw new InvariantError(
'createPrerenderParamsForClientSegment should not be called in cache contexts.'
)
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
case 'request':
......@@ -345,6 +355,22 @@ function createStaticPrerenderParams(
}
break
}
case 'prerender-ppr': {
const fallbackParams = prerenderStore.fallbackRouteParams
if (fallbackParams) {
for (const key in underlyingParams) {
if (fallbackParams.has(key)) {
return makeErroringParams(
underlyingParamsWithVarying,
fallbackParams,
workStore,
prerenderStore
)
}
}
}
break
}
case 'prerender-legacy':
break
default:
......@@ -469,6 +495,65 @@ function makeHangingParams(
return promise
}
function makeErroringParams(
underlyingParams: Params,
fallbackParams: OpaqueFallbackRouteParams,
workStore: WorkStore,
prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy
): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
return cachedParams
}
const augmentedUnderlying = { ...underlyingParams }
// We don't use makeResolvedReactPromise here because params
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.resolve(augmentedUnderlying)
CachedParams.set(underlyingParams, promise)
Object.keys(underlyingParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
if (fallbackParams.has(prop)) {
Object.defineProperty(augmentedUnderlying, prop, {
get() {
const expression = describeStringPropertyAccess('params', prop)
// In most dynamic APIs we also throw if `dynamic = "error"` however
// for params is only dynamic when we're generating a fallback shell
// and even when `dynamic = "error"` we still support generating dynamic
// fallback shells
// TODO remove this comment when cacheComponents is the default since there
// will be no `dynamic = "error"`
if (prerenderStore.type === 'prerender-ppr') {
// PPR Prerender (no cacheComponents)
postponeWithTracking(
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
// Legacy Prerender
throwToInterruptStaticGeneration(
expression,
workStore,
prerenderStore
)
}
},
enumerable: true,
})
}
}
})
return promise
}
function makeUntrackedParams(underlyingParams: Params): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
......
......@@ -3,11 +3,17 @@ import {
type WorkStore,
} from '../app-render/work-async-storage.external'
import {
postponeWithTracking,
type DynamicTrackingState,
} from '../app-render/dynamic-rendering'
import {
throwInvariantForMissingStore,
workUnitAsyncStorage,
type PrerenderStoreLegacy,
type PrerenderStoreModernServer,
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external'
import {
delayUntilRuntimeStage,
......@@ -26,6 +32,7 @@ export function createServerPathnameForMetadata(
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': {
return createPrerenderPathname(
underlyingPathname,
......@@ -62,7 +69,10 @@ export function createServerPathnameForMetadata(
function createPrerenderPathname(
underlyingPathname: string,
workStore: WorkStore,
prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer
prerenderStore:
| PrerenderStoreLegacy
| PrerenderStorePPR
| PrerenderStoreModernServer
): Promise<string> {
switch (prerenderStore.type) {
case 'prerender': {
......@@ -76,6 +86,13 @@ function createPrerenderPathname(
}
break
}
case 'prerender-ppr': {
const fallbackParams = prerenderStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) {
return makeErroringPathname(workStore, prerenderStore.dynamicTracking)
}
break
}
case 'prerender-legacy':
break
default:
......@@ -86,6 +103,41 @@ function createPrerenderPathname(
return Promise.resolve(underlyingPathname)
}
function makeErroringPathname<T>(
workStore: WorkStore,
dynamicTracking: null | DynamicTrackingState
): Promise<T> {
let reject: null | ((reason: unknown) => void) = null
const promise = new Promise<T>((_, re) => {
reject = re
})
const originalThen = promise.then.bind(promise)
// We instrument .then so that we can generate a tracking event only if you actually
// await this promise, not just that it is created.
promise.then = (onfulfilled, onrejected) => {
if (reject) {
try {
postponeWithTracking(
workStore.route,
'metadata relative url resolving',
dynamicTracking
)
} catch (error) {
reject(error)
reject = null
}
}
return originalThen(onfulfilled, onrejected)
}
// We wrap in a noop proxy to trick the runtime into thinking it
// isn't a native promise (it's not really). This is so that awaiting
// the promise will call the `then` property triggering the lazy postpone
return new Proxy(promise, {})
}
function createRenderPathname(underlyingPathname: string): Promise<string> {
return Promise.resolve(underlyingPathname)
}
import { InvariantError } from '../../shared/lib/invariant-error'
import {
postponeWithTracking,
throwToInterruptStaticGeneration,
} from '../app-render/dynamic-rendering'
import {
workAsyncStorage,
type WorkStore,
......@@ -7,9 +11,11 @@ import {
workUnitAsyncStorage,
type PrerenderStoreLegacy,
type PrerenderStoreModernServer,
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import type { ParamValue } from './params'
import { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'
import { actionAsyncStorage } from '../app-render/action-async-storage.external'
import { accumulateRootVaryParam } from '../app-render/vary-params'
......@@ -59,6 +65,7 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
)
}
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy': {
return createPrerenderRootParamPromise(
paramName,
......@@ -90,12 +97,16 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
function createPrerenderRootParamPromise(
paramName: string,
workStore: WorkStore,
prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer,
prerenderStore:
| PrerenderStorePPR
| PrerenderStoreLegacy
| PrerenderStoreModernServer,
apiName: string
): Promise<ParamValue> {
switch (prerenderStore.type) {
case 'prerender':
case 'prerender-legacy':
case 'prerender-ppr':
default:
}
......@@ -117,6 +128,22 @@ function createPrerenderRootParamPromise(
}
break
}
case 'prerender-ppr': {
// We aren't in a cacheComponents prerender, but the param is a fallback,
// so we need to make an erroring params object which will postpone/error if you access it
if (
prerenderStore.fallbackRouteParams &&
prerenderStore.fallbackRouteParams.has(paramName)
) {
return makeErroringRootParamPromise(
paramName,
workStore,
prerenderStore,
apiName
)
}
break
}
case 'prerender-legacy': {
// legacy prerenders can't have fallback params
break
......@@ -130,3 +157,36 @@ function createPrerenderRootParamPromise(
accumulateRootVaryParam(paramName)
return Promise.resolve(underlyingParams[paramName])
}
/** Deliberately async -- we want to create a rejected promise, not error synchronously. */
async function makeErroringRootParamPromise(
paramName: string,
workStore: WorkStore,
prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy,
apiName: string
): Promise<ParamValue> {
const expression = describeStringPropertyAccess(apiName, paramName)
// In most dynamic APIs, we also throw if `dynamic = "error"`.
// However, root params are only dynamic when we're generating a fallback shell,
// and even with `dynamic = "error"` we still support generating dynamic fallback shells.
// TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = "error"`
switch (prerenderStore.type) {
case 'prerender-ppr': {
return postponeWithTracking(
workStore.route,
expression,
prerenderStore.dynamicTracking
)
}
case 'prerender-legacy': {
return throwToInterruptStaticGeneration(
expression,
workStore,
prerenderStore
)
}
default: {
prerenderStore satisfies never
}
}
}
......@@ -11,12 +11,14 @@ import {
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
throwToInterruptStaticGeneration,
postponeWithTracking,
annotateDynamicAccess,
} from '../app-render/dynamic-rendering'
import {
workUnitAsyncStorage,
type PrerenderStoreLegacy,
type PrerenderStorePPR,
type PrerenderStoreModern,
type PrerenderStoreModernRuntime,
type StaticPrerenderStore,
......@@ -54,6 +56,7 @@ export function createSearchParamsFromClient(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
return createStaticPrerenderSearchParams(workStore, workUnitStore)
case 'validation-client':
......@@ -112,6 +115,7 @@ export function createServerSearchParamsForServerPage(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
return createStaticPrerenderSearchParams(workStore, workUnitStore)
case 'validation-client':
......@@ -182,6 +186,7 @@ export function createPrerenderSearchParamsForClientPage(): Promise<SearchParams
throw new InvariantError(
'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'
)
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
return Promise.resolve({})
......@@ -207,6 +212,7 @@ function createStaticPrerenderSearchParams(
case 'prerender-client':
// We are in a cacheComponents (PPR or otherwise) prerender
return makeHangingSearchParams(workStore, prerenderStore)
case 'prerender-ppr':
case 'prerender-legacy':
// We are in a legacy static generation and need to interrupt the
// prerender when search params are accessed.
......@@ -330,7 +336,7 @@ function makeHangingSearchParams(
function makeErroringSearchParams(
workStore: WorkStore,
prerenderStore: PrerenderStoreLegacy
prerenderStore: PrerenderStoreLegacy | PrerenderStorePPR
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(workStore)
if (cachedSearchParams) {
......@@ -360,6 +366,13 @@ function makeErroringSearchParams(
workStore.route,
expression
)
} else if (prerenderStore.type === 'prerender-ppr') {
// PPR Prerender (no cacheComponents)
postponeWithTracking(
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
// Legacy Prerender
throwToInterruptStaticGeneration(
......
......@@ -60,6 +60,7 @@ import { StaticGenBailoutError } from '../../../client/components/static-generat
import { isStaticGenEnabled } from './helpers/is-static-gen-enabled'
import {
abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
createDynamicTrackingState,
getFirstDynamicReason,
} from '../../app-render/dynamic-rendering'
......@@ -1219,6 +1220,12 @@ function trackDynamic(
throw new InvariantError(
'A runtime prerender store should not be used for a route handler.'
)
case 'prerender-ppr':
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
workUnitStore.revalidate = 0
......
......@@ -88,6 +88,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
......
......@@ -15,6 +15,7 @@ export function cacheTag(...tags: string[]): void {
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
......
......@@ -59,6 +59,7 @@ import { getCacheHandler } from './handlers'
import { UseCacheTimeoutError } from './use-cache-errors'
import {
createHangingInputAbortSignal,
postponeWithTracking,
throwToInterruptStaticGeneration,
} from '../app-render/dynamic-rendering'
import {
......@@ -242,6 +243,7 @@ function createUseCacheStore(
break
case 'prerender-runtime':
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
......@@ -389,6 +391,7 @@ function propagateCacheLifeAndTags(
case 'private-cache':
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
propagateCacheLifeAndTagsToRevalidateStore(
cacheContext.outerWorkUnitStore,
......@@ -536,7 +539,8 @@ async function collectResult(
case 'private-cache':
case 'cache':
case 'unstable-cache':
case 'prerender-legacy': {
case 'prerender-legacy':
case 'prerender-ppr': {
propagateCacheLifeAndTags(cacheContext, entry)
break
}
......@@ -616,6 +620,7 @@ async function generateCacheEntryImpl(
}
})
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......@@ -756,6 +761,7 @@ async function generateCacheEntryImpl(
await new Promise((resolve) => setTimeout(resolve))
}
// fallthrough
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -954,6 +960,12 @@ export async function cache(
workStore.route,
expression
)
case 'prerender-ppr':
return postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
return throwToInterruptStaticGeneration(
expression,
......@@ -1015,6 +1027,7 @@ export async function cache(
)
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......@@ -1263,6 +1276,7 @@ export async function cache(
break
}
// fallthrough
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
// TODO(restart-on-cache-miss): We need to handle params/searchParams on page components.
......@@ -1422,6 +1436,7 @@ export async function cache(
}
break
}
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -1470,6 +1485,7 @@ export async function cache(
break
}
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -1545,6 +1561,7 @@ export async function cache(
}
break
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......@@ -1673,6 +1690,7 @@ export async function cache(
break
}
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......@@ -1927,6 +1945,7 @@ function shouldForceRevalidate(
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
......@@ -1970,6 +1989,7 @@ function shouldDiscardCacheEntry(
case 'prerender-runtime':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......
......@@ -302,6 +302,7 @@ export async function adapter(
params.request.nextConfig?.experimental?.cacheLife,
cacheComponents: false,
experimental: {
isRoutePPREnabled: false,
authInterrupts:
!!params.request.nextConfig?.experimental?.authInterrupts,
},
......
import { abortAndThrowOnSynchronousRequestDataAccess } from '../../app-render/dynamic-rendering'
import {
abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
} from '../../app-render/dynamic-rendering'
import { isDynamicRoute } from '../../../shared/lib/router/utils'
import {
NEXT_CACHE_IMPLICIT_TAG_ID,
......@@ -161,6 +164,12 @@ function revalidate(
throw new InvariantError(
`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`
)
case 'prerender-ppr':
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
workUnitStore.revalidate = 0
......
......@@ -165,6 +165,7 @@ export function unstable_cache<T extends Callback>(
case 'private-cache':
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
// We update the store's revalidate property if the option.revalidate is a higher precedence
// options.revalidate === undefined doesn't affect timing.
......@@ -411,6 +412,7 @@ function getFetchUrlPrefix(
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
......
......@@ -38,6 +38,7 @@ export function unstable_noStore() {
case 'prerender-runtime':
// unstable_noStore() is a noop in Dynamic I/O.
return
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
......
......@@ -19,7 +19,7 @@ describe.skip('static-shell-debugging', () => {
: undefined,
},
nextConfig: {
cacheComponents: context.ppr,
experimental: { ppr: context.ppr },
},
})
......
......@@ -156,6 +156,21 @@ describe('Config Experimental Warning', () => {
expect(stdout).toMatch(' · cpus: 2')
})
// TODO: the incremental option has been removed, update to another string feature
it.skip('should show the configured value for string features', async () => {
configFile.write(`
module.exports = {
experimental: {
ppr: 'incremental'
}
}
`)
const stdout = await collectStdoutFromDev(appDir)
expect(stdout).toMatch(experimentalHeader)
expect(stdout).toMatch(' · ppr: "incremental"')
})
it('should show warning with config from object with experimental and multiple keys', async () => {
configFile.write(`
module.exports = {
......
import { Suspense } from 'react'
import { connection } from 'next/server'
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<DynamicContent />
</Suspense>
)
}
async function DynamicContent() {
export default async function Page() {
await connection()
return <p>dynamic</p>
}
import { Suspense } from 'react'
import { connection } from 'next/server'
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<DynamicContent />
</Suspense>
)
}
async function DynamicContent() {
export default async function Page() {
await connection()
return <p>ppr</p>
}
export const experimental_ppr = true
import { nextTestSetup } from 'e2e-utils'
describe('app-dir - metadata-streaming-config-customized', () => {
// TODO: the incremental option has been removed, update to use cacheComponents
describe.skip('app-dir - metadata-streaming-config-customized', () => {
const { next } = nextTestSetup({
files: __dirname,
skipDeployment: true,
......@@ -8,7 +9,9 @@ describe('app-dir - metadata-streaming-config-customized', () => {
'next.config.js': `
module.exports = {
htmlLimitedBots: /MyBot/i,
cacheComponents: true,
experimental: {
ppr: 'incremental',
}
}
`,
},
......@@ -30,26 +33,6 @@ describe('app-dir - metadata-streaming-config-customized', () => {
expect(bypassConfigs).toMatchInlineSnapshot(`
{
"/": {
"key": "user-agent",
"type": "header",
"value": "MyBot",
},
"/_global-error": {
"key": "user-agent",
"type": "header",
"value": "MyBot",
},
"/_not-found": {
"key": "user-agent",
"type": "header",
"value": "MyBot",
},
"/dynamic": {
"key": "user-agent",
"type": "header",
"value": "MyBot",
},
"/ppr": {
"key": "user-agent",
"type": "header",
......
......@@ -2,7 +2,9 @@
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
ppr: 'incremental',
},
}
module.exports = nextConfig
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