Unverified Commit cb1dbfb8 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

refactor: consume global-error from loader tree (#88437)

parent e78d35b3
...@@ -419,15 +419,6 @@ impl AppPageLoaderTreeBuilder { ...@@ -419,15 +419,6 @@ impl AppPageLoaderTreeBuilder {
let loader_tree = &*loader_tree.await?; let loader_tree = &*loader_tree.await?;
let modules = &loader_tree.modules; let modules = &loader_tree.modules;
// load global-error module
if let Some(global_error) = &modules.global_error {
let module = self
.base
.process_source(Vc::upcast(FileSource::new(global_error.clone())))
.to_resolved()
.await?;
self.base.inner_assets.insert(GLOBAL_ERROR.into(), module);
};
// load global-not-found module // load global-not-found module
if let Some(global_not_found) = &modules.global_not_found { if let Some(global_not_found) = &modules.global_not_found {
let module = self let module = self
...@@ -468,5 +459,4 @@ impl AppPageLoaderTreeModule { ...@@ -468,5 +459,4 @@ impl AppPageLoaderTreeModule {
} }
} }
pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR_MODULE";
pub const GLOBAL_NOT_FOUND: &str = "GLOBAL_NOT_FOUND_MODULE"; pub const GLOBAL_NOT_FOUND: &str = "GLOBAL_NOT_FOUND_MODULE";
...@@ -1742,6 +1742,13 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1742,6 +1742,13 @@ async fn directory_tree_to_entrypoints_internal_untraced(
.join("dist/client/components/builtin/unauthorized.js")?, .join("dist/client/components/builtin/unauthorized.js")?,
); );
} }
if modules.global_error.is_none() {
modules.global_error = Some(
get_next_package(app_dir.clone())
.await?
.join("dist/client/components/builtin/global-error.js")?,
);
}
// Next.js has this logic in "collect-app-paths", where the root not-found page // Next.js has this logic in "collect-app-paths", where the root not-found page
// is considered as its own entry point. // is considered as its own entry point.
...@@ -1843,7 +1850,9 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1843,7 +1850,9 @@ async fn directory_tree_to_entrypoints_internal_untraced(
// the build isn't app-only. If the build is app-only (no user pages/api), we should still // the build isn't app-only. If the build is app-only (no user pages/api), we should still
// expose the app global error so runtime errors render, but we shouldn't emit it otherwise. // expose the app global error so runtime errors render, but we shouldn't emit it otherwise.
if matches!(*next_mode.await?, NextMode::Build) { if matches!(*next_mode.await?, NextMode::Build) {
// Use built-in global-error.js to create a `_global-error/page` route. // Create a `_global-error/page` route using user's global-error.js or built-in
// fallback.
let next_package = get_next_package(app_dir.clone()).await?;
let global_error_tree = AppPageLoaderTree { let global_error_tree = AppPageLoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: directory_name.clone(), segment: directory_name.clone(),
...@@ -1853,8 +1862,7 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1853,8 +1862,7 @@ async fn directory_tree_to_entrypoints_internal_untraced(
segment: rcstr!("__PAGE__"), segment: rcstr!("__PAGE__"),
parallel_routes: FxIndexMap::default(), parallel_routes: FxIndexMap::default(),
modules: AppDirModules { modules: AppDirModules {
page: Some(get_next_package(app_dir.clone()) page: Some(next_package
.await?
.join("dist/client/components/builtin/app-error.js")?), .join("dist/client/components/builtin/app-error.js")?),
..Default::default() ..Default::default()
}, },
...@@ -1862,7 +1870,12 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1862,7 +1870,12 @@ async fn directory_tree_to_entrypoints_internal_untraced(
static_siblings: Vec::new(), static_siblings: Vec::new(),
} }
}, },
modules: AppDirModules::default(), // global-error is needed for getGlobalErrorStyles to work during rendering.
// Use user's custom global-error if defined, otherwise builtin fallback.
modules: AppDirModules {
global_error: modules.global_error.clone(),
..Default::default()
},
global_metadata, global_metadata,
static_siblings: Vec::new(), static_siblings: Vec::new(),
} }
......
...@@ -16,7 +16,7 @@ use turbopack_core::{ ...@@ -16,7 +16,7 @@ use turbopack_core::{
use turbopack_ecmascript::runtime_functions::{TURBOPACK_LOAD, TURBOPACK_REQUIRE}; use turbopack_ecmascript::runtime_functions::{TURBOPACK_LOAD, TURBOPACK_REQUIRE};
use crate::{ use crate::{
app_page_loader_tree::{AppPageLoaderTreeModule, GLOBAL_ERROR}, app_page_loader_tree::AppPageLoaderTreeModule,
app_structure::AppPageLoaderTree, app_structure::AppPageLoaderTree,
next_app::{AppPage, AppPath, app_entry::AppEntry}, next_app::{AppPage, AppPath, app_entry::AppEntry},
next_config::NextConfig, next_config::NextConfig,
...@@ -78,14 +78,6 @@ pub async fn get_app_page_entry( ...@@ -78,14 +78,6 @@ pub async fn get_app_page_entry(
[ [
("VAR_DEFINITION_PAGE", &*page.to_string()), ("VAR_DEFINITION_PAGE", &*page.to_string()),
("VAR_DEFINITION_PATHNAME", &pathname), ("VAR_DEFINITION_PATHNAME", &pathname),
(
"VAR_MODULE_GLOBAL_ERROR",
if inner_assets.contains_key(GLOBAL_ERROR) {
GLOBAL_ERROR
} else {
"next/dist/client/components/builtin/global-error"
},
),
], ],
[ [
("tree", &*loader_tree_code), ("tree", &*loader_tree_code),
......
...@@ -980,5 +980,6 @@ ...@@ -980,5 +980,6 @@
"979": "invariant: expected %s bytes of postponed state but only received %s bytes", "979": "invariant: expected %s bytes of postponed state but only received %s bytes",
"980": "Failed to load client middleware manifest", "980": "Failed to load client middleware manifest",
"981": "resolvedPathname must be set in request metadata", "981": "resolvedPathname must be set in request metadata",
"982": "`serializeResumeDataCache` should not be called in edge runtime." "982": "`serializeResumeDataCache` should not be called in edge runtime.",
"983": "Invariant: global-error module is required but not found in loader tree"
} }
...@@ -75,10 +75,6 @@ import { ...@@ -75,10 +75,6 @@ import {
*/ */
declare const tree: LoaderTree declare const tree: LoaderTree
// TODO this should ideally be read from the loader tree instead, where it's always inserted already anyway.
import GlobalError from 'VAR_MODULE_GLOBAL_ERROR' with { 'turbopack-transition': 'next-server-component' }
export { GlobalError }
// These are injected by the loader afterwards. // These are injected by the loader afterwards.
declare const __next_app_require__: (id: string | number) => unknown declare const __next_app_require__: (id: string | number) => unknown
declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown> declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown>
...@@ -86,7 +82,6 @@ declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown> ...@@ -86,7 +82,6 @@ declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown>
// We inject the tree and pages here so that we can use them in the route // We inject the tree and pages here so that we can use them in the route
// module. // module.
// INJECT:tree // INJECT:tree
// INJECT:__next_app_require__ // INJECT:__next_app_require__
// INJECT:__next_app_load_chunk__ // INJECT:__next_app_load_chunk__
...@@ -491,7 +486,6 @@ export async function handler( ...@@ -491,7 +486,6 @@ export async function handler(
const ComponentMod = { const ComponentMod = {
...entryBase, ...entryBase,
tree, tree,
GlobalError,
handler, handler,
routeModule, routeModule,
__next_app__, __next_app__,
......
...@@ -333,7 +333,7 @@ async function createTreeCodeFromPath( ...@@ -333,7 +333,7 @@ async function createTreeCodeFromPath(
filePathEntries filePathEntries
) )
// Only resolve global-* convention files at the root layer // Resolve global-* convention files at the root layer
if (isRootLayer) { if (isRootLayer) {
const resolvedGlobalErrorPath = await resolver( const resolvedGlobalErrorPath = await resolver(
`${appDirPrefix}/${GLOBAL_ERROR_FILE_TYPE}` `${appDirPrefix}/${GLOBAL_ERROR_FILE_TYPE}`
...@@ -341,9 +341,6 @@ async function createTreeCodeFromPath( ...@@ -341,9 +341,6 @@ async function createTreeCodeFromPath(
if (resolvedGlobalErrorPath) { if (resolvedGlobalErrorPath) {
globalError = resolvedGlobalErrorPath globalError = resolvedGlobalErrorPath
} }
// Add global-error to root layer's filePaths, so that it's always available,
// by default it's the built-in global-error.js
filePaths.set(GLOBAL_ERROR_FILE_TYPE, globalError)
// TODO(global-not-found): remove this flag assertion condition // TODO(global-not-found): remove this flag assertion condition
// once global-not-found is stable // once global-not-found is stable
...@@ -360,6 +357,10 @@ async function createTreeCodeFromPath( ...@@ -360,6 +357,10 @@ async function createTreeCodeFromPath(
} }
} }
// Add global-error to ALL layers' filePaths, so that it's always available.
// By default it's the built-in global-error.js, or user's custom one if defined.
filePaths.set(GLOBAL_ERROR_FILE_TYPE, globalError)
let definedFilePaths = Array.from(filePaths.entries()).filter( let definedFilePaths = Array.from(filePaths.entries()).filter(
([, filePath]) => filePath !== undefined ([, filePath]) => filePath !== undefined
) as [ValueOf<typeof FILE_TYPES>, string][] ) as [ValueOf<typeof FILE_TYPES>, string][]
...@@ -1103,7 +1104,6 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -1103,7 +1104,6 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
{ {
VAR_DEFINITION_PAGE: page, VAR_DEFINITION_PAGE: page,
VAR_DEFINITION_PATHNAME: pathname, VAR_DEFINITION_PATHNAME: pathname,
VAR_MODULE_GLOBAL_ERROR: treeCodeResult.globalError,
}, },
{ {
tree: treeCodeResult.treeCode, tree: treeCodeResult.treeCode,
......
...@@ -388,8 +388,12 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree { ...@@ -388,8 +388,12 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
{ {
children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents, null], children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents, null],
}, },
// When global-not-found is present, skip layout from components // Always include global-error so that getGlobalErrorStyles can access it.
hasGlobalNotFound ? components : {}, // When global-not-found is present, use full components.
// Otherwise, only include global-error module.
hasGlobalNotFound
? components
: { 'global-error': components['global-error'] },
null, // staticSiblings null, // staticSiblings
] ]
} }
...@@ -5538,26 +5542,29 @@ const getGlobalErrorStyles = async ( ...@@ -5538,26 +5542,29 @@ const getGlobalErrorStyles = async (
GlobalError: GlobalErrorComponent GlobalError: GlobalErrorComponent
styles: ReactNode | undefined styles: ReactNode | undefined
}> => { }> => {
const { const globalErrorModule = parseLoaderTree(tree).modules['global-error']
modules: { 'global-error': globalErrorModule },
} = parseLoaderTree(tree) if (!globalErrorModule) {
throw new Error(
'Invariant: global-error module is required but not found in loader tree'
)
}
const { const {
componentMod: { createElement }, componentMod: { createElement },
} = ctx } = ctx
const GlobalErrorComponent: GlobalErrorComponent =
ctx.componentMod.GlobalError // Get the GlobalError component and styles from the loader tree
let globalErrorStyles const [GlobalErrorComponent, styles] = await createComponentStylesAndScripts({
if (globalErrorModule) {
const [, styles] = await createComponentStylesAndScripts({
ctx, ctx,
filePath: globalErrorModule[1], filePath: globalErrorModule[1],
getComponent: globalErrorModule[0], getComponent: globalErrorModule[0],
injectedCSS: new Set(), injectedCSS: new Set(),
injectedJS: new Set(), injectedJS: new Set(),
}) })
globalErrorStyles = styles
} let globalErrorStyles: ReactNode = styles
if (ctx.renderOpts.dev) { if (ctx.renderOpts.dev) {
const dir = const dir =
(process.env.NEXT_RUNTIME === 'edge' (process.env.NEXT_RUNTIME === 'edge'
...@@ -5566,7 +5573,7 @@ const getGlobalErrorStyles = async ( ...@@ -5566,7 +5573,7 @@ const getGlobalErrorStyles = async (
const globalErrorModulePath = normalizeConventionFilePath( const globalErrorModulePath = normalizeConventionFilePath(
dir, dir,
globalErrorModule?.[1] globalErrorModule[1]
) )
if (globalErrorModulePath) { if (globalErrorModulePath) {
const SegmentViewNode = ctx.componentMod.SegmentViewNode const SegmentViewNode = ctx.componentMod.SegmentViewNode
......
...@@ -170,7 +170,7 @@ describe('opentelemetry', () => { ...@@ -170,7 +170,7 @@ describe('opentelemetry', () => {
}, },
{ {
attributes: { attributes: {
'next.clientComponentLoadCount': isNextDev ? 7 : 6, 'next.clientComponentLoadCount': isNextDev ? 8 : 7,
'next.span_type': 'next.span_type':
'NextNodeServer.clientComponentLoading', 'NextNodeServer.clientComponentLoading',
}, },
...@@ -578,7 +578,7 @@ describe('opentelemetry', () => { ...@@ -578,7 +578,7 @@ describe('opentelemetry', () => {
}, },
{ {
attributes: { attributes: {
'next.clientComponentLoadCount': isNextDev ? 10 : 8, 'next.clientComponentLoadCount': isNextDev ? 12 : 10,
'next.span_type': 'next.span_type':
'NextNodeServer.clientComponentLoading', 'NextNodeServer.clientComponentLoading',
}, },
...@@ -701,7 +701,7 @@ describe('opentelemetry', () => { ...@@ -701,7 +701,7 @@ describe('opentelemetry', () => {
}, },
{ {
attributes: { attributes: {
'next.clientComponentLoadCount': isNextDev ? 8 : 7, 'next.clientComponentLoadCount': isNextDev ? 9 : 8,
'next.span_type': 'next.span_type':
'NextNodeServer.clientComponentLoading', 'NextNodeServer.clientComponentLoading',
}, },
...@@ -1380,7 +1380,7 @@ describe('opentelemetry with custom server', () => { ...@@ -1380,7 +1380,7 @@ describe('opentelemetry with custom server', () => {
}, },
{ {
attributes: { attributes: {
'next.clientComponentLoadCount': isNextDev ? 7 : 6, 'next.clientComponentLoadCount': isNextDev ? 8 : 7,
'next.span_type': 'NextNodeServer.clientComponentLoading', 'next.span_type': 'NextNodeServer.clientComponentLoading',
}, },
kind: 0, kind: 0,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment