Unverified Commit 9fce25a5 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Instant] Don't block on client APIs that wouldn't block in the browser (#89924)

Closes NAR-778
parent df247d1b
......@@ -1058,5 +1058,11 @@
"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"
"1060": "Missing boundary tracking state",
"1061": "createPrerenderSearchParamsForClientPage should not be called in a client validation.",
"1062": "\\`import('next/root-params').%s()\\` must not be used within a client component. Next.js should be preventing \\`import('next/root-params').%s()\\` from being included in client components statically, but did not in this case.",
"1063": "`connection` must not be used within a Client Component. Next.js should be preventing `connection` from being included in Client Components statically, but did not in this case.",
"1064": "createServerParamsForRoute should not be called in client contexts.",
"1065": "createServerPathnameForMetadata should not be called in client contexts.",
"1066": "createServerSearchParamsForServerPage should not be called in a client validation."
}
......@@ -23,6 +23,9 @@ function hasFallbackRouteParams(): boolean {
case 'prerender-ppr':
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':
......
......@@ -17,8 +17,10 @@ import {
type WorkStore,
} from '../app-render/work-async-storage.external'
import type {
PrerenderStoreModernClient,
PrerenderStoreModernRuntime,
RequestStore,
ValidationStoreClient,
} from '../app-render/work-unit-async-storage.external'
import type { NextParsedUrlQuery } from '../request-meta'
import type { LoaderTree } from '../lib/app-dir-module'
......@@ -1946,6 +1948,7 @@ async function renderToHTMLOrFlightImpl(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'cache':
case 'private-cache':
......@@ -3747,6 +3750,8 @@ async function spawnStaticShellValidationInDev(
await warmupClientModulesForStagedValidationInDev(
// 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.
needsInstantValidation ? 'validation-client' : 'prerender-client',
needsInstantValidation ? dynamicChunks : runtimeChunks,
dynamicChunks,
rootParams,
......@@ -3804,8 +3809,6 @@ async function spawnStaticShellValidationInDev(
debugChunks,
startTime,
rootParams,
fallbackRouteParams,
allowEmptyStaticShell,
ctx,
hmrRefreshHash
)
......@@ -3816,6 +3819,7 @@ async function spawnStaticShellValidationInDev(
}
async function warmupClientModulesForStagedValidationInDev(
storeType: PrerenderStoreModernClient['type'] | ValidationStoreClient['type'],
partialServerChunks: Array<Uint8Array>,
allServerChunks: Array<Uint8Array>,
rootParams: Params,
......@@ -3833,29 +3837,59 @@ async function warmupClientModulesForStagedValidationInDev(
const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const initialClientPrerenderStore: PrerenderStore = {
type: 'prerender-client',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: initialClientRenderController.signal,
controller: initialClientPrerenderController,
// For HTML Generation the only cache tracked activity
// is module loading, which has it's own cache signal
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
// TODO should this be removed from client stores?
prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash: undefined,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
let initialClientPrerenderStore: PrerenderStore
if (storeType === 'prerender-client') {
const store: PrerenderStoreModernClient = {
type: 'prerender-client',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: initialClientRenderController.signal,
controller: initialClientPrerenderController,
// For HTML Generation the only cache tracked activity
// is module loading, which has it's own cache signal
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
// TODO should this be removed from client stores?
prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash: undefined,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
}
initialClientPrerenderStore = store
} else {
const store: ValidationStoreClient = {
type: 'validation-client',
phase: 'render',
rootParams,
implicitTags,
renderSignal: initialClientRenderController.signal,
controller: initialClientPrerenderController,
// For HTML Generation the only cache tracked activity
// is module loading, which has it's own cache signal
cacheSignal: null,
dynamicTracking: null,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
// TODO should this be removed from client stores?
prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash: undefined,
// Client prerenders don't track server param access
varyParamsAccumulator: null,
// We're not rendering any validation boundaries yet.
boundaryState: null,
}
initialClientPrerenderStore = store
}
// TODO: maybe conditionally switch between runtime chunks and all chunks?
......@@ -4128,8 +4162,6 @@ async function validateInstantConfigs(
debugChunks: null | Array<Uint8Array>,
startTime: number,
rootParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
allowEmptyStaticShell: boolean,
ctx: AppRenderContext,
hmrRefreshHash: string | undefined
): Promise<Array<unknown>> {
......@@ -4202,8 +4234,6 @@ async function validateInstantConfigs(
startTime,
stageEndTimes,
rootParams,
fallbackRouteParams,
allowEmptyStaticShell,
ctx,
hmrRefreshHash,
validationRouteTree,
......@@ -4223,8 +4253,6 @@ async function validateInstantConfigs(
startTime,
stageEndTimes,
rootParams,
fallbackRouteParams,
allowEmptyStaticShell,
ctx,
hmrRefreshHash,
validationRouteTree,
......@@ -4257,8 +4285,6 @@ async function validateInstantConfigNavigation(
startTime: number,
stageEndTimes: InstantValidation.StageEndTimes,
rootParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
allowEmptyStaticShell: boolean,
ctx: AppRenderContext,
hmrRefreshHash: string | undefined,
routeTree: InstantValidation.RouteTree,
......@@ -4283,17 +4309,15 @@ async function validateInstantConfigNavigation(
const boundaryState = createValidationBoundaryTracking()
const finalClientPrerenderStore: PrerenderStore = {
type: 'prerender-client',
type: 'validation-client',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: clientRenderController.signal,
controller: clientReactController,
// No APIs require a cacheSignal through the workUnitStore during the HTML prerender
cacheSignal: null,
dynamicTracking: clientDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
......
......@@ -315,6 +315,7 @@ async function createComponentTreeInternal(
case 'cache':
case 'private-cache':
case 'prerender-client':
case 'validation-client':
case 'unstable-cache':
break
default:
......
......@@ -26,6 +26,7 @@ import type {
PrerenderStoreLegacy,
PrerenderStoreModern,
PrerenderStoreModernRuntime,
ValidationStoreClient,
} from '../app-render/work-unit-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly
......@@ -243,6 +244,7 @@ export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {
case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client':
case 'validation-client':
break
case 'request':
if (process.env.NODE_ENV !== 'production') {
......@@ -555,6 +557,7 @@ export function createHangingInputAbortSignal(
return controller.signal
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......@@ -569,7 +572,7 @@ export function createHangingInputAbortSignal(
export function annotateDynamicAccess(
expression: string,
prerenderStore: PrerenderStoreModern
prerenderStore: PrerenderStoreModern | ValidationStoreClient
) {
const dynamicTracking = prerenderStore.dynamicTracking
if (dynamicTracking) {
......@@ -625,6 +628,9 @@ 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':
......@@ -649,6 +655,9 @@ export function useDynamicSearchParams(expression: string) {
}
switch (workUnitStore.type) {
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
return
case 'prerender-client': {
React.use(
makeHangingPromise(
......
......@@ -298,6 +298,7 @@ export async function decryptActionBoundArgs(
}
break
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......
......@@ -10,9 +10,10 @@ function getValidationBoundaryTracking(): ValidationBoundaryTracking | null {
const store = workUnitAsyncStorage.getStore()
if (!store) return null
switch (store.type) {
case 'prerender-client':
return store.boundaryState ?? null
case 'validation-client':
return store.boundaryState
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
......
......@@ -114,6 +114,7 @@ export function getFlightStream<T>(
switch (workUnitStore.type) {
case 'prerender-client':
case 'validation-client':
const responseOnNextTick = new Promise<T>((resolve) => {
process.nextTick(() => {
resolve(newResponse)
......
......@@ -132,6 +132,7 @@ export function createVaryParamsAccumulator(): VaryParamsAccumulator | null {
case 'cache':
case 'private-cache':
case 'prerender-client':
case 'validation-client':
case 'unstable-cache':
break
default:
......@@ -159,6 +160,7 @@ export function getMetadataVaryParamsAccumulator(): VaryParamsAccumulator | null
case 'cache':
case 'private-cache':
case 'prerender-client':
case 'validation-client':
case 'unstable-cache':
return null
default:
......@@ -205,6 +207,7 @@ export function getRootParamsVaryParamsAccumulator(): VaryParamsAccumulator | nu
case 'cache':
case 'private-cache':
case 'prerender-client':
case 'validation-client':
case 'unstable-cache':
return null
default:
......
......@@ -102,18 +102,25 @@ export type PrerenderStoreModern =
| PrerenderStoreModernClient
| PrerenderStoreModernServer
| PrerenderStoreModernRuntime
| ValidationStoreClient
/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */
export type StaticPrerenderStoreModern = Exclude<
PrerenderStoreModern,
PrerenderStoreModernRuntime
PrerenderStoreModernRuntime | ValidationStoreClient
>
export interface PrerenderStoreModernClient
extends PrerenderStoreModernCommon,
StaticPrerenderStoreCommon {
readonly type: 'prerender-client'
readonly boundaryState?: ValidationBoundaryTracking
}
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.
}
export interface PrerenderStoreModernServer
......@@ -264,7 +271,7 @@ export type PrerenderStore =
// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */
export type StaticPrerenderStore = Exclude<
PrerenderStore,
PrerenderStoreModernRuntime
PrerenderStoreModernRuntime | ValidationStoreClient
>
export interface CommonCacheStore
......@@ -351,6 +358,7 @@ export function getPrerenderResumeDataCache(
case 'prerender-ppr':
return workUnitStore.prerenderResumeDataCache
case 'prerender-client':
case 'validation-client':
// TODO eliminate fetch caching in client scope and stop exposing this data
// cache during SSR.
return workUnitStore.prerenderResumeDataCache
......@@ -379,6 +387,7 @@ export function getRenderResumeDataCache(
case 'prerender':
case 'prerender-runtime':
case 'prerender-client':
case 'validation-client':
if (workUnitStore.renderResumeDataCache) {
// If we are in a prerender, we might have a render resume data cache
// that is used to read from prefilled caches.
......@@ -412,6 +421,7 @@ export function getHmrRefreshHash(
case 'request':
return workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
......@@ -433,6 +443,7 @@ export function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {
return workUnitStore.isHmrRefresh ?? false
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
......@@ -457,6 +468,7 @@ export function getServerComponentsHmrCache(
return workUnitStore.serverComponentsHmrCache
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
......@@ -487,6 +499,7 @@ export function getDraftModeProviderForCacheScope(
return workUnitStore.draftMode
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
break
......@@ -504,6 +517,7 @@ export function getCacheSignal(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
return workUnitStore.cacheSignal
case 'request': {
......
......@@ -364,6 +364,7 @@ export function createPatchedFetcher(
case 'prerender-runtime':
// TODO: Stop accumulating tags in client prerender. (fallthrough)
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
......@@ -404,6 +405,7 @@ export function createPatchedFetcher(
break
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
......@@ -560,6 +562,8 @@ export function createPatchedFetcher(
workStore.route,
'fetch()'
)
case 'validation-client':
break
case 'request':
if (
process.env.NODE_ENV === 'development' &&
......@@ -677,6 +681,12 @@ export function createPatchedFetcher(
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
// If we're in an instant validation, a dynamic fetch won't
// have time to resolve during the validation prerender anyway,
// so we leave it hanging. This can cause false negatives in shared parents,
// but we accept that for now, because client data fetching is non-idiomatic.
// eslint-disable-next-line no-fallthrough
case 'validation-client':
if (cacheSignal) {
cacheSignal.endRead()
cacheSignal = null
......@@ -744,6 +754,7 @@ export function createPatchedFetcher(
break
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
......@@ -864,6 +875,7 @@ export function createPatchedFetcher(
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
return createCachedPrerenderResponse(
res,
......@@ -960,6 +972,7 @@ export function createPatchedFetcher(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
// We sometimes use the cache to dedupe fetches that do not
// specify a cache configuration. In these cases we want to
......@@ -1083,6 +1096,7 @@ export function createPatchedFetcher(
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'validation-client':
if (cacheSignal) {
cacheSignal.endRead()
cacheSignal = null
......@@ -1137,6 +1151,7 @@ export function createPatchedFetcher(
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'validation-client':
return makeHangingPromise<Response>(
workUnitStore.renderSignal,
workStore.route,
......
......@@ -228,6 +228,7 @@ function patchConsoleMethod(methodName: InterceptableConsoleMethod): void {
// to create a cache scope for arbitrary computation and can move over to cacheSignal exclusively.
// fallthrough
case 'prerender-client':
case 'validation-client': {
// This is a react-dom/server render and won't have a cacheSignal until React adds this for the client world.
const renderSignal = workUnitStore.renderSignal
if (renderSignal.aborted) {
......@@ -242,6 +243,7 @@ function patchConsoleMethod(methodName: InterceptableConsoleMethod): void {
args
)
}
}
// intentional fallthrough
case 'prerender-legacy':
case 'prerender-ppr':
......
......@@ -142,6 +142,7 @@ export function io(expression: string, type: ApiType) {
}
}
break
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
......
......@@ -590,6 +590,7 @@ function filteringUnhandledRejectionHandler(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime': {
const signal = workUnitStore.renderSignal
if (signal.aborted) {
......
......@@ -15,6 +15,7 @@ import {
} from '../dynamic-rendering-utils'
import { isRequestAPICallableInsideAfter } from './utils'
import { RenderStage } from '../app-render/staged-rendering'
import { InvariantError } from '../../shared/lib/invariant-error'
/**
* This function allows you to indicate that you require an actual user Request before continuing.
......@@ -84,6 +85,14 @@ export function connection(): Promise<void> {
workStore.route,
'`connection()`'
)
case 'validation-client': {
// TODO(NAR-789): make this consistent with the actual browser behavior when we change it.
// Until then, erroring is fine.
const exportName = '`connection`'
throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
)
}
case 'prerender-ppr':
// We use React's postpone API to interrupt rendering here to create a
// dynamic hole
......@@ -124,5 +133,7 @@ export function connection(): Promise<void> {
}
// If we end up here, there was no work store or work unit store present.
// TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,
// so we always error about a missing work unit store.
throwForMissingRequestStore(callingExpression)
}
......@@ -76,6 +76,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
case 'prerender':
return makeHangingCookies(workStore, workUnitStore)
case 'prerender-client':
case 'validation-client':
const exportName = '`cookies`'
throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
......
......@@ -59,11 +59,17 @@ export function draftMode(): Promise<DraftMode> {
// Otherwise, we fall through to providing an empty draft mode.
// eslint-disable-next-line no-fallthrough
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
// Return empty draft mode
return createOrGetCachedDraftMode(null, workStore)
case 'prerender-client':
case 'validation-client': {
const exportName = '`draftMode`'
throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
)
}
default:
return workUnitStore satisfies never
......@@ -217,6 +223,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
)
}
case 'prerender-client':
case 'validation-client':
const exportName = '`draftMode`'
throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
......
......@@ -76,6 +76,7 @@ export function headers(): Promise<ReadonlyHeaders> {
)
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'private-cache':
case 'prerender-runtime':
case 'prerender-ppr':
......@@ -98,6 +99,7 @@ export function headers(): Promise<ReadonlyHeaders> {
case 'prerender':
return makeHangingHeaders(workStore, workUnitStore)
case 'prerender-client':
case 'validation-client':
const exportName = '`headers`'
throw new InvariantError(
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
......
......@@ -63,6 +63,9 @@ export function createParamsFromClient(
workUnitStore,
varyParamsAccumulator
)
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
return createRenderParamsInProd(underlyingParams)
case 'cache':
case 'private-cache':
case 'unstable-cache':
......@@ -119,7 +122,6 @@ export function createServerParamsForRoute(
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
return createStaticPrerenderParams(
......@@ -128,6 +130,11 @@ export function createServerParamsForRoute(
workUnitStore,
varyParamsAccumulator
)
case 'prerender-client':
case 'validation-client':
throw new InvariantError(
'createServerParamsForRoute should not be called in client contexts.'
)
case 'cache':
case 'private-cache':
case 'unstable-cache':
......@@ -180,6 +187,9 @@ export function createServerParamsForServerSegment(
workUnitStore,
varyParamsAccumulator
)
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
return createRenderParamsInProd(underlyingParams)
case 'cache':
case 'private-cache':
case 'unstable-cache':
......@@ -246,6 +256,9 @@ export function createPrerenderParamsForClientSegment(
}
}
break
case 'validation-client':
// TODO(instant-validation): in build, this depends on samples
break
case 'cache':
case 'private-cache':
case 'unstable-cache':
......
......@@ -9,7 +9,9 @@ import {
import {
throwInvariantForMissingStore,
workUnitAsyncStorage,
type StaticPrerenderStore,
type PrerenderStoreLegacy,
type PrerenderStoreModernServer,
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
......@@ -22,7 +24,6 @@ export function createServerPathnameForMetadata(
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': {
return createPrerenderPathname(
......@@ -31,6 +32,11 @@ export function createServerPathnameForMetadata(
workUnitStore
)
}
case 'prerender-client':
case 'validation-client':
throw new InvariantError(
'createServerPathnameForMetadata should not be called in client contexts.'
)
case 'cache':
case 'private-cache':
case 'unstable-cache':
......@@ -55,13 +61,12 @@ export function createServerPathnameForMetadata(
function createPrerenderPathname(
underlyingPathname: string,
workStore: WorkStore,
prerenderStore: StaticPrerenderStore
prerenderStore:
| PrerenderStoreLegacy
| PrerenderStorePPR
| PrerenderStoreModernServer
): Promise<string> {
switch (prerenderStore.type) {
case 'prerender-client':
throw new InvariantError(
'createPrerenderPathname was called inside a client component scope.'
)
case 'prerender': {
const fallbackParams = prerenderStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) {
......
......@@ -10,8 +10,8 @@ import {
import {
workUnitAsyncStorage,
type PrerenderStoreLegacy,
type PrerenderStoreModernServer,
type PrerenderStorePPR,
type StaticPrerenderStore,
} from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import type { ParamValue } from './params'
......@@ -65,7 +65,6 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
)
}
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy': {
return createPrerenderRootParamPromise(
......@@ -75,6 +74,12 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
apiName
)
}
case 'validation-client':
case 'prerender-client': {
throw new InvariantError(
`${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': {
......@@ -92,15 +97,13 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
function createPrerenderRootParamPromise(
paramName: string,
workStore: WorkStore,
prerenderStore: StaticPrerenderStore,
prerenderStore:
| PrerenderStorePPR
| PrerenderStoreLegacy
| PrerenderStoreModernServer,
apiName: string
): Promise<ParamValue> {
switch (prerenderStore.type) {
case 'prerender-client': {
throw new InvariantError(
`${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 'prerender':
case 'prerender-legacy':
case 'prerender-ppr':
......
......@@ -54,6 +54,9 @@ 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 'prerender-runtime':
throw new InvariantError(
'createSearchParamsFromClient should not be called in a runtime prerender.'
......@@ -103,6 +106,10 @@ export function createServerSearchParamsForServerPage(
case 'prerender-ppr':
case 'prerender-legacy':
return createStaticPrerenderSearchParams(workStore, workUnitStore)
case 'validation-client':
throw new InvariantError(
'createServerSearchParamsForServerPage should not be called in a client validation.'
)
case 'cache':
case 'private-cache':
case 'unstable-cache':
......@@ -149,6 +156,10 @@ export function createPrerenderSearchParamsForClientPage(
workStore.route,
'`searchParams`'
)
case 'validation-client':
throw new InvariantError(
'createPrerenderSearchParamsForClientPage should not be called in a client validation.'
)
case 'prerender-runtime':
throw new InvariantError(
'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'
......
......@@ -1215,6 +1215,7 @@ function trackDynamic(
workUnitStore
)
case 'prerender-client':
case 'validation-client':
throw new InvariantError(
'A client prerender store should not be used for a route handler.'
)
......
......@@ -86,6 +86,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
......
......@@ -13,6 +13,7 @@ export function cacheTag(...tags: string[]): void {
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
......
......@@ -23,6 +23,7 @@ import type {
RequestStore,
RevalidateStore,
UseCacheStore,
ValidationStoreClient,
WorkUnitStore,
} from '../app-render/work-unit-async-storage.external'
import {
......@@ -83,7 +84,7 @@ interface PublicCacheContext {
readonly kind: 'public'
// TODO: We should probably forbid nesting "use cache" inside unstable_cache.
readonly outerWorkUnitStore:
| Exclude<WorkUnitStore, PrerenderStoreModernClient>
| Exclude<WorkUnitStore, PrerenderStoreModernClient | ValidationStoreClient>
| undefined
}
......@@ -952,6 +953,7 @@ export async function cache(
workUnitStore
)
case 'prerender-client':
case 'validation-client':
throw new InvariantError(
`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being allowed in client components statically, but did not in this case.`
)
......@@ -998,6 +1000,7 @@ export async function cache(
} else {
switch (workUnitStore?.type) {
case 'prerender-client':
case 'validation-client':
const expression = '"use cache"'
throw new InvariantError(
`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being allowed in client components statically, but did not in this case.`
......@@ -1912,6 +1915,7 @@ function shouldForceRevalidate(
case 'prerender-runtime':
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
......@@ -1955,6 +1959,7 @@ function shouldDiscardCacheEntry(
return false
case 'prerender-runtime':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......
......@@ -160,6 +160,7 @@ function revalidate(
workUnitStore
)
case 'prerender-client':
case 'validation-client':
throw new InvariantError(
`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`
)
......
......@@ -195,6 +195,7 @@ export function unstable_cache<T extends Callback>(
isNestedUnstableCache = true
break
case 'prerender-client':
case 'validation-client':
case 'request':
break
default:
......@@ -409,6 +410,7 @@ function getFetchUrlPrefix(
return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
......
......@@ -34,6 +34,7 @@ export function unstable_noStore() {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
// unstable_noStore() is a noop in Dynamic I/O.
return
......
......@@ -699,77 +699,19 @@ describe('instant validation', () => {
const browser = await navigateTo(
'/suspense-in-root/static/valid-client-api-in-parent/sync-io'
)
// TODO(instant-validation) - this should be valid, but currently isn't
// await waitForNoErrorToast(browser)
await expect(browser).toDisplayCollapsedRedbox(`
[
{
"description": "Route "/suspense-in-root/static/valid-client-api-in-parent/sync-io": Could not validate \`unstable_instant\` because a Client Component in a parent segment prevented the page from rendering.",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/suspense-in-root/layout.tsx (26:9) @ Header
> 26 | <div id="root-layout-timestamp">
| ^",
"stack": [
"div <anonymous>",
"Header app/suspense-in-root/layout.tsx (26:9)",
"RootLayout app/suspense-in-root/layout.tsx (12:11)",
],
},
{
"description": "Route "/suspense-in-root/static/valid-client-api-in-parent/sync-io": Could not validate \`unstable_instant\` because a Client Component in a parent segment prevented the page from rendering.",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/suspense-in-root/static/valid-client-api-in-parent/sync-io/layout.tsx (17:9) @ Layout
> 17 | <SyncIOInClient>{children}</SyncIOInClient>
| ^",
"stack": [
"Layout app/suspense-in-root/static/valid-client-api-in-parent/sync-io/layout.tsx (17:9)",
],
},
]
`)
await waitForNoErrorToast(browser)
})
it('valid - parent uses dynamic usePathname() in a client component', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/valid-client-api-in-parent/dynamic-params/123'
)
// TODO(instant-validation) - this should be valid, but currently isn't
// await waitForNoErrorToast(browser)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Route "/suspense-in-root/static/valid-client-api-in-parent/dynamic-params/[id]": Could not validate \`unstable_instant\` because a Client Component in a parent segment prevented the page from rendering.",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/suspense-in-root/static/valid-client-api-in-parent/dynamic-params/[id]/client.tsx (6:31) @ ShouldNotSuspendDuringValidation
> 6 | const pathname = usePathname()
| ^",
"stack": [
"ShouldNotSuspendDuringValidation app/suspense-in-root/static/valid-client-api-in-parent/dynamic-params/[id]/client.tsx (6:31)",
"Layout app/suspense-in-root/static/valid-client-api-in-parent/dynamic-params/[id]/layout.tsx (18:7)",
],
}
`)
await waitForNoErrorToast(browser)
})
it('valid - parent uses useSearchPatams() in a client component', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/valid-client-api-in-parent/search-params'
)
// TODO(instant-validation) - this should be valid, but currently isn't
// await waitForNoErrorToast(browser)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Route "/suspense-in-root/static/valid-client-api-in-parent/search-params": Could not validate \`unstable_instant\` because a Client Component in a parent segment prevented the page from rendering.",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/suspense-in-root/static/valid-client-api-in-parent/search-params/layout.tsx (19:7) @ Layout
> 19 | <ShouldNotSuspendDuringValidation>
| ^",
"stack": [
"Layout app/suspense-in-root/static/valid-client-api-in-parent/search-params/layout.tsx (19:7)",
],
}
`)
await waitForNoErrorToast(browser)
})
})
......
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