Unverified Commit 85d74bb4 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Instant] allow non-blocking dynamic holes and errors in shared parents (#89875)

Closes NAR-777
parent 32b1479a
...@@ -1052,5 +1052,11 @@ ...@@ -1052,5 +1052,11 @@
"1051": "Turbopack trace server is not supported on this platform (%s/%s) because native bindings are not available. Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings.", "1051": "Turbopack trace server is not supported on this platform (%s/%s) because native bindings are not available. Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings.",
"1052": "Turbopack is not supported on this platform (%s/%s) because native bindings are not available. Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings. Use the --webpack flag instead.", "1052": "Turbopack is not supported on this platform (%s/%s) because native bindings are not available. Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings. Use the --webpack flag instead.",
"1053": "Export encountered errors on %s %s:\\n\\t%s", "1053": "Export encountered errors on %s %s:\\n\\t%s",
"1054": "`runInSequentialTasks` should not be called in edge runtime." "1054": "`runInSequentialTasks` should not be called in edge runtime.",
"1055": "Route \"%s\" failed to render during instant validation and Next.js was unable to determine a reason.",
"1056": "Route \"%s\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering for an unknown reason.",
"1057": "Route \"%s\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to one of the following errors.",
"1058": "InstantValidationBoundary should only be rendered in SSR",
"1059": "Route \"%s\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to the following error.",
"1060": "Missing boundary tracking state"
} }
...@@ -142,6 +142,8 @@ import { ...@@ -142,6 +142,8 @@ import {
getNavigationDisallowedDynamicReasons, getNavigationDisallowedDynamicReasons,
trackDynamicHoleInNavigation, trackDynamicHoleInNavigation,
DynamicHoleKind, DynamicHoleKind,
trackThrownErrorInNavigation,
createInstantValidationState,
} from './dynamic-rendering' } from './dynamic-rendering'
import { import {
getClientComponentLoaderMetrics, getClientComponentLoaderMetrics,
...@@ -239,6 +241,7 @@ import { createNodeStreamWithLateRelease } from './instant-validation/stream-uti ...@@ -239,6 +241,7 @@ import { createNodeStreamWithLateRelease } from './instant-validation/stream-uti
// NOTE: Only use this for types, access implementations via ComponentMod // NOTE: Only use this for types, access implementations via ComponentMod
import type * as InstantValidation from './instant-validation/instant-validation' import type * as InstantValidation from './instant-validation/instant-validation'
import { createValidationBoundaryTracking } from './instant-validation/boundary-tracking'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// The LoaderTree to extract the dynamic param from // The LoaderTree to extract the dynamic param from
...@@ -4277,6 +4280,9 @@ async function validateInstantConfigNavigation( ...@@ -4277,6 +4280,9 @@ async function validateInstantConfigNavigation(
const preinitScripts = () => {} const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML() const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const dynamicValidation = createInstantValidationState()
const boundaryState = createValidationBoundaryTracking()
const finalClientPrerenderStore: PrerenderStore = { const finalClientPrerenderStore: PrerenderStore = {
type: 'prerender-client', type: 'prerender-client',
phase: 'render', phase: 'render',
...@@ -4299,10 +4305,9 @@ async function validateInstantConfigNavigation( ...@@ -4299,10 +4305,9 @@ async function validateInstantConfigNavigation(
hmrRefreshHash, hmrRefreshHash,
// We don't need to track vary params during validation. // We don't need to track vary params during validation.
varyParamsAccumulator: null, varyParamsAccumulator: null,
boundaryState,
} }
const dynamicValidation = createDynamicValidationState()
const clientReferenceManifest = getClientReferenceManifest() const clientReferenceManifest = getClientReferenceManifest()
const usedSegmentKinds = new Set<InstantValidation.SegmentStage>() const usedSegmentKinds = new Set<InstantValidation.SegmentStage>()
...@@ -4315,6 +4320,7 @@ async function validateInstantConfigNavigation( ...@@ -4315,6 +4320,7 @@ async function validateInstantConfigNavigation(
routeTree, routeTree,
navigationParent, navigationParent,
extraChunksReleaseSignal, extraChunksReleaseSignal,
boundaryState,
clientReferenceManifest, clientReferenceManifest,
stageEndTimes, stageEndTimes,
useRuntimeStageForPartialSegments, useRuntimeStageForPartialSegments,
...@@ -4370,10 +4376,20 @@ async function validateInstantConfigNavigation( ...@@ -4370,10 +4376,20 @@ async function validateInstantConfigNavigation(
componentStack, componentStack,
dynamicValidation, dynamicValidation,
clientDynamicTracking, clientDynamicTracking,
dynamicHoleKind dynamicHoleKind,
boundaryState
) )
} }
return return
} else if (!clientReactController.signal.aborted) {
const componentStack = errorInfo.componentStack
if (typeof componentStack === 'string') {
trackThrownErrorInNavigation(
dynamicValidation,
err,
componentStack
)
}
} }
if (isReactLargeShellError(err)) { if (isReactLargeShellError(err)) {
...@@ -4408,19 +4424,23 @@ async function validateInstantConfigNavigation( ...@@ -4408,19 +4424,23 @@ async function validateInstantConfigNavigation(
) )
const { preludeIsEmpty } = await processPrelude(unprocessedPrelude) const { preludeIsEmpty } = await processPrelude(unprocessedPrelude)
const reasons = getNavigationDisallowedDynamicReasons( const reasons = getNavigationDisallowedDynamicReasons(
workStore, workStore,
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full, preludeIsEmpty ? PreludeState.Empty : PreludeState.Full,
dynamicValidation dynamicValidation,
boundaryState
) )
return { dynamicHoleKind, errors: reasons } as const
return { dynamicHoleKind, errors: reasons }
} catch (thrownValue) { } catch (thrownValue) {
// Even if the root errors we still want to report any cache components errors // Even if the root errors we still want to report any cache components errors
// that were discovered before the root errored. // that were discovered before the root errored.
let errors: Array<unknown> = getNavigationDisallowedDynamicReasons( let errors: Array<unknown> = getNavigationDisallowedDynamicReasons(
workStore, workStore,
PreludeState.Errored, PreludeState.Errored,
dynamicValidation dynamicValidation,
boundaryState
) )
if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) { if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) {
......
...@@ -50,6 +50,7 @@ import { scheduleOnNextTick } from '../../lib/scheduler' ...@@ -50,6 +50,7 @@ import { scheduleOnNextTick } from '../../lib/scheduler'
import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants' import { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
const hasPostpone = typeof React.unstable_postpone === 'function' const hasPostpone = typeof React.unstable_postpone === 'function'
...@@ -773,12 +774,38 @@ export enum DynamicHoleKind { ...@@ -773,12 +774,38 @@ export enum DynamicHoleKind {
Dynamic = 2, Dynamic = 2,
} }
/** Stores dynamic reasons used during an SSR render in instant validation. */
export type InstantValidationState = {
hasDynamicMetadata: boolean
hasAllowedClientDynamicAboveBoundary: boolean
dynamicMetadata: null | Error
hasDynamicViewport: boolean
hasAllowedDynamic: boolean
dynamicErrors: Array<Error>
validationPreventingErrors: Array<Error>
thrownErrorsOutsideBoundary: Array<unknown>
}
export function createInstantValidationState(): InstantValidationState {
return {
hasDynamicMetadata: false,
hasAllowedClientDynamicAboveBoundary: false,
dynamicMetadata: null,
hasDynamicViewport: false,
hasAllowedDynamic: false,
dynamicErrors: [],
validationPreventingErrors: [],
thrownErrorsOutsideBoundary: [],
}
}
export function trackDynamicHoleInNavigation( export function trackDynamicHoleInNavigation(
workStore: WorkStore, workStore: WorkStore,
componentStack: string, componentStack: string,
dynamicValidation: DynamicValidationState, dynamicValidation: InstantValidationState,
clientDynamic: DynamicTrackingState, clientDynamic: DynamicTrackingState,
kind: DynamicHoleKind kind: DynamicHoleKind,
boundaryState: ValidationBoundaryTracking
) { ) {
if (hasOutletRegex.test(componentStack)) { if (hasOutletRegex.test(componentStack)) {
// We don't need to track that this is dynamic. It is only so when something else is also dynamic. // We don't need to track that this is dynamic. It is only so when something else is also dynamic.
...@@ -805,32 +832,62 @@ export function trackDynamicHoleInNavigation( ...@@ -805,32 +832,62 @@ export function trackDynamicHoleInNavigation(
return return
} }
// Check if we have a Suspense above the hole, but below the validation boundary. const boundaryLocation =
// If we do, then this dynamic usage wouldn't block a navigation to this subtree. hasPrefetchValidationBoundaryRegex.exec(componentStack)
// Conversely, if the nearest suspense is above the validation boundary, then this subtree would block. if (!boundaryLocation) {
// // We don't see the validation boundary in the component stack,
// Note that in the component stack, children come before parents. // so this hole must be coming from a shared parent.
// // Shared parents are fully resolved and don't have RSC holes,
// Valid: // but they can still suspend in a client component during SSR.
// ...
// at Suspense // If we managed to render all the validation boundaries, that means
// ... // that the client holes aren't blocking validation and we can disregard them.
// at __next_prefetch_validation_boundary__ // Note that we don't even care whether they have suspense or not.
// if (boundaryState.expectedIds.size === boundaryState.renderedIds.size) {
// Invalid: dynamicValidation.hasAllowedClientDynamicAboveBoundary = true
// ... dynamicValidation.hasAllowedDynamic = true // Holes outside the boundary contribute to allowing dynamic metadata
// at __next_prefetch_validation_boundary__ return
// ... } else {
// at Suspense // TODO(instant-validation) TODO(NAR-787)
// // If shared parents blocked us from validating, we should only log
const suspenseLocation = hasSuspenseRegex.exec(componentStack) // the errors from the innermost (segments), i.e. omit layouts whose
if (suspenseLocation) { // slots managed to render (because clearly they didn't block validation)
const boundaryLocation = const message = `Route "${workStore.route}": Could not validate \`unstable_instant\` because a Client Component in a parent segment prevented the page from rendering.`
hasPrefetchValidationBoundaryRegex.exec(componentStack) const error = createErrorWithComponentOrOwnerStack(
if (boundaryLocation) { message,
componentStack
)
dynamicValidation.validationPreventingErrors.push(error)
return
}
} else {
// The hole originates inside the validation boundary.
//
// Check if we have a Suspense above the hole, but below the validation boundary.
// If we do, then this dynamic usage wouldn't block a navigation to this subtree.
// Conversely, if the nearest suspense is above the validation boundary, then this subtree would block.
//
// Note that in the component stack, children come before parents.
//
// Valid:
// ...
// at Suspense
// ...
// at __next_prefetch_validation_boundary__
//
// Invalid:
// ...
// at __next_prefetch_validation_boundary__
// ...
// at Suspense
//
const suspenseLocation = hasSuspenseRegex.exec(componentStack)
if (suspenseLocation) {
if (suspenseLocation.index < boundaryLocation.index) { if (suspenseLocation.index < boundaryLocation.index) {
dynamicValidation.hasAllowedDynamic = true dynamicValidation.hasAllowedDynamic = true
return return
} else {
// invalid - fallthrough
} }
} }
} }
...@@ -853,6 +910,19 @@ export function trackDynamicHoleInNavigation( ...@@ -853,6 +910,19 @@ export function trackDynamicHoleInNavigation(
return return
} }
export function trackThrownErrorInNavigation(
dynamicValidation: InstantValidationState,
error: 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
}
dynamicValidation.thrownErrorsOutsideBoundary.push(error)
}
export function trackDynamicHoleInRuntimeShell( export function trackDynamicHoleInRuntimeShell(
workStore: WorkStore, workStore: WorkStore,
componentStack: string, componentStack: string,
...@@ -1110,27 +1180,57 @@ export function getStaticShellDisallowedDynamicReasons( ...@@ -1110,27 +1180,57 @@ export function getStaticShellDisallowedDynamicReasons(
export function getNavigationDisallowedDynamicReasons( export function getNavigationDisallowedDynamicReasons(
workStore: WorkStore, workStore: WorkStore,
prelude: PreludeState, prelude: PreludeState,
dynamicValidation: DynamicValidationState dynamicValidation: InstantValidationState,
boundaryState: ValidationBoundaryTracking
): Array<Error> { ): Array<Error> {
// NOTE: We don't care about Suspense above body here const { validationPreventingErrors } = dynamicValidation
// TODO: Need to make sure the logic here actually makes sense if (validationPreventingErrors.length > 0) {
return validationPreventingErrors
}
if (boundaryState.renderedIds.size < boundaryState.expectedIds.size) {
const { thrownErrorsOutsideBoundary } = dynamicValidation
if (thrownErrorsOutsideBoundary.length === 0) {
return [
new Error(
`Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering for an unknown reason.`
),
]
} else if (thrownErrorsOutsideBoundary.length === 1) {
return [
new Error(
`Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to the following error.`
),
thrownErrorsOutsideBoundary[0] as Error,
]
} else {
return [
new Error(
`Route "${workStore.route}": Could not validate \`unstable_instant\` because the target segment was prevented from rendering, likely due to one of the following errors.`
),
...(thrownErrorsOutsideBoundary as Error[]),
]
}
}
// NOTE: We don't care about Suspense above body here,
// we're only concerned with the validation boundary
if (prelude !== PreludeState.Full) { if (prelude !== PreludeState.Full) {
// We didn't have any sync bailouts but there may be user code which
// blocked the root. We would have captured these during the prerender
// and can log them here and then terminate the build/validating render
const dynamicErrors = dynamicValidation.dynamicErrors const dynamicErrors = dynamicValidation.dynamicErrors
if (dynamicErrors.length > 0) { if (dynamicErrors.length > 0) {
return dynamicErrors return dynamicErrors
} }
if (prelude === PreludeState.Empty) { if (prelude === PreludeState.Empty) {
// If a client component suspended prevented us from rendering a shell
// but didn't block validation, we don't require a prelude.
if (dynamicValidation.hasAllowedClientDynamicAboveBoundary) {
return []
}
// If we ever get this far then we messed up the tracking of invalid dynamic. // If we ever get this far then we messed up the tracking of invalid dynamic.
// We still adhere to the constraint that you must produce a shell but invite the
// user to report this as a bug in Next.js.
return [ return [
new InvariantError( new InvariantError(
`Route "${workStore.route}" did not produce a static shell and Next.js was unable to determine a reason.` `Route "${workStore.route}" failed to render during instant validation and Next.js was unable to determine a reason.`
), ),
] ]
} }
......
export type ValidationBoundaryTracking = {
expectedIds: Set<string>
renderedIds: Set<string>
}
export function createValidationBoundaryTracking(): ValidationBoundaryTracking {
return {
expectedIds: new Set(),
renderedIds: new Set(),
}
}
...@@ -2,15 +2,54 @@ ...@@ -2,15 +2,54 @@
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants' import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'
import { InvariantError } from '../../../shared/lib/invariant-error'
import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
import type { ValidationBoundaryTracking } from './boundary-tracking'
function getValidationBoundaryTracking(): ValidationBoundaryTracking | null {
const store = workUnitAsyncStorage.getStore()
if (!store) return null
switch (store.type) {
case 'prerender-client':
return store.boundaryState ?? null
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
case 'request':
case 'cache':
case 'private-cache':
case 'unstable-cache':
break
default:
store satisfies never
}
return null
}
// We use a namespace object to allow us to recover the name of the function // We use a namespace object to allow us to recover the name of the function
// at runtime even when production bundling/minification is used. // at runtime even when production bundling/minification is used.
const NameSpace = { const NameSpace = {
[INSTANT_VALIDATION_BOUNDARY_NAME]: function ({ [INSTANT_VALIDATION_BOUNDARY_NAME]: function ({
id,
children, children,
}: { }: {
id: string
children: ReactNode children: ReactNode
}) { }) {
if (typeof window !== 'undefined') {
throw new InvariantError(
'InstantValidationBoundary should only be rendered in SSR'
)
}
// Track which boundaries we actually managed to render.
const state = getValidationBoundaryTracking()
if (state === null) {
throw new InvariantError('Missing boundary tracking state')
}
state.renderedIds.add(id)
return children return children
}, },
} }
......
...@@ -19,7 +19,11 @@ import { ...@@ -19,7 +19,11 @@ import {
printDebugThrownValueForProspectiveRender, printDebugThrownValueForProspectiveRender,
} from '../prospective-render-utils' } from '../prospective-render-utils'
import { getDigestForWellKnownError } from '../create-error-handler' import { getDigestForWellKnownError } from '../create-error-handler'
import { InstantValidationBoundary } from './boundary' import {
// NOTE: we're in the server layer, so this is a client reference
InstantValidationBoundary,
} from './boundary'
import type { ValidationBoundaryTracking } from './boundary-tracking'
import { import {
getLayoutOrPageModule, getLayoutOrPageModule,
type LoaderTree, type LoaderTree,
...@@ -785,6 +789,7 @@ export async function createCombinedPayload( ...@@ -785,6 +789,7 @@ export async function createCombinedPayload(
* */ * */
navigationParent: SegmentPath, navigationParent: SegmentPath,
releaseSignal: AbortSignal, releaseSignal: AbortSignal,
boundaryState: ValidationBoundaryTracking,
clientReferenceManifest: ClientReferenceManifest, clientReferenceManifest: ClientReferenceManifest,
stageEndTimes: StageEndTimes, stageEndTimes: StageEndTimes,
/** Only used when retrying a failed validation to see what caused a dynamic hole. */ /** Only used when retrying a failed validation to see what caused a dynamic hole. */
...@@ -798,6 +803,7 @@ export async function createCombinedPayload( ...@@ -798,6 +803,7 @@ export async function createCombinedPayload(
validationRouteTree, validationRouteTree,
navigationParent, navigationParent,
releaseSignal, releaseSignal,
boundaryState,
clientReferenceManifest, clientReferenceManifest,
stageEndTimes, stageEndTimes,
useRuntimeStageForPartialSegments, useRuntimeStageForPartialSegments,
...@@ -838,6 +844,7 @@ function createValidationSeedData( ...@@ -838,6 +844,7 @@ function createValidationSeedData(
rootRouteTree: RouteTree, rootRouteTree: RouteTree,
navigationParent: SegmentPath, navigationParent: SegmentPath,
releaseSignal: AbortSignal, releaseSignal: AbortSignal,
boundaryState: ValidationBoundaryTracking,
clientReferenceManifest: ClientReferenceManifest, clientReferenceManifest: ClientReferenceManifest,
stageEndTimes: StageEndTimes, stageEndTimes: StageEndTimes,
useRuntimeStageForPartialSegments: boolean, useRuntimeStageForPartialSegments: boolean,
...@@ -945,12 +952,17 @@ function createValidationSeedData( ...@@ -945,12 +952,17 @@ function createValidationSeedData(
debug?.( debug?.(
` ['${path}' is in the new subtree, adding validation boundary around it]` ` ['${path}' is in the new subtree, adding validation boundary around it]`
) )
const boundaryId = path
boundaryState.expectedIds.add(boundaryId)
segmentData = { segmentData = {
...segmentData, ...segmentData,
node: ( node: (
// bundled in the server layer // bundled in the server layer
// eslint-disable-next-line @next/internal/no-ambiguous-jsx // eslint-disable-next-line @next/internal/no-ambiguous-jsx
<InstantValidationBoundary key="c" /* matching `cacheNodeKey` */> <InstantValidationBoundary
id={boundaryId}
key="c" /* matching `cacheNodeKey` */
>
{segmentData.node} {segmentData.node}
</InstantValidationBoundary> </InstantValidationBoundary>
), ),
......
...@@ -21,6 +21,7 @@ import type { WorkStore } from './work-async-storage.external' ...@@ -21,6 +21,7 @@ import type { WorkStore } from './work-async-storage.external'
import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../client/components/app-router-headers' import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../client/components/app-router-headers'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import type { StagedRenderingController } from './staged-rendering' import type { StagedRenderingController } from './staged-rendering'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
export type WorkUnitPhase = 'action' | 'render' | 'after' export type WorkUnitPhase = 'action' | 'render' | 'after'
...@@ -112,6 +113,7 @@ export interface PrerenderStoreModernClient ...@@ -112,6 +113,7 @@ export interface PrerenderStoreModernClient
extends PrerenderStoreModernCommon, extends PrerenderStoreModernCommon,
StaticPrerenderStoreCommon { StaticPrerenderStoreCommon {
readonly type: 'prerender-client' readonly type: 'prerender-client'
readonly boundaryState?: ValidationBoundaryTracking
} }
export interface PrerenderStoreModernServer export interface PrerenderStoreModernServer
......
...@@ -3899,7 +3899,7 @@ describe('Cache Components Errors', () => { ...@@ -3899,7 +3899,7 @@ describe('Cache Components Errors', () => {
935 | // "use cache: private" is dynamic in prerendering contexts. 935 | // "use cache: private" is dynamic in prerendering contexts.
936 | case 'prerender': 936 | case 'prerender':
> 937 | return makeHangingPromise( > 937 | return makeHangingPromise(
| ^ | ^
938 | workUnitStore.renderSignal, 938 | workUnitStore.renderSignal,
939 | workStore.route, 939 | workStore.route,
940 | expression 940 | expression
......
...@@ -81,6 +81,30 @@ export default async function Page() { ...@@ -81,6 +81,30 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/suspense-in-root/static/missing-suspense-in-parallel-route/bar" /> <DebugLinks href="/suspense-in-root/static/missing-suspense-in-parallel-route/bar" />
</li> </li>
<li>
<DebugLinks href="/suspense-in-root/static/invalid-client-data-blocks-validation" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-api-in-parent/sync-io" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-api-in-parent/dynamic-params/123" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-api-in-parent/search-params" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-data-does-not-block-validation" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/invalid-client-error-in-parent-blocks-children" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/invalid-client-error-in-parent-sibling" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/valid-client-error-in-parent-does-not-block-validation" />
</li>
</ul> </ul>
<h2>Disable Validation</h2> <h2>Disable Validation</h2>
......
'use client'
import { use } from 'react'
import { useDataCache } from '../../../../client-data-fetching-lib/client'
export function FetchesClientData({ children }) {
const dataCache = useDataCache()
const promise = dataCache.getOrLoad('my-key', async () => {
await new Promise<void>((resolve) => setTimeout(resolve, 10))
return 'My client data result'
})
const data = use(promise)
return (
<>
<div>Got client data: "{data}"</div>
<hr />
{children}
</>
)
}
import type { ReactNode } from 'react'
import { FetchesClientData } from './client'
import { DataCacheProvider } from '../../../../client-data-fetching-lib/server'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<DataCacheProvider>
<div>
<p>
This layout renders a client component that suspends in SSR and blocks
the children. This prevents us from validating the page below.
</p>
<FetchesClientData>{children}</FetchesClientData>
</div>
</DataCacheProvider>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>
This page is static, so it should pass instant validation, but client
data fetching above will prevent us from validating it.
</p>
</main>
)
}
'use client'
export function ErrorInSSR({ children }) {
if (typeof window === 'undefined') {
throw new Error('No SSR please')
}
return <>{children}</>
}
import { Suspense, type ReactNode } from 'react'
import { ErrorInSSR } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout errors in SSR, and the errors is caught by a Suspense
boundary, but it blocks the children slot so it prevents validation.
</p>
<Suspense>
<ErrorInSSR>{children}</ErrorInSSR>
</Suspense>
</div>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
export function ErrorInSSR() {
if (typeof window === 'undefined') {
throw new Error('No SSR please')
}
return <div>Hello, browser!</div>
}
import { type ReactNode } from 'react'
import { ErrorInSSR } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout errors in SSR and the error isn't caught by a Suspense
boundary, so it blocks the children slot and prevents validation.
</p>
</div>
<hr />
<ErrorInSSR />
{children}
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
import { usePathname } from 'next/navigation'
export function ShouldNotSuspendDuringValidation({ children }) {
const pathname = usePathname()
return (
<>
<div>Hello, browser! Pathname: "{pathname}"</div>
<hr />
{children}
</>
)
}
import type { ReactNode } from 'react'
import { ShouldNotSuspendDuringValidation } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout renders a client component that accesses usePathname()
with a dynamic param. This would suspend a prerender, but does not
affect client navigations, so this should be allowed.
</p>
</div>
<ShouldNotSuspendDuringValidation>
{children}
</ShouldNotSuspendDuringValidation>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
export function ShouldNotSuspendDuringValidation({ children }) {
const search = useSearchParams()
return (
<>
<div>Hello, browser! Search: "{search.toString()}"</div>
<hr />
{children}
</>
)
}
import type { ReactNode } from 'react'
import { ShouldNotSuspendDuringValidation } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout renders a client component that accesses
useSearchParams(). This would suspend a prerender, but does not affect
client navigations, so this should be allowed.
</p>
</div>
<hr />
<ShouldNotSuspendDuringValidation>
{children}
</ShouldNotSuspendDuringValidation>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
export function SyncIOInClient({ children }) {
const now = Date.now()
return (
<>
<div>
Hello, browser! Now: "<span suppressHydrationWarning>{now}</span>"
</div>
<hr />
{children}
</>
)
}
import type { ReactNode } from 'react'
import { SyncIOInClient } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout renders a client component that uses sync IO. We're
simulating a browser navigation, so sync IO in client components is
fine and should not prevent us from validating.
</p>
<SyncIOInClient>{children}</SyncIOInClient>
</div>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
'use client'
import { use } from 'react'
import { useDataCache } from '../../../../client-data-fetching-lib/client'
export function FetchesClientData() {
const dataCache = useDataCache()
const promise = dataCache.getOrLoad('my-key', async () => {
await new Promise<void>((resolve) => setTimeout(resolve, 10))
return 'My client data result'
})
const data = use(promise)
return <div>Got client data: "{data}"</div>
}
import type { ReactNode } from 'react'
import { FetchesClientData } from './client'
import { DataCacheProvider } from '../../../../client-data-fetching-lib/server'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<DataCacheProvider>
<div>
<p>
This layout renders a client component that suspends in SSR, but it
doesn't not block the children, so we can still validate them.
</p>
<FetchesClientData />
</div>
<hr />
{children}
</DataCacheProvider>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>
This page is static, so it should pass instant validation, but client
data fetching above will prevent us from validating it.
</p>
</main>
)
}
'use client'
export function ErrorInSSR() {
if (typeof window === 'undefined') {
throw new Error('No SSR please')
}
return null
}
import { Suspense, type ReactNode } from 'react'
import { ErrorInSSR } from './client'
// Make sure that the holes from this layout aren't factored in for validation
// (otherwise, we'd check a navigation into it from the root layout and fail)
export const unstable_instant = false
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<div>
<p>
This layout errors in SSR, but the error is wrapped in Suspense and
does not block the children slot, so it does not prevent us from
validating the page.
</p>
<Suspense>
<ErrorInSSR />
</Suspense>
{children}
</div>
</>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return (
<main>
<p>This page is static, so it should pass instant validation</p>
</main>
)
}
import 'client-only'
import { use } from 'react'
import { CacheIdentifierContext } from './internal-context'
export interface CacheIdentifier {}
const cacheById = new WeakMap<CacheIdentifier, DataCache>()
export type DataCache = Map<string, Promise<unknown>>
function createDataCache(): DataCache {
return new Map()
}
export function useDataCache() {
const id = use(CacheIdentifierContext)
if (id === null) {
throw new Error('Missing DataCacheProvider')
}
let cache = cacheById.get(id)
if (!cache) {
cacheById.set(id, (cache = createDataCache()))
}
return {
getOrLoad<T>(key: string, func: () => Promise<T>): Promise<T> {
let promise = cache.get(key) as Promise<T> | undefined
if (!promise) {
console.log('client-data-fetching-lib :: MISS', key)
cache.set(key, (promise = func()))
} else {
console.log('client-data-fetching-lib :: HIT', key)
}
return promise
},
}
}
'use client'
import { createContext } from 'react'
import type { CacheIdentifier } from './client'
export const CacheIdentifierContext = createContext<CacheIdentifier | null>(
null
)
import 'server-only'
import { CacheIdentifierContext } from './internal-context'
export function DataCacheProvider({ children }) {
// This object is used as a key a WeakMap of caches.
// This is a trick to make sure each SSR render gets a separate cache
// without worrying about client state getting reset due to suspense.
//
// It'll be a unique object every time we deserialize this RSC payload,
// so each client render gets a separate id and thus a separate cache.
const id = {}
return <CacheIdentifierContext value={id}>{children}</CacheIdentifierContext>
}
...@@ -72,7 +72,7 @@ interface ErrorSnapshotOptions { ...@@ -72,7 +72,7 @@ interface ErrorSnapshotOptions {
label?: boolean label?: boolean
} }
interface ErrorSnapshot { export interface ErrorSnapshot {
environmentLabel: string | null environmentLabel: string | null
label: string | null label: string | null
description: string | null description: string | null
...@@ -201,9 +201,9 @@ async function createErrorSnapshot( ...@@ -201,9 +201,9 @@ async function createErrorSnapshot(
return snapshot return snapshot
} }
type RedboxSnapshot = ErrorSnapshot | ErrorSnapshot[] export type RedboxSnapshot = ErrorSnapshot | ErrorSnapshot[]
async function createRedboxSnapshot( export async function createRedboxSnapshot(
browser: Playwright, browser: Playwright,
next: NextInstance | null, next: NextInstance | null,
opts?: ErrorSnapshotOptions opts?: ErrorSnapshotOptions
......
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