Unverified Commit 7bbea9d4 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Instant] Build-time validation (#90964)

Initial version of build-time instant validation.

During prerendering, if we have `unstable_instant` configs, we perform a
complete staged render of the page (including dynamic data). This render
mocks request data (`params`/`searchParams`/`cookies`/`headers`) using
the `samples` provided in `unstable_instant`. Then, we use the staged
chunks to run instant validation in mostly the same way that we would in
dev. Most changes in the validation flow are related to samples, which
also need to be passed into the client render to mock APIs like
`useParams`.

### Providing Mock data

We run everything in a fresh workStore+workUnitStore to (hopefully)
avoid any data from the prerender from sneaking in. This is quite
involved.

A big part of the trickiness is that if you do e.g. `(await
cookies()).get('myCookie')` but the `samples` don't contain `myCookie`,
we want the validation to error and require explicitly saying what state
`myCookie` is in.
If it's available, use
```ts
export const unstable_instant = {
  // ...
  samples: { cookies: [{ name: "myCookie", value: "someValue" }] }
}
```
If it's not available, use
```ts
export const unstable_instant = {
  // ...
  samples: { cookies: [{ name: "myCookie", value: null }] }
}
```
This explicitness makes it harder to e.g. unintentionally validate a
logged-out state.

Note that even validating a `prefetch: 'static'` page might require
samples, because we need the shared parent for the navigation to be
(mostly) complete. We might be able to relax this in the future, but
it's not straightforward.

Another issue is that a segment might access a missing sample in a
"benign" way, i.e. where it wouldn't block validation (or be inside a
suspense boundary). Ideally we wouldn't require providing a sample for
usages like that, but currently we do.

### Instrumenting APIs to detect missing samples

All request APIs are instrumented in this way.
- `params` throw when accessing a property that was not declared in
`samples`. same for the object from `useParams()`. `in` is allowed
because we know the shape of the params object statically, based on the
routing structure.
- `searchParams` throw when accessing a property that was not declared
in `samples` and `in` checks.
- objects returned from `cookies()`, `headers()`, `useSearchPrams()`
throw on `get()` and `has()`.

There's a lot of tests for this behavior in `instant-validation-build`.

One gap is that iteration/enumeration is currently not instrumented.
We're punting on it for now and will revisit in a follow-up.

### Relation to prerender

We kick off the validation after the prerender, in
`renderToHTMLOrFlightImpl`. Ideally, we should kick this off somewhere
higher up, separately from the prerender itself, but we're leaving that
for future work.

