Unverified Commit 43273a1d authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Instant validation for unstable_navigation() (#97309)

Adds discriminated error messages for `unstable_navigation()` used
outside of Suspense.

Previously we only had to discriminate two kinds of errors in each
validation flow:
- App Shell -- 1. link data (if it resolves in `Runtime`) or 2. dynamic
data (if it resolves in `Dynamic`)
- Static Shell -- 1. runtime data (if it resolves in `Runtime`) or 2.
dynamic data (if it resolves in `Dynamic`)

However, with `navigation()` (96908), the App Shell flow needs to
distinguish three kinds: 1. link data, 2. navigation (if it resolves in
`NavigationRuntime`), and 3. dynamic data. This complicates the
validation code a bit, because we can no longer get away with one retry.
To accommodate this, i restructured the validation code to no longer
recurse as a method of retrying. We just loop over an array that defines
what order we should try the stages in + what kind of hole shows up in
each stage.

I've also removed `hasAmbiguousErrors` and the associated logic. since
we're no longer mixing Static+Runtime segments in a runtime prefetch,
this is no longer relevant -- all segments used for validation use one
stage, so whether or not the error is ambiguous only depends on the
stage.

For ease of reviewing, this is split into two commits:
1. updating the (many) places that need a new `DynamicHoleKind` in our
error messages. This one has a lot of pretty mechanical changes, and was
also machine-reviewed for consistency already, but the messages
themselves are worth looking at (we'll also need to update docs --
leaving that for a follow-up)
2. the actual instant validation changes, i.e. using the new
`DynamicHoleKind` and adding the new pass
parent f5841365
...@@ -1490,5 +1490,9 @@ ...@@ -1490,5 +1490,9 @@
"1489": "Route %s used \\`unstable_prefetch()\\` inside a function cached with \\`unstable_cache()\\`. The \\`unstable_prefetch()\\` function is used to indicate the subsequent code must not run in the app shell, but \\`unstable_cache()\\` caches must be able to be produced before a prefetch, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache", "1489": "Route %s used \\`unstable_prefetch()\\` inside a function cached with \\`unstable_cache()\\`. The \\`unstable_prefetch()\\` function is used to indicate the subsequent code must not run in the app shell, but \\`unstable_cache()\\` caches must be able to be produced before a prefetch, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache",
"1490": "Route %s used \\`unstable_prefetch()\\` inside \\`after()\\` while rendering. The \\`unstable_prefetch()\\` function is used to indicate the subsequent code must not run in the app shell, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after", "1490": "Route %s used \\`unstable_prefetch()\\` inside \\`after()\\` while rendering. The \\`unstable_prefetch()\\` function is used to indicate the subsequent code must not run in the app shell, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1491": "Route %s used \\`unstable_prefetch()\\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents", "1491": "Route %s used \\`unstable_prefetch()\\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents",
"1492": "Route %s used \\`unstable_prefetch()\\` inside \"use cache: private\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await unstable_prefetch()\\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache" "1492": "Route %s used \\`unstable_prefetch()\\` inside \"use cache: private\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await unstable_prefetch()\\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"1493": "Route \"%s\": Next.js encountered \\`unstable_navigation()\\` in \\`generateViewport()\\`.\\n\\n\\`unstable_navigation()\\` in \\`generateViewport()\\` prevents creating a shell, leading to a slower user experience.\\n\\nWays to fix this:\\n - [static] Use a static viewport export instead of \\`generateViewport()\\`\\n - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\nLearn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime",
"1494": "Route \"%s\": Next.js encountered \\`unstable_navigation()\\` in \\`generateMetadata()\\`.\\n\\nThis route's metadata is blocked, but the rest of its content can be prefetched. \\`unstable_navigation()\\` called in \\`generateMetadata()\\` prevents it from being prefetched.\\n\\nWays to fix this:\\n - [static] Use a static metadata export instead of \\`generateMetadata()\\`\\n - [dynamic] Render a marker component that calls \\`await connection()\\` inside \\`<Suspense>\\` on the page\\n\\nLearn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime",
"1495": "Route \"%s\": Next.js encountered \\`unstable_navigation()\\` during prerendering or a navigation.\\n\\n\\`unstable_navigation()\\` called outside of \\`<Suspense>\\` may prevent the navigation from being instant, leading to a slower user experience.\\n\\nWays to fix this:\\n - [stream] Provide a placeholder with \\`<Suspense fallback={...}>\\` around the data access\\n - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\nLearn more: https://nextjs.org/docs/messages/instant-shell-url-data",
"1496": "%s segments do not unblock new data in %s prefetches"
} }
...@@ -2,14 +2,17 @@ import { ...@@ -2,14 +2,17 @@ import {
createRuntimeBodyError, createRuntimeBodyError,
createDynamicBodyError, createDynamicBodyError,
createRuntimeBodyErrorInNavigation, createRuntimeBodyErrorInNavigation,
createDynamicBodyErrorInNavigation,
createLinkBodyErrorInNavigation, createLinkBodyErrorInNavigation,
createNavigationBodyErrorInNavigation,
createDynamicBodyErrorInNavigation,
createRuntimeMetadataError, createRuntimeMetadataError,
createDynamicMetadataError,
createLinkMetadataError, createLinkMetadataError,
createNavigationMetadataError,
createDynamicMetadataError,
createRuntimeViewportError, createRuntimeViewportError,
createDynamicViewportError,
createLinkViewportError, createLinkViewportError,
createNavigationViewportError,
createDynamicViewportError,
} from '../../../../server/app-render/blocking-route-messages' } from '../../../../server/app-render/blocking-route-messages'
import { createLinkPrefetchPartialError } from '../../../../shared/lib/instant-messages' import { createLinkPrefetchPartialError } from '../../../../shared/lib/instant-messages'
import { import {
...@@ -22,6 +25,13 @@ import { ...@@ -22,6 +25,13 @@ import {
type GuidanceVariant, type GuidanceVariant,
} from './instant-guidance-data' } from './instant-guidance-data'
const GUIDANCE_VARIANTS = [
'runtime',
'link',
'navigation',
'dynamic',
] as const satisfies GuidanceVariant[]
function tagsFromMessage(message: string): string[] { function tagsFromMessage(message: string): string[] {
return Array.from(message.matchAll(/^\s*-\s*\[([a-z]+)\]/gm)).map((m) => m[1]) return Array.from(message.matchAll(/^\s*-\s*\[([a-z]+)\]/gm)).map((m) => m[1])
} }
...@@ -47,6 +57,7 @@ describe('instant-guidance-data card ordering', () => { ...@@ -47,6 +57,7 @@ describe('instant-guidance-data card ordering', () => {
'blocking-route', 'blocking-route',
'dynamic', 'dynamic',
], ],
[ [
'blocking-route runtime in navigation', 'blocking-route runtime in navigation',
createRuntimeBodyErrorInNavigation('/x').message, createRuntimeBodyErrorInNavigation('/x').message,
...@@ -54,53 +65,74 @@ describe('instant-guidance-data card ordering', () => { ...@@ -54,53 +65,74 @@ describe('instant-guidance-data card ordering', () => {
'runtime', 'runtime',
], ],
[ [
'blocking-route dynamic in navigation', 'blocking-route link in navigation',
createDynamicBodyErrorInNavigation('/x').message, createLinkBodyErrorInNavigation('/x').message,
'blocking-route', 'blocking-route',
'dynamic', 'link',
], ],
[ [
'blocking-route link', 'blocking-route navigation in navigation',
createLinkBodyErrorInNavigation('/x').message, createNavigationBodyErrorInNavigation('/x').message,
'blocking-route', 'blocking-route',
'link', 'navigation',
], ],
[
'blocking-route dynamic in navigation',
createDynamicBodyErrorInNavigation('/x').message,
'blocking-route',
'dynamic',
],
[ [
'metadata runtime', 'metadata runtime',
createRuntimeMetadataError('/x').message, createRuntimeMetadataError('/x').message,
'metadata', 'metadata',
'runtime', 'runtime',
], ],
[
'metadata dynamic',
createDynamicMetadataError('/x').message,
'metadata',
'dynamic',
],
[ [
'metadata link', 'metadata link',
createLinkMetadataError('/x').message, createLinkMetadataError('/x').message,
'metadata', 'metadata',
'link', 'link',
], ],
[
'metadata navigation',
createNavigationMetadataError('/x').message,
'metadata',
'navigation',
],
[
'metadata dynamic',
createDynamicMetadataError('/x').message,
'metadata',
'dynamic',
],
[ [
'viewport runtime', 'viewport runtime',
createRuntimeViewportError('/x').message, createRuntimeViewportError('/x').message,
'viewport', 'viewport',
'runtime', 'runtime',
], ],
[
'viewport dynamic',
createDynamicViewportError('/x').message,
'viewport',
'dynamic',
],
[ [
'viewport link', 'viewport link',
createLinkViewportError('/x').message, createLinkViewportError('/x').message,
'viewport', 'viewport',
'link', 'link',
], ],
[
'viewport navigation',
createNavigationViewportError('/x').message,
'viewport',
'navigation',
],
[
'viewport dynamic',
createDynamicViewportError('/x').message,
'viewport',
'dynamic',
],
[ [
'link-prefetch-partial', 'link-prefetch-partial',
createLinkPrefetchPartialError('/x').message, createLinkPrefetchPartialError('/x').message,
...@@ -117,17 +149,12 @@ describe('instant-guidance-data card ordering', () => { ...@@ -117,17 +149,12 @@ describe('instant-guidance-data card ordering', () => {
describe('instant-guidance-data card links', () => { describe('instant-guidance-data card links', () => {
it('every card.link ends with #card.id', () => { it('every card.link ends with #card.id', () => {
const variants: Array<[GuidanceKind, GuidanceVariant]> = [ type Item = [GuidanceKind, GuidanceVariant]
['blocking-route', 'runtime'], const variants: Array<Item> = [
['blocking-route', 'dynamic'], ...GUIDANCE_VARIANTS.map((v) => ['blocking-route', v] as Item),
['blocking-route', 'link'], ...GUIDANCE_VARIANTS.map((v) => ['metadata', v] as Item),
...GUIDANCE_VARIANTS.map((v) => ['viewport', v] as Item),
['client-hook', 'runtime'], ['client-hook', 'runtime'],
['metadata', 'runtime'],
['metadata', 'dynamic'],
['metadata', 'link'],
['viewport', 'runtime'],
['viewport', 'dynamic'],
['viewport', 'link'],
['unrendered-segment', 'runtime'], ['unrendered-segment', 'runtime'],
['link-prefetch-partial', 'runtime'], ['link-prefetch-partial', 'runtime'],
] ]
...@@ -143,20 +170,18 @@ describe('instant-guidance-data card links', () => { ...@@ -143,20 +170,18 @@ describe('instant-guidance-data card links', () => {
describe('instant-guidance-data card invariants', () => { describe('instant-guidance-data card invariants', () => {
function allCards() { function allCards() {
const cards = [] const cards = []
const variants: Array<[GuidanceKind, GuidanceVariant, string?]> = [ type Item = [GuidanceKind, GuidanceVariant, string?]
['blocking-route', 'runtime'], const variants: Array<Item> = [
['blocking-route', 'dynamic'], ...GUIDANCE_VARIANTS.map((v) => ['blocking-route', v] as Item),
['blocking-route', 'dynamic', 'connection'], ['blocking-route', 'dynamic', 'connection'],
['blocking-route', 'link'],
['client-hook', 'runtime'], ...GUIDANCE_VARIANTS.map((v) => ['metadata', v] as Item),
['metadata', 'runtime'],
['metadata', 'dynamic'],
['metadata', 'dynamic', 'connection'], ['metadata', 'dynamic', 'connection'],
['metadata', 'link'],
['viewport', 'runtime'], ...GUIDANCE_VARIANTS.map((v) => ['viewport', v] as Item),
['viewport', 'dynamic'],
['viewport', 'dynamic', 'connection'], ['viewport', 'dynamic', 'connection'],
['viewport', 'link'],
['client-hook', 'runtime'],
['unrendered-segment', 'runtime'], ['unrendered-segment', 'runtime'],
['link-prefetch-partial', 'runtime'], ['link-prefetch-partial', 'runtime'],
] ]
...@@ -214,17 +239,12 @@ describe('instant-guidance-data dispatcher', () => { ...@@ -214,17 +239,12 @@ describe('instant-guidance-data dispatcher', () => {
it('every group in FIX_CARD_GROUPS is used by at least one card', () => { it('every group in FIX_CARD_GROUPS is used by at least one card', () => {
const used = new Set<FixCardGroup>() const used = new Set<FixCardGroup>()
const variants: Array<[GuidanceKind, GuidanceVariant]> = [ type Item = [GuidanceKind, GuidanceVariant]
['blocking-route', 'runtime'], const variants: Array<Item> = [
['blocking-route', 'dynamic'], ...GUIDANCE_VARIANTS.map((v) => ['blocking-route', v] as Item),
['blocking-route', 'link'], ...GUIDANCE_VARIANTS.map((v) => ['metadata', v] as Item),
...GUIDANCE_VARIANTS.map((v) => ['viewport', v] as Item),
['client-hook', 'runtime'], ['client-hook', 'runtime'],
['metadata', 'runtime'],
['metadata', 'dynamic'],
['metadata', 'link'],
['viewport', 'runtime'],
['viewport', 'dynamic'],
['viewport', 'link'],
['unrendered-segment', 'runtime'], ['unrendered-segment', 'runtime'],
['link-prefetch-partial', 'runtime'], ['link-prefetch-partial', 'runtime'],
] ]
......
...@@ -98,6 +98,33 @@ const linkCards: FixCard[] = [ ...@@ -98,6 +98,33 @@ const linkCards: FixCard[] = [
}, },
] ]
// TODO(cache-stages): docs link
const navigationCards: FixCard[] = [
{
id: 'wrap-in-or-move-into-suspense',
title: 'Wrap in or move into Suspense',
group: 'stream',
link: 'https://nextjs.org/docs/messages/instant-shell-url-data#wrap-in-or-move-into-suspense',
snippets: [
{ text: '<Suspense fallback={…}>', highlight: true },
{ text: ' <DataChild />' },
{ text: '</Suspense>', highlight: true },
],
copyable: true,
},
{
id: 'allow-blocking-route',
title: 'Allow blocking route',
group: 'block',
link: 'https://nextjs.org/docs/messages/instant-shell-url-data#allow-blocking-route',
snippets: [
{ text: '// page.tsx or layout.tsx' },
{ text: 'export const instant = false', highlight: true },
],
copyable: true,
},
]
const runtimeCards: FixCard[] = [ const runtimeCards: FixCard[] = [
{ {
id: 'wrap-in-or-move-into-suspense', id: 'wrap-in-or-move-into-suspense',
...@@ -293,6 +320,33 @@ const metadataRuntimeCards: FixCard[] = [ ...@@ -293,6 +320,33 @@ const metadataRuntimeCards: FixCard[] = [
}, },
] ]
// TODO(cache-stages): docs link
const metadataNavigationCards: FixCard[] = [
{
id: 'use-static-metadata',
title: 'Use static metadata',
group: 'static',
link: 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata',
snippets: [
{ text: 'export const metadata = {', highlight: true },
{ text: ' title: "My Page"' },
{ text: '}' },
],
copyable: true,
},
{
id: 'mark-the-route-as-dynamic',
title: 'Mark the route as dynamic',
group: 'dynamic',
link: 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#mark-the-route-as-dynamic',
snippets: [
{ text: '// page.tsx or layout.tsx' },
{ text: 'await connection()', highlight: true },
],
copyable: true,
},
]
// URL data in `generateMetadata()` shares the same fixes as runtime data. // URL data in `generateMetadata()` shares the same fixes as runtime data.
const metadataLinkCards = metadataRuntimeCards const metadataLinkCards = metadataRuntimeCards
...@@ -348,6 +402,33 @@ const viewportRuntimeCards: FixCard[] = [ ...@@ -348,6 +402,33 @@ const viewportRuntimeCards: FixCard[] = [
}, },
] ]
// TODO(cache-stages): docs link
const viewportNavigationCards: FixCard[] = [
{
id: 'use-static-viewport',
title: 'Use static viewport',
group: 'static',
link: 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport',
snippets: [
{ text: 'export const viewport = {', highlight: true },
{ text: ' themeColor: "#000"' },
{ text: '}' },
],
copyable: true,
},
{
id: 'allow-blocking-route',
title: 'Allow blocking route',
group: 'block',
link: 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#allow-blocking-route',
snippets: [
{ text: '// page.tsx or layout.tsx' },
{ text: 'export const instant = false', highlight: true },
],
copyable: true,
},
]
// URL data in `generateViewport()` shares the same fixes as runtime data. // URL data in `generateViewport()` shares the same fixes as runtime data.
const viewportLinkCards = viewportRuntimeCards const viewportLinkCards = viewportRuntimeCards
...@@ -609,7 +690,7 @@ export type GuidanceKind = ...@@ -609,7 +690,7 @@ export type GuidanceKind =
| 'unrendered-segment' | 'unrendered-segment'
| 'link-prefetch-partial' | 'link-prefetch-partial'
export type GuidanceVariant = 'link' | 'runtime' | 'dynamic' export type GuidanceVariant = 'link' | 'runtime' | 'navigation' | 'dynamic'
export const DOCS_URLS: Record<GuidanceKind, string> = { export const DOCS_URLS: Record<GuidanceKind, string> = {
'blocking-route': 'https://nextjs.org/docs/messages/blocking-route', 'blocking-route': 'https://nextjs.org/docs/messages/blocking-route',
...@@ -627,6 +708,39 @@ export const DOCS_URLS: Record<GuidanceKind, string> = { ...@@ -627,6 +708,39 @@ export const DOCS_URLS: Record<GuidanceKind, string> = {
'https://nextjs.org/docs/messages/instant-link-prefetch-partial', 'https://nextjs.org/docs/messages/instant-link-prefetch-partial',
} }
export const BLOCKING_ROUTE_DOCS_URLS: Record<GuidanceVariant, string> = {
runtime: 'https://nextjs.org/docs/messages/blocking-prerender-runtime',
// TODO(app-shells): dedicated docs for link data errors (reuses runtime for now)
link: 'https://nextjs.org/docs/messages/blocking-prerender-runtime',
// TODO(cache-stages): dedicated docs for navigation errors (reuses runtime for now)
navigation: 'https://nextjs.org/docs/messages/blocking-prerender-runtime',
dynamic: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic',
}
export const BLOCKING_METADATA_DOCS_URLS: Record<GuidanceVariant, string> = {
runtime:
'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime',
// TODO(app-shells): dedicated docs for link data errors (reuses runtime for now)
link: 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime',
// TODO(cache-stages): dedicated docs for navigation errors (reuses runtime for now)
navigation:
'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime',
dynamic:
'https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic',
}
export const BLOCKING_VIEWPORT_DOCS_URLS: Record<GuidanceVariant, string> = {
runtime:
'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime',
// TODO(app-shells): dedicated docs for link data errors (reuses runtime for now)
link: 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime',
// TODO(cache-stages): dedicated docs for navigation errors (reuses runtime for now)
navigation:
'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime',
dynamic:
'https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic',
}
export const SYNC_IO_DOCS: Record<string, string> = { export const SYNC_IO_DOCS: Record<string, string> = {
'Math.random()': 'https://nextjs.org/docs/messages/blocking-prerender-random', 'Math.random()': 'https://nextjs.org/docs/messages/blocking-prerender-random',
'Date.now()': 'Date.now()':
...@@ -701,10 +815,10 @@ export const EXPLANATIONS: Record<GuidanceKind, string> = { ...@@ -701,10 +815,10 @@ export const EXPLANATIONS: Record<GuidanceKind, string> = {
'This will lead to slower, more expensive prefetches.', 'This will lead to slower, more expensive prefetches.',
} }
export const BLOCKING_ROUTE_NAVIGATION_EXPLANATION = export const BLOCKING_ROUTE_IN_NAVIGATION_EXPLANATION =
'This prevents the navigation from being instant, leading to a slower user experience.' 'This prevents the navigation from being instant, leading to a slower user experience.'
export const BLOCKING_ROUTE_LINK_EXPLANATION = export const BLOCKING_ROUTE_BLOCKED_SHELL_EXPLANATION =
'This may prevent the navigation from being instant, leading to a slower user experience.' 'This may prevent the navigation from being instant, leading to a slower user experience.'
const syncCardsByCause: Record<string, FixCard[]> = { const syncCardsByCause: Record<string, FixCard[]> = {
...@@ -755,26 +869,50 @@ export function getCards( ...@@ -755,26 +869,50 @@ export function getCards(
cause?: string cause?: string
): FixCard[] { ): FixCard[] {
switch (kind) { switch (kind) {
case 'blocking-route': case 'blocking-route': {
return variant === 'link' switch (variant) {
? linkCards case 'link':
: variant === 'dynamic' return linkCards
? filterCacheForConnection(dynamicCards, variant, cause) case 'runtime':
: runtimeCards return runtimeCards
case 'navigation':
return navigationCards
case 'dynamic':
return filterCacheForConnection(dynamicCards, variant, cause)
default:
return variant satisfies never
}
}
case 'client-hook': case 'client-hook':
return clientHookCards return clientHookCards
case 'metadata': case 'metadata': {
return variant === 'link' switch (variant) {
? metadataLinkCards case 'link':
: variant === 'runtime' return metadataLinkCards
? metadataRuntimeCards case 'runtime':
: filterCacheForConnection(metadataDynamicCards, variant, cause) return metadataRuntimeCards
case 'viewport': case 'navigation':
return variant === 'link' return metadataNavigationCards
? viewportLinkCards case 'dynamic':
: variant === 'runtime' return filterCacheForConnection(metadataDynamicCards, variant, cause)
? viewportRuntimeCards default:
: filterCacheForConnection(viewportDynamicCards, variant, cause) return variant satisfies never
}
}
case 'viewport': {
switch (variant) {
case 'link':
return viewportLinkCards
case 'runtime':
return viewportRuntimeCards
case 'navigation':
return viewportNavigationCards
case 'dynamic':
return filterCacheForConnection(viewportDynamicCards, variant, cause)
default:
return variant satisfies never
}
}
case 'sync-io': case 'sync-io':
return (cause && syncCardsByCause[cause]) || [] return (cause && syncCardsByCause[cause]) || []
case 'sync-io-client': case 'sync-io-client':
......
...@@ -17,6 +17,9 @@ import { ExternalIcon } from '../../icons/external' ...@@ -17,6 +17,9 @@ import { ExternalIcon } from '../../icons/external'
import { CopyPromptIcon } from '../../icons/copy-prompt' import { CopyPromptIcon } from '../../icons/copy-prompt'
import { css } from '../../utils/css' import { css } from '../../utils/css'
import { import {
BLOCKING_METADATA_DOCS_URLS,
BLOCKING_ROUTE_DOCS_URLS,
BLOCKING_VIEWPORT_DOCS_URLS,
DOCS_URLS, DOCS_URLS,
EXPLANATIONS, EXPLANATIONS,
FIX_CARD_GROUPS, FIX_CARD_GROUPS,
...@@ -243,37 +246,30 @@ export function InstantGuidance({ ...@@ -243,37 +246,30 @@ export function InstantGuidance({
}) { }) {
const cards = getCards(kind, variant, cause) const cards = getCards(kind, variant, cause)
let docsUrl: string let docsUrl: string
if (kind === 'sync-io' && cause) { switch (kind) {
docsUrl = SYNC_IO_DOCS[cause] || DOCS_URLS[kind] case 'sync-io':
} else if (kind === 'sync-io-client' && cause) { docsUrl = (cause ? SYNC_IO_DOCS[cause] : undefined) ?? DOCS_URLS[kind]
docsUrl = SYNC_IO_CLIENT_DOCS[cause] || DOCS_URLS[kind] break
} else if (kind === 'blocking-route') { case 'sync-io-client':
docsUrl = docsUrl =
// TODO(app-shells): dedicated docs for link data errors (reuses runtime for now) (cause ? SYNC_IO_CLIENT_DOCS[cause] : undefined) ?? DOCS_URLS[kind]
variant === 'link' break
? 'https://nextjs.org/docs/messages/blocking-prerender-runtime' case 'blocking-route':
: variant === 'runtime' docsUrl = BLOCKING_ROUTE_DOCS_URLS[variant]
? 'https://nextjs.org/docs/messages/blocking-prerender-runtime' break
: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic' case 'metadata':
} else if (kind === 'metadata') { docsUrl = BLOCKING_METADATA_DOCS_URLS[variant]
docsUrl = break
// TODO(app-shells): dedicated docs for link data errors (reuses runtime for now) case 'viewport':
variant === 'link' docsUrl = BLOCKING_VIEWPORT_DOCS_URLS[variant]
? 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime' break
: variant === 'runtime' case 'client-hook':
? 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime' case 'unrendered-segment':
: 'https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic' case 'link-prefetch-partial':
} else if (kind === 'viewport') { docsUrl = DOCS_URLS[kind]
docsUrl = break
// TODO(app-shells): dedicated docs for link data errors (reuses runtime for now)
variant === 'link'
? 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime'
: variant === 'runtime'
? 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime'
: 'https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic'
} else {
docsUrl = DOCS_URLS[kind]
} }
const defaultExplanation = explanation || EXPLANATIONS[kind] const defaultExplanation = explanation || EXPLANATIONS[kind]
return ( return (
...@@ -315,29 +311,11 @@ export function InstantHeaderExplanation({ ...@@ -315,29 +311,11 @@ export function InstantHeaderExplanation({
const resolvedExplanation = explanation || (kind ? EXPLANATIONS[kind] : '') const resolvedExplanation = explanation || (kind ? EXPLANATIONS[kind] : '')
let resolvedDocsUrl = docsUrl let resolvedDocsUrl = docsUrl
if (!resolvedDocsUrl && kind === 'blocking-route') { if (!resolvedDocsUrl && kind === 'blocking-route') {
resolvedDocsUrl = resolvedDocsUrl = BLOCKING_ROUTE_DOCS_URLS[variant ?? 'dynamic']
// TODO(app-shells): dedicated docs for link data errors (reuses runtime for now)
variant === 'link'
? 'https://nextjs.org/docs/messages/blocking-prerender-runtime'
: variant === 'runtime'
? 'https://nextjs.org/docs/messages/blocking-prerender-runtime'
: 'https://nextjs.org/docs/messages/blocking-prerender-dynamic'
} else if (!resolvedDocsUrl && kind === 'metadata') { } else if (!resolvedDocsUrl && kind === 'metadata') {
resolvedDocsUrl = resolvedDocsUrl = BLOCKING_METADATA_DOCS_URLS[variant ?? 'dynamic']
// TODO(app-shells): dedicated docs for link data errors (reuses runtime for now)
variant === 'link'
? 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime'
: variant === 'runtime'
? 'https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime'
: 'https://nextjs.org/docs/messages/blocking-prerender-metadata-dynamic'
} else if (!resolvedDocsUrl && kind === 'viewport') { } else if (!resolvedDocsUrl && kind === 'viewport') {
resolvedDocsUrl = resolvedDocsUrl = BLOCKING_VIEWPORT_DOCS_URLS[variant ?? 'dynamic']
// TODO(app-shells): dedicated docs for link data errors (reuses runtime for now)
variant === 'link'
? 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime'
: variant === 'runtime'
? 'https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime'
: 'https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic'
} else if (!resolvedDocsUrl && kind) { } else if (!resolvedDocsUrl && kind) {
resolvedDocsUrl = DOCS_URLS[kind] resolvedDocsUrl = DOCS_URLS[kind]
} }
......
...@@ -13,6 +13,9 @@ import { ...@@ -13,6 +13,9 @@ import {
createLinkBodyErrorInNavigation, createLinkBodyErrorInNavigation,
createLinkMetadataError, createLinkMetadataError,
createLinkViewportError, createLinkViewportError,
createNavigationBodyErrorInNavigation,
createNavigationMetadataError,
createNavigationViewportError,
} from '../../../server/app-render/blocking-route-messages' } from '../../../server/app-render/blocking-route-messages'
import { import {
createSyncIOClientError, createSyncIOClientError,
...@@ -37,25 +40,6 @@ const ROUTE = '/example' ...@@ -37,25 +40,6 @@ const ROUTE = '/example'
describe('getGuidanceVariant', () => { describe('getGuidanceVariant', () => {
describe('classifies runtime messages as runtime', () => { describe('classifies runtime messages as runtime', () => {
describe('classifies link messages as link', () => {
it.each([
{
description: 'body',
error: () => createLinkBodyErrorInNavigation(ROUTE),
},
{
description: 'metadata',
error: () => createLinkMetadataError(ROUTE),
},
{
description: 'viewport',
error: () => createLinkViewportError(ROUTE),
},
])('$description', ({ error }) => {
expect(getGuidanceVariant(error().message)).toBe('link')
})
})
it.each([ it.each([
{ description: 'body', error: () => createRuntimeBodyError(ROUTE) }, { description: 'body', error: () => createRuntimeBodyError(ROUTE) },
{ {
...@@ -75,6 +59,44 @@ describe('getGuidanceVariant', () => { ...@@ -75,6 +59,44 @@ describe('getGuidanceVariant', () => {
}) })
}) })
describe('classifies link messages as link', () => {
it.each([
{
description: 'body',
error: () => createLinkBodyErrorInNavigation(ROUTE),
},
{
description: 'metadata',
error: () => createLinkMetadataError(ROUTE),
},
{
description: 'viewport',
error: () => createLinkViewportError(ROUTE),
},
])('$description', ({ error }) => {
expect(getGuidanceVariant(error().message)).toBe('link')
})
})
describe('classifies navigation messages as navigation', () => {
it.each([
{
description: 'body',
error: () => createNavigationBodyErrorInNavigation(ROUTE),
},
{
description: 'metadata',
error: () => createNavigationMetadataError(ROUTE),
},
{
description: 'viewport',
error: () => createNavigationViewportError(ROUTE),
},
])('$description', ({ error }) => {
expect(getGuidanceVariant(error().message)).toBe('navigation')
})
})
describe('classifies dynamic messages as dynamic', () => { describe('classifies dynamic messages as dynamic', () => {
it.each([ it.each([
{ description: 'body', error: () => createDynamicBodyError(ROUTE) }, { description: 'body', error: () => createDynamicBodyError(ROUTE) },
...@@ -222,6 +244,16 @@ describe('getBlockingRouteErrorDetails', () => { ...@@ -222,6 +244,16 @@ describe('getBlockingRouteErrorDetails', () => {
}) })
}) })
it('classifies createNavigationBodyErrorInNavigation as blocking-route + navigation + inNavigation', () => {
expect(
getBlockingRouteErrorDetails(createNavigationBodyErrorInNavigation(ROUTE))
).toEqual({
type: 'blocking-route',
variant: 'navigation',
inNavigation: true,
})
})
it('classifies createDynamicOrRuntimeBodyError as blocking-route + dynamic (SSR-only)', () => { it('classifies createDynamicOrRuntimeBodyError as blocking-route + dynamic (SSR-only)', () => {
// The "either" factory has no clear runtime signal — falls into the // The "either" factory has no clear runtime signal — falls into the
// dynamic branch by `isRuntimeVariant`. Documents current behavior. // dynamic branch by `isRuntimeVariant`. Documents current behavior.
...@@ -240,6 +272,18 @@ describe('getBlockingRouteErrorDetails', () => { ...@@ -240,6 +272,18 @@ describe('getBlockingRouteErrorDetails', () => {
).toEqual({ type: 'dynamic-metadata', variant: 'runtime' }) ).toEqual({ type: 'dynamic-metadata', variant: 'runtime' })
}) })
it('classifies createLinkMetadataError as dynamic-metadata + link', () => {
expect(
getBlockingRouteErrorDetails(createLinkMetadataError(ROUTE))
).toEqual({ type: 'dynamic-metadata', variant: 'link' })
})
it('classifies createNavigationMetadataError as dynamic-metadata + navigation', () => {
expect(
getBlockingRouteErrorDetails(createNavigationMetadataError(ROUTE))
).toEqual({ type: 'dynamic-metadata', variant: 'navigation' })
})
it('classifies createDynamicMetadataError as dynamic-metadata + dynamic', () => { it('classifies createDynamicMetadataError as dynamic-metadata + dynamic', () => {
expect( expect(
getBlockingRouteErrorDetails(createDynamicMetadataError(ROUTE)) getBlockingRouteErrorDetails(createDynamicMetadataError(ROUTE))
...@@ -258,6 +302,18 @@ describe('getBlockingRouteErrorDetails', () => { ...@@ -258,6 +302,18 @@ describe('getBlockingRouteErrorDetails', () => {
).toEqual({ type: 'dynamic-viewport', variant: 'runtime' }) ).toEqual({ type: 'dynamic-viewport', variant: 'runtime' })
}) })
it('classifies createLinkViewportError as dynamic-viewport + link', () => {
expect(
getBlockingRouteErrorDetails(createLinkViewportError(ROUTE))
).toEqual({ type: 'dynamic-viewport', variant: 'link' })
})
it('classifies createNavigationViewportError as dynamic-viewport + navigation', () => {
expect(
getBlockingRouteErrorDetails(createNavigationViewportError(ROUTE))
).toEqual({ type: 'dynamic-viewport', variant: 'navigation' })
})
it('classifies createDynamicViewportError as dynamic-viewport + dynamic', () => { it('classifies createDynamicViewportError as dynamic-viewport + dynamic', () => {
expect( expect(
getBlockingRouteErrorDetails(createDynamicViewportError(ROUTE)) getBlockingRouteErrorDetails(createDynamicViewportError(ROUTE))
......
...@@ -35,8 +35,8 @@ import { ...@@ -35,8 +35,8 @@ import {
type GuidanceVariant, type GuidanceVariant,
} from '../components/instant/instant-guidance' } from '../components/instant/instant-guidance'
import { import {
BLOCKING_ROUTE_NAVIGATION_EXPLANATION, BLOCKING_ROUTE_IN_NAVIGATION_EXPLANATION,
BLOCKING_ROUTE_LINK_EXPLANATION, BLOCKING_ROUTE_BLOCKED_SHELL_EXPLANATION,
} from '../components/instant/instant-guidance-data' } from '../components/instant/instant-guidance-data'
import { UnrenderedSegmentInfo } from '../components/instant/unrendered-segment-info' import { UnrenderedSegmentInfo } from '../components/instant/unrendered-segment-info'
import { CodeFrame } from '../components/code-frame/code-frame' import { CodeFrame } from '../components/code-frame/code-frame'
...@@ -353,9 +353,12 @@ function InstantRuntimeError({ ...@@ -353,9 +353,12 @@ function InstantRuntimeError({
} }
export function getGuidanceVariant(message: string): GuidanceVariant { export function getGuidanceVariant(message: string): GuidanceVariant {
// Discriminates between `createLinkBodyErrorInNavigation`, // Discriminates between `createNavigationBodyErrorInNavigation`,
// `createRuntimeBodyError`, and `createDynamicBodyError` (and their // `createLinkBodyErrorInNavigation`, `createRuntimeBodyError`, and
// in-navigation variants). // `createDynamicBodyError` (and their in-navigation variants).
if (message.includes('encountered `unstable_navigation()`')) {
return 'navigation'
}
if ( if (
message.includes('encountered URL data') && message.includes('encountered URL data') &&
!message.includes('encountered uncached data') !message.includes('encountered uncached data')
...@@ -859,31 +862,47 @@ export function Errors({ ...@@ -859,31 +862,47 @@ export function Errors({
) )
} }
break break
case 'blocking-route': case 'blocking-route': {
switch (errorDetails.variant) {
case 'runtime':
errorMessage = errorDetails.inNavigation
? 'Next.js encountered runtime data during a navigation.'
: 'Next.js encountered runtime data during prerendering.'
break
case 'link':
errorMessage = 'Next.js encountered URL data outside of Suspense.'
break
case 'navigation':
errorMessage = (
<>
Next.js encountered <code>unstable_navigation()</code> outside of
Suspense.
</>
)
break
case 'dynamic':
errorMessage = errorDetails.inNavigation
? 'Next.js encountered uncached data during a navigation.'
: 'Next.js encountered uncached data during prerendering.'
break
default:
errorMessage = errorDetails.variant satisfies never
}
return ( return (
<ErrorOverlayLayout <ErrorOverlayLayout
errorCode={errorCode} errorCode={errorCode}
errorType={errorType} errorType={errorType}
errorMessage={ errorMessage={errorMessage}
errorDetails.variant === 'link'
? 'Next.js encountered URL data outside of Suspense.'
: errorDetails.variant === 'runtime'
? errorDetails.inNavigation
? 'Next.js encountered runtime data during a navigation.'
: 'Next.js encountered runtime data during prerendering.'
: errorDetails.inNavigation
? 'Next.js encountered uncached data during a navigation.'
: 'Next.js encountered uncached data during prerendering.'
}
headerChildren={ headerChildren={
<InstantHeaderExplanation <InstantHeaderExplanation
kind="blocking-route" kind="blocking-route"
variant={errorDetails.variant} variant={errorDetails.variant}
explanation={ explanation={
errorDetails.variant === 'link' errorDetails.variant === 'link' ||
? BLOCKING_ROUTE_LINK_EXPLANATION errorDetails.variant === 'navigation'
? BLOCKING_ROUTE_BLOCKED_SHELL_EXPLANATION
: errorDetails.inNavigation : errorDetails.inNavigation
? BLOCKING_ROUTE_NAVIGATION_EXPLANATION ? BLOCKING_ROUTE_IN_NAVIGATION_EXPLANATION
: undefined : undefined
} }
/> />
...@@ -915,6 +934,7 @@ export function Errors({ ...@@ -915,6 +934,7 @@ export function Errors({
</Suspense> </Suspense>
</ErrorOverlayLayout> </ErrorOverlayLayout>
) )
}
case 'client-hook': case 'client-hook':
return ( return (
<ErrorOverlayLayout <ErrorOverlayLayout
...@@ -957,28 +977,47 @@ export function Errors({ ...@@ -957,28 +977,47 @@ export function Errors({
</Suspense> </Suspense>
</ErrorOverlayLayout> </ErrorOverlayLayout>
) )
case 'dynamic-metadata': case 'dynamic-metadata': {
switch (errorDetails.variant) {
case 'runtime':
errorMessage = (
<>
Next.js encountered runtime data in{' '}
<code>generateMetadata()</code>.
</>
)
break
case 'link':
errorMessage = (
<>
Next.js encountered URL data in <code>generateMetadata()</code>.
</>
)
break
case 'navigation':
errorMessage = (
<>
Next.js encountered <code>unstable_navigation()</code> in{' '}
<code>generateMetadata()</code>.
</>
)
break
case 'dynamic':
errorMessage = (
<>
Next.js encountered uncached data in{' '}
<code>generateMetadata()</code>.
</>
)
break
default:
errorMessage = errorDetails.variant satisfies never
}
return ( return (
<ErrorOverlayLayout <ErrorOverlayLayout
errorCode={errorCode} errorCode={errorCode}
errorType={errorType} errorType={errorType}
errorMessage={ errorMessage={errorMessage}
errorDetails.variant === 'link' ? (
<>
Next.js encountered URL data in <code>generateMetadata()</code>.
</>
) : errorDetails.variant === 'runtime' ? (
<>
Next.js encountered runtime data in{' '}
<code>generateMetadata()</code>.
</>
) : (
<>
Next.js encountered uncached data in{' '}
<code>generateMetadata()</code>.
</>
)
}
headerChildren={ headerChildren={
<InstantHeaderExplanation <InstantHeaderExplanation
kind="metadata" kind="metadata"
...@@ -1013,28 +1052,49 @@ export function Errors({ ...@@ -1013,28 +1052,49 @@ export function Errors({
</Suspense> </Suspense>
</ErrorOverlayLayout> </ErrorOverlayLayout>
) )
case 'dynamic-viewport': }
case 'dynamic-viewport': {
switch (errorDetails.variant) {
case 'link':
errorMessage = (
<>
Next.js encountered URL data in <code>generateViewport()</code>.
</>
)
break
case 'runtime':
errorMessage = (
<>
Next.js encountered runtime data in{' '}
<code>generateViewport()</code>.
</>
)
break
case 'navigation':
errorMessage = (
<>
Next.js encountered <code>unstable_navigation()</code> in{' '}
<code>generateViewport()</code>.
</>
)
break
case 'dynamic':
errorMessage = (
<>
Next.js encountered uncached data in{' '}
<code>generateViewport()</code>.
</>
)
break
default:
errorMessage = errorDetails.variant satisfies never
}
return ( return (
<ErrorOverlayLayout <ErrorOverlayLayout
errorCode={errorCode} errorCode={errorCode}
errorType={errorType} errorType={errorType}
errorMessage={ errorMessage={errorMessage}
errorDetails.variant === 'link' ? (
<>
Next.js encountered URL data in <code>generateViewport()</code>.
</>
) : errorDetails.variant === 'runtime' ? (
<>
Next.js encountered runtime data in{' '}
<code>generateViewport()</code>.
</>
) : (
<>
Next.js encountered uncached data in{' '}
<code>generateViewport()</code>.
</>
)
}
headerChildren={ headerChildren={
<InstantHeaderExplanation <InstantHeaderExplanation
kind="viewport" kind="viewport"
...@@ -1069,6 +1129,7 @@ export function Errors({ ...@@ -1069,6 +1129,7 @@ export function Errors({
</Suspense> </Suspense>
</ErrorOverlayLayout> </ErrorOverlayLayout>
) )
}
case 'sync-io': case 'sync-io':
return ( return (
<ErrorOverlayLayout <ErrorOverlayLayout
......
...@@ -43,6 +43,18 @@ export function createLinkBodyErrorInNavigation(route: string): Error { ...@@ -43,6 +43,18 @@ export function createLinkBodyErrorInNavigation(route: string): Error {
) )
} }
export function createNavigationBodyErrorInNavigation(route: string): Error {
// TODO(cache-stages): docs link
return new Error(
`Route "${route}": Next.js encountered \`unstable_navigation()\` during prerendering or a navigation.\n\n` +
`\`unstable_navigation()\` called outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.\n\n` +
`Ways to fix this:\n` +
` - [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access\n` +
` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
`Learn more: https://nextjs.org/docs/messages/instant-shell-url-data`
)
}
export function createDynamicBodyErrorInNavigation(route: string): Error { export function createDynamicBodyErrorInNavigation(route: string): Error {
return new Error( return new Error(
`Route "${route}": Next.js encountered uncached data during prerendering or a navigation.\n\n` + `Route "${route}": Next.js encountered uncached data during prerendering or a navigation.\n\n` +
...@@ -94,6 +106,18 @@ export function createRuntimeMetadataError(route: string): Error { ...@@ -94,6 +106,18 @@ export function createRuntimeMetadataError(route: string): Error {
) )
} }
export function createNavigationMetadataError(route: string): Error {
// TODO(cache-stages): docs link
return new Error(
`Route "${route}": Next.js encountered \`unstable_navigation()\` in \`generateMetadata()\`.\n\n` +
`This route's metadata is blocked, but the rest of its content can be prefetched. \`unstable_navigation()\` called in \`generateMetadata()\` prevents it from being prefetched.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
` - [dynamic] Render a marker component that calls \`await connection()\` inside \`<Suspense>\` on the page\n\n` +
`Learn more: https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime`
)
}
export function createDynamicMetadataError(route: string): Error { export function createDynamicMetadataError(route: string): Error {
return new Error( return new Error(
`Route "${route}": Next.js encountered uncached data in \`generateMetadata()\`.\n\n` + `Route "${route}": Next.js encountered uncached data in \`generateMetadata()\`.\n\n` +
...@@ -127,6 +151,18 @@ export function createRuntimeViewportError(route: string): Error { ...@@ -127,6 +151,18 @@ export function createRuntimeViewportError(route: string): Error {
) )
} }
export function createNavigationViewportError(route: string): Error {
// TODO(cache-stages): docs link
return new Error(
`Route "${route}": Next.js encountered \`unstable_navigation()\` in \`generateViewport()\`.\n\n` +
`\`unstable_navigation()\` in \`generateViewport()\` prevents creating a shell, leading to a slower user experience.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
` - [block] Set \`export const instant = false\` to allow a blocking route\n\n` +
`Learn more: https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime`
)
}
export function createDynamicViewportError(route: string): Error { export function createDynamicViewportError(route: string): Error {
return new Error( return new Error(
`Route "${route}": Next.js encountered uncached data in \`generateViewport()\`.\n\n` + `Route "${route}": Next.js encountered uncached data in \`generateViewport()\`.\n\n` +
......
...@@ -79,9 +79,9 @@ export function beginDevValidation( ...@@ -79,9 +79,9 @@ export function beginDevValidation(
* Give incoming requests a chance to enter app rendering and supersede the * Give incoming requests a chance to enter app rendering and supersede the
* current validation before another expensive render attempt starts. * current validation before another expensive render attempt starts.
* *
* The regular global `setImmediate` is patched by staged rendering and can run * @returns Whether validation should continue.
* inside the current timer task. The original immediate is required here so we * - `true`: validation should continue
* actually pass through the event-loop poll phase where HTTP requests arrive. * - `false` the validation was superseded and should be aborted.
*/ */
export async function yieldToForegroundRequest( export async function yieldToForegroundRequest(
validationSignal: AbortSignal validationSignal: AbortSignal
...@@ -90,6 +90,9 @@ export async function yieldToForegroundRequest( ...@@ -90,6 +90,9 @@ export async function yieldToForegroundRequest(
return false return false
} }
// Pass through the event-loop poll phase where HTTP requests arrive.
// Defensively use the unpatched setImmediate (even though this should never run
// in a context where setImmediate is patched, e.g. in `runInSequentialTasks`)
await new Promise<void>((resolve) => unpatchedSetImmediate(resolve)) await new Promise<void>((resolve) => unpatchedSetImmediate(resolve))
return !validationSignal.aborted return !validationSignal.aborted
} }
...@@ -51,11 +51,13 @@ import { ...@@ -51,11 +51,13 @@ import {
createRuntimeBodyError, createRuntimeBodyError,
createDynamicBodyError, createDynamicBodyError,
createRuntimeBodyErrorInNavigation, createRuntimeBodyErrorInNavigation,
createNavigationBodyErrorInNavigation,
createDynamicBodyErrorInNavigation, createDynamicBodyErrorInNavigation,
createDynamicOrRuntimeBodyError, createDynamicOrRuntimeBodyError,
createRuntimeMetadataError, createRuntimeMetadataError,
createDynamicMetadataError, createDynamicMetadataError,
createRuntimeViewportError, createRuntimeViewportError,
createNavigationViewportError,
createDynamicViewportError, createDynamicViewportError,
createDynamicOrRuntimeViewportError, createDynamicOrRuntimeViewportError,
createDynamicOrRuntimeMetadataError, createDynamicOrRuntimeMetadataError,
...@@ -63,6 +65,7 @@ import { ...@@ -63,6 +65,7 @@ import {
createLinkBodyErrorInNavigation, createLinkBodyErrorInNavigation,
createLinkMetadataError, createLinkMetadataError,
createLinkViewportError, createLinkViewportError,
createNavigationMetadataError,
} from './blocking-route-messages' } from './blocking-route-messages'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { import {
...@@ -696,12 +699,14 @@ export function trackAllowedDynamicAccess( ...@@ -696,12 +699,14 @@ export function trackAllowedDynamicAccess(
} }
export enum DynamicHoleKind { export enum DynamicHoleKind {
/** We know that this hole is caused by link data. */
Link = 1,
/** We know that this hole is caused by runtime data. */ /** We know that this hole is caused by runtime data. */
Runtime = 2, Runtime = 1,
/** We know that this hole is caused by link data. */
Link = 2,
/** We know that this hole is caused by navigation(). */
Navigation = 3,
/** We know that this hole is caused by dynamic data. */ /** We know that this hole is caused by dynamic data. */
Dynamic = 3, Dynamic = 4,
} }
/** Stores dynamic reasons used during an SSR render in instant validation. */ /** Stores dynamic reasons used during an SSR render in instant validation. */
...@@ -760,11 +765,7 @@ export function trackDynamicHoleInNavigation( ...@@ -760,11 +765,7 @@ export function trackDynamicHoleInNavigation(
if (hasMetadataRegex.test(componentStack)) { if (hasMetadataRegex.test(componentStack)) {
const error = addErrorContext( const error = addErrorContext(
kind === DynamicHoleKind.Link createMetadataError(kind, workStore.route),
? createLinkMetadataError(workStore.route)
: kind === DynamicHoleKind.Runtime
? createRuntimeMetadataError(workStore.route)
: createDynamicMetadataError(workStore.route),
componentStack, componentStack,
effectiveCreateInstantStack effectiveCreateInstantStack
) )
...@@ -773,11 +774,7 @@ export function trackDynamicHoleInNavigation( ...@@ -773,11 +774,7 @@ export function trackDynamicHoleInNavigation(
} }
if (hasViewportRegex.test(componentStack)) { if (hasViewportRegex.test(componentStack)) {
const error = addErrorContext( const error = addErrorContext(
kind === DynamicHoleKind.Link createViewportError(kind, workStore.route),
? createLinkViewportError(workStore.route)
: kind === DynamicHoleKind.Runtime
? createRuntimeViewportError(workStore.route)
: createDynamicViewportError(workStore.route),
componentStack, componentStack,
effectiveCreateInstantStack effectiveCreateInstantStack
) )
...@@ -869,11 +866,7 @@ export function trackDynamicHoleInNavigation( ...@@ -869,11 +866,7 @@ export function trackDynamicHoleInNavigation(
} }
const error = addErrorContext( const error = addErrorContext(
kind === DynamicHoleKind.Link createBodyErrorInNavigation(kind, workStore.route),
? createLinkBodyErrorInNavigation(workStore.route)
: kind === DynamicHoleKind.Runtime
? createRuntimeBodyErrorInNavigation(workStore.route)
: createDynamicBodyErrorInNavigation(workStore.route),
componentStack, componentStack,
effectiveCreateInstantStack effectiveCreateInstantStack
) )
...@@ -881,6 +874,48 @@ export function trackDynamicHoleInNavigation( ...@@ -881,6 +874,48 @@ export function trackDynamicHoleInNavigation(
return return
} }
function createBodyErrorInNavigation(
kind: DynamicHoleKind,
route: string
): Error {
switch (kind) {
case DynamicHoleKind.Runtime:
return createRuntimeBodyErrorInNavigation(route)
case DynamicHoleKind.Link:
return createLinkBodyErrorInNavigation(route)
case DynamicHoleKind.Navigation:
return createNavigationBodyErrorInNavigation(route)
case DynamicHoleKind.Dynamic:
return createDynamicBodyErrorInNavigation(route)
}
}
function createMetadataError(kind: DynamicHoleKind, route: string): Error {
switch (kind) {
case DynamicHoleKind.Runtime:
return createRuntimeMetadataError(route)
case DynamicHoleKind.Link:
return createLinkMetadataError(route)
case DynamicHoleKind.Navigation:
return createNavigationMetadataError(route)
case DynamicHoleKind.Dynamic:
return createDynamicMetadataError(route)
}
}
function createViewportError(kind: DynamicHoleKind, route: string): Error {
switch (kind) {
case DynamicHoleKind.Runtime:
return createRuntimeViewportError(route)
case DynamicHoleKind.Link:
return createLinkViewportError(route)
case DynamicHoleKind.Navigation:
return createNavigationViewportError(route)
case DynamicHoleKind.Dynamic:
return createDynamicViewportError(route)
}
}
export function trackThrownErrorInNavigation( export function trackThrownErrorInNavigation(
workStore: WorkStore, workStore: WorkStore,
dynamicValidation: InstantValidationState, dynamicValidation: InstantValidationState,
......
...@@ -10,9 +10,12 @@ export type ValidationBoundaryTracking = { ...@@ -10,9 +10,12 @@ export type ValidationBoundaryTracking = {
renderedIds: Set<string> renderedIds: Set<string>
} }
export function createValidationBoundaryTracking(): ValidationBoundaryTracking { export function createValidationBoundaryTracking(
/** Pass if the render is expected to render the same IDs as a previous one. */
matchPrevious?: ValidationBoundaryTracking
): ValidationBoundaryTracking {
return { return {
requiredIds: new Map(), requiredIds: matchPrevious ? new Map(matchPrevious.requiredIds) : new Map(),
renderedIds: new Set(), renderedIds: new Set(),
} }
} }
......
...@@ -170,10 +170,11 @@ export type SegmentStage = ...@@ -170,10 +170,11 @@ export type SegmentStage =
| RenderStage.Static | RenderStage.Static
| RenderStage.ShellRuntime | RenderStage.ShellRuntime
| RenderStage.Runtime | RenderStage.Runtime
| RenderStage.NavigationRuntime
| RenderStage.Dynamic | RenderStage.Dynamic
/** The stages that a prefetched segment can be in. */ /** The stages that a prefetched segment can be in. */
type PrefetchedSegmentStage = Exclude<SegmentStage, RenderStage.Dynamic> export type PrefetchedSegmentStage = Exclude<SegmentStage, RenderStage.Dynamic>
export type StageChunks = Record<SegmentStage, Uint8Array[]> export type StageChunks = Record<SegmentStage, Uint8Array[]>
...@@ -206,7 +207,11 @@ export async function collectStagedSegmentData( ...@@ -206,7 +207,11 @@ export async function collectStagedSegmentData(
let partialStages: SegmentStage[] let partialStages: SegmentStage[]
switch (prefetchKind) { switch (prefetchKind) {
case ValidationPrefetchKind.Shell: { case ValidationPrefetchKind.Shell: {
partialStages = [RenderStage.ShellRuntime, RenderStage.Runtime] partialStages = [
RenderStage.ShellRuntime,
RenderStage.Runtime,
RenderStage.NavigationRuntime, // TODO(cache-stages): only if needed
]
break break
} }
case ValidationPrefetchKind.LegacySpeculative: { case ValidationPrefetchKind.LegacySpeculative: {
...@@ -282,6 +287,7 @@ async function collectSegmentDataForStage( ...@@ -282,6 +287,7 @@ async function collectSegmentDataForStage(
return 'Prerender' return 'Prerender'
case RenderStage.ShellRuntime: // TODO(app-shells) - proper environmentName case RenderStage.ShellRuntime: // TODO(app-shells) - proper environmentName
case RenderStage.Runtime: case RenderStage.Runtime:
case RenderStage.NavigationRuntime:
return 'Prefetch' return 'Prefetch'
case RenderStage.Dynamic: case RenderStage.Dynamic:
return 'Server' return 'Server'
...@@ -792,6 +798,7 @@ function createSegmentCacheItem(): SegmentCacheItem { ...@@ -792,6 +798,7 @@ function createSegmentCacheItem(): SegmentCacheItem {
[RenderStage.Static]: null, [RenderStage.Static]: null,
[RenderStage.ShellRuntime]: null, [RenderStage.ShellRuntime]: null,
[RenderStage.Runtime]: null, [RenderStage.Runtime]: null,
[RenderStage.NavigationRuntime]: null,
[RenderStage.Dynamic]: null, [RenderStage.Dynamic]: null,
} }
} }
...@@ -983,11 +990,6 @@ export function discoverValidationDepths(loaderTree: LoaderTree): number[] { ...@@ -983,11 +990,6 @@ export function discoverValidationDepths(loaderTree: LoaderTree): number[] {
*/ */
export type ValidationPayloadResult = { export type ValidationPayloadResult = {
payload: InitialRSCPayload payload: InitialRSCPayload
/** Whether errors from this payload could be ambiguous between runtime
* API access (cookies, headers) and uncached IO (connection, fetch).
* True when some segments used Static stage. False when all segments
* used Runtime stage and errors are definitively from uncached IO. */
hasAmbiguousErrors: boolean
/** Per-slot config factories indexed by slot marker index. When a /** Per-slot config factories indexed by slot marker index. When a
* boundary spans multiple parallel slots, each slot gets a marker * boundary spans multiple parallel slots, each slot gets a marker
* component in the tree. The marker's index maps to this array to * component in the tree. The marker's index maps to this array to
...@@ -1016,7 +1018,10 @@ export async function createCombinedPayloadAtDepth( ...@@ -1016,7 +1018,10 @@ export async function createCombinedPayloadAtDepth(
releaseSignal: AbortSignal, releaseSignal: AbortSignal,
boundaryState: ValidationBoundaryTracking, boundaryState: ValidationBoundaryTracking,
clientReferenceManifest: ClientReferenceManifest, clientReferenceManifest: ClientReferenceManifest,
useRuntimeStageForPartialSegments: boolean overrideStageForPartialSegments:
| null
| RenderStage.Runtime
| RenderStage.NavigationRuntime
): Promise<ValidationPayloadResult | null> { ): Promise<ValidationPayloadResult | null> {
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
if (!workStore) { if (!workStore) {
...@@ -1026,9 +1031,6 @@ export async function createCombinedPayloadAtDepth( ...@@ -1026,9 +1031,6 @@ export async function createCombinedPayloadAtDepth(
} }
const { validationLevel, route } = workStore const { validationLevel, route } = workStore
let hasStaticSegments = false
let hasRuntimeSegments = false
// Index 0 is reserved for the root config. Slot markers start at 1. // Index 0 is reserved for the root config. Slot markers start at 1.
const slotStacks: Array<(() => Error) | null> = [null] const slotStacks: Array<(() => Error) | null> = [null]
...@@ -1305,39 +1307,14 @@ export async function createCombinedPayloadAtDepth( ...@@ -1305,39 +1307,14 @@ export async function createCombinedPayloadAtDepth(
} }
let stage: PrefetchedSegmentStage let stage: PrefetchedSegmentStage
switch (prefetchKind) { switch (prefetchKind) {
case ValidationPrefetchKind.Shell: { case ValidationPrefetchKind.Shell: {
if (useRuntimeStageForPartialSegments) { stage = overrideStageForPartialSegments ?? RenderStage.ShellRuntime
stage = RenderStage.Runtime
} else {
stage = RenderStage.ShellRuntime
}
// We do not track `has{Static,Runtime}Segments` because they do not
// affect shell prefetches.
break break
} }
case ValidationPrefetchKind.LegacySpeculative: { case ValidationPrefetchKind.LegacySpeculative: {
if (useRuntimeStageForPartialSegments) { // In legacy speculative prefetches, we always use static.
stage = RenderStage.Runtime stage = overrideStageForPartialSegments ?? RenderStage.Static
} else {
// In legacy speculative prefetches, we always use static.
stage = RenderStage.Static
}
break
}
}
switch (stage) {
case RenderStage.Static: {
hasStaticSegments = true
break
}
case RenderStage.ShellRuntime: {
break
}
case RenderStage.Runtime: {
hasRuntimeSegments = true
break break
} }
} }
...@@ -1455,38 +1432,16 @@ export async function createCombinedPayloadAtDepth( ...@@ -1455,38 +1432,16 @@ export async function createCombinedPayloadAtDepth(
let headStage: PrefetchedSegmentStage let headStage: PrefetchedSegmentStage
switch (prefetchKind) { switch (prefetchKind) {
case ValidationPrefetchKind.Shell: { case ValidationPrefetchKind.Shell: {
if (useRuntimeStageForPartialSegments) { headStage = overrideStageForPartialSegments ?? RenderStage.ShellRuntime
headStage = RenderStage.Runtime
} else {
headStage = RenderStage.ShellRuntime
}
break break
} }
case ValidationPrefetchKind.LegacySpeculative: { case ValidationPrefetchKind.LegacySpeculative: {
headStage = hasRuntimeSegments ? RenderStage.Runtime : RenderStage.Static headStage = overrideStageForPartialSegments ?? RenderStage.Static
break break
} }
} }
debug?.(` /_head - ${RenderStage[headStage]}`) debug?.(` /_head - ${RenderStage[headStage]}`)
let hasAmbiguousErrors: boolean
switch (prefetchKind) {
case ValidationPrefetchKind.Shell: {
// In a shell prefetch, holes are always ambiguous
// (they can be either link data or dynamic data)
// unless we're already overriding and using the runtime stage,
// which resolves link data.
hasAmbiguousErrors = !useRuntimeStageForPartialSegments
break
}
case ValidationPrefetchKind.LegacySpeculative: {
// In the old prefetching mechanism, holes in static segments are ambiguous
// (they can be either runtime data or dynamic data).
hasAmbiguousErrors = hasStaticSegments
break
}
}
const head = await createValidationHead( const head = await createValidationHead(
cache, cache,
releaseSignal, releaseSignal,
...@@ -1508,7 +1463,6 @@ export async function createCombinedPayloadAtDepth( ...@@ -1508,7 +1463,6 @@ export async function createCombinedPayloadAtDepth(
return { return {
payload, payload,
hasAmbiguousErrors,
slotStacks, slotStacks,
} }
} }
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