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