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

[PPF] Scaffold `unstable_ensureStatic` segment config (#98190)

Adds the necessary plumbing and validation for a `unstable_ensureStatic`
segment config, allowing `"auto" | "shell" | "prefetch" | "navigation" |
false`

Also dedupes some checks that we were doing for `instant` and
`prefetch`, because `requireStatic` needs them too:
- is not exported from a client module
- is not used without Cache Components
parent a2470dbd
...@@ -124,6 +124,9 @@ pub struct NextSegmentConfig { ...@@ -124,6 +124,9 @@ pub struct NextSegmentConfig {
#[turbo_tasks(trace_ignore)] #[turbo_tasks(trace_ignore)]
#[bincode(with_serde)] #[bincode(with_serde)]
pub prefetch: Option<Span>, pub prefetch: Option<Span>,
#[turbo_tasks(trace_ignore)]
#[bincode(with_serde)]
pub unstable_ensure_static: Option<Span>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -548,36 +551,29 @@ pub async fn parse_segment_config_from_source( ...@@ -548,36 +551,29 @@ pub async fn parse_segment_config_from_source(
.await?; .await?;
} }
if let Some(span) = config.instant { let server_only_route_configs = [
invalid_config( ("instant", config.instant),
source, ("prefetch", config.prefetch),
"instant", ("unstable_ensureStatic", config.unstable_ensure_static),
span, ];
rcstr!( for (config_name, usage) in server_only_route_configs {
"\"instant\" is a route segment config and can only be used when the segment \ if let Some(span) = usage {
is a Server Component module. Remove the \"use client\" directive to use \ invalid_config(
this API." source,
), config_name,
None, span,
IssueSeverity::Error, format!(
) "\"{}\" is a route segment config and can only be used when the segment \
.await?; is a Server Component module. Remove the \"use client\" directive to use \
} this API.",
config_name
if let Some(span) = config.prefetch { )
invalid_config( .into(),
source, None,
"prefetch", IssueSeverity::Error,
span, )
rcstr!( .await?;
"\"prefetch\" is a route segment config and can only be used when the segment \ }
is a Server Component module. Remove the \"use client\" directive to use \
this API."
),
None,
IssueSeverity::Error,
)
.await?;
} }
} }
...@@ -1006,6 +1002,9 @@ async fn parse_config_value( ...@@ -1006,6 +1002,9 @@ async fn parse_config_value(
"prefetch" => { "prefetch" => {
config.prefetch = Some(span); config.prefetch = Some(span);
} }
"unstable_ensureStatic" => {
config.unstable_ensure_static = Some(span);
}
_ => {} _ => {}
} }
......
...@@ -692,30 +692,24 @@ export async function getAppPageStaticInfo({ ...@@ -692,30 +692,24 @@ export async function getAppPageStaticInfo({
) )
} }
// Prevent use client and instant in the same file. for (const exportName of [
if (directives?.has('client') && 'instant' in config) { 'instant',
throw new Error( 'prefetch',
`"instant" is a route segment config and can only be used when the segment is a Server Component module. Remove the "use client" directive from "${pageFilePath}" to use this API.` 'unstable_ensureStatic',
) ] as const) {
} if (exportName in config) {
if (directives?.has('client')) {
if ('instant' in config && !nextConfig.cacheComponents) { throw new Error(
throw new Error( `"${exportName}" is a route segment config and can only be used when the segment is a Server Component module. Remove the "use client" directive from "${pageFilePath}" to use this API.`
`Route "${page}" cannot use \`export const instant = ...\` without enabling \`cacheComponents\`.` )
) }
}
// Prevent use client and prefetch in the same file.
if (directives?.has('client') && 'prefetch' in config) {
throw new Error(
`"prefetch" is a route segment config and can only be used when the segment is a Server Component module. Remove the "use client" directive from "${pageFilePath}" to use this API.`
)
}
if ('prefetch' in config && !nextConfig.cacheComponents) { if (!nextConfig.cacheComponents) {
throw new Error( throw new Error(
`Route "${page}" cannot use \`export const prefetch = ...\` without enabling \`cacheComponents\`.` `Route "${page}" cannot use \`export const ${exportName} = ...\` without enabling \`cacheComponents\`.`
) )
}
}
} }
// Prevent unstable_dynamicStaleTime in layouts. // Prevent unstable_dynamicStaleTime in layouts.
......
...@@ -38,10 +38,17 @@ const InstantConfigSchema = z.union([ ...@@ -38,10 +38,17 @@ const InstantConfigSchema = z.union([
const PrefetchSchema = z.enum(['auto', 'partial', 'force-disabled']) const PrefetchSchema = z.enum(['auto', 'partial', 'force-disabled'])
const EnsureStaticSchema = z.union([
z.enum(['auto', 'shell', 'prefetch', 'navigation']),
z.literal(false),
])
export type Instant = InstantConfig | true | false export type Instant = InstantConfig | true | false
export type Prefetch = 'auto' | 'partial' | 'force-disabled' export type Prefetch = 'auto' | 'partial' | 'force-disabled'
export type EnsureStatic = 'auto' | 'shell' | 'prefetch' | 'navigation' | false
export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
// the __GenericInstantConfig type is used to avoid type widening issues with // the __GenericInstantConfig type is used to avoid type widening issues with
// our choice to make exports the medium for programming a Next.js application // our choice to make exports the medium for programming a Next.js application
...@@ -137,6 +144,11 @@ const AppSegmentConfigSchema = z.object({ ...@@ -137,6 +144,11 @@ const AppSegmentConfigSchema = z.object({
*/ */
prefetch: PrefetchSchema.optional(), prefetch: PrefetchSchema.optional(),
/**
* Controls which rendering phases require static output for this segment.
*/
unstable_ensureStatic: EnsureStaticSchema.optional(),
/** /**
* The stale time for dynamic responses in seconds. * The stale time for dynamic responses in seconds.
* Controls how long the client-side router cache retains dynamic page data. * Controls how long the client-side router cache retains dynamic page data.
...@@ -192,6 +204,11 @@ export function parseAppSegmentConfig( ...@@ -192,6 +204,11 @@ export function parseAppSegmentConfig(
message: `Invalid prefetch value ${JSON.stringify(ctx.data)} on "${route}", must be "auto", "partial", or "force-disabled".`, message: `Invalid prefetch value ${JSON.stringify(ctx.data)} on "${route}", must be "auto", "partial", or "force-disabled".`,
} }
} }
case 'unstable_ensureStatic': {
return {
message: `Invalid unstable_ensureStatic value ${JSON.stringify(ctx.data)} on "${route}", must be "auto", "shell", "prefetch", "navigation", or false.`,
}
}
case 'unstable_dynamicStaleTime': { case 'unstable_dynamicStaleTime': {
return { return {
message: `Invalid unstable_dynamicStaleTime value ${JSON.stringify(ctx.data)} on "${route}", must be a non-negative number`, message: `Invalid unstable_dynamicStaleTime value ${JSON.stringify(ctx.data)} on "${route}", must be a non-negative number`,
...@@ -261,6 +278,11 @@ export type AppSegmentConfig = { ...@@ -261,6 +278,11 @@ export type AppSegmentConfig = {
*/ */
prefetch?: Prefetch prefetch?: Prefetch
/**
* Controls which rendering phases require static output for this segment.
*/
unstable_ensureStatic?: EnsureStatic
/** /**
* The stale time for dynamic responses in seconds. * The stale time for dynamic responses in seconds.
* Controls how long the client-side router cache retains dynamic page data. * Controls how long the client-side router cache retains dynamic page data.
......
...@@ -54,7 +54,7 @@ ${ ...@@ -54,7 +54,7 @@ ${
: `import type { ResolvingMetadata, ResolvingViewport } from 'next/dist/lib/metadata/types/metadata-interface.js'` : `import type { ResolvingMetadata, ResolvingViewport } from 'next/dist/lib/metadata/types/metadata-interface.js'`
} }
import type { InstantConfigForTypeCheckInternal, Prefetch } from 'next/dist/build/segment-config/app/app-segment-config.js' import type { InstantConfigForTypeCheckInternal, Prefetch, EnsureStatic } from 'next/dist/build/segment-config/app/app-segment-config.js'
type TEntry = typeof import('${relativePath}.js') type TEntry = typeof import('${relativePath}.js')
...@@ -73,6 +73,7 @@ checkFields<Diff<{ ...@@ -73,6 +73,7 @@ checkFields<Diff<{
generateStaticParams?: Function generateStaticParams?: Function
instant?: InstantConfigForTypeCheckInternal instant?: InstantConfigForTypeCheckInternal
prefetch?: Prefetch prefetch?: Prefetch
unstable_ensureStatic?: EnsureStatic
unstable_dynamicStaleTime?: number unstable_dynamicStaleTime?: number
revalidate?: RevalidateRange<TEntry> | false revalidate?: RevalidateRange<TEntry> | false
dynamic?: 'auto' | 'force-dynamic' | 'error' | 'force-static' dynamic?: 'auto' | 'force-dynamic' | 'error' | 'force-static'
......
...@@ -1043,7 +1043,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -1043,7 +1043,7 @@ export class AppRouteRouteModule extends RouteModule<
break break
case 'error': case 'error':
workStore.dynamicShouldError = true workStore.dynamicShouldError = true
request = new Proxy(req, requireStaticRequestHandlers) request = new Proxy(req, ensureStaticRequestHandlers)
break break
case undefined: case undefined:
case 'auto': case 'auto':
...@@ -1361,7 +1361,7 @@ function proxyNextRequest(request: NextRequest, workStore: WorkStore) { ...@@ -1361,7 +1361,7 @@ function proxyNextRequest(request: NextRequest, workStore: WorkStore) {
return new Proxy(request, nextRequestHandlers) return new Proxy(request, nextRequestHandlers)
} }
const requireStaticRequestHandlers = { const ensureStaticRequestHandlers = {
get( get(
target: NextRequest & RequestSymbolTarget, target: NextRequest & RequestSymbolTarget,
prop: string | symbol, prop: string | symbol,
...@@ -1373,7 +1373,7 @@ const requireStaticRequestHandlers = { ...@@ -1373,7 +1373,7 @@ const requireStaticRequestHandlers = {
target[nextURLSymbol] || target[nextURLSymbol] ||
(target[nextURLSymbol] = new Proxy( (target[nextURLSymbol] = new Proxy(
target.nextUrl, target.nextUrl,
requireStaticNextUrlHandlers ensureStaticNextUrlHandlers
)) ))
) )
case 'headers': case 'headers':
...@@ -1401,7 +1401,7 @@ const requireStaticRequestHandlers = { ...@@ -1401,7 +1401,7 @@ const requireStaticRequestHandlers = {
// to probably embed the static generation logic into the class itself removing the need // to probably embed the static generation logic into the class itself removing the need
// for any kind of proxying // for any kind of proxying
target.clone() as NextRequest, target.clone() as NextRequest,
requireStaticRequestHandlers ensureStaticRequestHandlers
)) ))
) )
default: default:
...@@ -1412,7 +1412,7 @@ const requireStaticRequestHandlers = { ...@@ -1412,7 +1412,7 @@ const requireStaticRequestHandlers = {
// and will be ignored // and will be ignored
} }
const requireStaticNextUrlHandlers = { const ensureStaticNextUrlHandlers = {
get( get(
target: NextURL & UrlSymbolTarget, target: NextURL & UrlSymbolTarget,
prop: string | symbol, prop: string | symbol,
...@@ -1433,7 +1433,7 @@ const requireStaticNextUrlHandlers = { ...@@ -1433,7 +1433,7 @@ const requireStaticNextUrlHandlers = {
return ( return (
target[urlCloneSymbol] || target[urlCloneSymbol] ||
(target[urlCloneSymbol] = () => (target[urlCloneSymbol] = () =>
new Proxy(target.clone(), requireStaticNextUrlHandlers)) new Proxy(target.clone(), ensureStaticNextUrlHandlers))
) )
default: default:
return ReflectAdapter.get(target, prop, receiver) return ReflectAdapter.get(target, prop, receiver)
......
...@@ -9,7 +9,10 @@ import { ...@@ -9,7 +9,10 @@ import {
} from '../utils' } from '../utils'
import { NEXT_TS_ERRORS, ALLOWED_EXPORTS } from '../constant' import { NEXT_TS_ERRORS, ALLOWED_EXPORTS } from '../constant'
import type tsModule from 'typescript/lib/tsserverlibrary' import type tsModule from 'typescript/lib/tsserverlibrary'
import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config' import type {
AppSegmentConfig,
EnsureStatic,
} from '../../../build/segment-config/app/app-segment-config'
const API_DOCS: Record< const API_DOCS: Record<
string, string,
...@@ -168,6 +171,32 @@ const API_DOCS: Record< ...@@ -168,6 +171,32 @@ const API_DOCS: Record<
}, },
insertText: `prefetch = 'partial';`, insertText: `prefetch = 'partial';`,
}, },
unstable_ensureStatic: {
description: `Controls which rendering phases require static output for this segment. This option is experimental and may change.`,
link: '(docs coming soon)',
type: `"auto" | "shell" | "prefetch" | "navigation" | false`,
options: {
'"auto"':
'Default. The shell, prefetch, or entire page will automatically be prerendered statically if possible.',
'"shell"': 'Force the shell for the route to be prerendered statically.',
'"prefetch"':
'Force both the shell and the prefetch (`<Link prefetch={true}>`) for the route to be prerendered statically.',
'"navigation"': 'Require the route to be fully static.',
false:
'Indicate that this segment must use the default behavior and should not have `ensureStatic = "shell" | "prefetch" | "navigation"` applied to it by another segment. Errors if another segment on the route uses `ensureStatic` with those values.',
} satisfies DocsOptionsObject<
FullAppSegmentConfig['unstable_ensureStatic']
>,
insertText: `unstable_ensureStatic = 'shell';`,
isValid: (value) => {
try {
const parsed: unknown = JSON.parse(value)
return (VALID_ENSURE_STATIC_VALUES as unknown[]).includes(parsed)
} catch {
return false
}
},
},
unstable_dynamicStaleTime: { unstable_dynamicStaleTime: {
description: `Controls how long the client-side router cache retains dynamic page data (in seconds). Pages only — not allowed in layouts. Cannot be combined with \`instant\`.`, description: `Controls how long the client-side router cache retains dynamic page data (in seconds). Pages only — not allowed in layouts. Cannot be combined with \`instant\`.`,
link: '(docs coming soon)', link: '(docs coming soon)',
...@@ -181,6 +210,14 @@ const API_DOCS: Record< ...@@ -181,6 +210,14 @@ const API_DOCS: Record<
}, },
} }
const VALID_ENSURE_STATIC_VALUES: EnsureStatic[] = [
'auto',
'shell',
'prefetch',
'navigation',
false,
]
type FullAppSegmentConfig = Required<AppSegmentConfig> type FullAppSegmentConfig = Required<AppSegmentConfig>
/** /**
......
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