Unverified Commit 8f231d63 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[instant] Include declaration location of instant config in validation errors (#90169)

parent 77cd1afa
...@@ -12,10 +12,11 @@ use crate::{ ...@@ -12,10 +12,11 @@ use crate::{
next_config::NextConfig, next_config::NextConfig,
next_server::context::ServerContextType, next_server::context::ServerContextType,
next_shared::transforms::{ next_shared::transforms::{
get_next_dynamic_transform_rule, get_next_font_transform_rule, get_next_image_rule, get_next_debug_instant_stack_rule, get_next_dynamic_transform_rule,
get_next_lint_transform_rule, get_next_modularize_imports_rule, get_next_font_transform_rule, get_next_image_rule, get_next_lint_transform_rule,
get_next_pages_transforms_rule, get_next_track_dynamic_imports_transform_rule, get_next_modularize_imports_rule, get_next_pages_transforms_rule,
get_server_actions_transform_rule, next_cjs_optimizer::get_next_cjs_optimizer_rule, get_next_track_dynamic_imports_transform_rule, get_server_actions_transform_rule,
next_cjs_optimizer::get_next_cjs_optimizer_rule,
next_disallow_re_export_all_in_page::get_next_disallow_export_all_in_page_rule, next_disallow_re_export_all_in_page::get_next_disallow_export_all_in_page_rule,
next_edge_node_api_assert::next_edge_node_api_assert, next_edge_node_api_assert::next_edge_node_api_assert,
next_middleware_dynamic_assert::get_middleware_dynamic_assert_rule, next_middleware_dynamic_assert::get_middleware_dynamic_assert_rule,
...@@ -147,6 +148,10 @@ pub async fn get_next_server_transforms_rules( ...@@ -147,6 +148,10 @@ pub async fn get_next_server_transforms_rules(
ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => false, ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => false,
}; };
if is_app_dir {
rules.push(get_next_debug_instant_stack_rule(mdx_rs));
}
if is_app_dir && if is_app_dir &&
// `cacheComponents` is not supported in the edge runtime. // `cacheComponents` is not supported in the edge runtime.
// (also, the code generated by the dynamic imports transform relies on `CacheSignal`, which uses nodejs-specific APIs) // (also, the code generated by the dynamic imports transform relies on `CacheSignal`, which uses nodejs-specific APIs)
......
...@@ -2,6 +2,7 @@ pub(crate) mod debug_fn_name; ...@@ -2,6 +2,7 @@ pub(crate) mod debug_fn_name;
pub(crate) mod emotion; pub(crate) mod emotion;
pub(crate) mod modularize_imports; pub(crate) mod modularize_imports;
pub(crate) mod next_cjs_optimizer; pub(crate) mod next_cjs_optimizer;
pub(crate) mod next_debug_instant_stack;
pub(crate) mod next_disallow_re_export_all_in_page; pub(crate) mod next_disallow_re_export_all_in_page;
pub(crate) mod next_dynamic; pub(crate) mod next_dynamic;
pub(crate) mod next_edge_node_api_assert; pub(crate) mod next_edge_node_api_assert;
...@@ -23,6 +24,7 @@ pub(crate) mod swc_ecma_transform_plugins; ...@@ -23,6 +24,7 @@ pub(crate) mod swc_ecma_transform_plugins;
use anyhow::Result; use anyhow::Result;
pub use modularize_imports::{ModularizeImportPackageConfig, get_next_modularize_imports_rule}; pub use modularize_imports::{ModularizeImportPackageConfig, get_next_modularize_imports_rule};
pub use next_debug_instant_stack::get_next_debug_instant_stack_rule;
pub use next_dynamic::get_next_dynamic_transform_rule; pub use next_dynamic::get_next_dynamic_transform_rule;
pub use next_font::get_next_font_transform_rule; pub use next_font::get_next_font_transform_rule;
pub use next_lint::get_next_lint_transform_rule; pub use next_lint::get_next_lint_transform_rule;
......
use anyhow::Result;
use async_trait::async_trait;
use next_custom_transforms::transforms::debug_instant_stack::debug_instant_stack;
use swc_core::ecma::ast::Program;
use turbo_tasks::ResolvedVc;
use turbopack::module_options::{ModuleRule, ModuleRuleEffect};
use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext};
use super::module_rule_match_js_no_url;
pub fn get_next_debug_instant_stack_rule(enable_mdx_rs: bool) -> ModuleRule {
let transform =
EcmascriptInputTransform::Plugin(ResolvedVc::cell(Box::new(NextDebugInstantStack {}) as _));
ModuleRule::new(
module_rule_match_js_no_url(enable_mdx_rs),
vec![ModuleRuleEffect::ExtendEcmascriptTransforms {
preprocess: ResolvedVc::cell(vec![]),
main: ResolvedVc::cell(vec![]),
postprocess: ResolvedVc::cell(vec![transform]),
}],
)
}
#[derive(Debug)]
struct NextDebugInstantStack {}
#[async_trait]
impl CustomTransformer for NextDebugInstantStack {
#[tracing::instrument(level = tracing::Level::TRACE, name = "debug_instant_stack", skip_all)]
async fn transform(&self, program: &mut Program, _ctx: &TransformContext<'_>) -> Result<()> {
program.mutate(debug_instant_stack());
Ok(())
}
}
...@@ -347,6 +347,7 @@ where ...@@ -347,6 +347,7 @@ where
crate::transforms::debug_fn_name::debug_fn_name(), crate::transforms::debug_fn_name::debug_fn_name(),
opts.debug_function_name, opts.debug_function_name,
), ),
crate::transforms::debug_instant_stack::debug_instant_stack(),
visit_mut_pass(crate::transforms::pure::pure_magic(comments.clone())), visit_mut_pass(crate::transforms::pure::pure_magic(comments.clone())),
Optional::new( Optional::new(
linter(lint_codemod_comments(comments)), linter(lint_codemod_comments(comments)),
......
use swc_core::{
common::{Span, Spanned},
ecma::{
ast::*,
visit::{fold_pass, Fold},
},
quote,
};
pub fn debug_instant_stack() -> impl Pass {
fold_pass(DebugInstantStack {
instant_export_span: None,
})
}
struct DebugInstantStack {
instant_export_span: Option<Span>,
}
impl Fold for DebugInstantStack {
fn fold_module_items(&mut self, items: Vec<ModuleItem>) -> Vec<ModuleItem> {
// Scan for `export const unstable_instant = ...`
for item in &items {
if let ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) = item {
if let Decl::Var(var_decl) = &export_decl.decl {
for decl in &var_decl.decls {
if let Pat::Ident(ident) = &decl.name {
if ident.id.sym == "unstable_instant" {
if let Some(init) = &decl.init {
self.instant_export_span = Some(init.span());
}
}
}
}
}
}
}
if let Some(source_span) = self.instant_export_span {
let mut new_items = items;
// TODO: Change React to deserialize errors with a zero-length message
// instead of using a fallback message ("no message was provided").
// We're working around this by using a message that is empty
// after trimming but isn't to JavaScript before trimming (' '.length === 1).
let mut new_error = quote!("new Error(' ')" as Expr);
if let Expr::New(new_expr) = &mut new_error {
new_expr.span = source_span;
}
let mut cons = quote!(
"function unstable_instant() {
const error = $new_error
error.name = 'Instant Validation'
return error
}" as Expr,
new_error: Expr = new_error,
);
// Patch source_span onto the Function
// for sourcemap mapping back to the unstable_instant config value
if let Expr::Fn(f) = &mut cons {
f.function.span = source_span;
}
let export = quote!(
"export const __debugCreateInstantConfigStack =
process.env.NODE_ENV !== 'production' ? $cons : null"
as ModuleItem,
cons: Expr = cons,
);
new_items.push(export);
new_items
} else {
items
}
}
}
pub mod cjs_finder; pub mod cjs_finder;
pub mod cjs_optimizer; pub mod cjs_optimizer;
pub mod debug_fn_name; pub mod debug_fn_name;
pub mod debug_instant_stack;
pub mod disallow_re_export_all_in_page; pub mod disallow_re_export_all_in_page;
pub mod dynamic; pub mod dynamic;
pub mod fonts; pub mod fonts;
......
...@@ -8,6 +8,7 @@ use bytes_str::BytesStr; ...@@ -8,6 +8,7 @@ use bytes_str::BytesStr;
use next_custom_transforms::transforms::{ use next_custom_transforms::transforms::{
cjs_optimizer::cjs_optimizer, cjs_optimizer::cjs_optimizer,
debug_fn_name::debug_fn_name, debug_fn_name::debug_fn_name,
debug_instant_stack::debug_instant_stack,
dynamic::{next_dynamic, NextDynamicMode}, dynamic::{next_dynamic, NextDynamicMode},
fonts::{next_font_loaders, Config as FontLoaderConfig}, fonts::{next_font_loaders, Config as FontLoaderConfig},
named_import_transform::named_import_transform, named_import_transform::named_import_transform,
...@@ -869,6 +870,22 @@ fn test_debug_name(input: PathBuf) { ...@@ -869,6 +870,22 @@ fn test_debug_name(input: PathBuf) {
); );
} }
#[fixture("tests/fixture/debug-instant-stack/**/input.js")]
fn test_debug_instant_stack(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|_| debug_instant_stack(),
&input,
&output,
FixtureTestConfig {
sourcemap: true,
..Default::default()
},
);
}
#[fixture("tests/fixture/edge-assert/**/input.js")] #[fixture("tests/fixture/edge-assert/**/input.js")]
fn test_edge_assert(input: PathBuf) { fn test_edge_assert(input: PathBuf) {
let output = input.parent().unwrap().join("output.js"); let output = input.parent().unwrap().join("output.js");
......
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return <div>Hello</div>
}
export const unstable_instant = {
prefetch: 'static'
};
export default function Page() {
return <div>Hello</div>;
}
export const __debugCreateInstantConfigStack = process.env.NODE_ENV !== 'production' ? function unstable_instant() {
const error = new Error(' ');
error.name = 'Instant Validation';
return error;
} : null;
{"version":3,"sources":["input.js"],"sourcesContent":["export const unstable_instant = { prefetch: 'static' }\n\nexport default function Page() {\n return <div>Hello</div>\n}\n"],"names":[],"mappings":"AAAA,OAAO,MAAM,mBAAmB;IAAE,UAAU;AAAS,EAAC;AAEtD,eAAe,SAAS;IACtB,QAAQ,IAAI,KAAK,EAAE;AACrB;uFAJgC;kBAAA"}
export const revalidate = 60
export default function Page() {
return <div>Hello</div>
}
export const revalidate = 60;
export default function Page() {
return <div>Hello</div>;
}
{"version":3,"sources":["input.js"],"sourcesContent":["export const revalidate = 60\n\nexport default function Page() {\n return <div>Hello</div>\n}\n"],"names":[],"mappings":"AAAA,OAAO,MAAM,aAAa,GAAE;AAE5B,eAAe,SAAS;IACtB,QAAQ,IAAI,KAAK,EAAE;AACrB"}
...@@ -4144,7 +4144,7 @@ async function validateInstantConfigs( ...@@ -4144,7 +4144,7 @@ async function validateInstantConfigs(
const { const {
tree: validationRouteTree, tree: validationRouteTree,
treeNodes, treeNodes,
navigationParents, validationTasks,
segmentsWithInstantConfigs, segmentsWithInstantConfigs,
} = init } = init
...@@ -4155,6 +4155,7 @@ async function validateInstantConfigs( ...@@ -4155,6 +4155,7 @@ async function validateInstantConfigs(
? instantConfig.prefetch === 'runtime' ? instantConfig.prefetch === 'runtime'
: false : false
}) })
const clientReferenceManifest = getClientReferenceManifest() const clientReferenceManifest = getClientReferenceManifest()
const { const {
...@@ -4175,9 +4176,13 @@ async function validateInstantConfigs( ...@@ -4175,9 +4176,13 @@ async function validateInstantConfigs(
const getFilepathForSegment = (segmentPath: InstantValidation.SegmentPath) => const getFilepathForSegment = (segmentPath: InstantValidation.SegmentPath) =>
treeNodes.get(segmentPath)?.module?.conventionPath treeNodes.get(segmentPath)?.module?.conventionPath
const getCreateInstantStackForSegment = (
segmentPath: InstantValidation.SegmentPath
) => treeNodes.get(segmentPath)?.module?.createInstantStack ?? null
for (const navigationParent of navigationParents) { for (const { parents, target } of validationTasks) {
// TODO(instant-validation): report which segment had errors const createInstantStack = getCreateInstantStackForSegment(target)
for (const navigationParent of parents) {
debug?.( debug?.(
`-------------------------------\n` + `-------------------------------\n` +
`Validating navigation\n` + `Validating navigation\n` +
...@@ -4194,7 +4199,8 @@ async function validateInstantConfigs( ...@@ -4194,7 +4199,8 @@ async function validateInstantConfigs(
hmrRefreshHash, hmrRefreshHash,
validationRouteTree, validationRouteTree,
navigationParent, navigationParent,
false // use static stage for static segments false, // use static stage for static segments
createInstantStack
) )
if (initialResults.errors.length === 0) { if (initialResults.errors.length === 0) {
debug?.(` ✅ Validation successful`) debug?.(` ✅ Validation successful`)
...@@ -4213,7 +4219,8 @@ async function validateInstantConfigs( ...@@ -4213,7 +4219,8 @@ async function validateInstantConfigs(
hmrRefreshHash, hmrRefreshHash,
validationRouteTree, validationRouteTree,
navigationParent, navigationParent,
true // use runtime stage for static segments instead true, // use runtime stage for static segments instead
createInstantStack
) )
if (runtimeResults.errors.length > 0) { if (runtimeResults.errors.length > 0) {
// The errors remained in the runtime stage, so they were caused by a dynamic access. // The errors remained in the runtime stage, so they were caused by a dynamic access.
...@@ -4230,6 +4237,7 @@ async function validateInstantConfigs( ...@@ -4230,6 +4237,7 @@ async function validateInstantConfigs(
return initialResults.errors return initialResults.errors
} }
} }
}
debug?.(`✅ Passed`) debug?.(`✅ Passed`)
return [] return []
...@@ -4245,7 +4253,8 @@ async function validateInstantConfigNavigation( ...@@ -4245,7 +4253,8 @@ async function validateInstantConfigNavigation(
hmrRefreshHash: string | undefined, hmrRefreshHash: string | undefined,
routeTree: InstantValidation.RouteTree, routeTree: InstantValidation.RouteTree,
navigationParent: InstantValidation.SegmentPath, navigationParent: InstantValidation.SegmentPath,
useRuntimeStageForPartialSegments: boolean useRuntimeStageForPartialSegments: boolean,
createInstantStack: (() => Error) | null
): Promise<{ dynamicHoleKind: DynamicHoleKind; errors: Array<unknown> }> { ): Promise<{ dynamicHoleKind: DynamicHoleKind; errors: Array<unknown> }> {
const { implicitTags, nonce, workStore } = ctx const { implicitTags, nonce, workStore } = ctx
const isDebugChannelEnabled = !!ctx.renderOpts.setReactDebugChannel const isDebugChannelEnabled = !!ctx.renderOpts.setReactDebugChannel
...@@ -4261,7 +4270,7 @@ async function validateInstantConfigNavigation( ...@@ -4261,7 +4270,7 @@ async function validateInstantConfigNavigation(
const preinitScripts = () => {} const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML() const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const dynamicValidation = createInstantValidationState() const dynamicValidation = createInstantValidationState(createInstantStack)
const boundaryState = createValidationBoundaryTracking() const boundaryState = createValidationBoundaryTracking()
const finalClientPrerenderStore: PrerenderStore = { const finalClientPrerenderStore: PrerenderStore = {
......
...@@ -86,6 +86,7 @@ export type RouteTree = { ...@@ -86,6 +86,7 @@ export type RouteTree = {
// TODO(instant-validation): We should know if a layout segment is shared // TODO(instant-validation): We should know if a layout segment is shared
instantConfig: Instant | null instantConfig: Instant | null
conventionPath: string conventionPath: string
createInstantStack: (() => Error) | null
} }
slots: { [parallelRouteKey: string]: RouteTree } | null slots: { [parallelRouteKey: string]: RouteTree } | null
...@@ -143,10 +144,15 @@ export async function findNavigationsToValidate( ...@@ -143,10 +144,15 @@ export async function findNavigationsToValidate(
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules? // TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig = const instantConfig =
(layoutOrPageMod as AppSegmentConfig).unstable_instant ?? null (layoutOrPageMod as AppSegmentConfig).unstable_instant ?? null
const rawFactory: unknown = (layoutOrPageMod as any)
.__debugCreateInstantConfigStack
const createInstantStack: (() => Error) | null =
typeof rawFactory === 'function' ? (rawFactory as () => Error) : null
moduleInfo = { moduleInfo = {
type: modType!, type: modType!,
instantConfig, instantConfig,
conventionPath: conventionPath!, conventionPath: conventionPath!,
createInstantStack,
} }
if (isInsideParallelSlot) { if (isInsideParallelSlot) {
...@@ -171,9 +177,13 @@ export async function findNavigationsToValidate( ...@@ -171,9 +177,13 @@ export async function findNavigationsToValidate(
} else { } else {
const isRootLayout = parentLayoutPath === null const isRootLayout = parentLayoutPath === null
if (isRootLayout && instantConfig.prefetch === 'runtime') { if (isRootLayout && instantConfig.prefetch === 'runtime') {
throw new Error( const message = `${conventionPath}: \`unstable_instant\` with mode 'runtime' is not supported in root layouts.`
`${conventionPath}: \`unstable_instant\` with mode 'runtime' is not supported in root layouts.` const error =
) createInstantStack !== null
? createInstantStack()
: new Error()
error.message = message
throw error
} }
const task: ValidationTask = { const task: ValidationTask = {
...@@ -256,8 +266,7 @@ export async function findNavigationsToValidate( ...@@ -256,8 +266,7 @@ export async function findNavigationsToValidate(
return { return {
tree: routeTree, tree: routeTree,
treeNodes, treeNodes,
// TODO: do we want to preserve info about which config caused a validation to occur? validationTasks,
navigationParents: validationTasks.flatMap((task) => task.parents),
segmentsWithInstantConfigs, segmentsWithInstantConfigs,
} }
} }
......
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