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 {
|| name == "ExportError"
|| name == "FatalError"
|| name == "ImageError"
|| name == "InstantValidationError"
|| name == "InvariantError"
|| name == "ModuleBuildError"
|| name == "NestedMiddlewareError"
......
......@@ -1088,5 +1088,32 @@
"1087": "Failed to parse \"%s\":\\n%s%s",
"1088": "Expected RSC navigation response to have a body",
"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'
const CookieSchema = z
.object({
name: z.string(),
value: z.string(),
httpOnly: z.boolean().optional(),
path: z.string().optional(),
value: z.string().or(z.null()),
})
.strict()
const RuntimeSampleSchema = z
.object({
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(),
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(),
})
.strict()
......@@ -24,8 +22,11 @@ const RuntimeSampleSchema = z
const InstantConfigStaticSchema = z
.object({
prefetch: z.literal('static'),
samples: z.array(RuntimeSampleSchema).min(1).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()
......@@ -34,7 +35,9 @@ const InstantConfigRuntimeSchema = z
prefetch: z.literal('runtime'),
samples: z.array(RuntimeSampleSchema).min(1),
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()
......@@ -47,6 +50,7 @@ const InstantConfigSchema = z.union([
])
export type Instant = InstantConfigStatic | InstantConfigRuntime | false
export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
// the __GenericPrefetch type is used to avoid type widening issues with
// our choice to make exports the medium for programming a Next.js application
......@@ -56,41 +60,46 @@ export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
// delete the __GenericPrefetch member.
interface __GenericInstantConfig {
prefetch: string
samples?: Array<WideRuntimeSample>
samples?: Array<WideInstantSample>
from?: string[]
unstable_disableValidation?: boolean
unstable_disableDevValidation?: boolean
unstable_disableBuildValidation?: boolean
}
interface InstantConfigStatic {
prefetch: 'static'
samples?: Array<InstantSample>
from?: string[]
unstable_disableValidation?: boolean
unstable_disableValidation?: true
unstable_disableDevValidation?: true
unstable_disableBuildValidation?: true
}
interface InstantConfigRuntime {
prefetch: 'runtime'
samples: Array<RuntimeSample>
samples: Array<InstantSample>
from?: string[]
unstable_disableValidation?: boolean
unstable_disableValidation?: true
unstable_disableDevValidation?: true
unstable_disableBuildValidation?: true
}
type WideRuntimeSample = {
cookies?: RuntimeSample['cookies']
type WideInstantSample = {
cookies?: InstantSample['cookies']
headers?: Array<string[]>
params?: RuntimeSample['params']
searchParams?: RuntimeSample['searchParams']
params?: InstantSample['params']
searchParams?: InstantSample['searchParams']
}
type RuntimeSample = {
export type InstantSample = {
cookies?: Array<{
name: string
value: string
httpOnly?: boolean
path?: string
value: string | null
}>
headers?: Array<[string, string]>
headers?: Array<[string, string | null]>
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({
}
let maybeValidationBoundaryId: string | null = null
if (
typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_DEV_SERVER
) {
if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {
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)
}
......@@ -838,11 +834,10 @@ export default function OuterLayoutRouter({
if (
typeof window === 'undefined' &&
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_DEV_SERVER &&
typeof maybeValidationBoundaryId === 'string'
) {
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 = (
<RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}>
{templateValue}
......
......@@ -21,11 +21,9 @@ function hasFallbackRouteParams(): boolean {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'validation-client':
const fallbackParams = workUnitStore.fallbackRouteParams
return fallbackParams ? fallbackParams.size > 0 : false
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
return false
case 'prerender-legacy':
case 'request':
case 'prerender-runtime':
......
......@@ -32,6 +32,15 @@ const useDynamicSearchParams =
).useDynamicSearchParams
: 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
* that lets you *read* the current URL's search parameters.
......@@ -71,6 +80,16 @@ export function useSearchParams(): ReadonlyURLSearchParams {
return new ReadonlyURLSearchParams(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)
if (process.env.NODE_ENV !== 'production' && 'use' in React) {
const navigationPromises = use(NavigationPromisesContext)
......@@ -107,6 +126,17 @@ export function usePathname(): string {
// will add a new overload that changes the return type to include `null`.
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)
if (process.env.NODE_ENV !== 'production' && 'use' in React) {
const navigationPromises = use(NavigationPromisesContext)
......@@ -175,6 +205,16 @@ export function useParams<T extends Params = Params>(): 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)
if (process.env.NODE_ENV !== 'production' && 'use' in React) {
const navigationPromises = use(NavigationPromisesContext)
......@@ -221,6 +261,16 @@ export function useSelectedLayoutSegments(
// @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts
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)
if (process.env.NODE_ENV !== 'production' && 'use' in React) {
const navigationPromises = use(NavigationPromisesContext)
......@@ -264,6 +314,12 @@ export function useSelectedLayoutSegment(
const navigationPromises = useContext(NavigationPromisesContext)
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)
if (
process.env.NODE_ENV !== 'production' &&
......
......@@ -733,12 +733,21 @@ async function exportAppImpl(
const finalPhaseExportPaths: ExportPathEntry[] = []
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) {
if (exportPath._allowEmptyStaticShell) {
finalPhaseExportPaths.push(exportPath)
} else {
initialPhaseExportPaths.push(exportPath)
}
const route = exportPath.page
if (!routesWithInstantValidation.has(route)) {
exportPath._runInstantValidation = true
routesWithInstantValidation.add(route)
}
}
} else {
initialPhaseExportPaths = allExportPaths
......
......@@ -117,6 +117,9 @@ async function exportPageImpl(
// is generated while rendering using PPR and Cache Components.
_allowEmptyStaticShell: allowEmptyStaticShell = false,
// When true, attempt to run build-time instant validation for this export path.
_runInstantValidation: runInstantValidation = false,
// Pull the original query out.
query: originalQuery = {},
} = exportPath
......@@ -269,6 +272,7 @@ async function exportPageImpl(
// If it's dynamic, then it can be handled when request hits the route.
serveStreamingMetadata: true,
allowEmptyStaticShell,
runInstantValidation,
experimental: {
...commonRenderOpts.experimental,
isRoutePPREnabled,
......
......@@ -18,6 +18,7 @@ import {
type WorkStore,
} from '../app-render/work-async-storage.external'
import type {
InstantValidationSamples,
PrerenderStoreModernClient,
PrerenderStoreModernRuntime,
RequestStore,
......@@ -160,7 +161,10 @@ import {
wrapClientComponentLoader,
} from '../client-component-renderer-logger'
import { isNodeNextRequest } from '../base-http/helpers'
import { parseRelativeUrl } from '../../shared/lib/router/utils/parse-relative-url'
import {
parseRelativeUrl,
type ParsedRelativeUrl,
} from '../../shared/lib/router/utils/parse-relative-url'
import AppRouter from '../../client/components/app-router'
import type { ServerComponentsHmrCache } from '../response-cache'
import type { RequestErrorContext } from '../instrumentation/types'
......@@ -169,7 +173,10 @@ import { createInitialRouterState } from '../../client/components/router-reducer
import { createMutableActionQueue } from '../../client/components/app-router-instance'
import { getRevalidateReason } from '../instrumentation/utils'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
import {
getFallbackRouteParams,
type OpaqueFallbackRouteParams,
} from '../request/fallback-params'
import {
createReactServerPrerenderResult,
type ReactServerPrerenderResult,
......@@ -237,7 +244,9 @@ import { RenderStage, StagedRenderingController } from './staged-rendering'
import {
anySegmentHasRuntimePrefetchEnabled,
isPageAllowedToBlock,
anySegmentNeedsInstantValidation,
anySegmentNeedsInstantValidationInDev,
anySegmentNeedsInstantValidationInBuild,
resolveInstantConfigSamplesForPage,
} from './instant-validation/instant-config'
import { warnOnce } from '../../shared/lib/utils/warn-once'
import {
......@@ -250,6 +259,9 @@ import {
createValidationBoundaryTracking,
type ValidationBoundaryTracking,
} from './instant-validation/boundary-tracking'
import type { InstantSample } from '../../build/segment-config/app/app-segment-config'
import { ResponseCookies } from '../web/spec-extension/cookies'
import { isInstantValidationError } from './instant-validation/instant-validation-error'
export type GetDynamicParamFromSegment = (
// The LoaderTree to extract the dynamic param from
......@@ -549,7 +561,7 @@ async function generateDynamicRSCPayload(
process.env.__NEXT_DEV_SERVER &&
ctx.renderOpts.cacheComponents &&
!options?.actionResult && // Only for navigations
(await anySegmentNeedsInstantValidation(loaderTree))
(await anySegmentNeedsInstantValidationInDev(loaderTree))
const metadataIsRuntimePrefetchable =
await anySegmentHasRuntimePrefetchEnabled(loaderTree)
......@@ -784,12 +796,20 @@ async function generateStagedDynamicFlightRenderResult(
const selectStaleTime = createSelectStaleTime(experimental)
const staleTimeIterable = new StaleTimeIterable()
const stageController = new StagedRenderingController()
// TODO(cached-navs): this assumes that we checked during build that there's no sync IO.
// but it can happen e.g. after a revalidation or conditionally for a param that wasn't prerendered.
// we should change this to track sync IO, log an error and advance to dynamic.
const shouldTrackSyncIO = false
const stageController = new StagedRenderingController(
null, // no aborting
null, // no abandoning
shouldTrackSyncIO
)
// Initialize stale time tracking on the request store.
requestStore.stale = INFINITE_CACHE
requestStore.stagedRendering = stageController
requestStore.asyncApiPromises = createAsyncApiPromisesInDev(
requestStore.asyncApiPromises = createAsyncApiPromises(
stageController,
requestStore.cookies,
requestStore.mutableCookies,
......@@ -960,9 +980,12 @@ async function stagedRenderToReadableStreamWithoutCachesInDev(
// We aren't filling caches so we don't need to abort this render, it'll
// stream in a single pass
const abortSignal = null
const stageController = new StagedRenderingController(
null, // no aborting
null, // no abandoning
false // do not track sync IO (we don't have reliable stages)
)
const stageController = new StagedRenderingController(abortSignal)
const environmentName = () => {
const currentStage = stageController.currentStage
switch (currentStage) {
......@@ -982,7 +1005,7 @@ async function stagedRenderToReadableStreamWithoutCachesInDev(
}
requestStore.stagedRendering = stageController
requestStore.asyncApiPromises = createAsyncApiPromisesInDev(
requestStore.asyncApiPromises = createAsyncApiPromises(
stageController,
requestStore.cookies,
requestStore.mutableCookies,
......@@ -1067,7 +1090,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
const shouldValidate =
!isBypassingCachesInDev(initialRequestStore) &&
(initialRequestStore.isHmrRefresh === true ||
(await anySegmentNeedsInstantValidation(loaderTree)))
(await anySegmentNeedsInstantValidationInDev(loaderTree)))
const getPayload = async (requestStore: RequestStore) => {
const payload: RSCPayload &
......@@ -1448,7 +1471,9 @@ async function finalRuntimeServerPrerender(
)
const finalStageController = new StagedRenderingController(
finalServerController.signal
finalServerController.signal,
null, // no abandoning
true // track sync IO
)
const finalServerPrerenderStore: PrerenderStoreModernRuntime = {
......@@ -2357,7 +2382,24 @@ async function renderToHTMLOrFlightImpl(
}
const streamString = await streamToString(response.stream)
return new RenderResult(streamString, options)
const result = new RenderResult(streamString, options)
// Run build-time instant validation if the page has instant configs
// TODO(instant-validation-build): This is not a great place to wire this in.
if (
workStore.cacheComponentsEnabled &&
workStore.isBuildTimePrerendering &&
renderOpts.runInstantValidation &&
(await anySegmentNeedsInstantValidationInBuild(loaderTree))
) {
// Throws StaticGenBailoutError if validation failed.
await validateInstantConfigsInBuild(
ctx,
response.renderResumeDataCache ?? null
)
}
return result
} else {
// We're rendering dynamically
const renderResumeDataCache =
......@@ -2994,7 +3036,15 @@ async function renderToStream(
const selectStaleTime = createSelectStaleTime(experimental)
const staleTimeIterable = new StaleTimeIterable()
const stageController = new StagedRenderingController()
// TODO(cached-navs): this assumes that we checked during build that there's no sync IO.
// but it can happen e.g. after a revalidation or conditionally for a param that wasn't prerendered.
// we should change this to track sync IO, log an error and advance to dynamic.
const shouldTrackSyncIO = false
const stageController = new StagedRenderingController(
null, // no aborting
null, // no abandoning
shouldTrackSyncIO
)
requestStore.stale = INFINITE_CACHE
requestStore.stagedRendering = stageController
......@@ -3500,7 +3550,8 @@ async function renderWithRestartOnCacheMissInDev(
const initialAbandonController = new AbortController() // Controls whether this render is abandoned
const initialStageController = new StagedRenderingController(
initialDataController.signal,
initialAbandonController
initialAbandonController,
true // track sync IO
)
requestStore.prerenderResumeDataCache = prerenderResumeDataCache
......@@ -3508,7 +3559,7 @@ async function renderWithRestartOnCacheMissInDev(
// so not having a resume data cache won't break any expectations in case we don't need to restart.
requestStore.renderResumeDataCache = null
requestStore.stagedRendering = initialStageController
requestStore.asyncApiPromises = createAsyncApiPromisesInDev(
requestStore.asyncApiPromises = createAsyncApiPromises(
initialStageController,
requestStore.cookies,
requestStore.mutableCookies,
......@@ -3549,9 +3600,14 @@ async function renderWithRestartOnCacheMissInDev(
// If we abort the render, we want to reject the stage-dependent promises as well.
// Note that we want to install this listener after the render is started
// so that it runs after react is finished running its abort code.
initialReactController.signal.addEventListener('abort', () => {
initialDataController.abort(initialReactController.signal.reason)
})
initialReactController.signal.addEventListener(
'abort',
() => {
const { reason } = initialReactController.signal
initialDataController.abort(reason)
},
{ once: true }
)
const stream = streamPair[0]
const accumulatedChunksPromise = accumulateStreamChunks(
......@@ -3560,10 +3616,14 @@ async function renderWithRestartOnCacheMissInDev(
initialDataController.signal
)
initialDataController.signal.addEventListener('abort', () => {
accumulatedChunksPromise.catch(() => {})
stream.cancel()
})
initialDataController.signal.addEventListener(
'abort',
() => {
accumulatedChunksPromise.catch(() => {})
stream.cancel()
},
{ once: true }
)
return {
stream,
......@@ -3648,7 +3708,11 @@ async function renderWithRestartOnCacheMissInDev(
// We are going to render this pass all the way through because we've already
// filled any caches so we won't be aborting this time.
const abortSignal = null
const finalStageController = new StagedRenderingController(abortSignal)
const finalStageController = new StagedRenderingController(
abortSignal,
null, // no abandoning
true // track sync IO
)
// We've filled the caches, so now we can render as usual,
// without any cache-filling mechanics.
......@@ -3658,7 +3722,7 @@ async function renderWithRestartOnCacheMissInDev(
)
requestStore.stagedRendering = finalStageController
requestStore.cacheSignal = null
requestStore.asyncApiPromises = createAsyncApiPromisesInDev(
requestStore.asyncApiPromises = createAsyncApiPromises(
finalStageController,
requestStore.cookies,
requestStore.mutableCookies,
......@@ -3837,7 +3901,7 @@ async function countStaticStageBytes(
return byteLength
}
function createAsyncApiPromisesInDev(
function createAsyncApiPromises(
stagedRendering: StagedRenderingController,
cookies: RequestStore['cookies'],
mutableCookies: RequestStore['mutableCookies'],
......@@ -4073,12 +4137,16 @@ async function spawnStaticShellValidationInDevImpl(
const { staticChunks, runtimeChunks, dynamicChunks } = accumulatedChunks
const needsInstantValidation =
await anySegmentNeedsInstantValidation(loaderTree)
await anySegmentNeedsInstantValidationInDev(loaderTree)
// `samples` from instant config are only used during build
const validationSamples = null
const validationSampleTracking = null
// First we warmup SSR with the runtime chunks. This ensures that when we do
// the full prerender pass with dynamic tracking module loading won't
// interrupt the prerender and can properly observe the entire content
await warmupClientModulesForStagedValidationInDev(
await warmupClientModulesForStagedValidation(
// if we're going to be validating prefetches, we'll be rendering some segments in the dynamic stage.
// otherwise, for static shell validation, we only need to warm up to the runtime stage.
// we also need to use a different store type, because instant validation allows more APIs to resolve.
......@@ -4088,7 +4156,9 @@ async function spawnStaticShellValidationInDevImpl(
rootParams,
fallbackRouteParams,
allowEmptyStaticShell,
ctx
ctx,
validationSamples,
validationSampleTracking
)
debug?.(`Starting static shell validation...`)
......@@ -4140,8 +4210,10 @@ async function spawnStaticShellValidationInDevImpl(
debugChunks,
startTime,
rootParams,
fallbackRouteParams,
ctx,
hmrRefreshHash
hmrRefreshHash,
validationSamples
)
if (instantConfigsResult.length > 0) {
......@@ -4150,14 +4222,16 @@ async function spawnStaticShellValidationInDevImpl(
}
}
async function warmupClientModulesForStagedValidationInDev(
async function warmupClientModulesForStagedValidation(
storeType: PrerenderStoreModernClient['type'] | ValidationStoreClient['type'],
partialServerChunks: Array<Uint8Array>,
allServerChunks: Array<Uint8Array>,
rootParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
allowEmptyStaticShell: boolean,
ctx: AppRenderContext
ctx: AppRenderContext,
validationSamples: ValidationStoreClient['validationSamples'],
validationSampleTracking: ValidationStoreClient['validationSampleTracking']
) {
const { implicitTags, nonce, workStore } = ctx
......@@ -4220,6 +4294,9 @@ async function warmupClientModulesForStagedValidationInDev(
varyParamsAccumulator: null,
// We're not rendering any validation boundaries yet.
boundaryState: null,
validationSamples,
validationSampleTracking,
fallbackRouteParams,
}
initialClientPrerenderStore = store
}
......@@ -4495,8 +4572,10 @@ async function validateInstantConfigs(
debugChunks: null | Array<Uint8Array>,
startTime: number,
rootParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
ctx: AppRenderContext,
hmrRefreshHash: string | undefined
hmrRefreshHash: string | undefined,
validationSamples: ValidationStoreClient['validationSamples'] | null
): Promise<Array<unknown>> {
const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
......@@ -4505,7 +4584,10 @@ async function validateInstantConfigs(
createCombinedPayloadAtDepth,
createCombinedPayloadStream,
collectStagedSegmentData,
} = ctx.componentMod.InstantValidation!
} = ctx.componentMod.InstantValidation()!
const { createValidationSampleTracking } =
require('./instant-validation/instant-samples') as typeof import('./instant-validation/instant-samples')
debug?.('\nStarting depth-based instant validation...')
......@@ -4601,9 +4683,13 @@ async function validateInstantConfigs(
isDebugChannelEnabled
)
const dynamicValidation = createInstantValidationState(
const instantValidationState = createInstantValidationState(
payloadResult.createInstantStack
)
const validationSampleTracking =
validationSamples !== null ? createValidationSampleTracking() : null
const clientDynamicTracking = createDynamicTrackingState(false)
const prerenderStore: PrerenderStore = {
......@@ -4624,6 +4710,9 @@ async function validateInstantConfigs(
hmrRefreshHash,
varyParamsAccumulator: null,
boundaryState,
fallbackRouteParams,
validationSamples,
validationSampleTracking,
}
let errors: Array<unknown>
......@@ -4655,7 +4744,7 @@ async function validateInstantConfigs(
trackDynamicHoleInNavigation(
workStore,
componentStack,
dynamicValidation,
instantValidationState,
clientDynamicTracking,
payloadResult.hasAmbiguousErrors
? DynamicHoleKind.Runtime
......@@ -4667,9 +4756,29 @@ async function validateInstantConfigs(
} else if (!reactController.signal.aborted) {
const componentStack = errorInfo.componentStack
if (typeof componentStack === 'string') {
let errorForDisplay = err
if (process.env.NODE_ENV === 'production') {
// In production (i.e. build validation), Flight omits everything except the digest
// when serializing errors, which makes them very unfriendly for debugging.
// Map the deserialized errors back to their original error object to make it more useful.
if (
err &&
typeof err === 'object' &&
'digest' in err &&
typeof err.digest === 'string'
) {
const serverError =
workStore.reactServerErrorsByDigest.get(err.digest)
if (serverError !== undefined) {
errorForDisplay = serverError
}
}
}
trackThrownErrorInNavigation(
dynamicValidation,
err,
workStore,
instantValidationState,
errorForDisplay,
componentStack
)
}
......@@ -4705,31 +4814,23 @@ async function validateInstantConfigs(
errors = getNavigationDisallowedDynamicReasons(
workStore,
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full,
dynamicValidation,
instantValidationState,
validationSampleTracking,
boundaryState
)
} catch (thrownValue) {
errors = getNavigationDisallowedDynamicReasons(
workStore,
PreludeState.Errored,
dynamicValidation,
instantValidationState,
validationSampleTracking,
boundaryState
)
if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) {
// TODO(instant-validation) we should switch to pushing an Error with a cause of the
// thrownValue. Since we want to report the issue to code that largely expects
// Error objects we should aim to provide this whereever possible
errors.unshift(
'During dynamic validation the root of the page errored.',
thrownValue
)
}
}
if (errors === null || errors.length === 0) {
// This prerender did not produce any errors
return null
// This prerender did not produce any errors
if (errors.length === 0) {
return []
}
if (previousBoundaryState === null && payloadResult.hasAmbiguousErrors) {
......@@ -4772,6 +4873,663 @@ async function validateInstantConfigs(
return []
}
/**
* Two-pass render for build-time instant validation.
* The flow is similar to `renderWithRestartOnCacheMissInDev`: pass 1 warms caches,
* pass 2 renders with warm caches. If pass 1 has no cache misses,
* its result is returned directly.
*
* Differences from `renderWithRestartOnCacheMissInDev`:
* - both renders are abortable: if we know that we can't use a stream, we can just
* throw it away, we don't have to render a complete result.
* - We don't need to tee the stream, we only care about accumulating chunks.
*/
async function renderWithRestartOnCacheMissInValidation(
ctx: AppRenderContext,
initialRequestStore: RequestStore,
createRequestStore: () => RequestStore,
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
createOnError: (
signal: AbortSignal,
isRestart: boolean
) => (error: unknown) => void,
prefilledDataCache: RenderResumeDataCache | null
): Promise<{
accumulatedChunksPromise: Promise<AccumulatedStreamChunks>
startTime: number
stageController: StagedRenderingController
requestStore: RequestStore
}> {
const { componentMod: ComponentMod } = ctx
const { clientModules } = getClientReferenceManifest()
let startTime = -Infinity
let requestStore: RequestStore = initialRequestStore
//===============================================
// Initial render (prospective — may warm caches)
//===============================================
const cacheSignal = new CacheSignal()
trackPendingModules(cacheSignal)
// The prerender we rean before the validation probably already filled some caches,
// so we want to save work and re-use them.
const prerenderResumeDataCache = prefilledDataCache
? createPrerenderResumeDataCache(prefilledDataCache)
: createPrerenderResumeDataCache()
const initialReactController = new AbortController()
const initialDataController = new AbortController()
const initialAbandonController = new AbortController()
const initialStageController = new StagedRenderingController(
initialDataController.signal,
initialAbandonController,
true // track sync IO
)
requestStore.prerenderResumeDataCache = prerenderResumeDataCache
requestStore.renderResumeDataCache = null
requestStore.stagedRendering = initialStageController
requestStore.cacheSignal = cacheSignal
requestStore.asyncApiPromises = createAsyncApiPromises(
initialStageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
// We don't set `requestStore.controller and requestStore.renderSignal here.
// Right now, we only abort for sync IO, and in the first render, that's just a restart
// (after waiting for caches)
requestStore.controller = undefined
requestStore.renderSignal = undefined
const initialRscPayload = await getPayload(requestStore)
const advanceStageIfNoCacheMiss = (
stage: Parameters<StagedRenderingController['advanceStage']>[0]
) => {
if (initialAbandonController.signal.aborted === true) {
return
} else if (cacheSignal.hasPendingReads()) {
initialAbandonController.abort()
} else {
initialStageController.advanceStage(stage)
}
}
const initialResult = await runInSequentialTasks(
() => {
initialStageController.advanceStage(RenderStage.EarlyStatic)
startTime = performance.now() + performance.timeOrigin
const stream = workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
ComponentMod,
initialRscPayload,
clientModules,
{
onError: createOnError(initialReactController.signal, false),
startTime,
filterStackFrame,
signal: initialReactController.signal,
}
)
initialReactController.signal.addEventListener(
'abort',
() => {
const { reason } = initialReactController.signal
initialDataController.abort(reason)
},
{ once: true }
)
const accumulatedChunksPromise = accumulateStreamChunks(
stream,
initialStageController,
initialDataController.signal
)
accumulatedChunksPromise.catch(() => {})
return { accumulatedChunksPromise }
},
() => {
advanceStageIfNoCacheMiss(RenderStage.Static)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.EarlyRuntime)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.Runtime)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.Dynamic)
}
)
if (initialStageController.currentStage !== RenderStage.Abandoned) {
// No cache misses. Use the result as-is.
return {
accumulatedChunksPromise: initialResult.accumulatedChunksPromise,
startTime,
stageController: initialStageController,
requestStore,
}
}
// Cache miss. Wait for caches to fill, then re-render with warm caches.
await cacheSignal.cacheReady()
initialReactController.abort()
//===============================================
// Final render (restarted, with warm caches)
//===============================================
requestStore = createRequestStore()
// Unlike dev, where we're re-using the render that'll be visible in the browser,
// we *can* abort the validation render.
const finalReactController = new AbortController()
const finalDataController = new AbortController()
const finalStageController = new StagedRenderingController(
finalDataController.signal, // abortable
null, // no abandoning
true // track sync IO
)
requestStore.prerenderResumeDataCache = null
requestStore.renderResumeDataCache = createRenderResumeDataCache(
prerenderResumeDataCache
)
requestStore.stagedRendering = finalStageController
requestStore.cacheSignal = null
requestStore.asyncApiPromises = createAsyncApiPromises(
finalStageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
// Right now, we only abort for sync IO.
// If sync IO occurs in a place where it's not allowed, then we have to fail validation,
// and we can abort the render immediately, without waiting for anything else..
requestStore.controller = finalReactController
requestStore.renderSignal = finalDataController.signal
const finalRscPayload = await getPayload(requestStore)
const finalResult = await runInSequentialTasks(
() => {
finalStageController.advanceStage(RenderStage.EarlyStatic)
startTime = performance.now() + performance.timeOrigin
const stream = workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
ComponentMod,
finalRscPayload,
clientModules,
{
onError: createOnError(finalReactController.signal, true),
startTime,
filterStackFrame,
signal: finalReactController.signal,
}
)
finalReactController.signal.addEventListener(
'abort',
() => {
finalDataController.abort(finalReactController.signal.reason)
},
{ once: true }
)
const accumulatedChunksPromise = accumulateStreamChunks(
stream,
finalStageController,
null
)
accumulatedChunksPromise.catch(() => {})
return {
accumulatedChunksPromise,
}
},
() => {
finalStageController.advanceStage(RenderStage.Static)
},
() => {
finalStageController.advanceStage(RenderStage.EarlyRuntime)
},
() => {
finalStageController.advanceStage(RenderStage.Runtime)
},
() => {
finalStageController.advanceStage(RenderStage.Dynamic)
}
)
return {
accumulatedChunksPromise: finalResult.accumulatedChunksPromise,
startTime,
stageController: finalStageController,
requestStore,
}
}
async function validateInstantConfigsInBuild(
ctx: AppRenderContext,
prefilledDataCache: RenderResumeDataCache | null
): Promise<void> {
const run = async () => {
let success: boolean
try {
// The validation renders are separate renders, and use a separate WorkStore.
// However, we defensively exit the existing workStore to avoid relying on something from there
// before we shadow it.
success = await workAsyncStorage.exit(async () =>
validateInstantConfigsInBuildImpl(ctx, prefilledDataCache)
)
} catch (err) {
console.error(
new InvariantError(
'An unexpected error occcured during instant validation',
{ cause: err }
)
)
success = false
}
if (!success) {
console.error('Stopping prerender due to instant validation errors.')
throw new StaticGenBailoutError()
}
}
if (process.env.__NEXT_TEST_MODE && process.env.NEXT_TEST_LOG_VALIDATION) {
// In tests, we use these markers to extract the relevant portion of the CLI logs.
// We want consistent ordering of these messages and other console.error calls,
// so we use console.error here as well. Using console.log leads to non-deterministic
// log order, likely stdout/stderr can interleave in non-deterministic ways.
const requestId = Date.now()
const route = ctx.workStore.route
console.error(
'<VALIDATION_MESSAGE>' +
JSON.stringify({
type: 'validation_start',
requestId,
url: route,
}) +
'</VALIDATION_MESSAGE>'
)
try {
return await run()
} finally {
console.error(
'<VALIDATION_MESSAGE>' +
JSON.stringify({
type: 'validation_end',
requestId,
url: route,
}) +
'</VALIDATION_MESSAGE>'
)
}
} else {
return await run()
}
}
/**
* Runs instant validation at build time using the `samples` from `unstable_instant`.
*
* For each sample, this creates a staged RSC render with a synthetic `RequestStore`
* populated from sample data, then feeds the accumulated chunks to
* `validateInstantConfigs` which handles the actual validation.
*/
async function validateInstantConfigsInBuildImpl(
ctx: AppRenderContext,
prefilledDataCache: RenderResumeDataCache | null
): Promise<boolean> {
const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
const { workStore: outerWorkStore } = ctx
const route = outerWorkStore.route
const loaderTree = ctx.componentMod.routeModule.userland.loaderTree
let samples = await resolveInstantConfigSamplesForPage(loaderTree)
if (!samples || samples.length === 0) {
// No samples defined; use a single empty sample to still run validation
samples = [{}]
}
debug?.('Resolved samples:', samples)
const allPossibleFallbackRouteParams = getFallbackRouteParams(
route,
ctx.componentMod.routeModule
)
for (let sampleIndex = 0; sampleIndex < samples.length; sampleIndex++) {
const sample = samples[sampleIndex]
debug?.(`Validating sample (${sampleIndex + 1}/${samples.length}):`, sample)
let errors: unknown[]
try {
errors = await consoleAsyncStorage.run({ dim: true }, () =>
validateInstantConfigInBuildWithSample(
ctx,
sample,
allPossibleFallbackRouteParams,
prefilledDataCache
)
)
} catch (err) {
if (isInstantValidationError(err)) {
errors = [err]
} else {
throw err
}
}
if (errors.length > 0) {
debug?.(`❌ Sample failed validation (${errors.length} errors)`)
const sampleDesc =
samples.length > 1
? ` (sample ${sampleIndex + 1} of ${samples.length})`
: ''
for (const err of errors) {
console.error(err)
}
console.error(
`Build-time instant validation failed for route "${route}"${sampleDesc}.`
)
return false
} else {
debug?.('✅ Sample validated successfully')
}
}
return true
}
async function validateInstantConfigInBuildWithSample(
outerCtx: AppRenderContext,
sample: InstantSample,
allPossibleFallbackRouteParams: OpaqueFallbackRouteParams | null,
prefilledDataCache: RenderResumeDataCache | null
): Promise<unknown[]> {
// The flow for build mirrors what we do when validating in dev.
// We have to perform a full dynamic render to get the RSC chunks for each stage.
// In order to do that, we have to set up a mock AppRenderContext, workStore, and requestStore
// based on the `sample` we're using.
const { workStore: outerWorkStore } = outerCtx
const loaderTree = outerCtx.componentMod.routeModule.userland.loaderTree
const route = outerWorkStore.route
const {
createCookiesFromSample,
createHeadersFromSample,
createDraftModeForValidation,
createRelativeURLFromSamples,
createValidationSampleTracking,
} =
require('./instant-validation/instant-samples') as typeof import('./instant-validation/instant-samples')
// TODO(instant-validation-build): it feels like this should happen higher up
// and go through existing URL parsing/generation logic?
const sampleUrl = createRelativeURLFromSamples(
route,
sample.params,
sample.searchParams
)
const sampleParams = sample.params ?? {}
let fallbackRouteParams: OpaqueFallbackRouteParams | null = null
if (allPossibleFallbackRouteParams) {
const fallbackRouteParamsMut = new Map()
for (const [paramKey, value] of allPossibleFallbackRouteParams) {
if (!(paramKey in sampleParams)) {
fallbackRouteParamsMut.set(paramKey, value)
}
}
fallbackRouteParams = fallbackRouteParamsMut
}
const getDynamicParamFromSegment = makeGetDynamicParamFromSegment(
sampleParams,
fallbackRouteParams,
false
)
const sampleRootParams = getRootParams(loaderTree, getDynamicParamFromSegment)
let sampleUrlWithoutQuery: Omit<ParsedRelativeUrl, 'query'>
let sampleQuery: ParsedRelativeUrl['query']
;({ query: sampleQuery, ...sampleUrlWithoutQuery } = sampleUrl)
const { AfterContext } =
require('../after/after-context') as typeof import('../after/after-context')
// NOTE: Matching the field order in `createWorkStore` to avoid deopting.
const workStore: WorkStore = {
isStaticGeneration: false,
page: outerWorkStore.page,
route: outerWorkStore.route,
incrementalCache: outerWorkStore.incrementalCache,
cacheLifeProfiles: outerWorkStore.cacheLifeProfiles,
isBuildTimePrerendering: false,
fetchCache: outerWorkStore.fetchCache,
isOnDemandRevalidate: false,
isDraftMode: false,
isPrefetchRequest: false,
buildId: outerWorkStore.buildId,
reactLoadableManifest: outerWorkStore.reactLoadableManifest,
assetPrefix: outerWorkStore.assetPrefix,
nonce: outerWorkStore.nonce,
// Never run `after()` for this validation render. by definition, `after` can't affect the rendered output.
afterContext: new AfterContext({
waitUntil(promise) {
promise.catch(() => {})
},
onClose() {},
onTaskError() {},
}),
cacheComponentsEnabled: outerWorkStore.cacheComponentsEnabled,
previouslyRevalidatedTags: [],
refreshTagsByCacheKind: new Map(),
runInCleanSnapshot: outerWorkStore.runInCleanSnapshot,
shouldTrackFetchMetrics: false,
reactServerErrorsByDigest: new Map(),
}
return workAsyncStorage.run(workStore, async () => {
// NOTE: match field order in renderToHTMLOrFlightImpl to avoid deopts
const validationCtx: AppRenderContext = {
componentMod: outerCtx.componentMod,
url: sampleUrlWithoutQuery,
renderOpts: outerCtx.renderOpts,
workStore,
parsedRequestHeaders: outerCtx.parsedRequestHeaders,
getDynamicParamFromSegment,
interpolatedParams: sampleParams,
query: sampleQuery,
isPrefetch: false,
isPossibleServerAction: false,
requestTimestamp: outerCtx.requestTimestamp,
appUsingSizeAdjustment: outerCtx.appUsingSizeAdjustment,
flightRouterState: undefined,
requestId: outerCtx.requestId,
htmlRequestId: outerCtx.htmlRequestId,
pagePath: outerCtx.pagePath,
assetPrefix: outerCtx.assetPrefix,
isNotFoundPath: outerCtx.isNotFoundPath,
nonce: outerCtx.nonce,
res: outerCtx.res,
sharedContext: outerCtx.sharedContext,
implicitTags: outerCtx.implicitTags,
}
const validationSamples: InstantValidationSamples = {
params: sample.params,
searchParams: sample.searchParams,
}
const createRequestStore = (): RequestStore => {
// Create exhaustive request data from sample
const sampleCookies = createCookiesFromSample(sample.cookies, route)
// We don't have to bother initializing these, pages can't access them anyway,
// we just need them because RequestStore requires them.
const unusedMutableCookies = new ResponseCookies(new Headers())
// Create headers.
const sampleHeaders = createHeadersFromSample(
sample.headers,
sample.cookies,
route
)
const draftMode = createDraftModeForValidation()
return {
type: 'request',
phase: 'render',
implicitTags: outerCtx.implicitTags,
url: {
pathname: sampleUrl.pathname,
search: sampleUrl.search,
},
headers: sampleHeaders,
cookies: sampleCookies,
mutableCookies: unusedMutableCookies,
userspaceMutableCookies: unusedMutableCookies,
draftMode,
rootParams: sampleRootParams,
validationSamples,
validationSampleTracking: createValidationSampleTracking(),
// These will be set when rendering
renderResumeDataCache: null,
prerenderResumeDataCache: null,
stagedRendering: null,
asyncApiPromises: undefined,
}
}
// Track server errors. If one of them surfaces during the client render
// in the deserialized form (with no message/stack) we'll use this to map it
// back to the original.
const onServerError = createReactServerErrorHandler(
true, // shouldFormatError
true, // isBuildTimePrerendering - disables tracing
workStore.reactServerErrorsByDigest,
() => {} // Don't report anything here. If needed, it will be reported in the client render.
)
const {
accumulatedChunksPromise,
startTime,
stageController,
requestStore: finalServerStore,
} = await renderWithRestartOnCacheMissInValidation(
validationCtx,
createRequestStore(),
createRequestStore,
(requestStore) =>
workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
loaderTree,
validationCtx,
{ is404: false }
),
(signal) =>
function onError(err) {
const digest = getDigestForWellKnownError(err)
if (digest) {
return digest
}
if (signal.aborted) {
return
}
return onServerError(err)
},
prefilledDataCache
)
const accumulatedChunks = await accumulatedChunksPromise
const debugChunks = null // TODO(instant-validation-build): support debugChannel
// Missing sample errors take priority over everything else,
// because they prevent us from rendering everything we need to validate.
const serverValidationSampleTracking =
finalServerStore.validationSampleTracking!
if (serverValidationSampleTracking.missingSampleErrors.length > 0) {
return serverValidationSampleTracking.missingSampleErrors
}
// We also error for sync IO. This runs after the prerender,
// so if we get sync IO errors here, they're likely from the runtime stage --
// the prerender probably discovered sync IO in the static stage
if (
stageController.currentStage === RenderStage.Abandoned &&
stageController.syncInterruptReason
) {
return [stageController.syncInterruptReason]
}
const allowEmptyStaticShell =
(validationCtx.renderOpts.allowEmptyStaticShell ?? false) ||
(await isPageAllowedToBlock(loaderTree))
// Now we the chunks of a fully rendered page, just like in dev.
// We can use them to validate all the navigations required by `instant` configs.
// Note that we're not performing static shell validation here -- that happens
// implicitly as part of the static prerender.
// The static prerender has warmed some client modules already,
// but we'll be reaching Runtime/Dynamic stages and thus rendering more content,
// so we need to warm again.
// TODO(instant-validation-build): This might warm too much, possibly hitting errors on code that didn't expect
// to run at build time. For example, we generally don't need to render leaf segments (e.g. __PAGE__) in
// the Dynamic stage, they're Runtime at best.
const warmupValidationSamplesTracking = createValidationSampleTracking()
await warmupClientModulesForStagedValidation(
'validation-client',
accumulatedChunks.dynamicChunks,
accumulatedChunks.dynamicChunks,
sampleRootParams,
fallbackRouteParams,
allowEmptyStaticShell,
validationCtx,
validationSamples,
warmupValidationSamplesTracking
)
if (warmupValidationSamplesTracking.missingSampleErrors.length > 0) {
return warmupValidationSamplesTracking.missingSampleErrors
}
return await validateInstantConfigs(
accumulatedChunks,
debugChunks,
startTime,
sampleRootParams,
fallbackRouteParams,
validationCtx,
undefined, // hmrRefreshHash,
validationSamples
)
})
}
type PrerenderToStreamResult = {
stream: ReadableStream<Uint8Array>
digestErrorsMap: Map<string, DigestedError>
......
......@@ -12,6 +12,7 @@ import { isPrerenderInterruptedError } from './dynamic-rendering'
import { getProperError } from '../../lib/is-error'
import { createDigestWithErrorCode } from '../../lib/error-telemetry-utils'
import { isReactLargeShellError } from './react-large-shell-error'
import { isInstantValidationError } from './instant-validation/instant-validation-error'
declare global {
var __next_log_error__: undefined | ((err: unknown) => void)
......@@ -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 (isPrerenderInterruptedError(error)) return error.digest
if (isInstantValidationError(error)) return error.digest
return undefined
}
......
......@@ -50,6 +50,7 @@ import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { InvariantError } from '../../shared/lib/invariant-error'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
const hasPostpone = typeof React.unstable_postpone === 'function'
......@@ -618,6 +619,11 @@ export function useDynamicRouteParams(expression: string) {
}
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':
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.`
......@@ -627,9 +633,6 @@ export function useDynamicRouteParams(expression: string) {
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.`
)
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
break
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
......@@ -655,7 +658,8 @@ export function useDynamicSearchParams(expression: string) {
switch (workUnitStore.type) {
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
case 'prerender-client': {
React.use(
......@@ -722,7 +726,7 @@ const hasViewportRegex = new RegExp(
)
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]`
)
......@@ -853,7 +857,7 @@ export function trackDynamicHoleInNavigation(
}
const boundaryLocation =
hasPrefetchValidationBoundaryRegex.exec(componentStack)
hasInstantValidationBoundaryRegex.exec(componentStack)
if (!boundaryLocation) {
// We don't see the validation boundary in the component stack,
// so this hole must be coming from a shared parent.
......@@ -941,16 +945,42 @@ export function trackDynamicHoleInNavigation(
}
export function trackThrownErrorInNavigation(
workStore: WorkStore,
dynamicValidation: InstantValidationState,
error: unknown,
thrownError: unknown,
componentStack: string
) {
// If we see a validation boundary on the component stack,
// this error couldn't have blocked a validation boundary from rendering.
if (hasPrefetchValidationBoundaryRegex.test(componentStack)) {
return
const boundaryLocation =
hasInstantValidationBoundaryRegex.exec(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
} 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(
......@@ -1221,8 +1251,17 @@ export function getNavigationDisallowedDynamicReasons(
workStore: WorkStore,
prelude: PreludeState,
dynamicValidation: InstantValidationState,
validationSampleTracking: InstantValidationSampleTracking | null,
boundaryState: ValidationBoundaryTracking
): 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
if (validationPreventingErrors.length > 0) {
return validationPreventingErrors
......
......@@ -42,10 +42,16 @@ export { Postpone } from './rsc/postpone'
export { taintObjectReference } from './rsc/taint'
export { collectSegmentData } from './collect-segment-data'
export const InstantValidation =
process.env.NODE_ENV === 'development' && process.env.NEXT_RUNTIME !== 'edge'
? (require('./instant-validation/instant-validation') as typeof import('./instant-validation/instant-validation'))
: undefined
export const InstantValidation = () => {
if (
process.env.NEXT_RUNTIME !== 'edge' &&
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 { workAsyncStorage } from '../app-render/work-async-storage.external'
......
/* 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 { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'
import { InvariantError } from '../../../shared/lib/invariant-error'
import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
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 {
const store = workUnitAsyncStorage.getStore()
......@@ -39,12 +48,6 @@ const NameSpace = {
id: string
children: ReactNode
}) {
if (typeof window !== 'undefined') {
throw new InvariantError(
'InstantValidationBoundary should only be rendered in SSR'
)
}
// Track which boundaries we actually managed to render.
const state = getValidationBoundaryTracking()
if (state === null) {
......
import { getLayoutOrPageModule } from '../../lib/app-dir-module'
import type { LoaderTree } from '../../lib/app-dir-module'
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 {
workAsyncStorage,
type WorkStore,
......@@ -78,25 +81,41 @@ type FoundSegmentWithConfig = {
* 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.
* */
export const anySegmentNeedsInstantValidation = cacheScopedToWorkStore(
async (rootTree: LoaderTree): Promise<boolean> => {
const segments = await findSegmentsWithInstantConfig(rootTree)
// Check if there's any configs with `prefetch: 'static'` or `mode: 'instant'`.
// (If there's only `false`, there's no need to run validation).
// If any segment has `unstable_disableValidation`, we skip validation for the whole tree.
let needsValidation = false
for (const { config } of segments) {
if (typeof config === 'object') {
if (config.unstable_disableValidation) {
return false
}
// do not short-circuit, some other segment might still have `unstable_disableValidation`
needsValidation = true
// Shared helper (not exported, not cached — called by the cached wrappers)
async function anySegmentNeedsInstantValidation(
rootTree: LoaderTree,
mode: 'dev' | 'build'
): Promise<boolean> {
const segments = await findSegmentsWithInstantConfig(rootTree)
// Check if there's any configs with `prefetch: 'static'` or `mode: 'instant'`.
// (If there's only `false`, there's no need to run validation).
// If any segment has `unstable_disableValidation`, we skip validation for the whole tree.
let needsValidation = false
for (const { config } of segments) {
if (typeof config === 'object') {
if (
config.unstable_disableValidation === true ||
(mode === 'dev' && config.unstable_disableDevValidation === true) ||
(mode === 'build' && config.unstable_disableBuildValidation === true)
) {
return false
}
// do not short-circuit, some other segment might still have `unstable_disableValidation`
needsValidation = true
}
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(
......@@ -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.
* 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
}
import type { InstantSample } from '../../../build/segment-config/app/app-segment-config'
import type { ReadonlyRequestCookies } from '../../web/spec-extension/adapters/request-cookies'
import type { ReadonlyHeaders } from '../../web/spec-extension/adapters/headers'
import type { DraftModeProvider } from '../../async-storage/draft-mode-provider'
import type { Params } from '../../request/params'
import { RequestCookies } from '../../web/spec-extension/cookies'
import { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies'
import { HeadersAdapter } from '../../web/spec-extension/adapters/headers'
import type { SearchParams } from '../../request/search-params'
import { getSegmentParam } from '../../../shared/lib/router/utils/get-segment-param'
import { parseRelativeUrl } from '../../../shared/lib/router/utils/parse-relative-url'
import { InvariantError } from '../../../shared/lib/invariant-error'
import { InstantValidationError } from './instant-validation-error'
import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
import { wellKnownProperties } from '../../../shared/lib/utils/reflect-utils'
import type { WorkStore } from '../work-async-storage.external'
export type InstantValidationSampleTracking = {
// TODO(instant-validation-build): track which samples config we used and attribute errors
missingSampleErrors: InstantValidationError[]
}
export function createValidationSampleTracking(): InstantValidationSampleTracking {
return {
missingSampleErrors: [],
}
}
function getExpectedSampleTracking(): InstantValidationSampleTracking {
let validationSampleTracking: InstantValidationSampleTracking | null = null
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
switch (workUnitStore.type) {
case 'request':
case 'validation-client':
// TODO(instant-validation-build): do we need any special handling for caches?
validationSampleTracking =
workUnitStore.validationSampleTracking ?? null
break
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client':
case 'prerender':
case 'prerender-runtime':
break
default:
workUnitStore satisfies never
}
}
if (!validationSampleTracking) {
throw new InvariantError(
'Expected to have a workUnitStore that provides validationSampleTracking'
)
}
return validationSampleTracking
}
export function trackMissingSampleError(error: InstantValidationError): void {
const validationSampleTracking = getExpectedSampleTracking()
validationSampleTracking.missingSampleErrors.push(error)
}
export function trackMissingSampleErrorAndThrow(
error: InstantValidationError
): never {
// TODO(instant-validation-build): this should abort the render
trackMissingSampleError(error)
throw error
}
/**
* Creates ReadonlyRequestCookies from sample cookie data.
* Accessing a cookie not declared in the sample will throw an error.
* Cookies with `value: null` are declared (allowed to access) but return no value.
*/
export function createCookiesFromSample(
sampleCookies: InstantSample['cookies'],
route: string
): ReadonlyRequestCookies {
const declaredNames = new Set<string>()
const cookies = new RequestCookies(new Headers())
if (sampleCookies) {
for (const cookie of sampleCookies) {
declaredNames.add(cookie.name)
if (cookie.value !== null) {
cookies.set(cookie.name, cookie.value)
}
}
}
const sealed = RequestCookiesAdapter.seal(cookies)
return new Proxy(sealed, {
get(target, prop, receiver) {
if (prop === 'has') {
const originalMethod = Reflect.get(target, prop, receiver)
const wrappedMethod: typeof originalMethod = function (name) {
if (!declaredNames.has(name)) {
trackMissingSampleErrorAndThrow(
createMissingCookieSampleError(route, name)
)
}
return originalMethod.call(target, name)
}
return wrappedMethod
}
if (prop === 'get') {
const originalMethod = Reflect.get(target, prop, receiver)
const wrappedMethod: typeof originalMethod = function (nameOrCookie) {
let name: string
if (typeof nameOrCookie === 'string') {
name = nameOrCookie
} else if (
nameOrCookie &&
typeof nameOrCookie === 'object' &&
typeof nameOrCookie.name === 'string'
) {
name = nameOrCookie.name
} else {
// This is an invalid input. Pass it through to the original method so it can error.
return originalMethod.call(target, nameOrCookie)
}
if (!declaredNames.has(name)) {
trackMissingSampleErrorAndThrow(
createMissingCookieSampleError(route, name)
)
}
return originalMethod.call(target, name)
}
return wrappedMethod
}
// TODO(instant-validation-build): what should getAll do?
// Maybe we should only allow it if there's an array (possibly empty?)
return Reflect.get(target, prop, receiver)
},
})
}
function createMissingCookieSampleError(
route: string,
name: string
): InstantValidationError {
return new InstantValidationError(
`Route "${route}" accessed cookie "${name}" which is not defined in the \`samples\` ` +
`of \`unstable_instant\`. Add it to the sample's \`cookies\` array, ` +
`or \`{ name: "${name}", value: null }\` if it should be absent.`
)
}
/**
* Creates ReadonlyHeaders from sample header data.
* Accessing a header not declared in the sample will throw an error.
* Headers with `value: null` are declared (allowed to access) but return null.
*/
export function createHeadersFromSample(
rawSampleHeaders: InstantSample['headers'],
sampleCookies: InstantSample['cookies'],
route: string
): ReadonlyHeaders {
// If we have cookie samples, add a `cookie` header to match.
// Accessing it will be implicitly allowed by the proxy --
// if the user defined some cookies, accessing the "cookie" header is also fine.
const sampleHeaders = rawSampleHeaders ? [...rawSampleHeaders] : []
if (sampleHeaders.find(([name]) => name.toLowerCase() === 'cookie')) {
throw new InstantValidationError(
'Invalid sample: Defining cookies via a "cookie" header is not supported. Use `cookies: [{ name: ..., value: ... }]` instead.'
)
}
if (sampleCookies) {
const cookieHeaderValue = sampleCookies.toString()
sampleHeaders.push([
'cookie',
// if the `cookies` samples were empty, or they were all `null`, then we have no cookies,
// and the header isn't present, but should remains readable, so we set it to null.
cookieHeaderValue !== '' ? cookieHeaderValue : null,
])
}
const declaredNames = new Set<string>()
const headersInit: Record<string, string> = {}
for (const [name, value] of sampleHeaders) {
declaredNames.add(name.toLowerCase())
if (value !== null) {
headersInit[name.toLowerCase()] = value
}
}
const sealed = HeadersAdapter.seal(HeadersAdapter.from(headersInit))
return new Proxy(sealed, {
get(target, prop, receiver) {
if (prop === 'get' || prop === 'has') {
const originalMethod = Reflect.get(target, prop, receiver)
const patchedMethod: typeof originalMethod = function (rawName) {
const name = rawName.toLowerCase()
if (!declaredNames.has(name)) {
trackMissingSampleErrorAndThrow(
new InstantValidationError(
`Route "${route}" accessed header "${name}" which is not defined in the \`samples\` ` +
`of \`unstable_instant\`. Add it to the sample's \`headers\` array, ` +
`or \`["${name}", null]\` if it should be absent.`
)
)
}
// typescript can't reconcile a union of functions with a union of return types,
// so we have to cast the original return type away
return (originalMethod as (...args: any[]) => any).call(target, name)
}
return patchedMethod
}
return Reflect.get(target, prop, receiver)
},
})
}
/**
* Creates a DraftModeProvider that always returns isEnabled: false.
*/
export function createDraftModeForValidation(): DraftModeProvider {
// Create a minimal DraftModeProvider-compatible object
// that always reports draft mode as disabled.
//
// private properties that can't be set from outside the class.
return {
get isEnabled() {
return false
},
enable() {
throw new Error(
'Draft mode cannot be enabled during build-time instant validation.'
)
},
disable() {
throw new Error(
'Draft mode cannot be disabled during build-time instant validation.'
)
},
} as Partial<DraftModeProvider> as DraftModeProvider
}
/**
* Creates params wrapped with an exhaustive proxy.
* Accessing a param not declared in the sample will throw an error.
*/
export function createExhaustiveParamsProxy<TParams extends Params>(
underlyingParams: TParams,
declaredParamNames: Set<string>,
route: string
): TParams {
return new Proxy(underlyingParams, {
get(target, prop, receiver) {
if (
typeof prop === 'string' &&
!wellKnownProperties.has(prop) &&
// Only error when accessing a param that is part of the route but wasn't provided.
// accessing properties that aren't expected to be a valid param value is fine.
prop in underlyingParams &&
!declaredParamNames.has(prop)
) {
trackMissingSampleErrorAndThrow(
new InstantValidationError(
`Route "${route}" accessed param "${prop}" which is not defined in the \`samples\` ` +
`of \`unstable_instant\`. Add it to the sample's \`params\` object.`
)
)
}
return Reflect.get(target, prop, receiver)
},
// We don't need to override `has` or `ownKeys`.
// the shape of the params object is determined by the routing structure
// and independent of the samples. We only need to instrument accessing the values.
})
}
/**
* Creates searchParams wrapped with an exhaustive proxy.
* Accessing a searchParam not declared in the sample will throw an error.
* A searchParam with `value: undefined` means "declared but absent" (allowed to access, returns undefined).
*/
export function createExhaustiveSearchParamsProxy(
searchParams: SearchParams,
declaredSearchParamNames: Set<string>,
route: string
): SearchParams {
return new Proxy(searchParams, {
get(target, prop, receiver) {
if (
typeof prop === 'string' &&
!wellKnownProperties.has(prop) &&
!declaredSearchParamNames.has(prop)
) {
trackMissingSampleErrorAndThrow(
createMissingSearchParamSampleError(route, prop)
)
}
return Reflect.get(target, prop, receiver)
},
has(target, prop) {
if (
typeof prop === 'string' &&
!wellKnownProperties.has(prop) &&
!declaredSearchParamNames.has(prop)
) {
trackMissingSampleErrorAndThrow(
createMissingSearchParamSampleError(route, prop)
)
}
return Reflect.has(target, prop)
},
})
}
/**
* Wraps a URLSearchParams (or subclass like ReadonlyURLSearchParams) with an
* exhaustive proxy. Accessing a search param not declared in the sample via
* get/getAll/has will throw an error.
*/
export function createExhaustiveURLSearchParamsProxy<T extends URLSearchParams>(
searchParams: T,
declaredSearchParamNames: Set<string>,
route: string
): T {
return new Proxy(searchParams, {
get(target, prop, receiver) {
// Intercept method calls that access specific param names
if (prop === 'get' || prop === 'getAll' || prop === 'has') {
const originalMathod = Reflect.get(target, prop, receiver)
return (name: string) => {
if (typeof name === 'string' && !declaredSearchParamNames.has(name)) {
trackMissingSampleErrorAndThrow(
createMissingSearchParamSampleError(route, name)
)
}
return (originalMathod as (...args: any[]) => any).call(target, name)
}
}
const value = Reflect.get(target, prop, receiver)
// Prevent `TypeError: Value of "this" must be of type URLSearchParams` for methods
if (typeof value === 'function' && !Object.hasOwn(target, prop)) {
return value.bind(target)
}
return value
},
})
}
function createMissingSearchParamSampleError(
route: string,
name: string
): InstantValidationError {
return new InstantValidationError(
`Route "${route}" accessed searchParam "${name}" which is not defined in the \`samples\` ` +
`of \`unstable_instant\`. Add it to the sample's \`searchParams\` object, ` +
`or \`{ "${name}": null }\` if it should be absent.`
)
}
export function createRelativeURLFromSamples(
route: string,
sampleParams: InstantSample['params'],
sampleSearchParams: InstantSample['searchParams']
) {
// Build searchParams query object and URL search string from sample
const pathname = createPathnameFromRouteAndSampleParams(
route,
sampleParams ?? {}
)
let search = ''
if (sampleSearchParams) {
const qs = createURLSearchParamsFromSample(sampleSearchParams).toString()
if (qs) {
search = '?' + qs
}
}
return parseRelativeUrl(pathname + search, undefined, true)
}
function createURLSearchParamsFromSample(
sampleSearchParams: InstantSample['searchParams']
) {
const result = new URLSearchParams()
if (sampleSearchParams) {
for (const [key, value] of Object.entries(sampleSearchParams)) {
if (value === null || value === undefined) continue
if (Array.isArray(value)) {
for (const v of value) {
result.append(key, v)
}
} else {
result.set(key, value)
}
}
}
return result
}
/**
* Substitute sample params into `workStore.route` to create a plausible pathname.
* TODO(instant-validation-build): this logic is somewhat hacky and likely incomplete,
* but it should be good enough for some initial testing.
*/
function createPathnameFromRouteAndSampleParams(route: string, params: Params) {
let interpolatedSegments: string[] = []
const rawSegments = route.split('/')
for (const rawSegment of rawSegments) {
const param = getSegmentParam(rawSegment)
if (param) {
switch (param.paramType) {
case 'catchall':
case 'optional-catchall': {
let paramValue = params[param.paramName]
if (paramValue === undefined) {
// The value for the param was not provided. `usePathname` will detect this and throw
// before this can surface to userspace. Use `[...NAME]` as a placeholder for the param value
// in case it pops up somewhere unexpectedly.
paramValue = [rawSegment]
} else if (!Array.isArray(paramValue)) {
// NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`
throw new InstantValidationError(
`Expected sample param value for segment '${rawSegment}' to be an array of strings, got ${typeof paramValue}`
)
}
interpolatedSegments.push(
...paramValue.map((v) => encodeURIComponent(v))
)
break
}
case 'dynamic': {
let paramValue = params[param.paramName]
if (paramValue === undefined) {
// The value for the param was not provided. `usePathname` will detect this and throw
// before this can surface to userspace. Use `[NAME]` as a placeholder for the param value
// in case it pops up somewhere unexpectedly.
paramValue = rawSegment
} else if (typeof paramValue !== 'string') {
// NOTE: this happens outside of render, so we don't need `trackMissingSampleErrorAndThrow`
throw new InstantValidationError(
`Expected sample param value for segment '${rawSegment}' to be a string, got ${typeof paramValue}`
)
}
interpolatedSegments.push(encodeURIComponent(paramValue))
break
}
case 'catchall-intercepted-(..)(..)':
case 'catchall-intercepted-(.)':
case 'catchall-intercepted-(..)':
case 'catchall-intercepted-(...)':
case 'dynamic-intercepted-(..)(..)':
case 'dynamic-intercepted-(.)':
case 'dynamic-intercepted-(..)':
case 'dynamic-intercepted-(...)': {
// TODO(instant-validation-build): i don't know how these are supposed to work, or if we can even get them here
throw new InvariantError(
'Not implemented: Validation of interception routes'
)
}
default: {
param.paramType satisfies never
}
}
} else {
interpolatedSegments.push(rawSegment)
}
}
return interpolatedSegments.join('/')
}
export function assertRootParamInSamples(
workStore: WorkStore,
sampleParams: Params | undefined,
paramName: string
) {
if (sampleParams && paramName in sampleParams) {
// The param is defined in the samples.
} else {
const route = workStore.route
trackMissingSampleErrorAndThrow(
new InstantValidationError(
`Route "${route}" accessed root param "${paramName}" which is not defined in the \`samples\` ` +
`of \`unstable_instant\`. Add it to the sample's \`params\` object.`
)
)
}
}
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'
import {
// NOTE: we're in the server layer, so this is a client reference
PlaceValidationBoundaryBelowThisLevel,
} from './boundary'
} from '../../../client/components/instant-validation/boundary'
import type { ValidationBoundaryTracking } from './boundary-tracking'
import {
getLayoutOrPageModule,
......@@ -299,6 +299,17 @@ export async function collectStagedSegmentData(
if (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
// when generating the original Flight stream for the whole page.
if (
......@@ -526,6 +537,17 @@ export async function createCombinedPayloadStream(
if (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
// when generating the original Flight stream for the whole page.
if (
......
......@@ -35,8 +35,9 @@ export class StagedRenderingController {
private dynamicStagePromise = createPromiseWithResolvers<void>()
constructor(
private abortSignal: AbortSignal | null = null,
private abandonController: AbortController | null = null
private abortSignal: AbortSignal | null,
private abandonController: AbortController | null,
private shouldTrackSyncIO: boolean
) {
if (abortSignal) {
abortSignal.addEventListener(
......@@ -88,13 +89,15 @@ export class StagedRenderingController {
}
}
canSyncInterrupt() {
// If we haven't started the render yet, it can't be interrupted.
if (this.currentStage === RenderStage.Before) {
shouldTrackSyncInterrupt(): boolean {
if (!this.shouldTrackSyncIO) {
return false
}
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.Static:
return true
......@@ -132,8 +135,18 @@ export class StagedRenderingController {
return
}
// If we're in the final render, we cannot abandon it. We need to advance to the Dynamic stage
// and capture the interruption reason.
if (this.abortSignal) {
// 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) {
case RenderStage.EarlyStatic:
case RenderStage.Static:
......
......@@ -208,6 +208,13 @@ export interface RenderOptsPartial {
* Prerendering those routes would catch any invalid dynamic accesses.
*/
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> &
......
......@@ -23,6 +23,7 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import type { StagedRenderingController } from './staged-rendering'
import { RenderStage } from './staged-rendering'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
export type WorkUnitPhase = 'action' | 'render' | 'after'
......@@ -76,10 +77,23 @@ export interface RequestStore extends CommonWorkUnitStore {
prerenderResumeDataCache?: PrerenderResumeDataCache | 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
usedDynamic?: boolean
}
export type InstantValidationSamples = {
params: Params | undefined
searchParams: Record<string, string | string[] | null> | undefined
}
export type AsyncApiPromises = {
cookies: Promise<ReadonlyRequestCookies>
earlyCookies: Promise<ReadonlyRequestCookies>
......@@ -149,8 +163,9 @@ export interface PrerenderStoreModernClient
export interface ValidationStoreClient extends PrerenderStoreModernCommon {
readonly type: 'validation-client'
readonly boundaryState: ValidationBoundaryTracking | null
// When we implement build validation, the store will contain e.g. cookies
// and other values derived from samples.
validationSamples: InstantValidationSamples | null
validationSampleTracking: InstantValidationSampleTracking | null
fallbackRouteParams: OpaqueFallbackRouteParams | null
}
export interface PrerenderStoreModernServer
......
......@@ -1114,6 +1114,16 @@ export type ExportPathMap = {
* @internal
*/
_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,69 +82,79 @@ export function io(expression: string, type: ApiType) {
}
break
}
case 'request':
if (process.env.NODE_ENV === 'development') {
const stageController = workUnitStore.stagedRendering
if (stageController && stageController.canSyncInterrupt()) {
let message: string
if (
stageController.currentStage === RenderStage.Static ||
stageController.currentStage === RenderStage.EarlyStatic
) {
switch (type) {
case 'time':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing the current time in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`
break
case 'random':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random`
break
case 'crypto':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random cryptographic values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
} else {
// We're in the Runtime stage.
// We only error for Sync IO in the Runtime stage if the route has a runtime prefetch config.
// This check is implemented in `stageController.canSyncInterrupt()` --
// if runtime prefetching isn't enabled, then we won't get here.
let accessStatement: string
let additionalInfoLink: string
switch (type) {
case 'time':
accessStatement = 'the current time'
additionalInfoLink =
'https://nextjs.org/docs/messages/next-prerender-runtime-current-time'
break
case 'random':
accessStatement = 'random values synchronously'
additionalInfoLink =
'https://nextjs.org/docs/messages/next-prerender-runtime-random'
break
case 'crypto':
accessStatement = 'random cryptographic values synchronously'
additionalInfoLink =
'https://nextjs.org/docs/messages/next-prerender-runtime-crypto'
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or awaiting \`connection()\`. When configured for Runtime prefetching, accessing ${accessStatement} in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: ${additionalInfoLink}`
case 'request': {
const stageController = workUnitStore.stagedRendering
if (stageController && stageController.shouldTrackSyncInterrupt()) {
let message: string
if (
stageController.currentStage === RenderStage.Static ||
stageController.currentStage === RenderStage.EarlyStatic
) {
switch (type) {
case 'time':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing the current time in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`
break
case 'random':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random`
break
case 'crypto':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random cryptographic values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
} else {
// We're in the Runtime stage.
// We only error for Sync IO in the Runtime stage if the route has a runtime prefetch config.
// This check is implemented in `stageController.canSyncInterrupt()` --
// if runtime prefetching isn't enabled, then we won't get here.
let accessStatement: string
let additionalInfoLink: string
switch (type) {
case 'time':
accessStatement = 'the current time'
additionalInfoLink =
'https://nextjs.org/docs/messages/next-prerender-runtime-current-time'
break
case 'random':
accessStatement = 'random values synchronously'
additionalInfoLink =
'https://nextjs.org/docs/messages/next-prerender-runtime-random'
break
case 'crypto':
accessStatement = 'random cryptographic values synchronously'
additionalInfoLink =
'https://nextjs.org/docs/messages/next-prerender-runtime-crypto'
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
const syncIOError = applyOwnerStack(new Error(message))
stageController.syncInterruptCurrentStageWithReason(syncIOError)
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or awaiting \`connection()\`. When configured for Runtime prefetching, accessing ${accessStatement} in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: ${additionalInfoLink}`
}
const syncIOError = applyOwnerStack(new Error(message))
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
}
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
......
......@@ -24,6 +24,7 @@ import {
throwInvariantForMissingStore,
type PrerenderStoreModernRuntime,
type RequestStore,
type ValidationStoreClient,
} from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error'
import {
......@@ -67,8 +68,11 @@ export function createParamsFromClient(
varyParamsAccumulator
)
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
return createRenderParamsInProd(underlyingParams)
return createClientParamsInInstantValidation(
underlyingParams,
workStore,
workUnitStore.validationSamples
)
case 'cache':
case 'private-cache':
case 'unstable-cache':
......@@ -94,6 +98,12 @@ export function createParamsFromClient(
workUnitStore,
isRuntimePrefetchable
)
} else if (workUnitStore.validationSamples) {
return createClientParamsInInstantValidation(
underlyingParams,
workStore,
workUnitStore.validationSamples
)
} else {
return createRenderParamsInProd(underlyingParams)
}
......@@ -214,8 +224,9 @@ export function createServerParamsForServerSegment(
varyParamsAccumulator
)
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
return createRenderParamsInProd(underlyingParams)
throw new InvariantError(
'createServerParamsForServerSegment should not be called in client contexts.'
)
case 'cache':
case 'private-cache':
case 'unstable-cache':
......@@ -243,6 +254,17 @@ export function createServerParamsForServerSegment(
workUnitStore,
isRuntimePrefetchable
)
} else if (
workUnitStore.asyncApiPromises &&
workUnitStore.validationSamples
) {
return createServerParamsInInstantValidation(
underlyingParams,
workStore,
workUnitStore.validationSamples,
workUnitStore.asyncApiPromises,
isRuntimePrefetchable
)
} else if (
workUnitStore.asyncApiPromises &&
hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)
......@@ -295,7 +317,9 @@ export function createPrerenderParamsForClientSegment(
}
break
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
throw new InvariantError(
'createPrerenderParamsForClientSegment should not be called in validation contexts.'
)
break
case 'cache':
case 'private-cache':
......@@ -421,6 +445,44 @@ function hasFallbackRouteParams(
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> {
return makeUntrackedParams(underlyingParams)
}
......
......@@ -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.`
)
}
case 'private-cache':
case 'prerender-runtime':
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
}
default: {
......
......@@ -24,6 +24,7 @@ import {
type StaticPrerenderStore,
throwInvariantForMissingStore,
type RequestStore,
type ValidationStoreClient,
} from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error'
import {
......@@ -59,9 +60,13 @@ export function createSearchParamsFromClient(
case 'prerender-ppr':
case 'prerender-legacy':
return createStaticPrerenderSearchParams(workStore, workUnitStore)
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
return makeUntrackedSearchParams(underlyingSearchParams)
case 'validation-client': {
return createClientSearchParamsInValidation(
underlyingSearchParams,
workStore,
workUnitStore
)
}
case 'prerender-runtime':
throw new InvariantError(
'createSearchParamsFromClient should not be called in a runtime prerender.'
......@@ -266,6 +271,19 @@ function createRenderSearchParams(
isRuntimePrefetchable
)
} 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 (
isRuntimePrefetchable
? requestStore.asyncApiPromises.earlySharedSearchParamsParent
......@@ -674,3 +692,21 @@ function createSearchAccessError(
`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'
*/
type CacheStore<T> = Pick<
Map<string, T>,
'entries' | 'keys' | 'size' | 'get' | 'set'
'entries' | 'keys' | 'size' | 'get' | 'set' | typeof Symbol.iterator
>
/**
......
......@@ -147,12 +147,23 @@ export async function stringifyResumeDataCache(
*
* @returns A new empty PrerenderResumeDataCache instance
*/
export function createPrerenderResumeDataCache(): PrerenderResumeDataCache {
return {
cache: new Map(),
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
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 {
cache: new Map(),
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
}
}
}
......
......@@ -46,4 +46,7 @@ export const wellKnownProperties = new Set([
'toJSON',
'$$typeof',
'__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
}
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
}
export default async function Page() {
await privateCachedIO()
return (
<main>
<p>
This page awaits a private cache. stage. The page is runtime
prefetchable, so 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 privateCachedIO() {
'use cache: private'
await new Promise<void>((resolve) => setTimeout(resolve, 5))
}
import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
}
export default async function Page() {
await cookies()
await cachedIO('runtime')
return (
<main>
<p>
This page awaits a cache that is only 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
}
export const unstable_instant = {
prefetch: 'static',
}
export default async function Page() {
await cachedIO()
return (
<main>
<p>
This page awaits a cache. 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() {
'use cache'
await new Promise<void>((resolve) => setTimeout(resolve, 5))
}
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [{ name: 'auth', value: '1' }] }],
}
export default async function Page() {
return (
<main>
<p>
This page wraps all runtime/dynamic components in Suspense, so it should
pass validation.
</p>
<Suspense fallback={<div>Loading...</div>}>
<Runtime />
</Suspense>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</main>
)
}
async function Runtime() {
const c = await cookies()
return <div id="runtime-content">cookie: {c.get('auth')?.value}</div>
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content</div>
}
import { Instant } from 'next'
import { cookies } from 'next/headers'
import { lang } from 'next/root-params'
import { ensureRejects } from '../../../../ensure-error'
export const unstable_instant: Instant = {
prefetch: 'runtime',
// no samples
samples: [{}],
}
export default async function Page() {
// Guard behind cookies() so that the rest of this component only runs during validation
await cookies()
try {
await ensureRejects(
() => lang(),
`Expected lang() to error if sample is not provided`
)
} catch {
// We swallow the error. It should still be reported and fail the validation.
}
return (
<main>
<p>
This page uses a root param. It's missing a sample for it, so we can't
validate it. It catches the error thrown by the rootparam call, but
validation should still fail.
</p>
</main>
)
}
import { Instant } from 'next'
import { cookies } from 'next/headers'
import { lang } from 'next/root-params'
import { ensureRejects } from '../../../../ensure-error'
export const unstable_instant: Instant = {
prefetch: 'runtime',
// no samples
samples: [{}],
}
export default async function Page() {
// Guard behind cookies() so that the rest of this component only runs during validation
await cookies()
await ensureRejects(
() => lang(),
`Expected lang() to error if sample is not provided`
)
return (
<main>
<p>
This page uses a root param. It's missing a sample for it, so we can't
validate it.
</p>
</main>
)
}
import { connection } from 'next/server'
import { ReactNode, Suspense } from 'react'
export async function generateStaticParams() {
return [{ lang: 'en' }]
}
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>
}
import { Instant } from 'next'
import { cookies } from 'next/headers'
import { lang } from 'next/root-params'
import assert from 'node:assert/strict'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [{ params: { lang: 'en-from-samples' } }],
}
export default async function Page() {
// Guard behind cookies() so that the rest of this component only runs during validation
await cookies()
// We'll only get here during validation, so we should only observe the `lang` from `samples`
const currentLang = await lang()
assert.equal(currentLang, 'en-from-samples', `Unexpected \`lang()\``)
return (
<main>
<p>
This page uses a root param. It should get it from samples, not
generateStaticParams.
</p>
</main>
)
}
import { Instant } from 'next'
import { lang } from 'next/root-params'
import assert from 'node:assert/strict'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [{ params: { lang: 'en' } }],
}
export default async function Page() {
// Note that both `generateStaticParams` and `samples` set lang to "en".
const currentLang = await lang()
assert.equal(currentLang, 'en', `Unexpected \`lang()\``)
return (
<main>
<p>
This page uses a root param. It should get it from samples. Root param
values are known statically, so this is fully statically prefetchable.
</p>
</main>
)
}
class AssertionError extends Error {
constructor(message: string, opts?: ErrorOptions) {
super(message, opts)
this.name = 'AssertionError'
}
}
export function assert(
result: boolean,
message?: string
): asserts result is true {
if (!result) {
throw new AssertionError(message ?? 'Assertion failed')
}
}
/**
* This helper is used for testing code that should throw, without swallowing the error.
*
* It calls `callback` and checks if it throws.
* If it did, we rethrow the error.
* If it didn't throw, we throw a AssertionError/ClientAssertionError.
* */
export function ensureThrows(callback: () => any, message?: string): never {
let thrown: { value: unknown } | null = null
try {
callback()
} catch (err) {
thrown = { value: err }
}
if (thrown) {
// The callback threw, as expected.
throw thrown.value
} else {
// The callback didn't throw like it should have.
message ??= 'Expected callback to throw'
if (typeof window === 'undefined') {
const { fail } =
require('node:assert/strict') as typeof import('node:assert/strict')
fail(message)
} else {
throw new Error('This code should never run in the browser')
}
}
// For some reason, typescript doesn't believe that all codepaths above throw
throw new Error('Unreachable')
}
/**
* This helper is used for testing code that should throw, without swallowing the error.
*
* iT calls `callback` and checks if it rejected.
* If it did, we rethrow the error.
* If it didn't throw, we throw a AssertionError/ClientAssertionError.
* */
export async function ensureRejects(
callback: () => Promise<any>,
message?: string
): Promise<never> {
let thrown: { value: unknown } | null = null
try {
await callback()
} catch (err) {
thrown = { value: err }
}
if (thrown) {
// The callback rejected, as expected.
throw thrown.value
} else {
// The callback didn't reject like it should have.
message ??= 'Expected callback to reject'
if (typeof window === 'undefined') {
const { fail } =
require('node:assert/strict') as typeof import('node:assert/strict')
fail(message)
} else {
throw new Error('This code should never run in the browser')
}
}
// For some reason, typescript doesn't believe that all codepaths above throw
throw new Error('Unreachable')
}
import { nextTestSetup } from 'e2e-utils'
import {
expectNoBuildValidationErrors,
extractBuildValidationError,
parseValidationMessages,
} from 'e2e-utils/instant-validation'
describe('instant-validation-build', () => {
const { next, skipped, isNextStart, isTurbopack } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
if (!isNextStart) {
it.skip('Build-time only test', () => {})
return
}
if (!isTurbopack) {
// TODO(instant-validation-build): snapshot tests for webpack
it.skip('TODO: snapshot tests for webpack', () => {})
return
}
const prerender = async (pathname: string) => {
const args = [
'--experimental-build-mode',
'generate',
'--debug-build-paths',
`app${pathname}/page.tsx`,
]
return await next.build({
args,
env: {
NEXT_TEST_LOG_VALIDATION: '1',
},
})
}
beforeAll(async () => {
await next.build({ args: ['--experimental-build-mode', 'compile'] })
})
describe('basic dynamic hole detection', () => {
// We have extensive tests for this in the instant-validation test suite.
// This is just a basic test that we can validate a runtime prefetch, which static shell validation can't do.
describe('valid - suspense around runtime', () => {
it('should succeed build when cookies are inside Suspense', async () => {
const result = await prerender(
'/(default)/valid-suspense-around-runtime'
)
expectNoBuildValidationErrors(result)
})
})
describe('invalid - missing suspense around runtime', () => {
it('should fail build when cookies are outside Suspense', async () => {
const result = await prerender(
'/(default)/invalid-missing-suspense-around-runtime'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/invalid-missing-suspense-around-runtime": Uncached data or \`connection()\` was accessed outside of \`<Suspense>\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route
at main (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
Build-time instant validation failed for route "/invalid-missing-suspense-around-runtime".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
})
})
})
describe('server errors', () => {
it('valid - ignores server errors that do not surface in SSR', async () => {
const result = await prerender(
'/(default)/server-errors/error-passed-to-client-and-ignored'
)
expect(extractBuildValidationError(result.cliOutput)).toBe('')
expectNoBuildValidationErrors(result)
})
it('error - server error that blocks page validation with no suspense boundary', async () => {
const result = await prerender('/(default)/server-errors/page-throws')
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/server-errors/page-throws": Could not validate \`unstable_instant\` because an error prevented the target segment from rendering.
at main (<anonymous>)
at body (<anonymous>)
at html (<anonymous>) {
[cause]: Error: Kaboom
at a (app/(default)/server-errors/page-throws/page.tsx:24:9)
22 | async function Throws(): Promise<never> {
23 | await cookies()
> 24 | throw new Error('Kaboom')
| ^
25 | }
26 | {
digest: '<error-digest>'
}
}
Build-time instant validation failed for route "/server-errors/page-throws".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
})
it('error - server error that blocks page validation with a suspense boundary in a parent segment', async () => {
const result = await prerender(
'/(default)/server-errors/page-throws-with-suspense'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/server-errors/page-throws-with-suspense": Could not validate \`unstable_instant\` because an error prevented the target segment from rendering.
at main (<anonymous>)
at a (<anonymous>)
at body (<anonymous>)
at html (<anonymous>) {
[cause]: Error: Kaboom
at b (app/(default)/server-errors/page-throws-with-suspense/page.tsx:24:9)
22 | async function Throws(): Promise<never> {
23 | await cookies()
> 24 | throw new Error('Kaboom')
| ^
25 | }
26 | {
digest: '<error-digest>'
}
}
Build-time instant validation failed for route "/server-errors/page-throws-with-suspense".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
})
})
describe('client errors', () => {
it('error - server error that blocks page validation with no suspense boundary', async () => {
const result = await prerender('/(default)/client-errors/page-throws')
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/client-errors/page-throws": Could not validate \`unstable_instant\` because an error prevented the target segment from rendering.
at <unknown> (app/(default)/client-errors/page-throws/client.tsx:6:3)
at main (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
4 |
5 | export function ThrowsInClient(): Promise<never> {
> 6 | useSearchParams()
| ^
7 | throw new Error('Kaboom')
8 | }
9 | {
[cause]: Error: Kaboom
at <unknown> (app/(default)/client-errors/page-throws/client.tsx:7:9)
5 | export function ThrowsInClient(): Promise<never> {
6 | useSearchParams()
> 7 | throw new Error('Kaboom')
| ^
8 | }
9 |
}
Build-time instant validation failed for route "/client-errors/page-throws".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
})
it('error - client error that blocks page validation with a suspense boundary in a parent segment', async () => {
const result = await prerender(
'/(default)/client-errors/page-throws-with-suspense'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/client-errors/page-throws-with-suspense": Could not validate \`unstable_instant\` because an error prevented the target segment from rendering.
at <unknown> (app/(default)/client-errors/page-throws-with-suspense/client.tsx:6:3)
at main (<anonymous>)
at a (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
4 |
5 | export function ThrowsInClient(): Promise<never> {
> 6 | useSearchParams()
| ^
7 | throw new Error('Kaboom')
8 | }
9 | {
[cause]: Error: Kaboom
at <unknown> (app/(default)/client-errors/page-throws-with-suspense/client.tsx:7:9)
5 | export function ThrowsInClient(): Promise<never> {
6 | useSearchParams()
> 7 | throw new Error('Kaboom')
| ^
8 | }
9 |
}
Build-time instant validation failed for route "/client-errors/page-throws-with-suspense".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
})
})
describe('searchParams', () => {
it('search params are correctly read from samples', async () => {
const result = await prerender(
'/(default)/search-params/valid-search-params-in-samples'
)
expect(result.cliOutput).not.toContain('AssertionError')
expectNoBuildValidationErrors(result)
})
it('error - accessing search param not present in samples', async () => {
const result = await prerender(
'/(default)/search-params/invalid-undeclared-search-param'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/search-params/invalid-undeclared-search-param" accessed searchParam "undeclared" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`searchParams\` object, or \`{ "undeclared": null }\` if it should be absent.
at <unknown> (app/(default)/search-params/invalid-undeclared-search-param/page.tsx:31:14)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/search-params/invalid-undeclared-search-param/page.tsx:30:3)
29 | const sp = await searchParams
30 | ensureThrows(
> 31 | () => sp.undeclared,
| ^
32 | \`Expected accessing an undeclared search param to throw\`
33 | )
34 | return null {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/search-params/invalid-undeclared-search-param".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('useSearchParams() receives search params from samples', async () => {
const result = await prerender(
'/(default)/search-params/valid-use-search-params'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('error - accessing search param not present in samples and catching the error', async () => {
const result = await prerender(
'/(default)/search-params/invalid-undeclared-search-param-caught'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/search-params/invalid-undeclared-search-param-caught" accessed searchParam "undeclared" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`searchParams\` object, or \`{ "undeclared": null }\` if it should be absent.
at <unknown> (app/(default)/search-params/invalid-undeclared-search-param-caught/page.tsx:35:16)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/search-params/invalid-undeclared-search-param-caught/page.tsx:34:5)
33 | try {
34 | ensureThrows(
> 35 | () => sp.undeclared,
| ^
36 | \`Expected accessing an undeclared search param to throw\`
37 | )
38 | } catch (err) { {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/search-params/invalid-undeclared-search-param-caught".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - accessing undeclared search param via useSearchParams()', async () => {
const result = await prerender(
'/(default)/search-params/invalid-undeclared-use-search-params'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/search-params/invalid-undeclared-use-search-params" accessed searchParam "undeclared" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`searchParams\` object, or \`{ "undeclared": null }\` if it should be absent.
at <unknown> (app/(default)/search-params/invalid-undeclared-use-search-params/search-params-reader.tsx:9:14)
at <unknown> (ensure-error.ts:11:5)
at <unknown> (app/(default)/search-params/invalid-undeclared-use-search-params/search-params-reader.tsx:8:3)
7 | const sp = useSearchParams()
8 | ensureThrows(
> 9 | () => sp.get('undeclared'),
| ^
10 | \`Expected accessing an undeclared search param to throw\`
11 | )
12 | return null {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/search-params/invalid-undeclared-use-search-params".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - accessing undeclared search param via useSearchParams() and catching the error', async () => {
const result = await prerender(
'/(default)/search-params/invalid-undeclared-use-search-params-caught'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/search-params/invalid-undeclared-use-search-params-caught" accessed searchParam "undeclared" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`searchParams\` object, or \`{ "undeclared": null }\` if it should be absent.
at <unknown> (app/(default)/search-params/invalid-undeclared-use-search-params-caught/search-params-reader.tsx:10:16)
at <unknown> (ensure-error.ts:11:5)
at <unknown> (app/(default)/search-params/invalid-undeclared-use-search-params-caught/search-params-reader.tsx:9:5)
8 | try {
9 | ensureThrows(
> 10 | () => sp.get('undeclared'),
| ^
11 | \`Expected accessing an undeclared search param to throw\`
12 | )
13 | } catch { {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/search-params/invalid-undeclared-use-search-params-caught".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('valid - awaited search params passed to a cache', async () => {
const result = await prerender(
'/(default)/search-params/valid-search-params-passed-to-cache'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('valid - awaited search params passed to a client component', async () => {
const result = await prerender(
'/(default)/search-params/valid-search-params-passed-to-client'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
})
describe('headers', () => {
it('headers are correctly read from samples', async () => {
const result = await prerender(
'/(default)/headers/valid-headers-in-samples'
)
expect(result.cliOutput).not.toContain('AssertionError')
expectNoBuildValidationErrors(result)
})
it('error - .get() of header not present in samples', async () => {
const result = await prerender(
'/(default)/headers/invalid-undeclared-header-get'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/headers/invalid-undeclared-header-get" accessed header "undeclaredheader" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`headers\` array, or \`["undeclaredheader", null]\` if it should be absent.
at <unknown> (app/(default)/headers/invalid-undeclared-header-get/page.tsx:27:24)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/headers/invalid-undeclared-header-get/page.tsx:26:3)
25 | const headersStore = await headers()
26 | ensureThrows(
> 27 | () => headersStore.get('undeclaredHeader'),
| ^
28 | \`Expected get() to throw for undeclared headers\`
29 | )
30 | return null {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/headers/invalid-undeclared-header-get".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - .get() of header not present in samples and catching the error', async () => {
const result = await prerender(
'/(default)/headers/invalid-undeclared-header-get-caught'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/headers/invalid-undeclared-header-get-caught" accessed header "undeclaredheader" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`headers\` array, or \`["undeclaredheader", null]\` if it should be absent.
at <unknown> (app/(default)/headers/invalid-undeclared-header-get-caught/page.tsx:30:25)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/headers/invalid-undeclared-header-get-caught/page.tsx:29:5)
28 | try {
29 | ensureThrows(
> 30 | () => headerStore.get('undeclaredHeader'),
| ^
31 | \`Expected get() to throw for undeclared headers\`
32 | )
33 | } catch (err) { {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/headers/invalid-undeclared-header-get-caught".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
})
it('error - .has() of header not present in samples', async () => {
const result = await prerender(
'/(default)/headers/invalid-undeclared-header-has'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/headers/invalid-undeclared-header-has" accessed header "undeclaredheader" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`headers\` array, or \`["undeclaredheader", null]\` if it should be absent.
at <unknown> (app/(default)/headers/invalid-undeclared-header-has/page.tsx:27:23)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/headers/invalid-undeclared-header-has/page.tsx:26:3)
25 | const headerStore = await headers()
26 | ensureThrows(
> 27 | () => headerStore.has('undeclaredHeader'),
| ^
28 | \`Expected has() to throw for undeclared headers\`
29 | )
30 | return null {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/headers/invalid-undeclared-header-has".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('valid - header value passed to a cache', async () => {
const result = await prerender(
'/(default)/headers/valid-headers-passed-to-cache'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('valid - header value passed to a client component', async () => {
const result = await prerender(
'/(default)/headers/valid-headers-passed-to-client'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
})
describe('cookies', () => {
it('cookies are correctly read from samples', async () => {
const result = await prerender(
'/(default)/cookies/valid-cookies-in-samples'
)
expect(result.cliOutput).not.toContain('AssertionError')
expectNoBuildValidationErrors(result)
})
it('error - .get() of cookie not present in samples', async () => {
const result = await prerender(
'/(default)/cookies/invalid-undeclared-cookie-get'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/cookies/invalid-undeclared-cookie-get" accessed cookie "undeclaredCookie" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`cookies\` array, or \`{ name: "undeclaredCookie", value: null }\` if it should be absent.
at <unknown> (app/(default)/cookies/invalid-undeclared-cookie-get/page.tsx:28:23)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/cookies/invalid-undeclared-cookie-get/page.tsx:27:3)
26 |
27 | ensureThrows(
> 28 | () => cookieStore.get('undeclaredCookie'),
| ^
29 | \`Expected get() to throw for undeclared cookies\`
30 | )
31 | return null {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/cookies/invalid-undeclared-cookie-get".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - .get() of cookie not present in samples and catching the error', async () => {
const result = await prerender(
'/(default)/cookies/invalid-undeclared-cookie-get-caught'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/cookies/invalid-undeclared-cookie-get-caught" accessed cookie "undeclaredCookie" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`cookies\` array, or \`{ name: "undeclaredCookie", value: null }\` if it should be absent.
at <unknown> (app/(default)/cookies/invalid-undeclared-cookie-get-caught/page.tsx:30:25)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/cookies/invalid-undeclared-cookie-get-caught/page.tsx:29:5)
28 | try {
29 | ensureThrows(
> 30 | () => cookieStore.get('undeclaredCookie'),
| ^
31 | \`Expected get() to throw for undeclared cookies\`
32 | )
33 | } catch (err) { {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/cookies/invalid-undeclared-cookie-get-caught".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - .has() of cookie not present in samples', async () => {
const result = await prerender(
'/(default)/cookies/invalid-undeclared-cookie-has'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/cookies/invalid-undeclared-cookie-has" accessed cookie "undeclaredCookie" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`cookies\` array, or \`{ name: "undeclaredCookie", value: null }\` if it should be absent.
at <unknown> (app/(default)/cookies/invalid-undeclared-cookie-has/page.tsx:27:23)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/cookies/invalid-undeclared-cookie-has/page.tsx:26:3)
25 | const cookieStore = await cookies()
26 | ensureThrows(
> 27 | () => cookieStore.has('undeclaredCookie'),
| ^
28 | \`Expected has() to throw for undeclared cookies\`
29 | )
30 | return null {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/cookies/invalid-undeclared-cookie-has".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('valid - cookies passed to a cache', async () => {
const result = await prerender(
'/(default)/cookies/valid-cookies-passed-to-cache'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
})
describe('params', () => {
it('valid - params are correctly read from samples', async () => {
const result = await prerender(
'/(default)/params/valid-params-in-samples/[one]/[two]'
)
expect(result.cliOutput).not.toContain('AssertionError')
expectNoBuildValidationErrors(result)
})
it('error - reading a param not present in samples', async () => {
const result = await prerender(
'/(default)/params/invalid-param-not-provided/[one]/[two]'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/params/invalid-param-not-provided/[one]/[two]" accessed param "two" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object.
at <unknown> (app/(default)/params/invalid-param-not-provided/[one]/[two]/page.tsx:47:24)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/params/invalid-param-not-provided/[one]/[two]/page.tsx:47:3)
45 |
46 | // We're not allowed to access params not in the samples.
> 47 | ensureThrows(() => p.two)
| ^
48 |
49 | // TODO: test \`in\` and iteration
50 | // assert.deepStrictEqual( {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/params/invalid-param-not-provided/[one]/[two]".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - reading a param not present in samples and catching the error', async () => {
const result = await prerender(
'/(default)/params/invalid-param-not-provided-caught/[one]/[two]'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/params/invalid-param-not-provided-caught/[one]/[two]" accessed param "two" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object.
at <unknown> (app/(default)/params/invalid-param-not-provided-caught/[one]/[two]/page.tsx:45:26)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/params/invalid-param-not-provided-caught/[one]/[two]/page.tsx:45:5)
43 | try {
44 | // We're not allowed to access params not in the samples.
> 45 | ensureThrows(() => p.two, \`Expected accessing an undeclared param to throw\`)
| ^
46 | } catch (err) {
47 | // We swallow the error. It should still be reported and fail the validation.
48 | } {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/params/invalid-param-not-provided-caught/[one]/[two]".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('useParams() receives params from samples', async () => {
const result = await prerender(
'/(default)/params/valid-use-params/[one]/[two]'
)
expect(result.cliOutput).not.toContain('AssertionError')
expectNoBuildValidationErrors(result)
})
it('error - accessing a param not present in samples via useParams()', async () => {
const result = await prerender(
'/(default)/params/invalid-undeclared-use-params/[one]/[two]'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/params/invalid-undeclared-use-params/[one]/[two]" accessed param "two" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object.
at <unknown> (app/(default)/params/invalid-undeclared-use-params/[one]/[two]/params-reader.tsx:10:18)
at <unknown> (ensure-error.ts:11:5)
at <unknown> (app/(default)/params/invalid-undeclared-use-params/[one]/[two]/params-reader.tsx:9:3)
8 | // We're not allowed to access params not in the samples.
9 | ensureThrows(
> 10 | () => params.two,
| ^
11 | \`Expected accessing an undeclared param to throw\`
12 | )
13 | return null {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/params/invalid-undeclared-use-params/[one]/[two]".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - accessing a param not present in samples via useParams() and catching the error', async () => {
const result = await prerender(
'/(default)/params/invalid-undeclared-use-params-caught/[one]/[two]'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/params/invalid-undeclared-use-params-caught/[one]/[two]" accessed param "two" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object.
at <unknown> (app/(default)/params/invalid-undeclared-use-params-caught/[one]/[two]/params-reader.tsx:11:20)
at <unknown> (ensure-error.ts:11:5)
at <unknown> (app/(default)/params/invalid-undeclared-use-params-caught/[one]/[two]/params-reader.tsx:10:5)
9 | // We're not allowed to access params not in the samples.
10 | ensureThrows(
> 11 | () => params.two,
| ^
12 | \`Expected accessing an undeclared param to throw\`
13 | )
14 | } catch { {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/params/invalid-undeclared-use-params-caught/[one]/[two]".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('valid - awaited params passed to a cache', async () => {
const result = await prerender(
'/(default)/params/valid-params-passed-to-cache/[slug]'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('valid - awaited params passed to a client component', async () => {
const result = await prerender(
'/(default)/params/valid-params-passed-to-client/[slug]'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
})
describe('pathname', () => {
it('valid - usePathname() on a route without params', async () => {
const result = await prerender(
'/(default)/pathname/valid-use-pathname-no-params'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('valid - usePathname() on a route with params (all provided in samples)', async () => {
const result = await prerender(
'/(default)/pathname/valid-use-pathname-with-params/[one]/[two]'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('valid - usePathname() on a route inside a route group does not include the group segment', async () => {
const result = await prerender(
'/(default)/pathname/valid-use-pathname-route-group/(route-group)'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('valid - usePathname() on a catch-all route', async () => {
const result = await prerender(
'/(default)/pathname/valid-use-pathname-catch-all/[...catchAll]'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('valid - usePathname() on an optional catch-all route', async () => {
const result = await prerender(
'/(default)/pathname/valid-use-pathname-optional-catch-all/[[...optionalCatchAll]]'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('error - usePathname() on a route with params but not all provided in samples', async () => {
const result = await prerender(
'/(default)/pathname/invalid-use-pathname-missing-params/[one]/[two]'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/pathname/invalid-use-pathname-missing-params/[one]/[two]" called usePathname() but param "two" is not defined in the \`samples\` of \`unstable_instant\`. usePathname() requires all route params to be provided.
at <unknown> (app/(default)/pathname/invalid-use-pathname-missing-params/[one]/[two]/pathname-reader.tsx:9:11)
at <unknown> (ensure-error.ts:11:5)
at <unknown> (app/(default)/pathname/invalid-use-pathname-missing-params/[one]/[two]/pathname-reader.tsx:7:3)
7 | ensureThrows(
8 | // eslint-disable-next-line react-hooks/rules-of-hooks
> 9 | () => usePathname(),
| ^
10 | \`Expected usePathname() to throw when not all params are provided in samples\`
11 | )
12 | return null {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/pathname/invalid-use-pathname-missing-params/[one]/[two]".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
})
describe('root params', () => {
it.each(['static', 'runtime'])(
'valid - %s - root params are correctly read from samples',
async (variant) => {
const result = await prerender(
`/root-params/[lang]/valid-root-param-in-samples/${variant}`
)
expectNoBuildValidationErrors(result)
// The page asserts on the values
expect(result.cliOutput).not.toContain('AssertionError')
}
)
it('error - reading a root param not present in samples', async () => {
const result = await prerender(
'/root-params/[lang]/invalid-root-param-not-provided'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/root-params/[lang]/invalid-root-param-not-provided" accessed root param "lang" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object.
at <unknown> (app/root-params/[lang]/invalid-root-param-not-provided/page.tsx:17:11)
at a (ensure-error.ts:48:11)
at b (app/root-params/[lang]/invalid-root-param-not-provided/page.tsx:16:9)
15 |
16 | await ensureRejects(
> 17 | () => lang(),
| ^
18 | \`Expected lang() to error if sample is not provided\`
19 | )
20 | return ( {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/root-params/[lang]/invalid-root-param-not-provided".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - reading a root param not present in samples and catching the error', async () => {
const result = await prerender(
'/root-params/[lang]/invalid-root-param-not-provided-caught'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/root-params/[lang]/invalid-root-param-not-provided-caught" accessed root param "lang" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object.
at <unknown> (app/root-params/[lang]/invalid-root-param-not-provided-caught/page.tsx:18:13)
at a (ensure-error.ts:48:11)
at b (app/root-params/[lang]/invalid-root-param-not-provided-caught/page.tsx:17:11)
16 | try {
17 | await ensureRejects(
> 18 | () => lang(),
| ^
19 | \`Expected lang() to error if sample is not provided\`
20 | )
21 | } catch { {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/root-params/[lang]/invalid-root-param-not-provided-caught".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
})
describe('samples precedence', () => {
it('page samples override layout samples', async () => {
const result = await prerender(
'/(default)/samples-precedence/[slug]/page-overrides'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
it('page inherits samples from layout when it has none', async () => {
const result = await prerender(
'/(default)/samples-precedence/[slug]/page-inherits'
)
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
})
describe('generateStaticParams', () => {
it('valid - page with generateStaticParams and samples only runs validation once', async () => {
const result = await prerender('/(default)/gsp/[slug]')
// If validation ran once, we expect one "validation_start"/"validation_end" pair
const validationMessages = parseValidationMessages(result.cliOutput)
expect(validationMessages).toEqual([
expect.objectContaining({ type: 'validation_start' }),
expect.objectContaining({ type: 'validation_end' }),
])
expectNoBuildValidationErrors(result)
expect(result.cliOutput).not.toContain('AssertionError')
})
})
describe('caches', () => {
it('valid - static prefetch - awaiting a cache in the static stage does not require a suspense boundary', async () => {
const result = await prerender(
'/(default)/valid-await-cache-without-suspense/static'
)
expectNoBuildValidationErrors(result)
})
it('valid - runtime prefetch - awaiting a cache in the runtime stage does not require a suspense boundary', async () => {
const result = await prerender(
'/(default)/valid-await-cache-without-suspense/runtime'
)
expectNoBuildValidationErrors(result)
})
it('valid - runtime prefetch - awaiting a mix of caches in the static and runtime stages does not require a suspense boundary', async () => {
const result = await prerender(
'/(default)/valid-await-cache-without-suspense/mixed'
)
expectNoBuildValidationErrors(result)
})
it('valid - runtime prefetch - awaiting a private cache in the runtime stage does not require a suspense boundary', async () => {
const result = await prerender(
'/(default)/valid-await-cache-without-suspense/private'
)
expectNoBuildValidationErrors(result)
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
typescript: {
ignoreBuildErrors: true,
},
}
module.exports = nextConfig
import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'static',
unstable_disableBuildValidation: true,
}
export default async function Page() {
await connection()
return (
<main>
<p>
This page has <code>unstable_disableBuildValidation: true</code>, so
validation is disabled in build but runs in dev.
</p>
</main>
)
}
import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'static',
unstable_disableDevValidation: true,
}
export default async function Page() {
await connection()
return (
<main>
<p>
This page has <code>unstable_disableDevValidation: true</code>, so
validation is disabled in dev but runs in build.
</p>
</main>
)
}
......@@ -5,7 +5,7 @@ import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
samples: [{ cookies: [] }],
}
// Note that we're inside a root layout with suspense, so we skip the static shell
......
......@@ -5,7 +5,10 @@ import { cookies } from 'next/headers'
// This would be valid if it used a runtime prefetch (because then it wouldn't block navigation),
// but it's static, so it's invalid. As an extra sanity check, we put a runtime prefetch on the
// layout above, and that should not make this error go away.
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ cookies: [] }],
}
export async function generateViewport(): Promise<Viewport> {
await cookies()
......
......@@ -4,6 +4,7 @@ import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'static',
samples: [{ cookies: [] }],
}
export async function generateMetadata(): Promise<Metadata> {
......
......@@ -3,7 +3,7 @@ import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
samples: [{ cookies: [] }],
}
export async function generateViewport(): Promise<Viewport> {
......
......@@ -195,6 +195,12 @@ export default async function Page() {
<li>
<DebugLinks href="/suspense-in-root/disable-validation/in-page-with-outer" />
</li>
<li>
<DebugLinks href="/suspense-in-root/disable-validation/disable-dev" />
</li>
<li>
<DebugLinks href="/suspense-in-root/disable-validation/disable-build" />
</li>
</ul>
</main>
)
......
// Avoid static shell validation -- we only want to test the validation of `prefetch: 'runtime'` here.
export const unstable_instant = false
export default function DisableStaticShell({ children }) {
return <>{children}</>
}
......@@ -2,7 +2,7 @@ import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
samples: [{ cookies: [] }],
}
// This page HAS runtime prefetch enabled. cookies() is passed as a promise
......
......@@ -2,7 +2,7 @@ import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
samples: [{ cookies: [] }],
}
// This page HAS runtime prefetch enabled. The sync IO (Date.now()) after
......
......@@ -3,7 +3,7 @@ import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
samples: [{ cookies: [], params: { param: '123' } }],
}
export default async function Page({
......
......@@ -3,7 +3,7 @@ import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
samples: [{ cookies: [], searchParams: { foo: 'bar' } }],
}
export default async function Page({
......
import { cookies } from 'next/headers'
import { Suspense } from 'react'
// No unstable_instant — this page is NOT runtime-prefetchable.
// Sync IO in generateMetadata should be allowed.
// this page is NOT runtime-prefetchable,
// so Sync IO in generateMetadata should be allowed.
export const unstable_instant = { prefetch: 'static' }
export async function generateMetadata() {
await cookies()
......
......@@ -3,6 +3,7 @@ import { cookies } from 'next/headers'
// This layout does NOT have runtime prefetch and neither does the child
// page. Since no segment has runtime prefetch enabled, sync IO in
// generateMetadata should be allowed.
export const unstable_instant = { prefetch: 'static' }
export async function generateMetadata() {
await cookies()
......
......@@ -3,7 +3,7 @@ import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
samples: [{ cookies: [] }],
}
async function Runtime() {
......
import { cookies } from 'next/headers'
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ cookies: [] }],
}
export default async function Page() {
await cookies()
......
import { cookies } from 'next/headers'
import { ReactNode } from 'react'
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ cookies: [] }],
}
export default async function Layout({ children }: { children: ReactNode }) {
await cookies()
......
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ params: { param: '123' } }],
}
export default async function Page({
params,
......
import { cookies } from 'next/headers'
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ cookies: [] }],
}
export default async function Page() {
await cookies()
......
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ searchParams: { foo: 'bar' } }],
}
export default async function Page({ searchParams }) {
const search = await searchParams
......
......@@ -2,7 +2,10 @@ import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ cookies: [] }],
}
export default async function Page() {
return (
......
import { cookies } from 'next/headers'
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ cookies: [] }],
}
export default async function Page() {
await cookies()
......
export const unstable_instant = {
prefetch: 'static',
// `usePathname` will error if we don't have a sample for `[id]`.
samples: [{ params: { id: '123' } }],
}
export default function Page() {
......
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ cookies: [] }],
}
export default async function Page() {
return (
......
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export const unstable_instant = { prefetch: 'static' }
export const unstable_instant = {
prefetch: 'static',
samples: [{ cookies: [] }],
}
export default async function Page() {
return (
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -2,7 +2,7 @@ import { ReactNode } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
samples: [{ cookies: [{ name: 'test', value: null }] }],
}
export default function Layout({ children }: { children: ReactNode }) {
......
......@@ -4,7 +4,7 @@ import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
samples: [{ cookies: [{ name: 'test', value: null }] }],
}
export default async function Page() {
......
......@@ -5,7 +5,10 @@ import { ErrorBoundary } from '../../../../components/error-boundary'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
// We're intentionally testing error behavior at runtime.
// Build-time validation catches it and prevents that.
unstable_disableValidation: true,
samples: [{ cookies: [{ name: 'user-agent', value: null }] }],
}
export default async function Page() {
......
......@@ -4,6 +4,9 @@ import { DebugRenderKind } from '../../../../shared'
export const unstable_instant = {
prefetch: 'runtime',
// We're intentionally testing error behavior at runtime.
// Build-time validation catches it and prevents that.
unstable_disableValidation: true,
samples: [{ cookies: [] }],
}
......
......@@ -5,6 +5,9 @@ type Params = { id: string }
export const unstable_instant = {
prefetch: 'runtime',
// We're intentionally testing error behavior at runtime.
// Build-time validation catches it and prevents that.
unstable_disableValidation: true,
samples: [{ cookies: [] }],
}
......
......@@ -4,6 +4,9 @@ import { DebugRenderKind } from '../../../../shared'
export const unstable_instant = {
prefetch: 'runtime',
// We're intentionally testing error behavior at runtime.
// Build-time validation catches it and prevents that.
unstable_disableValidation: true,
samples: [{ cookies: [] }],
}
......
......@@ -3,6 +3,9 @@ import { cachedDelay, DebugRenderKind } from '../../../../shared'
export const unstable_instant = {
prefetch: 'runtime',
// We're intentionally testing error behavior at runtime.
// Build-time validation catches it and prevents that.
unstable_disableValidation: true,
samples: [{ cookies: [] }],
}
......
......@@ -4,6 +4,9 @@ import { cacheLife } from 'next/cache'
export const unstable_instant = {
prefetch: 'runtime',
// We're intentionally testing error behavior at runtime.
// Build-time validation catches it and prevents that.
unstable_disableValidation: true,
samples: [{ cookies: [] }],
}
......
......@@ -5,6 +5,9 @@ type AnySearchParams = { [key: string]: string | string[] | undefined }
export const unstable_instant = {
prefetch: 'runtime',
// We're intentionally testing error behavior at runtime.
// Build-time validation catches it and prevents that.
unstable_disableValidation: true,
samples: [{ cookies: [] }],
}
......
......@@ -4,7 +4,7 @@ import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ searchParams: { key: 'value' } }],
samples: [{ searchParams: { searchParam: 'value' } }],
}
type AnySearchParams = { [key: string]: string | string[] | undefined }
......
......@@ -4,7 +4,7 @@ import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ searchParams: { key: 'value' } }],
samples: [{ searchParams: { searchParam: 'value' } }],
}
type AnySearchParams = { [key: string]: string | string[] | undefined }
......
......@@ -5,7 +5,7 @@ import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ searchParams: { key: 'value' } }],
samples: [{ searchParams: { searchParam: 'value' } }],
}
type AnySearchParams = { [key: string]: string | string[] | undefined }
......
import { retry } from '../next-test-utils'
import { getDeterministicOutput } from '../../e2e/app-dir/cache-components-errors/utils'
export type ValidationEvent =
| { type: 'validation_start'; requestId: string; url: string }
| { type: 'validation_end'; requestId: string; url: string }
export function parseValidationMessages(output: string): ValidationEvent[] {
const messageRe = /<VALIDATION_MESSAGE>(.*?)<\/VALIDATION_MESSAGE>/g
const events: ValidationEvent[] = []
let match: RegExpExecArray | null
while ((match = messageRe.exec(output)) !== null) {
try {
events.push(JSON.parse(match[1]))
} catch (err) {
throw new Error(`Failed to parse message '${match[1]}'`, {
cause: err,
})
}
}
return events
}
export function extractBuildValidationError(
cliOutput: string,
{ isMinified = true } = {}
): string {
const markerRe = /<VALIDATION_MESSAGE>(.*?)<\/VALIDATION_MESSAGE>/g
// Find all marker positions and their content
const markers: {
index: number
endIndex: number
data: ValidationEvent
}[] = []
let m: RegExpExecArray | null
while ((m = markerRe.exec(cliOutput)) !== null) {
// JSON.parse must succeed — if it throws, let the error propagate
const data: ValidationEvent = JSON.parse(m[1])
markers.push({
index: m.index,
endIndex: m.index + m[0].length,
data,
})
}
// Expect exactly two markers: one validation_start and one validation_end
if (markers.length !== 2) {
throw new Error(
`Expected exactly 2 validation markers, found ${markers.length}.\n` +
`CLI output:\n${cliOutput}`
)
}
const [start, end] = markers
if (
start.data.type !== 'validation_start' ||
end.data.type !== 'validation_end'
) {
throw new Error(
`Expected [validation_start, validation_end] markers, got [${start.data.type}, ${end.data.type}].\n` +
`CLI output:\n${cliOutput}`
)
}
if (start.data.requestId !== end.data.requestId) {
throw new Error(
`Expected [validation_start, validation_end] markers to come from the same request`
)
}
const output = cliOutput.slice(start.endIndex, end.index).trim()
return getDeterministicOutput(output, { isMinified })
}
export function normalizeValidationUrl(url: string): string {
// RSC requests include ?_rsc=... in the URL. Strip it so the event URL
// matches what browser.url() returns (which has no _rsc param).
const parsed = new URL(url, 'http://n')
parsed.searchParams.delete('_rsc')
return parsed.pathname + parsed.search + parsed.hash
}
export async function waitForValidationStart(
targetUrl: string,
getOutput: () => string
): Promise<string> {
const parsedTargetUrl = new URL(targetUrl)
const relativeTargetUrl =
parsedTargetUrl.pathname + parsedTargetUrl.search + parsedTargetUrl.hash
const requestId = await retry(
async () => {
const events = parseValidationMessages(getOutput())
const start = events.find(
(e) =>
e.type === 'validation_start' &&
normalizeValidationUrl(e.url) === relativeTargetUrl
)
expect(start).toBeDefined()
return start!.requestId
},
undefined,
undefined,
`wait for validation of '${relativeTargetUrl}' to start`
)
return requestId
}
export async function waitForValidationEnd(
requestId: string,
getOutput: () => string
): Promise<void> {
await retry(
async () => {
const events = parseValidationMessages(getOutput())
const end = events.find(
(e) => e.type === 'validation_end' && e.requestId === requestId
)
expect(end).toBeDefined()
},
undefined,
undefined,
'wait for validation to end'
)
}
export async function waitForValidation(
url: string,
getOutput: () => string
): Promise<void> {
const requestId = await waitForValidationStart(url, getOutput)
await waitForValidationEnd(requestId, getOutput)
}
type PrerenderResult = {
cliOutput: string
exitCode: number | NodeJS.Signals
}
export function expectNoBuildValidationErrors(result: PrerenderResult) {
// Check the logs before checking the error code.
// If it fails, the logs are more likely to show a useful reason than an error code.
expect(result.cliOutput).not.toContain('Build-time instant validation failed')
// As a sanity check, parse the log and make sure that instant validation actually ran.
expect(extractBuildValidationError(result.cliOutput)).not.toContain(
'Build-time instant validation failed'
)
expect(result.exitCode).toBe(0)
}
export function expectBuildValidationSkipped(result: PrerenderResult) {
// Check the logs before checking the error code.
// If it fails, the logs are more likely to show a useful reason than an error code.
expect(result.cliOutput).not.toContain('Build-time instant validation failed')
expect(parseValidationMessages(result.cliOutput)).toHaveLength(0)
expect(result.exitCode).toBe(0)
}
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