Note that if we do multiple prerenders for the same page (e.g. due to
`generateStaticParams`, we'll only run validation for the first
prerender for that route. `generateStaticParams` is not currently
integrated into the validation at all, i.e. we don't use those params to
validate, so this is safe. All params need to be provided via `samples`.
This will likely change in the future, but we're not sure how yet.

### Disabling build validation

Build-time instant validation is experimental, and has more potential
problems to deal with than dev validation. To allow incremental rollout
and testing, we allow disabling it per instant config:
```ts
export const unstable_instant = {
  unstable_disableBuildValidation: true
  // ...
}
```

for parity, there's also `unstable_disableBuildValidation`, but we don't
expect that to see much use.
parent 87b7ca09
...@@ -57,6 +57,7 @@ fn is_error_class_name(name: &str) -> bool { ...@@ -57,6 +57,7 @@ fn is_error_class_name(name: &str) -> bool {
|| name == "ExportError" || name == "ExportError"
|| name == "FatalError" || name == "FatalError"
|| name == "ImageError" || name == "ImageError"
|| name == "InstantValidationError"
|| name == "InvariantError" || name == "InvariantError"
|| name == "ModuleBuildError" || name == "ModuleBuildError"
|| name == "NestedMiddlewareError" || name == "NestedMiddlewareError"
......
...@@ -1088,5 +1088,32 @@ ...@@ -1088,5 +1088,32 @@
"1087": "Failed to parse \"%s\":\\n%s%s", "1087": "Failed to parse \"%s\":\\n%s%s",
"1088": "Expected RSC navigation response to have a body", "1088": "Expected RSC navigation response to have a body",
"1089": "\\`experimental.cachedNavigations\\` requires \\`cacheComponents\\` to be enabled. Please update your %s accordingly.", "1089": "\\`experimental.cachedNavigations\\` requires \\`cacheComponents\\` to be enabled. Please update your %s accordingly.",
"1090": "`css.lightning.featureNamesToMask` is not supported by the wasm bindings." "1090": "`css.lightning.featureNamesToMask` is not supported by the wasm bindings.",
"1091": "Route \"%s\" accessed searchParam \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`searchParams\\` object, or \\`{ \"%s\": undefined }\\` if it should be absent.",
"1092": "Draft mode cannot be enabled during build-time instant validation.",
"1093": "Build-time instant validation failed for route \"%s\"%s:\\n%s",
"1094": "Draft mode cannot be disabled during build-time instant validation.",
"1095": "Route \"%s\" accessed param \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`params\\` object.",
"1096": "Route \"%s\" accessed %s \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`%s\\` array%s",
"1097": "An unexpected error occcured during instant validation",
"1098": "Route \"%s\" accessed searchParam \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`searchParams\\` object, or \\`{ \"%s\": null }\\` if it should be absent.",
"1099": "createPrerenderParamsForClientSegment should not be called in validation contexts.",
"1100": "Stopping prerender due to instant validation errors.",
"1101": "createServerParamsForServerSegment should not be called in client contexts.",
"1102": "Cannot call \\`%s\\` during instant validation unless all params are provided in \\`samples\\`",
"1103": "Expected sample param value for segment '%s' to a string, got %s",
"1104": "Expected sample param value for segment '%s' to be an array of strings, got %s",
"1105": "Route \"%s\" called usePathname() but param%s %s %s not defined in the \\`samples\\` of \\`unstable_instant\\`. usePathname() requires all route params to be provided.",
"1106": "Not implemented: Validation of interception routes",
"1107": "Invalid sample: Defining cookies via a \"cookie\" header is not supported. Use `cookies: [{ name: ..., value: ...}]` instead.",
"1108": "Expected sample param value for segment '%s' to be a string, got %s",
"1109": "Route \"%s\" called %s but param%s %s %s not defined in the \\`samples\\` of \\`unstable_instant\\`. %s requires all route params to be provided.",
"1110": "Expected to have a workUnitStore that provides validationSampleTracking",
"1111": "Invalid sample: Defining cookies via a \"cookie\" header is not supported. Use `cookies: [{ name: ..., value: ... }]` instead.",
"1112": "Route \"%s\": Could not validate \\`unstable_instant\\` because an error prevented the target segment from rendering.",
"1113": "Route \"%s\": Could not validate \\`unstable_instant\\` because an error prevented the page from rendering.",
"1114": "Route \"%s\" accessed root param \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`params\\` object.",
"1115": "Route \"%s\" accessed cookie \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`cookies\\` array, or \\`{ name: \"%s\", value: null }\\` if it should be absent.",
"1116": "Route \"%s\" accessed header \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`headers\\` array, or \\`[\"%s\", null]\\` if it should be absent.",
"1117": "Instant validation boundaries should never appear in browser bundles."
} }
...@@ -4,19 +4,17 @@ import { formatZodError } from '../../../shared/lib/zod' ...@@ -4,19 +4,17 @@ import { formatZodError } from '../../../shared/lib/zod'
const CookieSchema = z const CookieSchema = z
.object({ .object({
name: z.string(), name: z.string(),
value: z.string(), value: z.string().or(z.null()),
httpOnly: z.boolean().optional(),
path: z.string().optional(),
}) })
.strict() .strict()
const RuntimeSampleSchema = z const RuntimeSampleSchema = z
.object({ .object({
cookies: z.array(CookieSchema).optional(), cookies: z.array(CookieSchema).optional(),
headers: z.array(z.tuple([z.string(), z.string()])).optional(), headers: z.array(z.tuple([z.string(), z.string().or(z.null())])).optional(),
params: z.record(z.union([z.string(), z.array(z.string())])).optional(), params: z.record(z.union([z.string(), z.array(z.string())])).optional(),
searchParams: z searchParams: z
.record(z.union([z.string(), z.array(z.string()), z.undefined()])) .record(z.union([z.string(), z.array(z.string()), z.null()]))
.optional(), .optional(),
}) })
.strict() .strict()
...@@ -24,8 +22,11 @@ const RuntimeSampleSchema = z ...@@ -24,8 +22,11 @@ const RuntimeSampleSchema = z
const InstantConfigStaticSchema = z const InstantConfigStaticSchema = z
.object({ .object({
prefetch: z.literal('static'), prefetch: z.literal('static'),
samples: z.array(RuntimeSampleSchema).min(1).optional(),
from: z.array(z.string()).optional(), from: z.array(z.string()).optional(),
unstable_disableValidation: z.boolean().optional(), unstable_disableValidation: z.literal(true).optional(),
unstable_disableDevValidation: z.literal(true).optional(),
unstable_disableBuildValidation: z.literal(true).optional(),
}) })
.strict() .strict()
...@@ -34,7 +35,9 @@ const InstantConfigRuntimeSchema = z ...@@ -34,7 +35,9 @@ const InstantConfigRuntimeSchema = z
prefetch: z.literal('runtime'), prefetch: z.literal('runtime'),
samples: z.array(RuntimeSampleSchema).min(1), samples: z.array(RuntimeSampleSchema).min(1),
from: z.array(z.string()).optional(), from: z.array(z.string()).optional(),
unstable_disableValidation: z.boolean().optional(), unstable_disableValidation: z.literal(true).optional(),
unstable_disableDevValidation: z.literal(true).optional(),
unstable_disableBuildValidation: z.literal(true).optional(),
}) })
.strict() .strict()
...@@ -47,6 +50,7 @@ const InstantConfigSchema = z.union([ ...@@ -47,6 +50,7 @@ const InstantConfigSchema = z.union([
]) ])
export type Instant = InstantConfigStatic | InstantConfigRuntime | false export type Instant = InstantConfigStatic | InstantConfigRuntime | false
export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
// the __GenericPrefetch type is used to avoid type widening issues with // the __GenericPrefetch 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
...@@ -56,41 +60,46 @@ export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant ...@@ -56,41 +60,46 @@ export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
// delete the __GenericPrefetch member. // delete the __GenericPrefetch member.
interface __GenericInstantConfig { interface __GenericInstantConfig {
prefetch: string prefetch: string
samples?: Array<WideRuntimeSample> samples?: Array<WideInstantSample>
from?: string[] from?: string[]
unstable_disableValidation?: boolean unstable_disableValidation?: boolean
unstable_disableDevValidation?: boolean
unstable_disableBuildValidation?: boolean
} }
interface InstantConfigStatic { interface InstantConfigStatic {
prefetch: 'static' prefetch: 'static'
samples?: Array<InstantSample>
from?: string[] from?: string[]
unstable_disableValidation?: boolean unstable_disableValidation?: true
unstable_disableDevValidation?: true
unstable_disableBuildValidation?: true
} }
interface InstantConfigRuntime { interface InstantConfigRuntime {
prefetch: 'runtime' prefetch: 'runtime'
samples: Array<RuntimeSample> samples: Array<InstantSample>
from?: string[] from?: string[]
unstable_disableValidation?: boolean unstable_disableValidation?: true
unstable_disableDevValidation?: true
unstable_disableBuildValidation?: true
} }
type WideRuntimeSample = { type WideInstantSample = {
cookies?: RuntimeSample['cookies'] cookies?: InstantSample['cookies']
headers?: Array<string[]> headers?: Array<string[]>
params?: RuntimeSample['params'] params?: InstantSample['params']
searchParams?: RuntimeSample['searchParams'] searchParams?: InstantSample['searchParams']
} }
type RuntimeSample = { export type InstantSample = {
cookies?: Array<{ cookies?: Array<{
name: string name: string
value: string value: string | null
httpOnly?: boolean
path?: string
}> }>
headers?: Array<[string, string]> headers?: Array<[string, string | null]>
params?: { [key: string]: string | string[] } params?: { [key: string]: string | string[] }
searchParams?: { [key: string]: string | string[] | undefined } searchParams?: { [key: string]: string | string[] | null }
} }
/** /**
......
'use client'
// This facade ensures that the boundary code is DCE'd in browser bundles.
//
// It also exists to satisfy `browser-chunks.test.ts`, which looks for
// references to code in `packages/next/src/server` in browser bundles and errors if it finds any.
// A "use client" module seems to always have always have an entry in the browser bundle,
// so this module cannot be colocated with the rest of the instant validation code,
// because it ends up looking like it's importing server code in the browser
// even though all the server code inside is actually DCE'd.
const {
InstantValidationBoundaryContext,
PlaceValidationBoundaryBelowThisLevel,
RenderValidationBoundaryAtThisLevel,
} =
typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS
? (require('../../../server/app-render/instant-validation/boundary-impl') as typeof import('../../../server/app-render/instant-validation/boundary-impl'))
: ({} as typeof import('../../../server/app-render/instant-validation/boundary-impl'))
export {
InstantValidationBoundaryContext,
PlaceValidationBoundaryBelowThisLevel,
RenderValidationBoundaryAtThisLevel,
}
...@@ -695,13 +695,9 @@ export default function OuterLayoutRouter({ ...@@ -695,13 +695,9 @@ export default function OuterLayoutRouter({
} }
let maybeValidationBoundaryId: string | null = null let maybeValidationBoundaryId: string | null = null
if ( if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {
typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_DEV_SERVER
) {
const { InstantValidationBoundaryContext } = const { InstantValidationBoundaryContext } =
require('../../server/app-render/instant-validation/boundary') as typeof import('../../server/app-render/instant-validation/boundary') require('./instant-validation/boundary') as typeof import('./instant-validation/boundary')
maybeValidationBoundaryId = use(InstantValidationBoundaryContext) maybeValidationBoundaryId = use(InstantValidationBoundaryContext)
} }
...@@ -838,11 +834,10 @@ export default function OuterLayoutRouter({ ...@@ -838,11 +834,10 @@ export default function OuterLayoutRouter({
if ( if (
typeof window === 'undefined' && typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS && process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_DEV_SERVER &&
typeof maybeValidationBoundaryId === 'string' typeof maybeValidationBoundaryId === 'string'
) { ) {
const { RenderValidationBoundaryAtThisLevel } = const { RenderValidationBoundaryAtThisLevel } =
require('../../server/app-render/instant-validation/boundary') as typeof import('../../server/app-render/instant-validation/boundary') require('./instant-validation/boundary') as typeof import('./instant-validation/boundary')
templateValue = ( templateValue = (
<RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}> <RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}>
{templateValue} {templateValue}
......
...@@ -21,11 +21,9 @@ function hasFallbackRouteParams(): boolean { ...@@ -21,11 +21,9 @@ function hasFallbackRouteParams(): boolean {
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
case 'prerender-ppr': case 'prerender-ppr':
case 'validation-client':
const fallbackParams = workUnitStore.fallbackRouteParams const fallbackParams = workUnitStore.fallbackRouteParams
return fallbackParams ? fallbackParams.size > 0 : false return fallbackParams ? fallbackParams.size > 0 : false
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
return false
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'prerender-runtime': case 'prerender-runtime':
......
...@@ -32,6 +32,15 @@ const useDynamicSearchParams = ...@@ -32,6 +32,15 @@ const useDynamicSearchParams =
).useDynamicSearchParams ).useDynamicSearchParams
: undefined : undefined
const {
instrumentParamsForClientValidation,
instrumentSearchParamsForClientValidation,
expectCompleteParamsInClientValidation,
} =
typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS
? (require('../../server/app-render/instant-validation/instant-samples-client') as typeof import('../../server/app-render/instant-validation/instant-samples-client'))
: {}
/** /**
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
* that lets you *read* the current URL's search parameters. * that lets you *read* the current URL's search parameters.
...@@ -71,6 +80,16 @@ export function useSearchParams(): ReadonlyURLSearchParams { ...@@ -71,6 +80,16 @@ export function useSearchParams(): ReadonlyURLSearchParams {
return new ReadonlyURLSearchParams(searchParams) return new ReadonlyURLSearchParams(searchParams)
}, [searchParams]) }, [searchParams])
// During build-time instant validation, wrap with an proxy
// so that accessing undeclared search params throws an error.
if (
typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS &&
readonlySearchParams
) {
return instrumentSearchParamsForClientValidation!(readonlySearchParams)
}
// Instrument with Suspense DevTools (dev-only) // Instrument with Suspense DevTools (dev-only)
if (process.env.NODE_ENV !== 'production' && 'use' in React) { if (process.env.NODE_ENV !== 'production' && 'use' in React) {
const navigationPromises = use(NavigationPromisesContext) const navigationPromises = use(NavigationPromisesContext)
...@@ -107,6 +126,17 @@ export function usePathname(): string { ...@@ -107,6 +126,17 @@ export function usePathname(): string {
// will add a new overload that changes the return type to include `null`. // will add a new overload that changes the return type to include `null`.
const pathname = useContext(PathnameContext) as string const pathname = useContext(PathnameContext) as string
// During build-time instant validation, error if fallback params exist
// because usePathname() can't return a sensible value without all params.
if (
typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS &&
pathname
) {
expectCompleteParamsInClientValidation!('usePathname()')
return pathname
}
// Instrument with Suspense DevTools (dev-only) // Instrument with Suspense DevTools (dev-only)
if (process.env.NODE_ENV !== 'production' && 'use' in React) { if (process.env.NODE_ENV !== 'production' && 'use' in React) {
const navigationPromises = use(NavigationPromisesContext) const navigationPromises = use(NavigationPromisesContext)
...@@ -175,6 +205,16 @@ export function useParams<T extends Params = Params>(): T { ...@@ -175,6 +205,16 @@ export function useParams<T extends Params = Params>(): T {
const params = useContext(PathParamsContext) as T const params = useContext(PathParamsContext) as T
// During build-time instant validation, wrap with a proxy
// so that accessing undeclared params throws an error.
if (
typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS &&
params
) {
return instrumentParamsForClientValidation!(params)
}
// Instrument with Suspense DevTools (dev-only) // Instrument with Suspense DevTools (dev-only)
if (process.env.NODE_ENV !== 'production' && 'use' in React) { if (process.env.NODE_ENV !== 'production' && 'use' in React) {
const navigationPromises = use(NavigationPromisesContext) const navigationPromises = use(NavigationPromisesContext)
...@@ -221,6 +261,16 @@ export function useSelectedLayoutSegments( ...@@ -221,6 +261,16 @@ export function useSelectedLayoutSegments(
// @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts // @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts
if (!context) return null if (!context) return null
// During build-time instant validation, error if fallback params exist
// because useSelectedLayoutSegments() can't return a sensible value without all params.
if (
typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS &&
context
) {
expectCompleteParamsInClientValidation!('useSelectedLayoutSegments()')
}
// Instrument with Suspense DevTools (dev-only) // Instrument with Suspense DevTools (dev-only)
if (process.env.NODE_ENV !== 'production' && 'use' in React) { if (process.env.NODE_ENV !== 'production' && 'use' in React) {
const navigationPromises = use(NavigationPromisesContext) const navigationPromises = use(NavigationPromisesContext)
...@@ -264,6 +314,12 @@ export function useSelectedLayoutSegment( ...@@ -264,6 +314,12 @@ export function useSelectedLayoutSegment(
const navigationPromises = useContext(NavigationPromisesContext) const navigationPromises = useContext(NavigationPromisesContext)
const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey) const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey)
// During build-time instant validation, error if fallback params exist
// because useSelectedLayoutSegment() can't return a sensible value without all params.
if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {
expectCompleteParamsInClientValidation!('useSelectedLayoutSegment()')
}
// Instrument with Suspense DevTools (dev-only) // Instrument with Suspense DevTools (dev-only)
if ( if (
process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'production' &&
......
...@@ -733,12 +733,21 @@ async function exportAppImpl( ...@@ -733,12 +733,21 @@ async function exportAppImpl(
const finalPhaseExportPaths: ExportPathEntry[] = [] const finalPhaseExportPaths: ExportPathEntry[] = []
if (renderOpts.cacheComponents) { if (renderOpts.cacheComponents) {
// Only run instant validation once per route, even if multiple param sets from generateStaticParams exist.
const routesWithInstantValidation = new Set<string>()
for (const exportPath of allExportPaths) { for (const exportPath of allExportPaths) {
if (exportPath._allowEmptyStaticShell) { if (exportPath._allowEmptyStaticShell) {
finalPhaseExportPaths.push(exportPath) finalPhaseExportPaths.push(exportPath)
} else { } else {
initialPhaseExportPaths.push(exportPath) initialPhaseExportPaths.push(exportPath)
} }
const route = exportPath.page
if (!routesWithInstantValidation.has(route)) {
exportPath._runInstantValidation = true
routesWithInstantValidation.add(route)
}
} }
} else { } else {
initialPhaseExportPaths = allExportPaths initialPhaseExportPaths = allExportPaths
......
...@@ -117,6 +117,9 @@ async function exportPageImpl( ...@@ -117,6 +117,9 @@ async function exportPageImpl(
// is generated while rendering using PPR and Cache Components. // is generated while rendering using PPR and Cache Components.
_allowEmptyStaticShell: allowEmptyStaticShell = false, _allowEmptyStaticShell: allowEmptyStaticShell = false,
// When true, attempt to run build-time instant validation for this export path.
_runInstantValidation: runInstantValidation = false,
// Pull the original query out. // Pull the original query out.
query: originalQuery = {}, query: originalQuery = {},
} = exportPath } = exportPath
...@@ -269,6 +272,7 @@ async function exportPageImpl( ...@@ -269,6 +272,7 @@ async function exportPageImpl(
// If it's dynamic, then it can be handled when request hits the route. // If it's dynamic, then it can be handled when request hits the route.
serveStreamingMetadata: true, serveStreamingMetadata: true,
allowEmptyStaticShell, allowEmptyStaticShell,
runInstantValidation,
experimental: { experimental: {
...commonRenderOpts.experimental, ...commonRenderOpts.experimental,
isRoutePPREnabled, isRoutePPREnabled,
......
...@@ -12,6 +12,7 @@ import { isPrerenderInterruptedError } from './dynamic-rendering' ...@@ -12,6 +12,7 @@ import { isPrerenderInterruptedError } from './dynamic-rendering'
import { getProperError } from '../../lib/is-error' import { getProperError } from '../../lib/is-error'
import { createDigestWithErrorCode } from '../../lib/error-telemetry-utils' import { createDigestWithErrorCode } from '../../lib/error-telemetry-utils'
import { isReactLargeShellError } from './react-large-shell-error' import { isReactLargeShellError } from './react-large-shell-error'
import { isInstantValidationError } from './instant-validation/instant-validation-error'
declare global { declare global {
var __next_log_error__: undefined | ((err: unknown) => void) var __next_log_error__: undefined | ((err: unknown) => void)
...@@ -46,6 +47,8 @@ export function getDigestForWellKnownError(error: unknown): string | undefined { ...@@ -46,6 +47,8 @@ export function getDigestForWellKnownError(error: unknown): string | undefined {
// If this is a prerender interrupted error, we don't need to log the error. // If this is a prerender interrupted error, we don't need to log the error.
if (isPrerenderInterruptedError(error)) return error.digest if (isPrerenderInterruptedError(error)) return error.digest
if (isInstantValidationError(error)) return error.digest
return undefined return undefined
} }
......
...@@ -50,6 +50,7 @@ import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' ...@@ -50,6 +50,7 @@ import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { InvariantError } from '../../shared/lib/invariant-error' 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'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
const hasPostpone = typeof React.unstable_postpone === 'function' const hasPostpone = typeof React.unstable_postpone === 'function'
...@@ -618,6 +619,11 @@ export function useDynamicRouteParams(expression: string) { ...@@ -618,6 +619,11 @@ export function useDynamicRouteParams(expression: string) {
} }
break break
} }
case 'validation-client': {
// Don't check fallbackRouteParams here. We handle params that weren't
// provided in the samples using a proxy that throws when accessed.
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.`
...@@ -627,9 +633,6 @@ export function useDynamicRouteParams(expression: string) { ...@@ -627,9 +633,6 @@ export function useDynamicRouteParams(expression: string) {
throw new InvariantError( throw new InvariantError(
`\`${expression}\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.` `\`${expression}\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`
) )
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
break
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
case 'unstable-cache': case 'unstable-cache':
...@@ -655,7 +658,8 @@ export function useDynamicSearchParams(expression: string) { ...@@ -655,7 +658,8 @@ export function useDynamicSearchParams(expression: string) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'validation-client': case 'validation-client':
// TODO(instant-validation): in build, this depends on samples // During instant validation we try to behave as close to client as possible,
// so this shouldn't hang during SSR.
return return
case 'prerender-client': { case 'prerender-client': {
React.use( React.use(
...@@ -722,7 +726,7 @@ const hasViewportRegex = new RegExp( ...@@ -722,7 +726,7 @@ const hasViewportRegex = new RegExp(
) )
const hasOutletRegex = new RegExp(`\\n\\s+at ${OUTLET_BOUNDARY_NAME}[\\n\\s]`) const hasOutletRegex = new RegExp(`\\n\\s+at ${OUTLET_BOUNDARY_NAME}[\\n\\s]`)
const hasPrefetchValidationBoundaryRegex = new RegExp( const hasInstantValidationBoundaryRegex = new RegExp(
`\\n\\s+at ${INSTANT_VALIDATION_BOUNDARY_NAME}[\\n\\s]` `\\n\\s+at ${INSTANT_VALIDATION_BOUNDARY_NAME}[\\n\\s]`
) )
...@@ -853,7 +857,7 @@ export function trackDynamicHoleInNavigation( ...@@ -853,7 +857,7 @@ export function trackDynamicHoleInNavigation(
} }
const boundaryLocation = const boundaryLocation =
hasPrefetchValidationBoundaryRegex.exec(componentStack) hasInstantValidationBoundaryRegex.exec(componentStack)
if (!boundaryLocation) { if (!boundaryLocation) {
// We don't see the validation boundary in the component stack, // We don't see the validation boundary in the component stack,
// so this hole must be coming from a shared parent. // so this hole must be coming from a shared parent.
...@@ -941,16 +945,42 @@ export function trackDynamicHoleInNavigation( ...@@ -941,16 +945,42 @@ export function trackDynamicHoleInNavigation(
} }
export function trackThrownErrorInNavigation( export function trackThrownErrorInNavigation(
workStore: WorkStore,
dynamicValidation: InstantValidationState, dynamicValidation: InstantValidationState,
error: unknown, thrownError: unknown,
componentStack: string componentStack: string
) { ) {
// If we see a validation boundary on the component stack, const boundaryLocation =
// this error couldn't have blocked a validation boundary from rendering. hasInstantValidationBoundaryRegex.exec(componentStack)
if (hasPrefetchValidationBoundaryRegex.test(componentStack)) { if (!boundaryLocation) {
// There's no validation boundary on the component stack.
// This error may have blocked a boundary from rendering.
dynamicValidation.thrownErrorsOutsideBoundary.push(thrownError)
} else {
// There's validation boundary on the component stack,
// so we know this error didn't block a validation boundary from rendering.
// However, this error might be hiding be hiding dynamic content that would
// cause validation to fail.
const suspenseLocation = hasSuspenseRegex.exec(componentStack)
if (suspenseLocation) {
if (suspenseLocation.index < boundaryLocation.index) {
// There's a Suspense below the validation boundary but above this error's location.
// This subtree can't fail instant validation because any potential
// dynamic holes would be guarded by the Suspense anyway,
// so we can allow this.
return return
} else {
// invalid - fallthrough
}
}
const message = `Route "${workStore.route}": Could not validate \`unstable_instant\` because an error prevented the target segment from rendering.`
const error = addErrorContext(
new Error(message, { cause: thrownError }),
componentStack,
null // TODO(instant-validation-build): conflicting use of cause
)
dynamicValidation.validationPreventingErrors.push(error)
} }
dynamicValidation.thrownErrorsOutsideBoundary.push(error)
} }
export function trackDynamicHoleInRuntimeShell( export function trackDynamicHoleInRuntimeShell(
...@@ -1221,8 +1251,17 @@ export function getNavigationDisallowedDynamicReasons( ...@@ -1221,8 +1251,17 @@ export function getNavigationDisallowedDynamicReasons(
workStore: WorkStore, workStore: WorkStore,
prelude: PreludeState, prelude: PreludeState,
dynamicValidation: InstantValidationState, dynamicValidation: InstantValidationState,
validationSampleTracking: InstantValidationSampleTracking | null,
boundaryState: ValidationBoundaryTracking boundaryState: ValidationBoundaryTracking
): Array<Error> { ): Array<Error> {
// If we have errors related to missing samples, those should take precedence over everything else.
if (validationSampleTracking) {
const { missingSampleErrors } = validationSampleTracking
if (missingSampleErrors.length > 0) {
return missingSampleErrors
}
}
const { validationPreventingErrors } = dynamicValidation const { validationPreventingErrors } = dynamicValidation
if (validationPreventingErrors.length > 0) { if (validationPreventingErrors.length > 0) {
return validationPreventingErrors return validationPreventingErrors
......
...@@ -42,10 +42,16 @@ export { Postpone } from './rsc/postpone' ...@@ -42,10 +42,16 @@ 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'
export const InstantValidation = export const InstantValidation = () => {
process.env.NODE_ENV === 'development' && process.env.NEXT_RUNTIME !== 'edge' if (
? (require('./instant-validation/instant-validation') as typeof import('./instant-validation/instant-validation')) process.env.NEXT_RUNTIME !== 'edge' &&
: undefined process.env.__NEXT_CACHE_COMPONENTS
) {
return require('./instant-validation/instant-validation') as typeof import('./instant-validation/instant-validation')
} else {
return undefined
}
}
import type { NodeJsPartialHmrUpdate } from '../../build/swc/types' import type { NodeJsPartialHmrUpdate } from '../../build/swc/types'
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
......
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */ /* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
'use client'
// Do not put a "use client" directive here. Import this module via the shim in
// `packages/next/src/client/components/instant-validation/boundary.tsx` instead.
// 'use client'
import { createContext, type ReactNode } from 'react' import { createContext, type ReactNode } from 'react'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants' import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'
import { InvariantError } from '../../../shared/lib/invariant-error' import { InvariantError } from '../../../shared/lib/invariant-error'
import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
import type { ValidationBoundaryTracking } from './boundary-tracking' import type { ValidationBoundaryTracking } from './boundary-tracking'
import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
if (typeof window !== 'undefined') {
throw new InvariantError(
'Instant validation boundaries should never appear in browser bundles.'
)
}
function getValidationBoundaryTracking(): ValidationBoundaryTracking | null { function getValidationBoundaryTracking(): ValidationBoundaryTracking | null {
const store = workUnitAsyncStorage.getStore() const store = workUnitAsyncStorage.getStore()
...@@ -39,12 +48,6 @@ const NameSpace = { ...@@ -39,12 +48,6 @@ const NameSpace = {
id: string id: string
children: ReactNode children: ReactNode
}) { }) {
if (typeof window !== 'undefined') {
throw new InvariantError(
'InstantValidationBoundary should only be rendered in SSR'
)
}
// Track which boundaries we actually managed to render. // Track which boundaries we actually managed to render.
const state = getValidationBoundaryTracking() const state = getValidationBoundaryTracking()
if (state === null) { if (state === null) {
......
import { getLayoutOrPageModule } from '../../lib/app-dir-module' import { getLayoutOrPageModule } from '../../lib/app-dir-module'
import type { LoaderTree } from '../../lib/app-dir-module' import type { LoaderTree } from '../../lib/app-dir-module'
import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree' import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree'
import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config' import type {
AppSegmentConfig,
InstantSample,
} from '../../../build/segment-config/app/app-segment-config'
import { import {
workAsyncStorage, workAsyncStorage,
type WorkStore, type WorkStore,
...@@ -78,8 +81,11 @@ type FoundSegmentWithConfig = { ...@@ -78,8 +81,11 @@ type FoundSegmentWithConfig = {
* Checks if any segments in the loader tree have `instant` configs that need validating. * Checks if any segments in the loader tree have `instant` configs that need validating.
* NOTE: Client navigations call this multiple times, so we cache it. * NOTE: Client navigations call this multiple times, so we cache it.
* */ * */
export const anySegmentNeedsInstantValidation = cacheScopedToWorkStore( // Shared helper (not exported, not cached — called by the cached wrappers)
async (rootTree: LoaderTree): Promise<boolean> => { async function anySegmentNeedsInstantValidation(
rootTree: LoaderTree,
mode: 'dev' | 'build'
): Promise<boolean> {
const segments = await findSegmentsWithInstantConfig(rootTree) const segments = await findSegmentsWithInstantConfig(rootTree)
// Check if there's any configs with `prefetch: 'static'` or `mode: 'instant'`. // Check if there's any configs with `prefetch: 'static'` or `mode: 'instant'`.
...@@ -88,7 +94,11 @@ export const anySegmentNeedsInstantValidation = cacheScopedToWorkStore( ...@@ -88,7 +94,11 @@ export const anySegmentNeedsInstantValidation = cacheScopedToWorkStore(
let needsValidation = false let needsValidation = false
for (const { config } of segments) { for (const { config } of segments) {
if (typeof config === 'object') { if (typeof config === 'object') {
if (config.unstable_disableValidation) { if (
config.unstable_disableValidation === true ||
(mode === 'dev' && config.unstable_disableDevValidation === true) ||
(mode === 'build' && config.unstable_disableBuildValidation === true)
) {
return false return false
} }
// do not short-circuit, some other segment might still have `unstable_disableValidation` // do not short-circuit, some other segment might still have `unstable_disableValidation`
...@@ -96,7 +106,16 @@ export const anySegmentNeedsInstantValidation = cacheScopedToWorkStore( ...@@ -96,7 +106,16 @@ export const anySegmentNeedsInstantValidation = cacheScopedToWorkStore(
} }
} }
return needsValidation return needsValidation
} }
export const anySegmentNeedsInstantValidationInDev = cacheScopedToWorkStore(
async (rootTree: LoaderTree): Promise<boolean> =>
anySegmentNeedsInstantValidation(rootTree, 'dev')
)
export const anySegmentNeedsInstantValidationInBuild = cacheScopedToWorkStore(
async (rootTree: LoaderTree): Promise<boolean> =>
anySegmentNeedsInstantValidation(rootTree, 'build')
) )
export const findSegmentsWithInstantConfig = cacheScopedToWorkStore( export const findSegmentsWithInstantConfig = cacheScopedToWorkStore(
...@@ -129,6 +148,43 @@ export const findSegmentsWithInstantConfig = cacheScopedToWorkStore( ...@@ -129,6 +148,43 @@ export const findSegmentsWithInstantConfig = cacheScopedToWorkStore(
} }
) )
export const resolveInstantConfigSamplesForPage = async (
tree: LoaderTree
): Promise<InstantSample[] | null> => {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
let samples: InstantSample[] | null = null
if (
instantConfig !== undefined &&
typeof instantConfig === 'object' &&
instantConfig.samples
) {
samples = instantConfig.samples
}
// The samples from inner segments override samples from outer segments,
// i.e. a page overrides the samples from a layout.
// We do not perform any merging logic.
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
if (parallelRouteKey !== 'children') {
// TODO(instant-validation-build): do something with with samples from non-children slots?
continue
}
const childTree = parallelRoutes[parallelRouteKey]
const childSamples = await resolveInstantConfigSamplesForPage(childTree)
if (childSamples !== null) {
samples = childSamples
}
}
return samples
}
/** /**
* A simple cache wrapper for 1-argument functions. * A simple cache wrapper for 1-argument functions.
* The cache will live as long as the current WorkStore, * The cache will live as long as the current WorkStore,
......
import type { Params } from '../../request/params'
import type { ReadonlyURLSearchParams } from '../../../client/components/readonly-url-search-params'
import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
import { workAsyncStorage } from '../work-async-storage.external'
import {
createExhaustiveParamsProxy,
createExhaustiveURLSearchParamsProxy,
trackMissingSampleErrorAndThrow,
} from './instant-samples'
import { InstantValidationError } from './instant-validation-error'
export function instrumentParamsForClientValidation<TPArams extends Params>(
underlyingParams: TPArams
): TPArams {
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (workStore && workUnitStore) {
switch (workUnitStore.type) {
case 'validation-client': {
if (workUnitStore.validationSamples) {
const declaredKeys = new Set(
Object.keys(workUnitStore.validationSamples.params ?? {})
)
return createExhaustiveParamsProxy(
underlyingParams,
declaredKeys,
workStore.route
)
}
break
}
case 'prerender-runtime':
case 'prerender-client':
case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender':
case 'cache':
case 'request':
case 'private-cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
return underlyingParams
}
export function expectCompleteParamsInClientValidation(
expression: string
): void {
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (workStore && workUnitStore) {
switch (workUnitStore.type) {
case 'validation-client': {
if (workUnitStore.validationSamples) {
const fallbackParams = workUnitStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) {
const missingParams = Array.from(fallbackParams.keys())
trackMissingSampleErrorAndThrow(
new InstantValidationError(
`Route "${workStore.route}" called ${expression} but param${missingParams.length > 1 ? 's' : ''} ${missingParams.map((p) => `"${p}"`).join(', ')} ${missingParams.length > 1 ? 'are' : 'is'} not defined in the \`samples\` of \`unstable_instant\`. ` +
`${expression} requires all route params to be provided.`
)
)
}
}
break
}
case 'prerender-runtime':
case 'prerender-client':
case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender':
case 'cache':
case 'request':
case 'private-cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
}
export function instrumentSearchParamsForClientValidation(
underlyingSearchParams: ReadonlyURLSearchParams
): ReadonlyURLSearchParams {
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (workStore && workUnitStore) {
switch (workUnitStore.type) {
case 'validation-client': {
if (workUnitStore.validationSamples) {
const declaredKeys = new Set(
Object.keys(workUnitStore.validationSamples.searchParams ?? {})
)
return createExhaustiveURLSearchParamsProxy(
underlyingSearchParams,
declaredKeys,
workStore.route
)
}
break
}
case 'prerender-runtime':
case 'prerender-client':
case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender':
case 'cache':
case 'request':
case 'private-cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
return underlyingSearchParams
}
const INSTANT_VALIDATION_ERROR_DIGEST = 'INSTANT_VALIDATION_ERROR'
/** Check if an error is an exhaustive samples validation error (by digest). */
export function isInstantValidationError(
err: unknown
): err is InstantValidationError {
return !!(
err &&
typeof err === 'object' &&
err instanceof Error &&
(err as any).digest === INSTANT_VALIDATION_ERROR_DIGEST
)
}
export class InstantValidationError extends Error {
digest = INSTANT_VALIDATION_ERROR_DIGEST
}
...@@ -19,7 +19,7 @@ import { getDigestForWellKnownError } from '../create-error-handler' ...@@ -19,7 +19,7 @@ import { getDigestForWellKnownError } from '../create-error-handler'
import { import {
// NOTE: we're in the server layer, so this is a client reference // NOTE: we're in the server layer, so this is a client reference
PlaceValidationBoundaryBelowThisLevel, PlaceValidationBoundaryBelowThisLevel,
} from './boundary' } from '../../../client/components/instant-validation/boundary'
import type { ValidationBoundaryTracking } from './boundary-tracking' import type { ValidationBoundaryTracking } from './boundary-tracking'
import { import {
getLayoutOrPageModule, getLayoutOrPageModule,
...@@ -299,6 +299,17 @@ export async function collectStagedSegmentData( ...@@ -299,6 +299,17 @@ export async function collectStagedSegmentData(
if (digest) { if (digest) {
return digest return digest
} }
// Forward existing digests
if (
error &&
typeof error === 'object' &&
'digest' in error &&
typeof error.digest === 'string'
) {
return error.digest
}
// We don't need to log the errors because we would have already done that // We don't need to log the errors because we would have already done that
// when generating the original Flight stream for the whole page. // when generating the original Flight stream for the whole page.
if ( if (
...@@ -526,6 +537,17 @@ export async function createCombinedPayloadStream( ...@@ -526,6 +537,17 @@ export async function createCombinedPayloadStream(
if (digest) { if (digest) {
return digest return digest
} }
// Forward existing digests
if (
error &&
typeof error === 'object' &&
'digest' in error &&
typeof error.digest === 'string'
) {
return error.digest
}
// We don't need to log the errors because we would have already done that // We don't need to log the errors because we would have already done that
// when generating the original Flight stream for the whole page. // when generating the original Flight stream for the whole page.
if ( if (
......
...@@ -35,8 +35,9 @@ export class StagedRenderingController { ...@@ -35,8 +35,9 @@ export class StagedRenderingController {
private dynamicStagePromise = createPromiseWithResolvers<void>() private dynamicStagePromise = createPromiseWithResolvers<void>()
constructor( constructor(
private abortSignal: AbortSignal | null = null, private abortSignal: AbortSignal | null,
private abandonController: AbortController | null = null private abandonController: AbortController | null,
private shouldTrackSyncIO: boolean
) { ) {
if (abortSignal) { if (abortSignal) {
abortSignal.addEventListener( abortSignal.addEventListener(
...@@ -88,13 +89,15 @@ export class StagedRenderingController { ...@@ -88,13 +89,15 @@ export class StagedRenderingController {
} }
} }
canSyncInterrupt() { shouldTrackSyncInterrupt(): boolean {
// If we haven't started the render yet, it can't be interrupted. if (!this.shouldTrackSyncIO) {
if (this.currentStage === RenderStage.Before) {
return false return false
} }
switch (this.currentStage) { switch (this.currentStage) {
case RenderStage.Before:
// If we haven't started the render yet, it can't be interrupted.
return false
case RenderStage.EarlyStatic: case RenderStage.EarlyStatic:
case RenderStage.Static: case RenderStage.Static:
return true return true
...@@ -132,8 +135,18 @@ export class StagedRenderingController { ...@@ -132,8 +135,18 @@ export class StagedRenderingController {
return return
} }
// If we're in the final render, we cannot abandon it. We need to advance to the Dynamic stage if (this.abortSignal) {
// and capture the interruption reason. // If this is an abortable render, we capture the interruption reason and stop advancing.
// We don't release any more promises.
// The caller is expected to abort the signal.
this.syncInterruptReason = reason
this.currentStage = RenderStage.Abandoned
return
}
// If we're in a non-abandonable & non-abortable render,
// we need to advance to the Dynamic stage and capture the interruption reason.
// (in dev, this will be the restarted render)
switch (this.currentStage) { switch (this.currentStage) {
case RenderStage.EarlyStatic: case RenderStage.EarlyStatic:
case RenderStage.Static: case RenderStage.Static:
......
...@@ -208,6 +208,13 @@ export interface RenderOptsPartial { ...@@ -208,6 +208,13 @@ export interface RenderOptsPartial {
* Prerendering those routes would catch any invalid dynamic accesses. * Prerendering those routes would catch any invalid dynamic accesses.
*/ */
allowEmptyStaticShell?: boolean allowEmptyStaticShell?: boolean
/**
* When true, attempt to run build-time instant validation for this prerender.
* Only the first prerender per page sets this, since validation uses
* unstable_instant.samples and is independent of actual route params.
*/
runInstantValidation?: boolean
} }
export type RenderOpts = LoadComponentsReturnType<AppPageModule> & export type RenderOpts = LoadComponentsReturnType<AppPageModule> &
......
...@@ -23,6 +23,7 @@ import { InvariantError } from '../../shared/lib/invariant-error' ...@@ -23,6 +23,7 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import type { StagedRenderingController } from './staged-rendering' import type { StagedRenderingController } from './staged-rendering'
import { RenderStage } from './staged-rendering' import { RenderStage } from './staged-rendering'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking' import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
export type WorkUnitPhase = 'action' | 'render' | 'after' export type WorkUnitPhase = 'action' | 'render' | 'after'
...@@ -76,10 +77,23 @@ export interface RequestStore extends CommonWorkUnitStore { ...@@ -76,10 +77,23 @@ export interface RequestStore extends CommonWorkUnitStore {
prerenderResumeDataCache?: PrerenderResumeDataCache | null prerenderResumeDataCache?: PrerenderResumeDataCache | null
fallbackParams?: OpaqueFallbackRouteParams | null fallbackParams?: OpaqueFallbackRouteParams | null
// Only in build-time instant-validation
// We mirror the controller/renderSignal from prerender stores to allow aborting the render
// in case we hit an error that makes it unnecessary to continue
controller?: AbortController
renderSignal?: AbortSignal
validationSamples?: InstantValidationSamples
validationSampleTracking?: InstantValidationSampleTracking | null
// DEV-only // DEV-only
usedDynamic?: boolean usedDynamic?: boolean
} }
export type InstantValidationSamples = {
params: Params | undefined
searchParams: Record<string, string | string[] | null> | undefined
}
export type AsyncApiPromises = { export type AsyncApiPromises = {
cookies: Promise<ReadonlyRequestCookies> cookies: Promise<ReadonlyRequestCookies>
earlyCookies: Promise<ReadonlyRequestCookies> earlyCookies: Promise<ReadonlyRequestCookies>
...@@ -149,8 +163,9 @@ export interface PrerenderStoreModernClient ...@@ -149,8 +163,9 @@ export interface PrerenderStoreModernClient
export interface ValidationStoreClient extends PrerenderStoreModernCommon { export interface ValidationStoreClient extends PrerenderStoreModernCommon {
readonly type: 'validation-client' readonly type: 'validation-client'
readonly boundaryState: ValidationBoundaryTracking | null readonly boundaryState: ValidationBoundaryTracking | null
// When we implement build validation, the store will contain e.g. cookies validationSamples: InstantValidationSamples | null
// and other values derived from samples. validationSampleTracking: InstantValidationSampleTracking | null
fallbackRouteParams: OpaqueFallbackRouteParams | null
} }
export interface PrerenderStoreModernServer export interface PrerenderStoreModernServer
......
...@@ -1114,6 +1114,16 @@ export type ExportPathMap = { ...@@ -1114,6 +1114,16 @@ export type ExportPathMap = {
* @internal * @internal
*/ */
_allowEmptyStaticShell?: boolean _allowEmptyStaticShell?: boolean
/**
* When true, run build-time instant validation for this export path.
* Only set on the first export entry per page, since validation uses
* unstable_instant.samples (not actual params from generateStaticParams),
* so the result is the same for all param combinations.
*
* @internal
*/
_runInstantValidation?: boolean
} }
} }
......
...@@ -82,10 +82,9 @@ export function io(expression: string, type: ApiType) { ...@@ -82,10 +82,9 @@ export function io(expression: string, type: ApiType) {
} }
break break
} }
case 'request': case 'request': {
if (process.env.NODE_ENV === 'development') {
const stageController = workUnitStore.stagedRendering const stageController = workUnitStore.stagedRendering
if (stageController && stageController.canSyncInterrupt()) { if (stageController && stageController.shouldTrackSyncInterrupt()) {
let message: string let message: string
if ( if (
stageController.currentStage === RenderStage.Static || stageController.currentStage === RenderStage.Static ||
...@@ -142,9 +141,20 @@ export function io(expression: string, type: ApiType) { ...@@ -142,9 +141,20 @@ export function io(expression: string, type: ApiType) {
const syncIOError = applyOwnerStack(new Error(message)) const syncIOError = applyOwnerStack(new Error(message))
stageController.syncInterruptCurrentStageWithReason(syncIOError) stageController.syncInterruptCurrentStageWithReason(syncIOError)
// A build-time validation render uses a 'request' store type, but may be abortable.
// If we're in the second, restarted render of the restart-on-cache miss flow,
// Sync IO is an error, and unlike dev, there's no need to continue the render past the sync IO,
// so we can abort it.
if (
workUnitStore.controller &&
!workUnitStore.controller.signal.aborted
) {
workUnitStore.controller.abort(syncIOError)
} }
} }
break break
}
case 'validation-client': case 'validation-client':
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
......
...@@ -24,6 +24,7 @@ import { ...@@ -24,6 +24,7 @@ import {
throwInvariantForMissingStore, throwInvariantForMissingStore,
type PrerenderStoreModernRuntime, type PrerenderStoreModernRuntime,
type RequestStore, type RequestStore,
type ValidationStoreClient,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { import {
...@@ -67,8 +68,11 @@ export function createParamsFromClient( ...@@ -67,8 +68,11 @@ export function createParamsFromClient(
varyParamsAccumulator varyParamsAccumulator
) )
case 'validation-client': case 'validation-client':
// TODO(instant-validation): in build, this depends on samples return createClientParamsInInstantValidation(
return createRenderParamsInProd(underlyingParams) underlyingParams,
workStore,
workUnitStore.validationSamples
)
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
...@@ -94,6 +98,12 @@ export function createParamsFromClient( ...@@ -94,6 +98,12 @@ export function createParamsFromClient(
workUnitStore, workUnitStore,
isRuntimePrefetchable isRuntimePrefetchable
) )
} else if (workUnitStore.validationSamples) {
return createClientParamsInInstantValidation(
underlyingParams,
workStore,
workUnitStore.validationSamples
)
} else { } else {
return createRenderParamsInProd(underlyingParams) return createRenderParamsInProd(underlyingParams)
} }
...@@ -214,8 +224,9 @@ export function createServerParamsForServerSegment( ...@@ -214,8 +224,9 @@ export function createServerParamsForServerSegment(
varyParamsAccumulator varyParamsAccumulator
) )
case 'validation-client': case 'validation-client':
// TODO(instant-validation): in build, this depends on samples throw new InvariantError(
return createRenderParamsInProd(underlyingParams) 'createServerParamsForServerSegment should not be called in client contexts.'
)
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
case 'unstable-cache': case 'unstable-cache':
...@@ -243,6 +254,17 @@ export function createServerParamsForServerSegment( ...@@ -243,6 +254,17 @@ export function createServerParamsForServerSegment(
workUnitStore, workUnitStore,
isRuntimePrefetchable isRuntimePrefetchable
) )
} else if (
workUnitStore.asyncApiPromises &&
workUnitStore.validationSamples
) {
return createServerParamsInInstantValidation(
underlyingParams,
workStore,
workUnitStore.validationSamples,
workUnitStore.asyncApiPromises,
isRuntimePrefetchable
)
} else if ( } else if (
workUnitStore.asyncApiPromises && workUnitStore.asyncApiPromises &&
hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams) hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)
...@@ -295,7 +317,9 @@ export function createPrerenderParamsForClientSegment( ...@@ -295,7 +317,9 @@ export function createPrerenderParamsForClientSegment(
} }
break break
case 'validation-client': case 'validation-client':
// TODO(instant-validation): in build, this depends on samples throw new InvariantError(
'createPrerenderParamsForClientSegment should not be called in validation contexts.'
)
break break
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -421,6 +445,44 @@ function hasFallbackRouteParams( ...@@ -421,6 +445,44 @@ function hasFallbackRouteParams(
return false return false
} }
function createServerParamsInInstantValidation(
underlyingParams: Params,
workStore: WorkStore,
validationSamples: NonNullable<RequestStore['validationSamples']>,
asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,
isRuntimePrefetchable: boolean
): Promise<Params> {
const { createExhaustiveParamsProxy } =
require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')
const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))
const proxiedUnderlying = createExhaustiveParamsProxy(
underlyingParams,
declaredParams,
workStore.route
)
return (
isRuntimePrefetchable
? asyncApiPromises.earlySharedParamsParent
: asyncApiPromises.sharedParamsParent
).then(() => proxiedUnderlying)
}
function createClientParamsInInstantValidation(
underlyingParams: Params,
workStore: WorkStore,
validationSamples: ValidationStoreClient['validationSamples']
): Promise<Params> {
const { createExhaustiveParamsProxy } =
require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')
const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))
const proxiedUnderlying = createExhaustiveParamsProxy(
underlyingParams,
declaredParams,
workStore.route
)
return Promise.resolve(proxiedUnderlying)
}
function createRenderParamsInProd(underlyingParams: Params): Promise<Params> { function createRenderParamsInProd(underlyingParams: Params): Promise<Params> {
return makeUntrackedParams(underlyingParams) return makeUntrackedParams(underlyingParams)
} }
......
...@@ -80,9 +80,28 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -80,9 +80,28 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
`${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.` `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`
) )
} }
case 'private-cache':
case 'prerender-runtime':
case 'request': { case 'request': {
if (
process.env.__NEXT_CACHE_COMPONENTS &&
workUnitStore.validationSamples
) {
const { assertRootParamInSamples } =
require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')
// If we error, make sure we return a rejected promise instead of erroring synchronously.
try {
assertRootParamInSamples(
workStore,
workUnitStore.validationSamples.params,
paramName
)
} catch (err) {
return Promise.reject(err)
}
}
break
}
case 'private-cache':
case 'prerender-runtime': {
break break
} }
default: { default: {
......
...@@ -24,6 +24,7 @@ import { ...@@ -24,6 +24,7 @@ import {
type StaticPrerenderStore, type StaticPrerenderStore,
throwInvariantForMissingStore, throwInvariantForMissingStore,
type RequestStore, type RequestStore,
type ValidationStoreClient,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { import {
...@@ -59,9 +60,13 @@ export function createSearchParamsFromClient( ...@@ -59,9 +60,13 @@ export function createSearchParamsFromClient(
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
return createStaticPrerenderSearchParams(workStore, workUnitStore) return createStaticPrerenderSearchParams(workStore, workUnitStore)
case 'validation-client': case 'validation-client': {
// TODO(instant-validation): in build, this depends on samples return createClientSearchParamsInValidation(
return makeUntrackedSearchParams(underlyingSearchParams) underlyingSearchParams,
workStore,
workUnitStore
)
}
case 'prerender-runtime': case 'prerender-runtime':
throw new InvariantError( throw new InvariantError(
'createSearchParamsFromClient should not be called in a runtime prerender.' 'createSearchParamsFromClient should not be called in a runtime prerender.'
...@@ -266,6 +271,19 @@ function createRenderSearchParams( ...@@ -266,6 +271,19 @@ function createRenderSearchParams(
isRuntimePrefetchable isRuntimePrefetchable
) )
} else if (requestStore.asyncApiPromises) { } else if (requestStore.asyncApiPromises) {
if (requestStore.validationSamples) {
const { createExhaustiveSearchParamsProxy } =
require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')
const declaredKeys = new Set(
Object.keys(requestStore.validationSamples.searchParams ?? {})
)
underlyingSearchParams = createExhaustiveSearchParamsProxy(
underlyingSearchParams,
declaredKeys,
workStore.route
)
}
return ( return (
isRuntimePrefetchable isRuntimePrefetchable
? requestStore.asyncApiPromises.earlySharedSearchParamsParent ? requestStore.asyncApiPromises.earlySharedSearchParamsParent
...@@ -674,3 +692,21 @@ function createSearchAccessError( ...@@ -674,3 +692,21 @@ function createSearchAccessError(
`Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis` `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
) )
} }
function createClientSearchParamsInValidation(
underlyingSearchParams: SearchParams,
workStore: WorkStore,
workUnitStore: ValidationStoreClient
) {
const { createExhaustiveSearchParamsProxy } =
require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')
const declaredKeys = new Set(
Object.keys(workUnitStore.validationSamples?.searchParams ?? {})
)
underlyingSearchParams = createExhaustiveSearchParamsProxy(
underlyingSearchParams,
declaredKeys,
workStore.route
)
return Promise.resolve(underlyingSearchParams)
}
...@@ -11,7 +11,7 @@ import type { CollectedCacheResult } from '../use-cache/use-cache-wrapper' ...@@ -11,7 +11,7 @@ import type { CollectedCacheResult } from '../use-cache/use-cache-wrapper'
*/ */
type CacheStore<T> = Pick< type CacheStore<T> = Pick<
Map<string, T>, Map<string, T>,
'entries' | 'keys' | 'size' | 'get' | 'set' 'entries' | 'keys' | 'size' | 'get' | 'set' | typeof Symbol.iterator
> >
/** /**
......
...@@ -147,13 +147,24 @@ export async function stringifyResumeDataCache( ...@@ -147,13 +147,24 @@ export async function stringifyResumeDataCache(
* *
* @returns A new empty PrerenderResumeDataCache instance * @returns A new empty PrerenderResumeDataCache instance
*/ */
export function createPrerenderResumeDataCache(): PrerenderResumeDataCache { export function createPrerenderResumeDataCache(
source?: PrerenderResumeDataCache | RenderResumeDataCache
): PrerenderResumeDataCache {
if (source) {
return {
cache: new Map(source.cache),
fetch: new Map(source.fetch),
encryptedBoundArgs: new Map(source.encryptedBoundArgs),
decryptedBoundArgs: new Map(source.decryptedBoundArgs),
}
} else {
return { return {
cache: new Map(), cache: new Map(),
fetch: new Map(), fetch: new Map(),
encryptedBoundArgs: new Map(), encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(), decryptedBoundArgs: new Map(),
} }
}
} }
/** /**
......
...@@ -46,4 +46,7 @@ export const wellKnownProperties = new Set([ ...@@ -46,4 +46,7 @@ export const wellKnownProperties = new Set([
'toJSON', 'toJSON',
'$$typeof', '$$typeof',
'__esModule', '__esModule',
// Tested by flight when checking for iterables
'@@iterator',
]) ])
'use client'
import { useSearchParams } from 'next/navigation'
export function ThrowsInClient(): Promise<never> {
useSearchParams()
throw new Error('Kaboom')
}
import { Suspense } from 'react'
export default function Layout({ children }) {
return (
<>
<p>This layout wraps the children in Suspense.</p>
<hr />
<Suspense fallback={<div>Fallback from layout...</div>}>
{children}
</Suspense>
</>
)
}
import { Instant } from 'next'
import { ThrowsInClient } from './client'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [{ searchParams: {} }],
}
export default function Page() {
return (
<main>
<p>
This page has an error in a client component with no suspense
boundaries. It didn't render successfully, so it should be treated as
blocking validation -- we don't know what content would be rendered if
the error didn't occur.
</p>
<ThrowsInClient />
</main>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
export function ThrowsInClient(): Promise<never> {
useSearchParams()
throw new Error('Kaboom')
}
import { Instant } from 'next'
import { ThrowsInClient } from './client'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [{ searchParams: {} }],
}
export default function Page() {
return (
<main>
<p>
This page has an error in a client component with no suspense
boundaries. It didn't render successfully, so it should be treated as
blocking validation -- we don't know what content would be rendered if
the error didn't occur.
</p>
<ThrowsInClient />
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { ensureThrows } from '../../../../ensure-error'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Page() {
return (
<main>
<p>
This page reads a cookie that is not declared in the sample, so it
should fail validation with an exhaustiveness error. It catches the
error thrown by the cookie access, but validation should still fail.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestCookies />
</Suspense>
</main>
)
}
async function TestCookies() {
const cookieStore = await cookies()
try {
ensureThrows(
() => cookieStore.get('undeclaredCookie'),
`Expected get() to throw for undeclared cookies`
)
} catch (err) {
// We swallow the error. It should still be reported and fail the validation.
}
return null
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { ensureThrows } from '../../../../ensure-error'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Page() {
return (
<main>
<p>
This page reads a cookie that is not declared in the sample, so it
should fail validation with an exhaustiveness error.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestCookies />
</Suspense>
</main>
)
}
async function TestCookies() {
const cookieStore = await cookies()
ensureThrows(
() => cookieStore.get('undeclaredCookie'),
`Expected get() to throw for undeclared cookies`
)
return null
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { ensureThrows } from '../../../../ensure-error'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Page() {
return (
<main>
<p>
This page reads a cookie that is not declared in the sample, so it
should fail validation with an exhaustiveness error.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestCookies />
</Suspense>
</main>
)
}
async function TestCookies() {
const cookieStore = await cookies()
ensureThrows(
() => cookieStore.has('undeclaredCookie'),
`Expected has() to throw for undeclared cookies`
)
return null
}
import type { Instant } from 'next'
import { cookies } from 'next/headers'
import assert from 'node:assert'
import { Suspense } from 'react'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
cookies: [
{ name: 'testCookie', value: 'testValue' },
{ name: 'missingCookie', value: null },
],
},
],
}
export default async function Page() {
return (
<main>
<p>
When validated in build, the page should receive the cookies specified
in the sample.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestCookies />
</Suspense>
</main>
)
}
async function TestCookies() {
const cookieStore = await cookies()
const testCookie = cookieStore.get('testCookie')
assert.deepStrictEqual(testCookie, {
name: 'testCookie',
value: 'testValue',
})
const missingCookie = cookieStore.get('missingCookie')
assert.equal(missingCookie, undefined)
assert.equal(cookieStore.has('missingCookie'), false)
assert.deepStrictEqual(cookieStore.getAll(), [
{ name: 'testCookie', value: 'testValue' },
])
return null
}
import type { Instant } from 'next'
import { cookies } from 'next/headers'
import assert from 'node:assert/strict'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
cookies: [{ name: 'testCookie', value: 'testValue' }],
},
],
}
export default async function Page() {
return (
<main>
<CachedChild cookieStore={await cookies()} />
</main>
)
}
async function CachedChild({ cookieStore }: { cookieStore: unknown }) {
'use cache'
// Flight serializes cookies as an iterable, i.e. a sequence of entries
assert.deepStrictEqual(cookieStore, [
['testCookie', { name: 'testCookie', value: 'testValue' }],
])
return null
}
'use client'
import { assert } from '../../../../client-assertion-error'
export function ClientChild({ cookieStore }: { cookieStore: unknown }) {
// Flight serializes cookies as an iterable, i.e. a sequence of entries
assert(
JSON.stringify(cookieStore) ===
JSON.stringify([
['testCookie', { name: 'testCookie', value: 'testValue' }],
]),
`Unexpected value for cookieStore: ${JSON.stringify(cookieStore)}`
)
return null
}
import type { Instant } from 'next'
import { cookies } from 'next/headers'
import { ClientChild } from './client'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
cookies: [{ name: 'testCookie', value: 'testValue' }],
},
],
}
export default async function Page() {
return (
<main>
<p>
Passing the whole cookies object to the client is generally a bad idea,
but it shouldn't crash validation, so we still do it
</p>
<ClientChild cookieStore={await cookies()} />
</main>
)
}
'use client'
import { useParams, usePathname } from 'next/navigation'
import { assert } from '../../../../client-assertion-error'
/**
* Asserts that client hooks receive sample params during instant validation,
* not the values from generateStaticParams. This component is inside a Suspense
* boundary gated by `await cookies()`, so it only renders during validation.
*/
export function AssertParamsClient() {
const params = useParams()
const pathname = usePathname()
// During validation, useParams() should return the sample param ('hello'),
// not a value from generateStaticParams ('foo' or 'bar').
assert(
params.slug === 'hello',
`Expected useParams().slug === 'hello' (from sample), got '${params.slug}'`
)
// usePathname() should reflect the sample param value too.
assert(
pathname === '/gsp/hello',
`Expected usePathname() === '/gsp/hello', got '${pathname}'`
)
return null
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { AssertParamsClient } from './client'
// samples use 'hello', but generateStaticParams uses 'foo'/'bar'.
// During validation, the sample params should be used, not the GSP values.
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
params: {
slug: 'hello',
},
},
],
}
export function generateStaticParams() {
return [{ slug: 'foo' }, { slug: 'bar' }]
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<Suspense fallback={<div>Loading...</div>}>
<AssertSampleParams params={params} />
</Suspense>
</main>
)
}
async function AssertSampleParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
// Gate behind cookies() so this subtree is only reachable during
// instant validation (not during regular GSP prerenders, where
// cookies() creates a dynamic hole and defers the Suspense boundary).
await cookies()
const p = await params
// During validation, the param value should come from the sample ('hello'),
// not from generateStaticParams ('foo' or 'bar').
assert.equal(
p.slug,
'hello',
`Expected param 'slug' to be 'hello' (from sample), got '${p.slug}'`
)
// Client component rendered after the cookies() gate, so it also
// only runs during validation.
return (
<>
<div id="slug">{p.slug}</div>
<AssertParamsClient />
</>
)
}
import { headers } from 'next/headers'
import { Suspense } from 'react'
import { ensureThrows } from '../../../../ensure-error'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ headers: [] }],
}
export default async function Page() {
return (
<main>
<p>
This page reads a header that is not declared in the sample, so it
should fail validation with an exhaustiveness error. It catches the
error thrown by the header access, but validation should still fail.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestHeaders />
</Suspense>
</main>
)
}
async function TestHeaders() {
const headerStore = await headers()
try {
ensureThrows(
() => headerStore.get('undeclaredHeader'),
`Expected get() to throw for undeclared headers`
)
} catch (err) {
// We swallow the error. It should still be reported and fail the validation.
}
return null
}
import { headers } from 'next/headers'
import { Suspense } from 'react'
import { ensureThrows } from '../../../../ensure-error'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ headers: [] }],
}
export default async function Page() {
return (
<main>
<p>
This page reads a header that is not declared in the sample, so it
should fail validation with an exhaustiveness error.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestHeaders />
</Suspense>
</main>
)
}
async function TestHeaders() {
const headersStore = await headers()
ensureThrows(
() => headersStore.get('undeclaredHeader'),
`Expected get() to throw for undeclared headers`
)
return null
}
import { headers } from 'next/headers'
import { Suspense } from 'react'
import { ensureThrows } from '../../../../ensure-error'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ headers: [] }],
}
export default async function Page() {
return (
<main>
<p>
This page reads a header that is not declared in the sample, so it
should fail validation with an exhaustiveness error.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestHeaders />
</Suspense>
</main>
)
}
async function TestHeaders() {
const headerStore = await headers()
ensureThrows(
() => headerStore.has('undeclaredHeader'),
`Expected has() to throw for undeclared headers`
)
return null
}
import type { Instant } from 'next'
import { headers } from 'next/headers'
import assert from 'node:assert'
import { Suspense } from 'react'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
headers: [
['testHeader', 'testValue'],
['missingHeader', null],
],
},
],
}
export default async function Page() {
return (
<main>
<p>
When validated in build, the page should receive the headers specified
in the sample.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestHeaders />
</Suspense>
</main>
)
}
async function TestHeaders() {
const headerStore = await headers()
const testHeader = headerStore.get('testHeader')
assert.equal(testHeader, 'testValue')
const missingHeader = headerStore.get('missingHeader')
assert.equal(missingHeader, undefined)
assert.equal(headerStore.has('missingHeader'), false)
// TODO(instant-validation-build): test iteration
return null
}
import type { Instant } from 'next'
import { headers } from 'next/headers'
import assert from 'node:assert/strict'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
headers: [['x-test-header', 'testValue']],
},
],
}
export default async function Page() {
return (
<main>
<CachedChild headerStore={await headers()} />
</main>
)
}
async function CachedChild({ headerStore }: { headerStore: unknown }) {
'use cache'
// Flight serializes headers as an iterable, i.e. a sequence of entries
assert.deepStrictEqual(headerStore, [['x-test-header', 'testValue']])
return null
}
'use client'
import { assert } from '../../../../client-assertion-error'
export function ClientChild({ headerStore }: { headerStore: unknown }) {
// Flight serializes headers as an iterable, i.e. a sequence of entries
assert(
JSON.stringify(headerStore) ===
JSON.stringify([['x-test-header', 'testValue']]),
`Unexpected value for headerStore: ${JSON.stringify(headerStore)}`
)
return null
}
import type { Instant } from 'next'
import { headers } from 'next/headers'
import { ClientChild } from './client'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
headers: [['x-test-header', 'testValue']],
},
],
}
export default async function Page() {
return (
<main>
<p>
Passing the whole headers object to the client is generally a bad idea,
but it shouldn't crash validation, so we still do it
</p>
<ClientChild headerStore={await headers()} />
</main>
)
}
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [{ name: 'auth', value: '1' }] }],
}
export default async function Page() {
const c = await cookies()
return (
<main>
<p>
This page reads cookies outside Suspense, so it should fail validation
because it would block navigation.
</p>
<div id="runtime-content">cookie: {c.get('auth')?.value}</div>
<Dynamic />
</main>
)
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content</div>
}
import { connection } from 'next/server'
import { ReactNode, Suspense } from 'react'
export const unstable_instant = false
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>
<Suspense fallback="...">
<Now />
</Suspense>
{children}
</body>
</html>
)
}
async function Now() {
await connection()
return <span>{Date.now()}</span>
}
export default function Page() {
return <p>hello world</p>
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
import { ensureThrows } from '../../../../../../ensure-error'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
params: {
one: '123',
// two: <missing>
},
},
],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<p>
This page reads a param that is not declared in the sample, so it should
fail validation with an exhaustiveness error. It catches the error
thrown by the param access, but validation should still fail.
</p>
<TestParams params={params} />
</main>
)
}
async function TestParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
const p = await params
assert.equal(p.one, '123', `Unexpected value for param 'one'`)
try {
// We're not allowed to access params not in the samples.
ensureThrows(() => p.two, `Expected accessing an undeclared param to throw`)
} catch (err) {
// We swallow the error. It should still be reported and fail the validation.
}
// TODO(instant-validation-build): test `in` and iteration
// assert.deepStrictEqual(
// { ...p },
// { one: '123', two: '456' },
// `Unexpected value when iterating over params object`
// )
return null
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
import { ensureThrows } from '../../../../../../ensure-error'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
params: {
one: '123',
// two: <missing>
},
},
],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<p>
This page reads a param that is not declared in the sample, so it should
fail validation with an exhaustiveness error.
</p>
<TestParams params={params} />
</main>
)
}
async function TestParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
const p = await params
assert.equal(p.one, '123', `Unexpected value for param 'one'`)
// We're allowed to access names that don't correspond to a param.
assert.equal('three' in p, false)
assert.equal(p.three, undefined)
// We're not allowed to access params not in the samples.
ensureThrows(() => p.two)
// TODO: test `in` and iteration
// assert.deepStrictEqual(
// { ...p },
// { one: '123', two: '456' },
// `Unexpected value when iterating over params object`
// )
return null
}
import type { Instant } from 'next'
import { ParamsReader } from './params-reader'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [
{
params: {
one: '123',
// two: <missing>
},
},
],
}
export default function Page() {
return (
<main>
<p>
This page reads a param via useParams() that is not declared in the
sample, so it should fail validation with an exhaustiveness error.
</p>
<ParamsReader />
</main>
)
}
'use client'
import { useParams } from 'next/navigation'
import { ensureThrows } from '../../../../../../ensure-error'
export function ParamsReader() {
const params = useParams()
try {
// We're not allowed to access params not in the samples.
ensureThrows(
() => params.two,
`Expected accessing an undeclared param to throw`
)
} catch {
// We swallow the error. It should still be reported and fail the validation.
}
return null
}
import type { Instant } from 'next'
import { ParamsReader } from './params-reader'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [
{
params: {
one: '123',
// two: <missing>
},
},
],
}
export default function Page() {
return (
<main>
<p>
This page reads a param via useParams() that is not declared in the
sample, so it should fail validation with an exhaustiveness error.
</p>
<ParamsReader />
</main>
)
}
'use client'
import { useParams } from 'next/navigation'
import { ensureThrows } from '../../../../../../ensure-error'
export function ParamsReader() {
const params = useParams()
// We're not allowed to access params not in the samples.
ensureThrows(
() => params.two,
`Expected accessing an undeclared param to throw`
)
return null
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
params: {
one: '123',
two: '456',
},
},
],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<p>
When validated in build, the page should receive the params specified in
the sample.
</p>
<TestParams params={params} />
</main>
)
}
async function TestParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
const p = await params
const { one, two } = p
assert.equal(one, '123', `Unexpected value for param 'one'`)
assert.equal(two, '456', `Unexpected value for param 'two'`)
assert.equal('three' in p, false)
assert.equal(p.three, undefined)
assert.deepStrictEqual(
{ ...p },
{ one: '123', two: '456' },
`Unexpected value when iterating over params object`
)
return null
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [{ params: { slug: 'hello' } }],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<CachedChild params={await params} />
</main>
)
}
async function CachedChild({ params }: { params: Record<string, string> }) {
'use cache'
assert.equal(
params.slug,
'hello',
`Expected params.slug to be 'hello', got '${params.slug}'`
)
assert.deepStrictEqual(Object.keys(params), ['slug'])
return <div id="slug">{params.slug}</div>
}
'use client'
import { assert } from '../../../../../client-assertion-error'
export function ClientChild({ params }: { params: Record<string, string> }) {
assert(
params.slug === 'hello',
`Expected params.slug === 'hello', got '${params.slug}'`
)
assert(
JSON.stringify(Object.keys(params)) === JSON.stringify(['slug']),
`Expected Object.keys(params) to be ["slug"], got ${JSON.stringify(Object.keys(params))}`
)
return <div id="slug">{params.slug}</div>
}
import type { Instant } from 'next'
import { ClientChild } from './client'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [{ params: { slug: 'hello' } }],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<ClientChild params={await params} />
</main>
)
}
import type { Instant } from 'next'
import { ParamsReader } from './params-reader'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [
{
params: {
one: '123',
two: '456',
},
},
],
}
export default function Page() {
return (
<main>
<p>
When validated in build, useParams() should receive the params specified
in the sample.
</p>
<ParamsReader />
</main>
)
}
'use client'
import { useParams } from 'next/navigation'
import { assert } from '../../../../../../client-assertion-error'
export function ParamsReader() {
const params = useParams()
assert(
params.one === '123',
`Expected params.one === '123', got '${params.one}'`
)
assert(
params.two === '456',
`Expected params.two === '456', got '${params.two}'`
)
// We're allowed to access names that don't correspond to a param.
assert(
'three' in params === false,
`Expected \`'three' in params\` to be false`
)
assert(
params.three === undefined,
`Expected \`params.three\` to be undefined, got ${params.three}`
)
return null
}
import type { Instant } from 'next'
import { PathnameReader } from './pathname-reader'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [
{
params: {
one: '123',
// two: <missing>
},
},
],
}
export default function Page() {
return (
<main>
<p>
usePathname() on a route with dynamic params where not all params are
provided in the sample should fail validation.
</p>
<PathnameReader />
</main>
)
}
'use client'
import { usePathname } from 'next/navigation'
import { ensureThrows } from '../../../../../../ensure-error'
export function PathnameReader() {
ensureThrows(
// eslint-disable-next-line react-hooks/rules-of-hooks
() => usePathname(),
`Expected usePathname() to throw when not all params are provided in samples`
)
return null
}
import type { Instant } from 'next'
import { Suspense } from 'react'
import { PathnameReader } from './pathname-reader'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [
{
params: {
catchAll: ['aaa', 'bbb', 'ccc'],
},
},
],
}
export default function Page() {
return (
<main>
<p>
usePathname() on a catch-all route should return the pathname with the
sample array items joined by slashes.
</p>
<Suspense fallback={<div>Loading...</div>}>
<PathnameReader />
</Suspense>
</main>
)
}
'use client'
import { usePathname } from 'next/navigation'
import { assert } from '../../../../../client-assertion-error'
export function PathnameReader() {
const pathname = usePathname()
assert(
pathname === '/pathname/valid-use-pathname-catch-all/aaa/bbb/ccc',
`Expected pathname to be '/pathname/valid-use-pathname-catch-all/aaa/bbb/ccc', got '${pathname}'`
)
return <div id="result">pathname: {pathname}</div>
}
import type { Instant } from 'next'
import { Suspense } from 'react'
import { PathnameReader } from './pathname-reader'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [{}],
}
export default function Page() {
return (
<main>
<p>usePathname() on a route without dynamic params should work fine.</p>
<Suspense fallback={<div>Loading...</div>}>
<PathnameReader />
</Suspense>
</main>
)
}
'use client'
import { usePathname } from 'next/navigation'
import { assert } from '../../../../client-assertion-error'
export function PathnameReader() {
const pathname = usePathname()
assert(
pathname === '/pathname/valid-use-pathname-no-params',
`Expected pathname to be '/pathname/valid-use-pathname-no-params', got '${pathname}'`
)
return <div id="result">pathname: {pathname}</div>
}
import type { Instant } from 'next'
import { Suspense } from 'react'
import { PathnameReader } from './pathname-reader'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [
{
params: {
optionalCatchAll: ['xxx', 'yyy'],
},
},
],
}
export default function Page() {
return (
<main>
<p>
usePathname() on an optional catch-all route should return the pathname
with the sample array items joined by slashes.
</p>
<Suspense fallback={<div>Loading...</div>}>
<PathnameReader />
</Suspense>
</main>
)
}
'use client'
import { usePathname } from 'next/navigation'
import { assert } from '../../../../../client-assertion-error'
export function PathnameReader() {
const pathname = usePathname()
assert(
pathname === '/pathname/valid-use-pathname-optional-catch-all/xxx/yyy',
`Expected pathname to be '/pathname/valid-use-pathname-optional-catch-all/xxx/yyy', got '${pathname}'`
)
return <div id="result">pathname: {pathname}</div>
}
import type { Instant } from 'next'
import { Suspense } from 'react'
import { PathnameReader } from './pathname-reader'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [{}],
}
export default function Page() {
return (
<main>
<p>
usePathname() on a route inside a route group should not contain the
route group segment in the pathname.
</p>
<Suspense fallback={<div>Loading...</div>}>
<PathnameReader />
</Suspense>
</main>
)
}
'use client'
import { usePathname } from 'next/navigation'
import { assert } from '../../../../../client-assertion-error'
export function PathnameReader() {
const pathname = usePathname()
assert(
pathname === '/pathname/valid-use-pathname-route-group',
`Expected pathname to be '/pathname/valid-use-pathname-route-group', got '${pathname}'`
)
return <div id="result">pathname: {pathname}</div>
}
import type { Instant } from 'next'
import { Suspense } from 'react'
import { PathnameReader } from './pathname-reader'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [
{
params: {
one: '123',
two: '456',
},
},
],
}
export default function Page() {
return (
<main>
<p>
usePathname() on a route with dynamic params should return the pathname
with the sample param values substituted.
</p>
<Suspense fallback={<div>Loading...</div>}>
<PathnameReader />
</Suspense>
</main>
)
}
'use client'
import { usePathname } from 'next/navigation'
import { assert } from '../../../../../../client-assertion-error'
export function PathnameReader() {
const pathname = usePathname()
assert(
pathname === '/pathname/valid-use-pathname-with-params/123/456',
`Expected pathname to be '/pathname/valid-use-pathname-with-params/123/456', got '${pathname}'`
)
return <div id="result">pathname: {pathname}</div>
}
import type { Instant } from 'next'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [
{
params: {
slug: 'from-layout',
},
},
],
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
import assert from 'node:assert/strict'
import { Suspense } from 'react'
// No unstable_instant here — should inherit samples from the layout.
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<p>
This page does not define unstable_instant samples, so it should inherit
the samples from the parent layout.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestParams params={params} />
</Suspense>
</main>
)
}
async function TestParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
const p = await params
assert.equal(
p.slug,
'from-layout',
`Expected param 'slug' to be 'from-layout', got '${p.slug}'`
)
return null
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
import { Suspense } from 'react'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [
{
params: {
slug: 'from-page',
},
},
],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<p>
This page defines its own unstable_instant samples, which should
override the layout samples (no merging).
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestParams params={params} />
</Suspense>
</main>
)
}
async function TestParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
const p = await params
assert.equal(
p.slug,
'from-page',
`Expected param 'slug' to be 'from-page', got '${p.slug}'`
)
return null
}
import { ensureThrows } from '../../../../ensure-error'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ searchParams: { q: 'test' } }],
}
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string; undeclared?: string }>
}) {
return (
<main>
<p>
This page reads a searchParam that is not declared in the sample, so it
should fail validation with an exhaustiveness error. It catches the
error thrown by the searchParam access, but validation should still
fail.
</p>
<SearchResult searchParams={searchParams} />
</main>
)
}
async function SearchResult({
searchParams,
}: {
searchParams: Promise<{ q?: string; undeclared?: string }>
}) {
const sp = await searchParams
try {
ensureThrows(
() => sp.undeclared,
`Expected accessing an undeclared search param to throw`
)
} catch (err) {
// We swallow the error. It should still be reported and fail the validation.
}
return <div id="search-result">query: {sp.q}</div>
}
import { ensureThrows } from '../../../../ensure-error'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ searchParams: { q: 'test' } }],
}
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string; undeclared?: string }>
}) {
return (
<main>
<p>
This page reads a searchParam that is not declared in the sample, so it
should fail validation with an exhaustiveness error.
</p>
<SearchResult searchParams={searchParams} />
</main>
)
}
async function SearchResult({
searchParams,
}: {
searchParams: Promise<{ q?: string; undeclared?: string }>
}) {
const sp = await searchParams
ensureThrows(
() => sp.undeclared,
`Expected accessing an undeclared search param to throw`
)
return null
}
import type { Instant } from 'next'
import { Suspense } from 'react'
import { SearchParamsReader } from './search-params-reader'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
searchParams: {
q: 'test',
},
},
],
}
export default function Page() {
return (
<main>
<p>
This page reads a searchParam via useSearchParams() that is not declared
in the sample, so it should fail validation with an exhaustiveness
error.
</p>
<Suspense fallback={<div>Loading...</div>}>
<SearchParamsReader />
</Suspense>
</main>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
import { ensureThrows } from '../../../../ensure-error'
export function SearchParamsReader() {
const sp = useSearchParams()
try {
ensureThrows(
() => sp.get('undeclared'),
`Expected accessing an undeclared search param to throw`
)
} catch {
// We swallow the error. It should still be reported and fail the validation.
}
return null
}
import type { Instant } from 'next'
import { SearchParamsReader } from './search-params-reader'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
searchParams: {
q: 'test',
},
},
],
}
export default function Page() {
return (
<main>
<p>
This page reads a searchParam via useSearchParams() that is not declared
in the sample, so it should fail validation with an exhaustiveness
error.
</p>
<SearchParamsReader />
</main>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
import { ensureThrows } from '../../../../ensure-error'
export function SearchParamsReader() {
const sp = useSearchParams()
ensureThrows(
() => sp.get('undeclared'),
`Expected accessing an undeclared search param to throw`
)
return null
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
import { Suspense } from 'react'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
searchParams: {
// TODO(instant-validation-build): specify and test escaping behavior for spaces etc
single: 'test',
multiple: ['a', 'b'],
missing: null,
},
},
],
}
type SearchParams = Record<string, string | string[]>
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ foo?: string | string[] }>
}) {
return (
<main>
<p>
When validated in build, the page should receive the search params
specified in the sample.
</p>
<Suspense fallback={<div>Loading...</div>}>
<TestSearchParams searchParams={searchParams} />
</Suspense>
</main>
)
}
async function TestSearchParams({
searchParams,
}: {
searchParams: Promise<SearchParams>
}) {
const search = await searchParams
assert.equal(
search.single,
'test',
`Unexpected search param value for 'single'`
)
assert.deepStrictEqual(
search.multiple,
['a', 'b'],
`Unexpected search param value for 'multiple'`
)
assert.equal(
search.missing,
undefined,
`search param 'missing' should not be defined`
)
assert.equal(
'missing' in search,
false,
`search param 'missing' should not be in the keys of searchParams`
)
return null
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
searchParams: {
single: 'test',
multiple: ['a', 'b'],
},
},
],
}
export default async function Page({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[]>>
}) {
return (
<main>
<CachedChild searchParams={await searchParams} />
</main>
)
}
async function CachedChild({
searchParams,
}: {
searchParams: Record<string, string | string[]>
}) {
'use cache'
assert.equal(
searchParams.single,
'test',
`Expected searchParams.single to be 'test', got '${searchParams.single}'`
)
assert.deepStrictEqual(
searchParams.multiple,
['a', 'b'],
`Unexpected value for 'multiple'`
)
return <div id="single">{searchParams.single}</div>
}
'use client'
import { assert } from '../../../../client-assertion-error'
export function ClientChild({
searchParams,
}: {
searchParams: Record<string, string | string[]>
}) {
assert(
searchParams.single === 'test',
`Expected searchParams.single === 'test', got '${searchParams.single}'`
)
return <div id="single">{searchParams.single}</div>
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
import { ClientChild } from './client'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
searchParams: {
single: 'test',
multiple: ['a', 'b'],
},
},
],
}
export default async function Page({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[]>>
}) {
return (
<main>
<TestSearchParams searchParams={searchParams} />
</main>
)
}
async function TestSearchParams({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[]>>
}) {
const sp = await searchParams
assert.equal(
sp.single,
'test',
`Expected 'single' to be 'test', got '${sp.single}'`
)
assert.deepStrictEqual(
sp.multiple,
['a', 'b'],
`Unexpected value for 'multiple'`
)
return <ClientChild searchParams={sp} />
}
import type { Instant } from 'next'
import { Suspense } from 'react'
import { SearchParamsReader } from './search-params-reader'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
searchParams: {
single: 'test',
multiple: ['a', 'b'],
missing: null,
},
},
],
}
export default function Page() {
return (
<main>
<p>
When validated in build, useSearchParams() should receive the search
params specified in the sample.
</p>
<Suspense fallback={<div>Loading...</div>}>
<SearchParamsReader />
</Suspense>
</main>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
import { assert } from '../../../../client-assertion-error'
export function SearchParamsReader() {
const sp = useSearchParams()
assert(
sp.get('single') === 'test',
`Expected sp.get('single') === 'test', got '${sp.get('single')}'`
)
const multiple = sp.getAll('multiple')
assert(
multiple.length === 2 && multiple[0] === 'a' && multiple[1] === 'b',
`Expected sp.getAll('multiple') === ['a', 'b'], got ${JSON.stringify(multiple)}`
)
assert(
sp.get('missing') === null,
`Expected sp.get('missing') === null, got '${sp.get('missing')}'`
)
return null
}
'use client'
import { ReactNode } from 'react'
export function IgnoreServerContent(_props: { content: ReactNode }) {
return <p>Does nothing</p>
}
import { cookies } from 'next/headers'
import { IgnoreServerContent } from './client'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default function Page() {
return (
<main>
<p>
This page passes an erroring server component to a client component that
ignores it. The error didn't block validation, so the page should pass
validation.
</p>
<IgnoreServerContent content={<Throws />} />
</main>
)
}
async function Throws(): Promise<never> {
await cookies()
throw new Error('Kaboom')
}
import { Suspense } from 'react'
export default function Layout({ children }) {
return (
<>
<p>This layout wraps the children in Suspense.</p>
<hr />
<Suspense fallback={<div>Fallback from layout...</div>}>
{children}
</Suspense>
</>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default function Page() {
return (
<main>
<p>
This page has an error in a server component with no suspense
boundaries. It didn't render successfully, so it should be treated as
blocking validation -- we don't know what content would be rendered if
the error didn't occur.
</p>
<Throws />
</main>
)
}
async function Throws(): Promise<never> {
await cookies()
throw new Error('Kaboom')
}
import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default function Page() {
return (
<main>
<p>
This page has an error in a server component with no suspense
boundaries. It didn't render successfully, so it should be treated as
blocking validation -- we don't know what content would be rendered if
the error didn't occur.
</p>
<Throws />
</main>
)
}
async function Throws(): Promise<never> {
await cookies()
throw new Error('Kaboom')
}
import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
}
export default async function Page() {
await cachedIO('static')
await cookies()
await cachedIO('runtime')
return (
<main>
<p>
This page awaits a cache that is reachable in the static stage and a
cache that is reachable in the runtime stage. This should never need a
suspense boundary. This is a sanity check to make sure that we warm
caches correctly when validating.
</p>
</main>
)
}
async function cachedIO(key: any) {
'use cache'
await new Promise<void>((resolve) => setTimeout(resolve, 5))
return key
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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