Unverified Commit 7e0fc3b2 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: refactor segment config parsing (#83297)

Closes PACK-5382

Previously, Turbopack validated every single module for route segment config, leading to false positives (on non-page files) and worse build performance. There were also three separate implementations of this logic.

Now, all of these cases are fatal errors, not just warnings.



Examples for errors

```
./bench/basic-app/app/export/inherit/page.tsx:1:28
Next.js can't recognize the exported `preferredRegion` field in route. It needs to be a static string or array of static strings.
> 1 | export { default, runtime, preferredRegion } from '../basic/foo'
    |                            ^^^^^^^^^^^^^^^
The exported configuration object in a source file needs to have a very specific format from which some properties can be statically parsed at compiled-time.

https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config
```

This error message is slightly different now:

```
    browser log: ./test/integration/app-dir-export/app/another/[slug]/page.js:6:8
    Next.js can't recognize the exported `generateStaticParams` field in route. App pages cannot use both "use client" and export function "generateStaticParams()".
       4 |
       5 |
    >  6 | export function generateStaticParams() {
         |        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    >  7 |   return [{ slug: 'first' }, { slug: 'second' }]
         | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    >  8 | }
         | ^^
       9 |
      10 | export default async function Page(props) {
      11 |   const params = await props.params

    The exported configuration object in a source file needs to have a very specific format from which some properties can be statically parsed at compiled-time.

    Import traces:
      Client Component Browser:
        ./test/integration/app-dir-export/app/another/[slug]/page.js [Client Component Browser]
        ./test/integration/app-dir-export/app/another/[slug]/page.js [Server Component]

      Client Component SSR:
        ./test/integration/app-dir-export/app/another/[slug]/page.js [Client Component SSR]
        ./test/integration/app-dir-export/app/another/[slug]/page.js [Server Component]

    https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config
```
parent f2e3357b
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use next_core::{ use next_core::{
all_assets_from_entries, all_assets_from_entries,
app_segment_config::NextSegmentConfig,
app_structure::{ app_structure::{
AppPageLoaderTree, CollectedRootParams, Entrypoint as AppEntrypoint, AppPageLoaderTree, CollectedRootParams, Entrypoint as AppEntrypoint,
Entrypoints as AppEntrypoints, FileSystemPathVec, MetadataItem, collect_root_params, Entrypoints as AppEntrypoints, FileSystemPathVec, MetadataItem, collect_root_params,
...@@ -34,6 +33,7 @@ use next_core::{ ...@@ -34,6 +33,7 @@ use next_core::{
}, },
next_server_utility::{NEXT_SERVER_UTILITY_MERGE_TAG, NextServerUtilityTransition}, next_server_utility::{NEXT_SERVER_UTILITY_MERGE_TAG, NextServerUtilityTransition},
parse_segment_config_from_source, parse_segment_config_from_source,
segment_config::{NextSegmentConfig, ParseSegmentMode},
util::{NextRuntime, app_function_name, module_styles_rule_condition, styles_rule_condition}, util::{NextRuntime, app_function_name, module_styles_rule_condition, styles_rule_condition},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
...@@ -1106,7 +1106,7 @@ impl AppEndpoint { ...@@ -1106,7 +1106,7 @@ impl AppEndpoint {
for layout in root_layouts.iter().rev() { for layout in root_layouts.iter().rev() {
let source = Vc::upcast(FileSource::new(layout.clone())); let source = Vc::upcast(FileSource::new(layout.clone()));
let layout_config = parse_segment_config_from_source(source); let layout_config = parse_segment_config_from_source(source, ParseSegmentMode::App);
config.apply_parent_config(&*layout_config.await?); config.apply_parent_config(&*layout_config.await?);
} }
......
...@@ -7,7 +7,9 @@ use next_core::{ ...@@ -7,7 +7,9 @@ use next_core::{
next_edge::entry::wrap_edge_entry, next_edge::entry::wrap_edge_entry,
next_manifests::{EdgeFunctionDefinition, MiddlewareMatcher, MiddlewaresManifestV2, Regions}, next_manifests::{EdgeFunctionDefinition, MiddlewareMatcher, MiddlewaresManifestV2, Regions},
next_server::{ServerContextType, get_server_runtime_entries}, next_server::{ServerContextType, get_server_runtime_entries},
util::{MiddlewareMatcherKind, NextRuntime, parse_config_from_source}, parse_segment_config_from_source,
segment_config::ParseSegmentMode,
util::{MiddlewareMatcherKind, NextRuntime},
}; };
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
...@@ -86,10 +88,12 @@ impl MiddlewareEndpoint { ...@@ -86,10 +88,12 @@ impl MiddlewareEndpoint {
userland_module, userland_module,
); );
let config = let runtime = parse_segment_config_from_source(*self.source, ParseSegmentMode::Base)
parse_config_from_source(*self.source, userland_module, NextRuntime::Edge).await?; .await?
.runtime
.unwrap_or(NextRuntime::Edge);
if matches!(config.runtime, NextRuntime::NodeJs) { if matches!(runtime, NextRuntime::NodeJs) {
return Ok(module); return Ok(module);
} }
Ok(wrap_edge_entry( Ok(wrap_edge_entry(
...@@ -175,11 +179,9 @@ impl MiddlewareEndpoint { ...@@ -175,11 +179,9 @@ impl MiddlewareEndpoint {
async fn output_assets(self: Vc<Self>) -> Result<Vc<OutputAssets>> { async fn output_assets(self: Vc<Self>) -> Result<Vc<OutputAssets>> {
let this = self.await?; let this = self.await?;
let userland_module = self.userland_module();
let config = let config =
parse_config_from_source(*self.await?.source, userland_module, NextRuntime::Edge) parse_segment_config_from_source(*self.await?.source, ParseSegmentMode::Base).await?;
.await?; let runtime = config.runtime.unwrap_or(NextRuntime::Edge);
let next_config = this.project.next_config().await?; let next_config = this.project.next_config().await?;
let has_i18n = next_config.i18n.is_some(); let has_i18n = next_config.i18n.is_some();
...@@ -190,7 +192,7 @@ impl MiddlewareEndpoint { ...@@ -190,7 +192,7 @@ impl MiddlewareEndpoint {
.unwrap_or(false); .unwrap_or(false);
let base_path = next_config.base_path.as_ref(); let base_path = next_config.base_path.as_ref();
let matchers = if let Some(matchers) = config.matcher.as_ref() { let matchers = if let Some(matchers) = config.middleware_matcher.as_ref() {
matchers matchers
.iter() .iter()
.map(|matcher| { .map(|matcher| {
...@@ -247,7 +249,7 @@ impl MiddlewareEndpoint { ...@@ -247,7 +249,7 @@ impl MiddlewareEndpoint {
}] }]
}; };
if matches!(config.runtime, NextRuntime::NodeJs) { if matches!(runtime, NextRuntime::NodeJs) {
let chunk = self.node_chunk().to_resolved().await?; let chunk = self.node_chunk().to_resolved().await?;
let mut output_assets = vec![chunk]; let mut output_assets = vec![chunk];
if this.project.next_mode().await?.is_production() { if this.project.next_mode().await?.is_production() {
...@@ -296,7 +298,7 @@ impl MiddlewareEndpoint { ...@@ -296,7 +298,7 @@ impl MiddlewareEndpoint {
let all_assets = let all_assets =
get_asset_paths_from_root(&node_root_value, &all_output_assets).await?; get_asset_paths_from_root(&node_root_value, &all_output_assets).await?;
let regions = if let Some(regions) = config.regions.as_ref() { let regions = if let Some(regions) = config.preferred_region.as_ref() {
if regions.len() == 1 { if regions.len() == 1 {
regions regions
.first() .first()
......
...@@ -23,9 +23,9 @@ use next_core::{ ...@@ -23,9 +23,9 @@ use next_core::{
pages_structure::{ pages_structure::{
PagesDirectoryStructure, PagesStructure, PagesStructureItem, find_pages_structure, PagesDirectoryStructure, PagesStructure, PagesStructureItem, find_pages_structure,
}, },
util::{ parse_segment_config_from_source,
NextRuntime, get_asset_prefix_from_pathname, pages_function_name, parse_config_from_source, segment_config::ParseSegmentMode,
}, util::{NextRuntime, get_asset_prefix_from_pathname, pages_function_name},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
...@@ -930,7 +930,9 @@ impl PageEndpoint { ...@@ -930,7 +930,9 @@ impl PageEndpoint {
.module(); .module();
let config = let config =
parse_config_from_source(self.source(), ssr_module, NextRuntime::default()).await?; parse_segment_config_from_source(self.source(), ParseSegmentMode::Base).await?;
let runtime = config.runtime.unwrap_or(NextRuntime::NodeJs);
Ok( Ok(
// `/_app` and `/_document` never get rendered directly so they don't need to be // `/_app` and `/_document` never get rendered directly so they don't need to be
...@@ -944,9 +946,9 @@ impl PageEndpoint { ...@@ -944,9 +946,9 @@ impl PageEndpoint {
// /_app and /_document are always rendered for Node.js for this case. For edge // /_app and /_document are always rendered for Node.js for this case. For edge
// they're included in the page bundle. // they're included in the page bundle.
runtime: NextRuntime::NodeJs, runtime: NextRuntime::NodeJs,
regions: config.regions.clone(), regions: config.preferred_region.clone(),
} }
} else if config.runtime == NextRuntime::Edge { } else if runtime == NextRuntime::Edge {
let modules = create_page_ssr_entry_module( let modules = create_page_ssr_entry_module(
this.pathname.clone(), this.pathname.clone(),
reference_type, reference_type,
...@@ -955,7 +957,7 @@ impl PageEndpoint { ...@@ -955,7 +957,7 @@ impl PageEndpoint {
self.source(), self.source(),
this.original_name.clone(), this.original_name.clone(),
*this.pages_structure, *this.pages_structure,
config.runtime, runtime,
this.pages_project.project().next_config(), this.pages_project.project().next_config(),
) )
.await?; .await?;
...@@ -964,8 +966,8 @@ impl PageEndpoint { ...@@ -964,8 +966,8 @@ impl PageEndpoint {
ssr_module: modules.ssr_module, ssr_module: modules.ssr_module,
app_module: modules.app_module, app_module: modules.app_module,
document_module: modules.document_module, document_module: modules.document_module,
runtime: config.runtime, runtime,
regions: config.regions.clone(), regions: config.preferred_region.clone(),
} }
} else { } else {
let modules = create_page_ssr_entry_module( let modules = create_page_ssr_entry_module(
...@@ -976,7 +978,7 @@ impl PageEndpoint { ...@@ -976,7 +978,7 @@ impl PageEndpoint {
self.source(), self.source(),
this.original_name.clone(), this.original_name.clone(),
*this.pages_structure, *this.pages_structure,
config.runtime, runtime,
this.pages_project.project().next_config(), this.pages_project.project().next_config(),
) )
.await?; .await?;
...@@ -984,8 +986,8 @@ impl PageEndpoint { ...@@ -984,8 +986,8 @@ impl PageEndpoint {
ssr_module: modules.ssr_module, ssr_module: modules.ssr_module,
app_module: modules.app_module, app_module: modules.app_module,
document_module: modules.document_module, document_module: modules.document_module,
runtime: config.runtime, runtime,
regions: config.regions.clone(), regions: config.preferred_region.clone(),
} }
} }
.cell(), .cell(),
......
...@@ -21,7 +21,9 @@ use next_core::{ ...@@ -21,7 +21,9 @@ use next_core::{
get_server_module_options_context, get_server_resolve_options_context, get_server_module_options_context, get_server_resolve_options_context,
}, },
next_telemetry::NextFeatureTelemetry, next_telemetry::NextFeatureTelemetry,
util::{NextRuntime, OptionEnvMap, parse_config_from_source}, parse_segment_config_from_source,
segment_config::ParseSegmentMode,
util::{NextRuntime, OptionEnvMap},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
...@@ -66,7 +68,6 @@ use turbopack_core::{ ...@@ -66,7 +68,6 @@ use turbopack_core::{
export_usage::{OptionExportUsageInfo, compute_export_usage_info}, export_usage::{OptionExportUsageInfo, compute_export_usage_info},
}, },
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
reference_type::{EntryReferenceSubType, ReferenceType},
resolve::{FindContextFileResult, find_context_file}, resolve::{FindContextFileResult, find_context_file},
source_map::OptionStringifiedSourceMap, source_map::OptionStringifiedSourceMap,
version::{ version::{
...@@ -1412,16 +1413,12 @@ impl Project { ...@@ -1412,16 +1413,12 @@ impl Project {
}; };
let source = Vc::upcast(FileSource::new(fs_path.clone())); let source = Vc::upcast(FileSource::new(fs_path.clone()));
let module = edge_module_context let runtime = parse_segment_config_from_source(source, ParseSegmentMode::Base)
.process( .await?
source, .runtime
ReferenceType::Entry(EntryReferenceSubType::Middleware), .unwrap_or(NextRuntime::Edge);
)
.module();
let config = parse_config_from_source(source, module, NextRuntime::Edge).await?;
if matches!(config.runtime, NextRuntime::NodeJs) { if matches!(runtime, NextRuntime::NodeJs) {
Ok(self.node_middleware_context()) Ok(self.node_middleware_context())
} else { } else {
Ok(edge_module_context) Ok(edge_module_context)
......
This diff is collapsed.
...@@ -5,7 +5,6 @@ ...@@ -5,7 +5,6 @@
#![feature(iter_intersperse)] #![feature(iter_intersperse)]
mod app_page_loader_tree; mod app_page_loader_tree;
pub mod app_segment_config;
pub mod app_structure; pub mod app_structure;
mod base_loader_tree; mod base_loader_tree;
mod bootstrap; mod bootstrap;
...@@ -36,14 +35,12 @@ mod next_shared; ...@@ -36,14 +35,12 @@ mod next_shared;
pub mod next_telemetry; pub mod next_telemetry;
mod page_loader; mod page_loader;
pub mod pages_structure; pub mod pages_structure;
pub mod segment_config;
pub mod tracing_presets; pub mod tracing_presets;
mod transform_options; mod transform_options;
pub mod url_node; pub mod url_node;
pub mod util; pub mod util;
pub use app_segment_config::{
parse_segment_config_from_loader_tree, parse_segment_config_from_source,
};
pub use emit::{all_assets_from_entries, emit_all_assets, emit_assets}; pub use emit::{all_assets_from_entries, emit_all_assets, emit_assets};
pub use next_edge::context::{ pub use next_edge::context::{
get_edge_chunking_context, get_edge_chunking_context_with_client_assets, get_edge_chunking_context, get_edge_chunking_context_with_client_assets,
...@@ -51,4 +48,5 @@ pub use next_edge::context::{ ...@@ -51,4 +48,5 @@ pub use next_edge::context::{
}; };
pub use next_import_map::get_next_package; pub use next_import_map::get_next_package;
pub use page_loader::{PageLoaderAsset, create_page_loader_entry_module}; pub use page_loader::{PageLoaderAsset, create_page_loader_entry_module};
pub use segment_config::{parse_segment_config_from_loader_tree, parse_segment_config_from_source};
pub use util::{PathType, get_asset_path_from_pathname, pathname_for_path}; pub use util::{PathType, get_asset_path_from_pathname, pathname_for_path};
...@@ -2,7 +2,7 @@ use turbo_rcstr::RcStr; ...@@ -2,7 +2,7 @@ use turbo_rcstr::RcStr;
use turbo_tasks::ResolvedVc; use turbo_tasks::ResolvedVc;
use turbopack_core::module::Module; use turbopack_core::module::Module;
use crate::app_segment_config::NextSegmentConfig; use crate::segment_config::NextSegmentConfig;
/// The entry module asset for a Next.js app route or page. /// The entry module asset for a Next.js app route or page.
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
......
...@@ -11,11 +11,11 @@ use turbopack_core::{ ...@@ -11,11 +11,11 @@ use turbopack_core::{
}; };
use crate::{ use crate::{
app_segment_config::NextSegmentConfig,
next_app::{AppEntry, AppPage, AppPath}, next_app::{AppEntry, AppPage, AppPath},
next_config::{NextConfig, OutputType}, next_config::{NextConfig, OutputType},
next_edge::entry::wrap_edge_entry, next_edge::entry::wrap_edge_entry,
parse_segment_config_from_source, parse_segment_config_from_source,
segment_config::{NextSegmentConfig, ParseSegmentMode},
util::{NextRuntime, app_function_name, load_next_js_template}, util::{NextRuntime, app_function_name, load_next_js_template},
}; };
...@@ -36,7 +36,7 @@ pub async fn get_app_route_entry( ...@@ -36,7 +36,7 @@ pub async fn get_app_route_entry(
original_segment_config: Option<Vc<NextSegmentConfig>>, original_segment_config: Option<Vc<NextSegmentConfig>>,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
) -> Result<Vc<AppEntry>> { ) -> Result<Vc<AppEntry>> {
let segment_from_source = parse_segment_config_from_source(source); let segment_from_source = parse_segment_config_from_source(source, ParseSegmentMode::App);
let config = if let Some(original_segment_config) = original_segment_config { let config = if let Some(original_segment_config) = original_segment_config {
let mut segment_config = segment_from_source.owned().await?; let mut segment_config = segment_from_source.owned().await?;
segment_config.apply_parent_config(&*original_segment_config.await?); segment_config.apply_parent_config(&*original_segment_config.await?);
......
...@@ -27,6 +27,7 @@ use crate::{ ...@@ -27,6 +27,7 @@ use crate::{
}, },
next_config::NextConfig, next_config::NextConfig,
parse_segment_config_from_source, parse_segment_config_from_source,
segment_config::ParseSegmentMode,
}; };
/// Computes the route source for a Next.js metadata file. /// Computes the route source for a Next.js metadata file.
...@@ -68,7 +69,7 @@ pub async fn get_app_metadata_route_entry( ...@@ -68,7 +69,7 @@ pub async fn get_app_metadata_route_entry(
let original_path = metadata.clone().into_path(); let original_path = metadata.clone().into_path();
let source = Vc::upcast(FileSource::new(original_path)); let source = Vc::upcast(FileSource::new(original_path));
let segment_config = parse_segment_config_from_source(source); let segment_config = parse_segment_config_from_source(source, ParseSegmentMode::App);
let is_dynamic_metadata = matches!(metadata, MetadataItem::Dynamic { .. }); let is_dynamic_metadata = matches!(metadata, MetadataItem::Dynamic { .. });
let is_multi_dynamic: bool = if Some(segment_config).is_some() { let is_multi_dynamic: bool = if Some(segment_config).is_some() {
// is_multi_dynamic is true when config.generateSitemaps or // is_multi_dynamic is true when config.generateSitemaps or
......
...@@ -15,9 +15,8 @@ use crate::{ ...@@ -15,9 +15,8 @@ use crate::{
get_server_actions_transform_rule, next_amp_attributes::get_next_amp_attr_rule, get_server_actions_transform_rule, next_amp_attributes::get_next_amp_attr_rule,
next_cjs_optimizer::get_next_cjs_optimizer_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_page_config::get_next_page_config_rule, next_page_config::get_next_page_config_rule, next_pure::get_next_pure_rule,
next_page_static_info::get_next_page_static_info_assert_rule, server_actions::ActionsTransform,
next_pure::get_next_pure_rule, server_actions::ActionsTransform,
}, },
}; };
...@@ -103,11 +102,6 @@ pub async fn get_next_client_transforms_rules( ...@@ -103,11 +102,6 @@ pub async fn get_next_client_transforms_rules(
); );
rules.push(get_next_image_rule().await?); rules.push(get_next_image_rule().await?);
rules.push(get_next_page_static_info_assert_rule(
enable_mdx_rs,
None,
Some(context_ty),
));
} }
Ok(rules) Ok(rules)
......
...@@ -18,7 +18,6 @@ use crate::{ ...@@ -18,7 +18,6 @@ use crate::{
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,
next_page_static_info::get_next_page_static_info_assert_rule,
next_pure::get_next_pure_rule, server_actions::ActionsTransform, next_pure::get_next_pure_rule, server_actions::ActionsTransform,
}, },
util::{NextRuntime, module_styles_rule_condition, styles_rule_condition}, util::{NextRuntime, module_styles_rule_condition, styles_rule_condition},
...@@ -66,14 +65,6 @@ pub async fn get_next_server_transforms_rules( ...@@ -66,14 +65,6 @@ pub async fn get_next_server_transforms_rules(
]); ]);
} }
if !foreign_code {
rules.push(get_next_page_static_info_assert_rule(
mdx_rs,
Some(context_ty.clone()),
None,
));
}
let use_cache_enabled = *next_config.enable_use_cache().await?; let use_cache_enabled = *next_config.enable_use_cache().await?;
let cache_kinds = next_config.cache_kinds().to_resolved().await?; let cache_kinds = next_config.cache_kinds().to_resolved().await?;
let mut is_app_dir = false; let mut is_app_dir = false;
......
...@@ -11,7 +11,6 @@ pub(crate) mod next_lint; ...@@ -11,7 +11,6 @@ pub(crate) mod next_lint;
pub(crate) mod next_middleware_dynamic_assert; pub(crate) mod next_middleware_dynamic_assert;
pub(crate) mod next_optimize_server_react; pub(crate) mod next_optimize_server_react;
pub(crate) mod next_page_config; pub(crate) mod next_page_config;
pub(crate) mod next_page_static_info;
pub(crate) mod next_pure; pub(crate) mod next_pure;
pub(crate) mod next_react_server_components; pub(crate) mod next_react_server_components;
pub(crate) mod next_shake_exports; pub(crate) mod next_shake_exports;
......
use anyhow::Result;
use async_trait::async_trait;
use next_custom_transforms::transforms::page_static_info::{
Const, collect_exported_const_visitor::GetMut, collect_exports, extract_exported_const_values,
};
use serde_json::Value;
use swc_core::{
atoms::{Atom, atom},
common::source_map::SmallPos,
ecma::ast::Program,
};
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::{ModuleRule, ModuleRuleEffect};
use turbopack_core::issue::{
Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, OptionIssueSource, OptionStyledString,
StyledString,
};
use turbopack_ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext};
use super::module_rule_match_js_no_url;
use crate::{next_client::ClientContextType, next_server::ServerContextType};
/// Create a rule to run assertions for the page-static-info.
/// This assertion is partial implementation to the original
/// (analysis/get-page-static-info) Due to not able to bring all the evaluations
/// in the js implementation,
pub fn get_next_page_static_info_assert_rule(
enable_mdx_rs: bool,
server_context: Option<ServerContextType>,
client_context: Option<ClientContextType>,
) -> ModuleRule {
let transformer =
EcmascriptInputTransform::Plugin(ResolvedVc::cell(Box::new(NextPageStaticInfo {
server_context,
client_context,
}) as _));
ModuleRule::new(
module_rule_match_js_no_url(enable_mdx_rs),
vec![ModuleRuleEffect::ExtendEcmascriptTransforms {
preprocess: ResolvedVc::cell(vec![transformer]),
main: ResolvedVc::cell(vec![]),
postprocess: ResolvedVc::cell(vec![]),
}],
)
}
#[derive(Debug)]
struct NextPageStaticInfo {
server_context: Option<ServerContextType>,
client_context: Option<ClientContextType>,
}
#[derive(Default)]
struct PropertiesToExtract {
config: Option<Const>,
}
impl GetMut<Atom, Option<Const>> for PropertiesToExtract {
fn get_mut(&mut self, key: &Atom) -> Option<&mut Option<Const>> {
if key == &atom!("config") {
Some(&mut self.config)
} else {
None
}
}
}
#[async_trait]
impl CustomTransformer for NextPageStaticInfo {
#[tracing::instrument(level = tracing::Level::TRACE, name = "next_page_static_info", skip_all)]
async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
if let Some(collected_exports) = collect_exports(program)? {
let mut properties_to_extract = PropertiesToExtract::default();
extract_exported_const_values(program, &mut properties_to_extract);
let is_server_layer_page = matches!(
self.server_context,
Some(ServerContextType::AppRSC { .. }) | Some(ServerContextType::AppSSR { .. })
);
let is_app_page = is_server_layer_page
|| matches!(self.client_context, Some(ClientContextType::App { .. }));
if is_server_layer_page {
for warning in collected_exports.warnings.iter() {
PageStaticInfoIssue {
source: IssueSource::from_swc_offsets(
ctx.source,
warning.span.lo.to_u32(),
warning.span.hi.to_u32(),
),
messages: vec![
format!(
"Next.js can't recognize the exported `{}` field in \"{}\" as {}.",
warning.key, ctx.file_path_str, warning.message
),
"The default runtime will be used instead.".to_string(),
],
severity: IssueSeverity::Warning,
}
.resolved_cell()
.emit();
}
}
if is_app_page
&& let Some(Const::Value(Value::Object(config_obj), span)) =
properties_to_extract.config
{
let mut messages = vec![format!(
"Page config in {} is deprecated. Replace `export const config=…` with the \
following:",
ctx.file_path_str
)];
if let Some(runtime) = config_obj.get("runtime") {
messages.push(format!("- `export const runtime = {runtime}`"));
}
if let Some(regions) = config_obj.get("regions") {
messages.push(format!("- `export const preferredRegion = {regions}`"));
}
messages.push("Visit https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config for more information.".to_string());
PageStaticInfoIssue {
source: IssueSource::from_swc_offsets(
ctx.source,
span.lo.to_u32(),
span.hi.to_u32(),
),
messages,
severity: IssueSeverity::Warning,
}
.resolved_cell()
.emit();
}
if collected_exports.directives.contains(&atom!("client"))
&& let Some(span) = collected_exports.generate_static_params
&& is_app_page
{
PageStaticInfoIssue {
source: IssueSource::from_swc_offsets(
ctx.source,
span.lo.to_u32(),
span.hi.to_u32(),
),
messages: vec![format!(r#"Page "{}" cannot use both "use client" and export function "generateStaticParams()"."#, ctx.file_path_str)],
severity: IssueSeverity::Error,
}
.resolved_cell()
.emit();
}
}
Ok(())
}
}
#[turbo_tasks::value(shared)]
struct PageStaticInfoIssue {
source: IssueSource,
messages: Vec<String>,
severity: IssueSeverity,
}
#[turbo_tasks::value_impl]
impl Issue for PageStaticInfoIssue {
fn severity(&self) -> IssueSeverity {
self.severity
}
#[turbo_tasks::function]
fn stage(&self) -> Vc<IssueStage> {
IssueStage::Transform.into()
}
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
StyledString::Text(rcstr!("Invalid page configuration")).cell()
}
#[turbo_tasks::function]
fn file_path(&self) -> Vc<FileSystemPath> {
self.source.file_path()
}
#[turbo_tasks::function]
fn description(&self) -> Vc<OptionStyledString> {
Vc::cell(Some(
StyledString::Line(
self.messages
.iter()
.map(|v| StyledString::Text(format!("{v}\n").into()))
.collect::<Vec<StyledString>>(),
)
.resolved_cell(),
))
}
#[turbo_tasks::function]
fn source(&self) -> Vc<OptionIssueSource> {
Vc::cell(Some(self.source))
}
}
This diff is collapsed.
This diff is collapsed.
...@@ -12,7 +12,6 @@ pub mod next_ssg; ...@@ -12,7 +12,6 @@ pub mod next_ssg;
pub mod optimize_barrel; pub mod optimize_barrel;
pub mod optimize_server_react; pub mod optimize_server_react;
pub mod page_config; pub mod page_config;
pub mod page_static_info;
pub mod pure; pub mod pure;
pub mod react_server_components; pub mod react_server_components;
pub mod server_actions; pub mod server_actions;
......
use serde_json::{Map, Number, Value};
use swc_core::{
atoms::Atom,
common::{Mark, Span, Spanned, SyntaxContext},
ecma::{
ast::{
BindingIdent, Decl, ExportDecl, Expr, Lit, Module, ModuleDecl, ModuleItem, Pat,
Program, Prop, PropName, PropOrSpread, VarDecl, VarDeclKind, VarDeclarator,
},
utils::{ExprCtx, ExprExt},
},
};
/// The values extracted for the corresponding AST node.
/// refer extract_exported_const_values for the supported value types.
/// Undefined / null is treated as None.
pub enum Const {
Value(Value, Span),
Unsupported(String, Span),
}
pub(crate) struct CollectExportedConstVisitor<'a, M>
where
M: GetMut<Atom, Option<Const>>,
{
pub properties: &'a mut M,
expr_ctx: ExprCtx,
}
impl<'a, M> CollectExportedConstVisitor<'a, M>
where
M: GetMut<Atom, Option<Const>>,
{
pub fn new(properties: &'a mut M) -> Self {
Self {
properties,
expr_ctx: ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(Mark::new()),
is_unresolved_ref_safe: false,
in_strict: false,
remaining_depth: 4,
},
}
}
pub fn check_program(&mut self, program: &Program) {
let Program::Module(Module { body, .. }) = program else {
return;
};
for module_item in body {
if let ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Var(decl),
..
})) = module_item
{
let VarDecl { kind, decls, .. } = &**decl;
if kind == &VarDeclKind::Const {
for decl in decls {
if let VarDeclarator {
name: Pat::Ident(BindingIdent { id, .. }),
init: Some(init),
..
} = decl
{
let id = &id.sym;
if let Some(prop) = self.properties.get_mut(id) {
*prop = extract_value(self.expr_ctx, init, id.to_string());
};
}
}
}
}
}
}
}
pub trait GetMut<K, V> {
fn get_mut(&mut self, key: &K) -> Option<&mut V>;
}
/// Coerece the actual value of the given ast node.
fn extract_value(ctx: ExprCtx, init: &Expr, id: String) -> Option<Const> {
match init {
init if init.is_undefined(ctx) => Some(Const::Value(Value::Null, init.span())),
Expr::Ident(ident) => Some(Const::Unsupported(
format!("Unknown identifier \"{}\" at \"{}\".", ident.sym, id),
init.span(),
)),
Expr::Lit(lit) => match lit {
Lit::Num(num) => Some(Const::Value(
Value::Number(
Number::from_f64(num.value).expect("Should able to convert f64 to Number"),
),
init.span(),
)),
Lit::Null(_) => Some(Const::Value(Value::Null, init.span())),
Lit::Str(s) => Some(Const::Value(
Value::String(s.value.to_string()),
init.span(),
)),
Lit::Bool(b) => Some(Const::Value(Value::Bool(b.value), init.span())),
Lit::Regex(r) => Some(Const::Value(
Value::String(format!("/{}/{}", r.exp, r.flags)),
init.span(),
)),
_ => Some(Const::Unsupported(
"Unsupported Literal".to_string(),
init.span(),
)),
},
Expr::Array(arr) => {
let mut a = vec![];
for elem in &arr.elems {
match elem {
Some(elem) => {
if elem.spread.is_some() {
return Some(Const::Unsupported(
format!(
"Unsupported spread operator in the Array Expression at \
\"{id}\""
),
init.span(),
));
}
match extract_value(ctx, &elem.expr, id.clone()) {
Some(Const::Value(value, _)) => a.push(value),
Some(Const::Unsupported(message, loc)) => {
return Some(Const::Unsupported(
format!("Unsupported value in the Array Expression: {message}"),
loc,
));
}
_ => {
return Some(Const::Unsupported(
"Unsupported value in the Array Expression".to_string(),
elem.expr.span(),
));
}
}
}
None => {
a.push(Value::Null);
}
}
}
Some(Const::Value(Value::Array(a), arr.span()))
}
Expr::Object(obj) => {
let mut o = Map::new();
for prop in &obj.props {
let (key, value) = match prop {
PropOrSpread::Prop(box Prop::KeyValue(kv)) => (
match &kv.key {
PropName::Ident(i) => i.sym.as_ref(),
PropName::Str(s) => s.value.as_ref(),
_ => {
return Some(Const::Unsupported(
format!(
"Unsupported key type in the Object Expression at \"{id}\""
),
kv.key.span(),
));
}
},
&kv.value,
),
_ => {
return Some(Const::Unsupported(
format!(
"Unsupported spread operator in the Object Expression at \"{id}\""
),
prop.span(),
));
}
};
let new_value = extract_value(ctx, value, format!("{id}.{key}"));
if let Some(Const::Unsupported(_, _)) = new_value {
return new_value;
}
if let Some(Const::Value(value, _)) = new_value {
o.insert(key.to_string(), value);
}
}
Some(Const::Value(Value::Object(o), obj.span()))
}
Expr::Tpl(tpl) => {
// [TODO] should we add support for `${'e'}d${'g'}'e'`?
if !tpl.exprs.is_empty() {
Some(Const::Unsupported(
format!("Unsupported template literal with expressions at \"{id}\"."),
tpl.span(),
))
} else {
Some(
tpl.quasis
.first()
.map(|q| {
// When TemplateLiteral has 0 expressions, the length of quasis is
// always 1. Because when parsing
// TemplateLiteral, the parser yields the first quasi,
// then the first expression, then the next quasi, then the next
// expression, etc., until the last quasi.
// Thus if there is no expression, the parser ends at the first and also
// last quasis
//
// A "cooked" interpretation where backslashes have special meaning,
// while a "raw" interpretation where
// backslashes do not have special meaning https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw
let cooked = q.cooked.as_ref();
let raw = q.raw.as_ref();
Const::Value(
Value::String(
cooked.map(|c| c.to_string()).unwrap_or(raw.to_string()),
),
tpl.span(),
)
})
.unwrap_or(Const::Unsupported(
format!("Unsupported node type at \"{id}\""),
tpl.span(),
)),
)
}
}
_ => Some(Const::Unsupported(
format!("Unsupported node type at \"{id}\""),
init.span(),
)),
}
}
use std::{iter::FromIterator, sync::LazyLock};
use rustc_hash::FxHashSet;
use swc_core::{
atoms::atom,
common::Spanned,
ecma::{
ast::{
Decl, ExportDecl, ExportNamedSpecifier, ExportSpecifier, Expr, ExprOrSpread, ExprStmt,
Lit, ModuleExportName, ModuleItem, NamedExport, Pat, Stmt, Str, VarDeclarator,
},
visit::{Visit, VisitWith},
},
};
use super::{ExportInfo, ExportInfoWarning};
static EXPORTS_SET: LazyLock<FxHashSet<&'static str>> = LazyLock::new(|| {
FxHashSet::from_iter([
"getStaticProps",
"getServerSideProps",
"generateImageMetadata",
"generateSitemaps",
"generateStaticParams",
])
});
pub(crate) struct CollectExportsVisitor {
pub export_info: Option<ExportInfo>,
}
impl CollectExportsVisitor {
pub fn new() -> Self {
Self {
export_info: Default::default(),
}
}
}
impl Visit for CollectExportsVisitor {
fn visit_module_items(&mut self, stmts: &[swc_core::ecma::ast::ModuleItem]) {
let mut is_directive = true;
for stmt in stmts {
if let ModuleItem::Stmt(Stmt::Expr(ExprStmt {
expr: box Expr::Lit(Lit::Str(Str { value, .. })),
..
})) = stmt
{
if is_directive {
if value == "use server" {
let export_info = self.export_info.get_or_insert(Default::default());
export_info.directives.insert(atom!("server"));
}
if value == "use client" {
let export_info = self.export_info.get_or_insert(Default::default());
export_info.directives.insert(atom!("client"));
}
}
} else {
is_directive = false;
}
stmt.visit_children_with(self);
}
}
fn visit_export_decl(&mut self, export_decl: &ExportDecl) {
match &export_decl.decl {
Decl::Var(box var_decl) => {
if let Some(VarDeclarator {
name: Pat::Ident(name),
..
}) = var_decl.decls.first()
{
if EXPORTS_SET.contains(&name.sym.as_str()) {
let export_info = self.export_info.get_or_insert(Default::default());
export_info.ssg = name.sym == "getStaticProps";
export_info.ssr = name.sym == "getServerSideProps";
export_info.generate_image_metadata =
Some(name.sym == "generateImageMetadata");
export_info.generate_sitemaps = Some(name.sym == "generateSitemaps");
export_info.generate_static_params =
(name.sym == "generateStaticParams").then_some(name.span());
}
}
for decl in &var_decl.decls {
if let Pat::Ident(id) = &decl.name {
if id.sym == "runtime" {
let export_info = self.export_info.get_or_insert(Default::default());
export_info.runtime = decl.init.as_ref().and_then(|init| {
if let Expr::Lit(Lit::Str(Str { value, .. })) = &**init {
Some(value.clone())
} else {
None
}
})
} else if id.sym == "preferredRegion" {
if let Some(init) = &decl.init {
if let Expr::Array(arr) = &**init {
for expr in arr.elems.iter().flatten() {
if let ExprOrSpread {
expr: box Expr::Lit(Lit::Str(Str { value, .. })),
..
} = expr
{
let export_info =
self.export_info.get_or_insert(Default::default());
export_info.preferred_region.push(value.clone());
}
}
} else if let Expr::Lit(Lit::Str(Str { value, .. })) = &**init {
let export_info =
self.export_info.get_or_insert(Default::default());
export_info.preferred_region.push(value.clone());
}
}
} else {
let export_info = self.export_info.get_or_insert(Default::default());
export_info.extra_properties.insert(id.sym.clone());
}
}
}
}
Decl::Fn(fn_decl) => {
let id = &fn_decl.ident;
let export_info = self.export_info.get_or_insert(Default::default());
export_info.ssg = id.sym == "getStaticProps";
export_info.ssr = id.sym == "getServerSideProps";
export_info.generate_image_metadata = Some(id.sym == "generateImageMetadata");
export_info.generate_sitemaps = Some(id.sym == "generateSitemaps");
export_info.generate_static_params =
(id.sym == "generateStaticParams").then_some(id.span());
}
_ => {}
}
export_decl.visit_children_with(self);
}
fn visit_named_export(&mut self, named_export: &NamedExport) {
for specifier in &named_export.specifiers {
if let ExportSpecifier::Named(ExportNamedSpecifier {
orig: ModuleExportName::Ident(value),
..
}) = specifier
{
let export_info = self.export_info.get_or_insert(Default::default());
if !export_info.ssg && value.sym == "getStaticProps" {
export_info.ssg = true;
}
if !export_info.ssr && value.sym == "getServerSideProps" {
export_info.ssr = true;
}
if !export_info.generate_image_metadata.unwrap_or_default()
&& value.sym == "generateImageMetadata"
{
export_info.generate_image_metadata = Some(true);
}
if !export_info.generate_sitemaps.unwrap_or_default()
&& value.sym == "generateSitemaps"
{
export_info.generate_sitemaps = Some(true);
}
if export_info.generate_static_params.is_none()
&& value.sym == "generateStaticParams"
{
export_info.generate_static_params = Some(value.span());
}
if export_info.runtime.is_none() && value.sym == "runtime" {
export_info.warnings.push(ExportInfoWarning::new(
value.sym.clone(),
"it was not assigned to a string literal",
value.span,
));
}
if export_info.preferred_region.is_empty() && value.sym == "preferredRegion" {
export_info.warnings.push(ExportInfoWarning::new(
value.sym.clone(),
"it was not assigned to a string literal or an array of string literals",
value.span,
));
}
}
}
named_export.visit_children_with(self);
}
}
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
describe('app-dir edge SSR invalid reexport', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: {
'app/export': new FileRef(path.join(__dirname, 'app', 'export')),
'app/export/inherit/page.tsx':
"export { default, runtime, preferredRegion } from '../basic/page'",
},
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should warn or error about the re-export of a pages runtime/preferredRegion config', async () => {
try {
await next.start()
} catch (_) {
// We expect the build to fail
}
if (isNextDev) {
const browser = await next.browser('/export/inherit')
// Turbopack is stricter and disallows reexports completely
// webpack merely warns in the CLI and still serves the page wuthout a redbox
if (process.env.IS_TURBOPACK_TEST) {
await expect(browser).toDisplayRedbox(`
{
"description": "Next.js can't recognize the exported \`preferredRegion\` field in route. It mustn't be reexported.",
"environmentLabel": null,
"label": "Build Error",
"source": "./app/export/inherit/page.tsx (1:28)
Next.js can't recognize the exported \`preferredRegion\` field in route. It mustn't be reexported.
> 1 | export { default, runtime, preferredRegion } from '../basic/page'
| ^^^^^^^^^^^^^^^",
"stack": [],
}
`)
}
}
expect(next.cliOutput).toInclude(
`Next.js can't recognize the exported \`runtime\` field in`
)
expect(next.cliOutput).toInclude(
`Next.js can't recognize the exported \`preferredRegion\` field in`
)
})
})
...@@ -35,29 +35,6 @@ describe('app-dir edge SSR', () => { ...@@ -35,29 +35,6 @@ describe('app-dir edge SSR', () => {
}) })
if ((globalThis as any).isNextDev) { if ((globalThis as any).isNextDev) {
it('should warn about the re-export of a pages runtime/preferredRegion config', async () => {
const logs = []
next.on('stderr', (log) => {
logs.push(log)
})
const appHtml = await next.render('/export/inherit')
expect(appHtml).toContain('<p>Node!</p>')
expect(
logs.some((log) =>
log.includes(
`Next.js can't recognize the exported \`runtime\` field in`
)
)
).toBe(true)
expect(
logs.some((log) =>
log.includes(
`Next.js can't recognize the exported \`preferredRegion\` field in`
)
)
).toBe(true)
})
it('should resolve module without error in edge runtime', async () => { it('should resolve module without error in edge runtime', async () => {
const logs = [] const logs = []
next.on('stderr', (log) => { next.on('stderr', (log) => {
......
export { default, runtime, preferredRegion } from '../basic/page' export { default } from '../basic/page'
...@@ -25,8 +25,8 @@ describe('app dir - with output export - dynamic missing gsp dev', () => { ...@@ -25,8 +25,8 @@ describe('app dir - with output export - dynamic missing gsp dev', () => {
}) })
it('should error when client component has generateStaticParams', async () => { it('should error when client component has generateStaticParams', async () => {
const expectedErrMsg = process.env.TURBOPACK_DEV const expectedErrMsg = process.env.IS_TURBOPACK_TEST
? 'Page "test/integration/app-dir-export/app/another/[slug]/page.js" cannot use both "use client" and export function "generateStaticParams()".' ? 'App pages cannot use both "use client" and export function "generateStaticParams()".'
: 'Page "/another/[slug]/page" cannot use both "use client" and export function "generateStaticParams()".' : 'Page "/another/[slug]/page" cannot use both "use client" and export function "generateStaticParams()".'
await runTests({ await runTests({
isDev: true, isDev: true,
......
...@@ -10,17 +10,20 @@ describe('app dir - with output export - dynamic missing gsp prod', () => { ...@@ -10,17 +10,20 @@ describe('app dir - with output export - dynamic missing gsp prod', () => {
dynamicPage: 'undefined', dynamicPage: 'undefined',
generateStaticParamsOpt: 'set noop', generateStaticParamsOpt: 'set noop',
expectedErrMsg: expectedErrMsg:
/Page ".*\/another\/\[slug\].*" is missing "generateStaticParams\(\)" so it cannot be used with "output: export" config\./, 'Page "/another/[slug]" is missing "generateStaticParams()" so it cannot be used with "output: export" config.',
}) })
}) })
it('should error when client component has generateStaticParams', async () => { it('should error when client component has generateStaticParams', async () => {
const expectedErrMsg = process.env.IS_TURBOPACK_TEST
? 'App pages cannot use both "use client" and export function "generateStaticParams()".'
: 'Page "/another/[slug]/page" cannot use both "use client" and export function "generateStaticParams()".'
await runTests({ await runTests({
isDev: false, isDev: false,
dynamicPage: 'undefined', dynamicPage: 'undefined',
generateStaticParamsOpt: 'set client', generateStaticParamsOpt: 'set client',
expectedErrMsg: expectedErrMsg: expectedErrMsg,
/Page ".*\/another\/\[slug\]\/page.*" cannot use both "use client" and export function "generateStaticParams\(\)"\./,
}) })
}) })
} }
......
...@@ -24,9 +24,7 @@ const writeMiddleware = async (matchers) => { ...@@ -24,9 +24,7 @@ const writeMiddleware = async (matchers) => {
) )
} }
let getStderr const runTests = (getStderr, isDev) => {
const runTests = () => {
it('should error when source length is exceeded', async () => { it('should error when source length is exceeded', async () => {
await writeMiddleware([{ source: `/${Array(4096).join('a')}` }]) await writeMiddleware([{ source: `/${Array(4096).join('a')}` }])
const stderr = await getStderr() const stderr = await getStderr()
...@@ -85,36 +83,66 @@ const runTests = () => { ...@@ -85,36 +83,66 @@ const runTests = () => {
]) ])
const stderr = await getStderr() const stderr = await getStderr()
expect(stderr).toContain( // TODO the Javascript "/middleware contains invalid middleware config" error currently shadows the Turbopack one in development
'Expected string, received object at "matcher[0]", or source is required at "matcher[0].source"' if (process.env.IS_TURBOPACK_TEST && !isDev) {
) expect(stderr).toContain('Turbopack build failed with 10 errors')
expect(stderr).toContain(
'Expected string, received number at "matcher[1].source"' let matches = 0
) matches += stderr.includes('Missing `source` in `matcher[0]` object')
expect(stderr).toContain('source must start with / at "matcher[2]"') matches += stderr.includes('Missing `source` in `matcher[1]` object')
expect(stderr).toContain( matches += stderr.includes('Unexpected property in `matcher[3]` object')
'Unrecognized key(s) in object: \'destination\' at "matcher[3]"' matches += stderr.includes(
) 'Entry `matcher[4]` need to be static strings or static objects.'
expect(stderr).toContain('Expected string, received null at "matcher[4]"') )
expect(stderr).toContain( matches += stderr.includes(
"Expected 'header' | 'query' | 'cookie' | 'host' at \"matcher[6].has[1].type\"" "`matcher[5].has[0].type` must be one of the strings: 'header', 'cookie', 'query', 'host'"
) )
matches += stderr.includes(
"`matcher[6].has[0].type` must be one of the strings: 'header', 'cookie', 'query', 'host'"
)
matches += stderr.includes('Unexpected property in `matcher[7]` object')
matches += stderr.includes(
'`locale` in `matcher[8]` object must be false or undefined'
)
// TODO somehow stderr is doesn't contain everything. It does print 10 messages when running next standalone
if (matches < 4) {
throw new Error('Missing error messages for stderr:\n' + stderr)
}
} else {
expect(stderr).toContain(
'Expected string, received object at "matcher[0]", or source is required at "matcher[0].source"'
)
expect(stderr).toContain(
'Expected string, received number at "matcher[1].source"'
)
expect(stderr).toContain(
'Unrecognized key(s) in object: \'destination\' at "matcher[3]"'
)
expect(stderr).toContain('Expected string, received null at "matcher[4]"')
expect(stderr).toContain(
"Expected 'header' | 'query' | 'cookie' | 'host' at \"matcher[6].has[1].type\""
)
expect(stderr).toContain(
"Expected 'header' | 'query' | 'cookie' | 'host' at \"matcher[5].has[0].type\""
)
expect(stderr).toContain(
"Expected 'header' | 'query' | 'cookie' | 'host' at \"matcher[6].has[0].type\""
)
expect(stderr).toContain(
"Expected 'header' | 'query' | 'cookie' | 'host' at \"matcher[6].has[1].type\""
)
expect(stderr).toContain(
'Unrecognized key(s) in object: \'basePath\' at "matcher[7]"'
)
expect(stderr).toContain(
'Expected string, received object at "matcher[8]", or Invalid literal value, expected false at "matcher[8].locale", or Expected undefined, received boolean at "matcher[8].locale"'
)
expect(stderr).toContain( // TODO currently not covered by Turbopack
"Expected 'header' | 'query' | 'cookie' | 'host' at \"matcher[5].has[0].type\"" expect(stderr).toContain('source must start with / at "matcher[2]"')
) }
expect(stderr).toContain(
"Expected 'header' | 'query' | 'cookie' | 'host' at \"matcher[6].has[0].type\""
)
expect(stderr).toContain(
"Expected 'header' | 'query' | 'cookie' | 'host' at \"matcher[6].has[1].type\""
)
expect(stderr).toContain(
'Unrecognized key(s) in object: \'basePath\' at "matcher[7]"'
)
expect(stderr).toContain(
'Expected string, received object at "matcher[8]", or Invalid literal value, expected false at "matcher[8].locale", or Expected undefined, received boolean at "matcher[8].locale"'
)
}) })
} }
...@@ -123,34 +151,27 @@ describe('Errors on invalid custom middleware matchers', () => { ...@@ -123,34 +151,27 @@ describe('Errors on invalid custom middleware matchers', () => {
;(process.env.TURBOPACK_BUILD ? describe.skip : describe)( ;(process.env.TURBOPACK_BUILD ? describe.skip : describe)(
'development mode', 'development mode',
() => { () => {
beforeAll(() => { runTests(async () => {
getStderr = async () => { let stderr = ''
let stderr = '' const port = await findPort()
const port = await findPort() await launchApp(appDir, port, {
await launchApp(appDir, port, { onStderr(msg) {
onStderr(msg) { stderr += msg
stderr += msg },
}, })
}) await fetchViaHTTP(port, '/').catch(() => {})
await fetchViaHTTP(port, '/').catch(() => {}) return stderr
return stderr }, true)
}
})
runTests()
} }
) )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
() => { () => {
beforeAll(() => { runTests(async () => {
getStderr = async () => { const { stderr } = await nextBuild(appDir, [], { stderr: true })
const { stderr } = await nextBuild(appDir, [], { stderr: true }) console.log(stderr)
return stderr return stderr
} }, false)
})
runTests()
} }
) )
}) })
...@@ -10,9 +10,13 @@ describe('Exported runtimes value validation', () => { ...@@ -10,9 +10,13 @@ describe('Exported runtimes value validation', () => {
) )
expect(result).toMatchObject({ expect(result).toMatchObject({
code: 1, code: 1,
stderr: expect.stringContaining( stderr: process.env.IS_TURBOPACK_TEST
`Invalid enum value. Expected 'edge' | 'experimental-edge' | 'nodejs', received 'something-odd'` ? expect.stringContaining(
), 'runtime` has an invalid value: unknown variant `something-odd`, expected one of `nodejs`, `edge`, `experimental-edge`'
)
: expect.stringContaining(
`Invalid enum value. Expected 'edge' | 'experimental-edge' | 'nodejs', received 'something-odd'`
),
}) })
}) })
...@@ -33,6 +37,11 @@ describe('Exported runtimes value validation', () => { ...@@ -33,6 +37,11 @@ describe('Exported runtimes value validation', () => {
"Next.js can't recognize the exported `config` field in route" "Next.js can't recognize the exported `config` field in route"
) )
) )
expect(result.stderr).toEqual(
expect.stringContaining(
' Entry `matcher[1]` need to be static strings or static objects.'
)
)
} else { } else {
expect(result.stderr).toEqual( expect(result.stderr).toEqual(
expect.stringContaining( expect.stringContaining(
...@@ -143,8 +152,6 @@ describe('Exported runtimes value validation', () => { ...@@ -143,8 +152,6 @@ describe('Exported runtimes value validation', () => {
"Next.js can't recognize the exported `config` field in route" "Next.js can't recognize the exported `config` field in route"
) )
) )
// ensure only 1 occurrence of the log
expect(result.stderr.match(/\/array-spread-operator/g)?.length).toBe(1)
// TODO: Turbopack has this information in issue.detail but it's not logged to the user. // TODO: Turbopack has this information in issue.detail but it's not logged to the user.
// expect(result.stderr).toEqual( // expect(result.stderr).toEqual(
// expect.stringContaining( // expect.stringContaining(
......
...@@ -418,6 +418,15 @@ impl EvalContext { ...@@ -418,6 +418,15 @@ impl EvalContext {
Expr::Lit(e) => JsValue::Constant(e.clone().into()), Expr::Lit(e) => JsValue::Constant(e.clone().into()),
Expr::Ident(i) => self.eval_ident(i), Expr::Ident(i) => self.eval_ident(i),
Expr::Unary(UnaryExpr {
op: op!("void"),
// Only treat literals as constant undefined, allowing arbitrary values inside here
// would mean that they can have sideeffects, and `JsValue::Constant` can't model
// that.
arg: box Expr::Lit(_),
..
}) => JsValue::Constant(ConstantValue::Undefined),
Expr::Unary(UnaryExpr { Expr::Unary(UnaryExpr {
op: op!("!"), arg, .. op: op!("!"), arg, ..
}) => { }) => {
......
...@@ -427,17 +427,13 @@ literalEscape = (...) => s["replace"](/\\/g, "\\\\")["replace"](/"/g, "\\\"")["r ...@@ -427,17 +427,13 @@ literalEscape = (...) => s["replace"](/\\/g, "\\\\")["replace"](/"/g, "\\\"")["r
location#105 = ( location#105 = (
| arguments[1] | arguments[1]
| ((location !== ???*0*) ? location : peg$computeLocation(peg$savedPos, peg$currPos)) | ((location !== undefined) ? location : peg$computeLocation(peg$savedPos, peg$currPos))
) )
- *0* unsupported expression
⚠️ This value might have side effects
location#106 = ( location#106 = (
| arguments[1] | arguments[1]
| ((location !== ???*0*) ? location : peg$computeLocation(peg$savedPos, peg$currPos)) | ((location !== undefined) ? location : peg$computeLocation(peg$savedPos, peg$currPos))
) )
- *0* unsupported expression
⚠️ This value might have side effects
location#123 = arguments[1] location#123 = arguments[1]
...@@ -467,9 +463,7 @@ operator#1802 = arguments[1][1] ...@@ -467,9 +463,7 @@ operator#1802 = arguments[1][1]
operator#87 = arguments[0] operator#87 = arguments[0]
options = (arguments[1] | ((options !== ???*0*) ? options : {})) options = (arguments[1] | ((options !== undefined) ? options : {}))
- *0* unsupported expression
⚠️ This value might have side effects
order = arguments[1] order = arguments[1]
...@@ -1823,11 +1817,9 @@ s0#982 = (???*0* | peg$c57 | peg$FAILED | peg$c54 | peg$c129 | peg$currPos | s1) ...@@ -1823,11 +1817,9 @@ s0#982 = (???*0* | peg$c57 | peg$FAILED | peg$c54 | peg$c129 | peg$currPos | s1)
- *0* s0 - *0* s0
⚠️ pattern without value ⚠️ pattern without value
s1#1019 = (???*0* | peg$currPos | ???*1* | peg$FAILED | peg$c149()) s1#1019 = (???*0* | peg$currPos | undefined | peg$FAILED | peg$c149())
- *0* s1 - *0* s1
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s1#1031 = (???*0* | peg$c150 | peg$FAILED | peg$c152(s2)) s1#1031 = (???*0* | peg$c150 | peg$FAILED | peg$c152(s2))
- *0* s1 - *0* s1
...@@ -2136,11 +2128,9 @@ s1#854 = (???*0* | peg$c114 | peg$FAILED | [s1, s2]) ...@@ -2136,11 +2128,9 @@ s1#854 = (???*0* | peg$c114 | peg$FAILED | [s1, s2])
- *0* s1 - *0* s1
⚠️ pattern without value ⚠️ pattern without value
s1#886 = (???*0* | peg$currPos | ???*1* | peg$FAILED | peg$c116(s2)) s1#886 = (???*0* | peg$currPos | undefined | peg$FAILED | peg$c116(s2))
- *0* s1 - *0* s1
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s1#897 = (???*0* | peg$parseidentifier_start() | peg$c121(s1, s2)) s1#897 = (???*0* | peg$parseidentifier_start() | peg$c121(s1, s2))
- *0* s1 - *0* s1
...@@ -2150,17 +2140,13 @@ s1#909 = (???*0* | peg$c122 | peg$FAILED | peg$c124()) ...@@ -2150,17 +2140,13 @@ s1#909 = (???*0* | peg$c122 | peg$FAILED | peg$c124())
- *0* s1 - *0* s1
⚠️ pattern without value ⚠️ pattern without value
s1#930 = (???*0* | peg$currPos | ???*1* | peg$FAILED | peg$c131() | peg$c129 | peg$c132(s2)) s1#930 = (???*0* | peg$currPos | undefined | peg$FAILED | peg$c131() | peg$c129 | peg$c132(s2))
- *0* s1 - *0* s1
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s1#952 = (???*0* | peg$currPos | ???*1* | peg$FAILED | peg$c131() | peg$c129 | peg$c132(s2)) s1#952 = (???*0* | peg$currPos | undefined | peg$FAILED | peg$c131() | peg$c129 | peg$c132(s2))
- *0* s1 - *0* s1
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s1#982 = ( s1#982 = (
| ???*0* | ???*0*
...@@ -2393,137 +2379,93 @@ s2#617 = (???*0* | []) ...@@ -2393,137 +2379,93 @@ s2#617 = (???*0* | [])
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
s2#644 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#644 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#654 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#654 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#664 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#664 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#674 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#674 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#684 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#684 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#694 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#694 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#704 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#704 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#714 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#714 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#724 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#724 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#734 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#734 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#744 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#744 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#754 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#754 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#764 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#764 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#774 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#774 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#784 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#784 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#794 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#794 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#804 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#804 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#814 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#814 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#824 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#824 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#834 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#834 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#844 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#844 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#854 = (???*0* | peg$currPos | ???*1* | peg$FAILED) s2#854 = (???*0* | peg$currPos | undefined | peg$FAILED)
- *0* s2 - *0* s2
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s2#886 = (???*0* | peg$parsereserved() | peg$parseidentifier_name()) s2#886 = (???*0* | peg$parsereserved() | peg$parseidentifier_name())
- *0* s2 - *0* s2
...@@ -2958,11 +2900,9 @@ s4#567 = (???*0* | []) ...@@ -2958,11 +2900,9 @@ s4#567 = (???*0* | [])
- *0* s4 - *0* s4
⚠️ pattern without value ⚠️ pattern without value
s4#617 = (???*0* | peg$currPos | ???*1* | peg$FAILED | [s4, s5]) s4#617 = (???*0* | peg$currPos | undefined | peg$FAILED | [s4, s5])
- *0* s4 - *0* s4
⚠️ pattern without value ⚠️ pattern without value
- *1* unsupported expression
⚠️ This value might have side effects
s5#1031 = (???*0* | peg$parsehex_digit()) s5#1031 = (???*0* | peg$parsehex_digit())
- *0* s5 - *0* s5
......
...@@ -555,21 +555,17 @@ ...@@ -555,21 +555,17 @@
- *0* unreachable - *0* unreachable
⚠️ This value might have side effects ⚠️ This value might have side effects
0 -> 157 conditional = ((???*0* | ???*1*) !== ???*6*) 0 -> 157 conditional = ((???*0* | ???*1*) !== undefined)
- *0* arguments[1] - *0* arguments[1]
⚠️ function calls are not analysed yet ⚠️ function calls are not analysed yet
- *1* (???*2* ? ???*5* : {}) - *1* (???*2* ? ???*4* : {})
⚠️ nested operation ⚠️ nested operation
- *2* (???*3* !== ???*4*) - *2* (???*3* !== undefined)
⚠️ nested operation ⚠️ nested operation
- *3* options - *3* options
⚠️ circular variable reference ⚠️ circular variable reference
- *4* unsupported expression - *4* options
⚠️ This value might have side effects
- *5* options
⚠️ circular variable reference ⚠️ circular variable reference
- *6* unsupported expression
⚠️ This value might have side effects
0 -> 158 unreachable = ???*0* 0 -> 158 unreachable = ???*0*
- *0* unreachable - *0* unreachable
...@@ -1153,11 +1149,9 @@ ...@@ -1153,11 +1149,9 @@
- *0* unreachable - *0* unreachable
⚠️ This value might have side effects ⚠️ This value might have side effects
0 -> 342 conditional = (???*0* !== ???*1*) 0 -> 342 conditional = (???*0* !== undefined)
- *0* max number of linking steps reached - *0* max number of linking steps reached
⚠️ This value might have side effects ⚠️ This value might have side effects
- *1* unsupported expression
⚠️ This value might have side effects
342 -> 343 call = (...) => { 342 -> 343 call = (...) => {
"start": {"offset": startPos, "line": startPosDetails["line"], "column": startPosDetails["column"]}, "start": {"offset": startPos, "line": startPosDetails["line"], "column": startPosDetails["column"]},
...@@ -1190,11 +1184,9 @@ ...@@ -1190,11 +1184,9 @@
- *3* max number of linking steps reached - *3* max number of linking steps reached
⚠️ This value might have side effects ⚠️ This value might have side effects
0 -> 348 conditional = (???*0* !== ???*1*) 0 -> 348 conditional = (???*0* !== undefined)
- *0* max number of linking steps reached - *0* max number of linking steps reached
⚠️ This value might have side effects ⚠️ This value might have side effects
- *1* unsupported expression
⚠️ This value might have side effects
348 -> 349 call = (...) => { 348 -> 349 call = (...) => {
"start": {"offset": startPos, "line": startPosDetails["line"], "column": startPosDetails["column"]}, "start": {"offset": startPos, "line": startPosDetails["line"], "column": startPosDetails["column"]},
......
...@@ -694,16 +694,14 @@ operator#87 = ???*0* ...@@ -694,16 +694,14 @@ operator#87 = ???*0*
- *0* arguments[0] - *0* arguments[0]
⚠️ function calls are not analysed yet ⚠️ function calls are not analysed yet
options = (???*0* | (???*1* ? ???*4* : {})) options = (???*0* | (???*1* ? ???*3* : {}))
- *0* arguments[1] - *0* arguments[1]
⚠️ function calls are not analysed yet ⚠️ function calls are not analysed yet
- *1* (???*2* !== ???*3*) - *1* (???*2* !== undefined)
⚠️ nested operation ⚠️ nested operation
- *2* options - *2* options
⚠️ circular variable reference ⚠️ circular variable reference
- *3* unsupported expression - *3* options
⚠️ This value might have side effects
- *4* options
⚠️ circular variable reference ⚠️ circular variable reference
order = ???*0* order = ???*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