Unverified Commit e1e25e16 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

use server component transform for segment validation (#72051)

After adding validation that fixing invalid segment configs (when DIO is
enabled), it revealed that errors weren't being displayed in Turbopack,
because `setHMRServerError` wasn't implemented.

This refactors the implementation to use the existing server component
transform when validating if the segments are valid. This has the
benefit of highlighting precisely where the segment is coming, making it
easier to remove. The test that was skipped in Turbopack is also
re-enabled.

<details>
<summary>Screenshot</summary>

![CleanShot 2024-10-29 at 17 03
46@2x](https://github.com/user-attachments/assets/a68c060a-6ae7-4c6c-8243-6c48c2703f66)



</details>
parent 7a340320
...@@ -517,7 +517,8 @@ pub struct ExperimentalConfig { ...@@ -517,7 +517,8 @@ pub struct ExperimentalConfig {
pub server_actions: Option<ServerActionsOrLegacyBool>, pub server_actions: Option<ServerActionsOrLegacyBool>,
pub sri: Option<SubResourceIntegrity>, pub sri: Option<SubResourceIntegrity>,
react_compiler: Option<ReactCompilerOptionsOrBoolean>, react_compiler: Option<ReactCompilerOptionsOrBoolean>,
#[serde(rename = "dynamicIO")]
pub dynamic_io: Option<bool>,
// --- // ---
// UNSUPPORTED // UNSUPPORTED
// --- // ---
...@@ -561,8 +562,6 @@ pub struct ExperimentalConfig { ...@@ -561,8 +562,6 @@ pub struct ExperimentalConfig {
ppr: Option<ExperimentalPartialPrerendering>, ppr: Option<ExperimentalPartialPrerendering>,
taint: Option<bool>, taint: Option<bool>,
react_owner_stack: Option<bool>, react_owner_stack: Option<bool>,
#[serde(rename = "dynamicIO")]
dynamic_io: Option<bool>,
proxy_timeout: Option<f64>, proxy_timeout: Option<f64>,
/// enables the minification of server code. /// enables the minification of server code.
server_minification: Option<bool>, server_minification: Option<bool>,
......
...@@ -34,9 +34,15 @@ pub async fn get_next_react_server_components_transform_rule( ...@@ -34,9 +34,15 @@ pub async fn get_next_react_server_components_transform_rule(
app_dir: Option<Vc<FileSystemPath>>, app_dir: Option<Vc<FileSystemPath>>,
) -> Result<ModuleRule> { ) -> Result<ModuleRule> {
let enable_mdx_rs = next_config.mdx_rs().await?.is_some(); let enable_mdx_rs = next_config.mdx_rs().await?.is_some();
let dynamic_io_enabled = next_config
.experimental()
.await?
.dynamic_io
.unwrap_or(false);
Ok(get_ecma_transform_rule( Ok(get_ecma_transform_rule(
Box::new(NextJsReactServerComponents::new( Box::new(NextJsReactServerComponents::new(
is_react_server_layer, is_react_server_layer,
dynamic_io_enabled,
app_dir, app_dir,
)), )),
enable_mdx_rs, enable_mdx_rs,
...@@ -47,13 +53,19 @@ pub async fn get_next_react_server_components_transform_rule( ...@@ -47,13 +53,19 @@ pub async fn get_next_react_server_components_transform_rule(
#[derive(Debug)] #[derive(Debug)]
struct NextJsReactServerComponents { struct NextJsReactServerComponents {
is_react_server_layer: bool, is_react_server_layer: bool,
dynamic_io_enabled: bool,
app_dir: Option<Vc<FileSystemPath>>, app_dir: Option<Vc<FileSystemPath>>,
} }
impl NextJsReactServerComponents { impl NextJsReactServerComponents {
fn new(is_react_server_layer: bool, app_dir: Option<Vc<FileSystemPath>>) -> Self { fn new(
is_react_server_layer: bool,
dynamic_io_enabled: bool,
app_dir: Option<Vc<FileSystemPath>>,
) -> Self {
Self { Self {
is_react_server_layer, is_react_server_layer,
dynamic_io_enabled,
app_dir, app_dir,
} }
} }
...@@ -73,6 +85,7 @@ impl CustomTransformer for NextJsReactServerComponents { ...@@ -73,6 +85,7 @@ impl CustomTransformer for NextJsReactServerComponents {
file_name, file_name,
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: self.is_react_server_layer, is_react_server_layer: self.is_react_server_layer,
dynamic_io_enabled: self.dynamic_io_enabled,
}), }),
match self.app_dir { match self.app_dir {
None => None, None => None,
......
...@@ -43,6 +43,7 @@ impl Config { ...@@ -43,6 +43,7 @@ impl Config {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct Options { pub struct Options {
pub is_react_server_layer: bool, pub is_react_server_layer: bool,
pub dynamic_io_enabled: bool,
} }
/// A visitor that transforms given module to use module proxy if it's a React /// A visitor that transforms given module to use module proxy if it's a React
...@@ -51,6 +52,7 @@ pub struct Options { ...@@ -51,6 +52,7 @@ pub struct Options {
/// same purpose, so does not run this transform. /// same purpose, so does not run this transform.
struct ReactServerComponents<C: Comments> { struct ReactServerComponents<C: Comments> {
is_react_server_layer: bool, is_react_server_layer: bool,
dynamic_io_enabled: bool,
filepath: String, filepath: String,
app_dir: Option<PathBuf>, app_dir: Option<PathBuf>,
comments: C, comments: C,
...@@ -77,6 +79,12 @@ enum RSCErrorKind { ...@@ -77,6 +79,12 @@ enum RSCErrorKind {
NextRscErrInvalidApi((String, Span)), NextRscErrInvalidApi((String, Span)),
NextRscErrDeprecatedApi((String, String, Span)), NextRscErrDeprecatedApi((String, String, Span)),
NextSsrDynamicFalseNotAllowed(Span), NextSsrDynamicFalseNotAllowed(Span),
NextRscErrIncompatibleDynamicIoSegment(Span, String),
}
enum InvalidExportKind {
General,
DynamicIoSegment,
} }
impl<C: Comments> VisitMut for ReactServerComponents<C> { impl<C: Comments> VisitMut for ReactServerComponents<C> {
...@@ -86,6 +94,7 @@ impl<C: Comments> VisitMut for ReactServerComponents<C> { ...@@ -86,6 +94,7 @@ impl<C: Comments> VisitMut for ReactServerComponents<C> {
// Run the validator first to assert, collect directives and imports. // Run the validator first to assert, collect directives and imports.
let mut validator = ReactServerComponentValidator::new( let mut validator = ReactServerComponentValidator::new(
self.is_react_server_layer, self.is_react_server_layer,
self.dynamic_io_enabled,
self.filepath.clone(), self.filepath.clone(),
self.app_dir.clone(), self.app_dir.clone(),
); );
...@@ -307,6 +316,10 @@ fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorK ...@@ -307,6 +316,10 @@ fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorK
.to_string(), .to_string(),
span, span,
), ),
RSCErrorKind::NextRscErrIncompatibleDynamicIoSegment(span, segment) => (
format!("\"{}\" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.", segment),
span,
),
}; };
HANDLER.with(|handler| handler.struct_span_err(span, msg.as_str()).emit()) HANDLER.with(|handler| handler.struct_span_err(span, msg.as_str()).emit())
...@@ -500,6 +513,7 @@ fn collect_top_level_directives_and_imports( ...@@ -500,6 +513,7 @@ fn collect_top_level_directives_and_imports(
/// A visitor to assert given module file is a valid React server component. /// A visitor to assert given module file is a valid React server component.
struct ReactServerComponentValidator { struct ReactServerComponentValidator {
is_react_server_layer: bool, is_react_server_layer: bool,
dynamic_io_enabled: bool,
filepath: String, filepath: String,
app_dir: Option<PathBuf>, app_dir: Option<PathBuf>,
invalid_server_imports: Vec<JsWord>, invalid_server_imports: Vec<JsWord>,
...@@ -515,9 +529,15 @@ struct ReactServerComponentValidator { ...@@ -515,9 +529,15 @@ struct ReactServerComponentValidator {
type RcVec<T> = Rc<Vec<T>>; type RcVec<T> = Rc<Vec<T>>;
impl ReactServerComponentValidator { impl ReactServerComponentValidator {
pub fn new(is_react_server_layer: bool, filename: String, app_dir: Option<PathBuf>) -> Self { pub fn new(
is_react_server_layer: bool,
dynamic_io_enabled: bool,
filename: String,
app_dir: Option<PathBuf>,
) -> Self {
Self { Self {
is_react_server_layer, is_react_server_layer,
dynamic_io_enabled,
filepath: filename, filepath: filename,
app_dir, app_dir,
directive_import_collection: None, directive_import_collection: None,
...@@ -734,20 +754,28 @@ impl ReactServerComponentValidator { ...@@ -734,20 +754,28 @@ impl ReactServerComponentValidator {
if is_layout_or_page { if is_layout_or_page {
let mut span = DUMMY_SP; let mut span = DUMMY_SP;
let mut invalid_export_name = String::new(); let mut invalid_export_name = String::new();
let mut invalid_exports: HashMap<String, bool> = HashMap::new(); let mut invalid_exports: HashMap<String, InvalidExportKind> = HashMap::new();
fn invalid_exports_matcher( let mut invalid_exports_matcher = |export_name: &str| -> bool {
export_name: &str,
invalid_exports: &mut HashMap<String, bool>,
) -> bool {
match export_name { match export_name {
"getServerSideProps" | "getStaticProps" | "generateMetadata" | "metadata" => { "getServerSideProps" | "getStaticProps" | "generateMetadata" | "metadata" => {
invalid_exports.insert(export_name.to_string(), true); invalid_exports.insert(export_name.to_string(), InvalidExportKind::General);
true true
} }
_ => false, "dynamicParams" | "dynamic" | "fetchCache" | "runtime" | "revalidate" => {
if self.dynamic_io_enabled {
invalid_exports.insert(
export_name.to_string(),
InvalidExportKind::DynamicIoSegment,
);
true
} else {
false
}
} }
_ => false,
} }
};
for export in &module.body { for export in &module.body {
match export { match export {
...@@ -756,13 +784,13 @@ impl ReactServerComponentValidator { ...@@ -756,13 +784,13 @@ impl ReactServerComponentValidator {
if let ExportSpecifier::Named(named) = specifier { if let ExportSpecifier::Named(named) = specifier {
match &named.orig { match &named.orig {
ModuleExportName::Ident(i) => { ModuleExportName::Ident(i) => {
if invalid_exports_matcher(&i.sym, &mut invalid_exports) { if invalid_exports_matcher(&i.sym) {
span = named.span; span = named.span;
invalid_export_name = i.sym.to_string(); invalid_export_name = i.sym.to_string();
} }
} }
ModuleExportName::Str(s) => { ModuleExportName::Str(s) => {
if invalid_exports_matcher(&s.value, &mut invalid_exports) { if invalid_exports_matcher(&s.value) {
span = named.span; span = named.span;
invalid_export_name = s.value.to_string(); invalid_export_name = s.value.to_string();
} }
...@@ -773,7 +801,7 @@ impl ReactServerComponentValidator { ...@@ -773,7 +801,7 @@ impl ReactServerComponentValidator {
} }
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export)) => match &export.decl { ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export)) => match &export.decl {
Decl::Fn(f) => { Decl::Fn(f) => {
if invalid_exports_matcher(&f.ident.sym, &mut invalid_exports) { if invalid_exports_matcher(&f.ident.sym) {
span = f.ident.span; span = f.ident.span;
invalid_export_name = f.ident.sym.to_string(); invalid_export_name = f.ident.sym.to_string();
} }
...@@ -781,7 +809,7 @@ impl ReactServerComponentValidator { ...@@ -781,7 +809,7 @@ impl ReactServerComponentValidator {
Decl::Var(v) => { Decl::Var(v) => {
for decl in &v.decls { for decl in &v.decls {
if let Pat::Ident(i) = &decl.name { if let Pat::Ident(i) = &decl.name {
if invalid_exports_matcher(&i.sym, &mut invalid_exports) { if invalid_exports_matcher(&i.sym) {
span = i.span; span = i.span;
invalid_export_name = i.sym.to_string(); invalid_export_name = i.sym.to_string();
} }
...@@ -798,6 +826,19 @@ impl ReactServerComponentValidator { ...@@ -798,6 +826,19 @@ impl ReactServerComponentValidator {
let has_gm_export = invalid_exports.contains_key("generateMetadata"); let has_gm_export = invalid_exports.contains_key("generateMetadata");
let has_metadata_export = invalid_exports.contains_key("metadata"); let has_metadata_export = invalid_exports.contains_key("metadata");
for (export_name, kind) in &invalid_exports {
match kind {
InvalidExportKind::DynamicIoSegment => {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrIncompatibleDynamicIoSegment(
span,
export_name.clone(),
),
);
}
InvalidExportKind::General => {
// Client entry can't export `generateMetadata` or `metadata`. // Client entry can't export `generateMetadata` or `metadata`.
if is_client_entry { if is_client_entry {
if has_gm_export || has_metadata_export { if has_gm_export || has_metadata_export {
...@@ -827,11 +868,17 @@ impl ReactServerComponentValidator { ...@@ -827,11 +868,17 @@ impl ReactServerComponentValidator {
report_error( report_error(
&self.app_dir, &self.app_dir,
&self.filepath, &self.filepath,
RSCErrorKind::NextRscErrInvalidApi((invalid_export_name.clone(), span)), RSCErrorKind::NextRscErrInvalidApi((
invalid_export_name.clone(),
span,
)),
); );
} }
} }
} }
}
}
}
/// ```js /// ```js
/// import dynamic from 'next/dynamic' /// import dynamic from 'next/dynamic'
...@@ -946,12 +993,15 @@ pub fn server_components_assert( ...@@ -946,12 +993,15 @@ pub fn server_components_assert(
Config::WithOptions(x) => x.is_react_server_layer, Config::WithOptions(x) => x.is_react_server_layer,
_ => false, _ => false,
}; };
let dynamic_io_enabled: bool = match &config {
Config::WithOptions(x) => x.dynamic_io_enabled,
_ => false,
};
let filename = match filename { let filename = match filename {
FileName::Custom(path) => format!("<{path}>"), FileName::Custom(path) => format!("<{path}>"),
_ => filename.to_string(), _ => filename.to_string(),
}; };
ReactServerComponentValidator::new(is_react_server_layer, filename, app_dir) ReactServerComponentValidator::new(is_react_server_layer, dynamic_io_enabled, filename, app_dir)
} }
/// Runs react server component transform for the module proxy, as well as /// Runs react server component transform for the module proxy, as well as
...@@ -966,8 +1016,13 @@ pub fn server_components<C: Comments>( ...@@ -966,8 +1016,13 @@ pub fn server_components<C: Comments>(
Config::WithOptions(x) => x.is_react_server_layer, Config::WithOptions(x) => x.is_react_server_layer,
_ => false, _ => false,
}; };
let dynamic_io_enabled: bool = match &config {
Config::WithOptions(x) => x.dynamic_io_enabled,
_ => false,
};
as_folder(ReactServerComponents { as_folder(ReactServerComponents {
is_react_server_layer, is_react_server_layer,
dynamic_io_enabled,
comments, comments,
filepath: match &*filename { filepath: match &*filename {
FileName::Custom(path) => format!("<{path}>"), FileName::Custom(path) => format!("<{path}>"),
......
...@@ -96,6 +96,7 @@ fn react_server_components_server_graph_errors(input: PathBuf) { ...@@ -96,6 +96,7 @@ fn react_server_components_server_graph_errors(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/layout.js")).into(), FileName::Real(PathBuf::from("/some-project/src/layout.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: false,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, None,
...@@ -121,6 +122,7 @@ fn react_server_components_client_graph_errors(input: PathBuf) { ...@@ -121,6 +122,7 @@ fn react_server_components_client_graph_errors(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/page.js")).into(), FileName::Real(PathBuf::from("/some-project/src/page.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: false, is_react_server_layer: false,
dynamic_io_enabled: false,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, None,
...@@ -167,7 +169,8 @@ fn react_server_actions_server_errors(input: PathBuf) { ...@@ -167,7 +169,8 @@ fn react_server_actions_server_errors(input: PathBuf) {
server_components( server_components(
FileName::Real(PathBuf::from("/app/item.js")).into(), FileName::Real(PathBuf::from("/app/item.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: true is_react_server_layer: true,
dynamic_io_enabled: false
},), },),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, None,
...@@ -204,7 +207,8 @@ fn react_server_actions_client_errors(input: PathBuf) { ...@@ -204,7 +207,8 @@ fn react_server_actions_client_errors(input: PathBuf) {
server_components( server_components(
FileName::Real(PathBuf::from("/app/item.js")).into(), FileName::Real(PathBuf::from("/app/item.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: false is_react_server_layer: false,
dynamic_io_enabled: false
},), },),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, None,
......
...@@ -321,6 +321,7 @@ fn react_server_components_typescript(input: PathBuf) { ...@@ -321,6 +321,7 @@ fn react_server_components_typescript(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(), FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: false,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, None,
...@@ -343,6 +344,7 @@ fn react_server_components_server_graph_fixture(input: PathBuf) { ...@@ -343,6 +344,7 @@ fn react_server_components_server_graph_fixture(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(), FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: true, is_react_server_layer: true,
dynamic_io_enabled: false,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, None,
...@@ -365,6 +367,7 @@ fn react_server_components_client_graph_fixture(input: PathBuf) { ...@@ -365,6 +367,7 @@ fn react_server_components_client_graph_fixture(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(), FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: false, is_react_server_layer: false,
dynamic_io_enabled: false,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, None,
......
...@@ -79,12 +79,6 @@ export interface AppPageStaticInfo { ...@@ -79,12 +79,6 @@ export interface AppPageStaticInfo {
runtime: AppSegmentConfig['runtime'] | undefined runtime: AppSegmentConfig['runtime'] | undefined
preferredRegion: AppSegmentConfig['preferredRegion'] | undefined preferredRegion: AppSegmentConfig['preferredRegion'] | undefined
maxDuration: number | undefined maxDuration: number | undefined
/**
* This field is only populated when `experimental.dynamicIO` is enabled.
* It contains a list of segment configs that are part of the page
* and are not supported with the feature.
*/
unsupportedSegmentConfigs: string[] | undefined
} }
export interface PagesPageStaticInfo { export interface PagesPageStaticInfo {
...@@ -495,7 +489,6 @@ export async function getAppPageStaticInfo({ ...@@ -495,7 +489,6 @@ export async function getAppPageStaticInfo({
runtime: undefined, runtime: undefined,
preferredRegion: undefined, preferredRegion: undefined,
maxDuration: undefined, maxDuration: undefined,
unsupportedSegmentConfigs: undefined,
} }
} }
...@@ -535,22 +528,6 @@ export async function getAppPageStaticInfo({ ...@@ -535,22 +528,6 @@ export async function getAppPageStaticInfo({
const route = normalizeAppPath(page) const route = normalizeAppPath(page)
const config = parseAppSegmentConfig(exportedConfig, route) const config = parseAppSegmentConfig(exportedConfig, route)
let unsupportedSegmentConfigs: string[] | undefined
// Enabling dynamicIO will disable certain segment configs, as they pertain to the old
// model of detecting dynamic behavior and these options aren't meant to be used together.
if (nextConfig.experimental?.dynamicIO) {
const unsupportedSegments = [
'dynamicParams',
'dynamic',
'runtime',
'fetchCache',
'revalidate',
] as const
unsupportedSegmentConfigs = unsupportedSegments
.filter((prop) => typeof config[prop] !== 'undefined')
.sort()
}
// Prevent edge runtime and generateStaticParams in the same file. // Prevent edge runtime and generateStaticParams in the same file.
if (isEdgeRuntime(config.runtime) && generateStaticParams) { if (isEdgeRuntime(config.runtime) && generateStaticParams) {
...@@ -577,7 +554,6 @@ export async function getAppPageStaticInfo({ ...@@ -577,7 +554,6 @@ export async function getAppPageStaticInfo({
runtime: config.runtime, runtime: config.runtime,
preferredRegion: config.preferredRegion, preferredRegion: config.preferredRegion,
maxDuration: config.maxDuration, maxDuration: config.maxDuration,
unsupportedSegmentConfigs,
} }
} }
......
...@@ -160,18 +160,6 @@ export async function getStaticInfoIncludingLayouts({ ...@@ -160,18 +160,6 @@ export async function getStaticInfoIncludingLayouts({
pageType: isInsideAppDir ? PAGE_TYPES.APP : PAGE_TYPES.PAGES, pageType: isInsideAppDir ? PAGE_TYPES.APP : PAGE_TYPES.PAGES,
}) })
if (layoutStaticInfo.unsupportedSegmentConfigs) {
// Merge unsupported segment configs from the layout into the page
// while deduping the list as it's possible for overlap
layoutStaticInfo.unsupportedSegmentConfigs =
layoutStaticInfo.unsupportedSegmentConfigs.concat(
pageStaticInfo.unsupportedSegmentConfigs || []
)
pageStaticInfo.unsupportedSegmentConfigs = [
...new Set(layoutStaticInfo.unsupportedSegmentConfigs),
]
}
segments.unshift(layoutStaticInfo) segments.unshift(layoutStaticInfo)
} }
} }
......
...@@ -2458,38 +2458,11 @@ export default async function build( ...@@ -2458,38 +2458,11 @@ export default async function build(
pageDuration: undefined, pageDuration: undefined,
ssgPageDurations: undefined, ssgPageDurations: undefined,
hasEmptyPrelude: undefined, hasEmptyPrelude: undefined,
unsupportedSegmentConfigs:
staticInfo && 'unsupportedSegmentConfigs' in staticInfo
? staticInfo.unsupportedSegmentConfigs
: undefined,
}) })
}) })
}) })
) )
// When dynamicIO is enabled, certain segment configs are not supported as they conflict with dynamicIO behavior.
// This will print all the pages along with the segment configs that were used.
if (config.experimental.dynamicIO) {
const pagesWithSegmentConfigs: string[] = []
pageInfos.forEach((pageInfo, page) => {
if (
pageInfo.unsupportedSegmentConfigs &&
pageInfo.unsupportedSegmentConfigs.length > 0
) {
const configs = pageInfo.unsupportedSegmentConfigs.join(', ')
pagesWithSegmentConfigs.push(`${page}: ${configs}`)
}
})
if (pagesWithSegmentConfigs.length > 0) {
Log.error(
`The following pages used segment configs which are not supported with "experimental.dynamicIO" and must be removed to build your application:\n${pagesWithSegmentConfigs.join('\n')}\n`
)
process.exit(1)
}
}
if (hadUnsupportedValue) { if (hadUnsupportedValue) {
Log.error( Log.error(
`Invalid config value exports detected, these can cause unexpected behavior from the configs not being applied. Please fix them to continue` `Invalid config value exports detected, these can cause unexpected behavior from the configs not being applied. Please fix them to continue`
......
...@@ -64,6 +64,7 @@ function getBaseSWCOptions({ ...@@ -64,6 +64,7 @@ function getBaseSWCOptions({
serverComponents, serverComponents,
serverReferenceHashSalt, serverReferenceHashSalt,
bundleLayer, bundleLayer,
isDynamicIo,
}: { }: {
filename: string filename: string
jest?: boolean jest?: boolean
...@@ -80,6 +81,7 @@ function getBaseSWCOptions({ ...@@ -80,6 +81,7 @@ function getBaseSWCOptions({
serverComponents?: boolean serverComponents?: boolean
serverReferenceHashSalt: string serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName bundleLayer?: WebpackLayerName
isDynamicIo?: boolean
}) { }) {
const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer) const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer)
const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer) const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer)
...@@ -200,6 +202,7 @@ function getBaseSWCOptions({ ...@@ -200,6 +202,7 @@ function getBaseSWCOptions({
serverComponents && !jest serverComponents && !jest
? { ? {
isReactServerLayer, isReactServerLayer,
dynamicIoEnabled: isDynamicIo,
} }
: undefined, : undefined,
serverActions: serverActions:
...@@ -338,6 +341,7 @@ export function getLoaderSWCOptions({ ...@@ -338,6 +341,7 @@ export function getLoaderSWCOptions({
pagesDir, pagesDir,
appDir, appDir,
isPageFile, isPageFile,
isDynamicIo,
hasReactRefresh, hasReactRefresh,
modularizeImports, modularizeImports,
optimizeServerReact, optimizeServerReact,
...@@ -362,6 +366,7 @@ export function getLoaderSWCOptions({ ...@@ -362,6 +366,7 @@ export function getLoaderSWCOptions({
hasReactRefresh: boolean hasReactRefresh: boolean
optimizeServerReact?: boolean optimizeServerReact?: boolean
modularizeImports: NextConfig['modularizeImports'] modularizeImports: NextConfig['modularizeImports']
isDynamicIo?: boolean
optimizePackageImports?: NonNullable< optimizePackageImports?: NonNullable<
NextConfig['experimental'] NextConfig['experimental']
>['optimizePackageImports'] >['optimizePackageImports']
...@@ -391,6 +396,7 @@ export function getLoaderSWCOptions({ ...@@ -391,6 +396,7 @@ export function getLoaderSWCOptions({
serverComponents, serverComponents,
serverReferenceHashSalt, serverReferenceHashSalt,
esm: !!esm, esm: !!esm,
isDynamicIo,
}) })
baseOptions.fontLoaders = { baseOptions.fontLoaders = {
fontLoaders: ['next/font/local', 'next/font/google'], fontLoaders: ['next/font/local', 'next/font/google'],
......
...@@ -372,7 +372,6 @@ export interface PageInfo { ...@@ -372,7 +372,6 @@ export interface PageInfo {
hasEmptyPrelude?: boolean hasEmptyPrelude?: boolean
hasPostponed?: boolean hasPostponed?: boolean
isDynamicAppRoute?: boolean isDynamicAppRoute?: boolean
unsupportedSegmentConfigs: string[] | undefined
} }
export type PageInfos = Map<string, PageInfo> export type PageInfos = Map<string, PageInfo>
......
...@@ -127,6 +127,7 @@ async function loaderTransform( ...@@ -127,6 +127,7 @@ async function loaderTransform(
development: development:
this.mode === 'development' || this.mode === 'development' ||
!!nextConfig.experimental?.allowDevelopmentBuild, !!nextConfig.experimental?.allowDevelopmentBuild,
isDynamicIo: nextConfig.experimental?.dynamicIO,
hasReactRefresh, hasReactRefresh,
modularizeImports: nextConfig?.modularizeImports, modularizeImports: nextConfig?.modularizeImports,
optimizePackageImports: nextConfig?.experimental?.optimizePackageImports, optimizePackageImports: nextConfig?.experimental?.optimizePackageImports,
......
...@@ -289,7 +289,6 @@ async function startWatcher(opts: SetupOpts) { ...@@ -289,7 +289,6 @@ async function startWatcher(opts: SetupOpts) {
let enabledTypeScript = usingTypeScript let enabledTypeScript = usingTypeScript
let previousClientRouterFilters: any let previousClientRouterFilters: any
let previousConflictingPagePaths: Set<string> = new Set() let previousConflictingPagePaths: Set<string> = new Set()
let previouslyHadSegmentError = false
wp.on('aggregated', async () => { wp.on('aggregated', async () => {
let middlewareMatchers: MiddlewareMatcher[] | undefined let middlewareMatchers: MiddlewareMatcher[] | undefined
...@@ -493,28 +492,6 @@ async function startWatcher(opts: SetupOpts) { ...@@ -493,28 +492,6 @@ async function startWatcher(opts: SetupOpts) {
appFiles.add(pageName) appFiles.add(pageName)
} }
if (nextConfig.experimental.dynamicIO) {
const staticInfo = await getStaticInfoIncludingLayouts({
pageFilePath: fileName,
config: nextConfig,
appDir: appDir,
page: rootFile,
isDev: true,
isInsideAppDir: isAppPath,
pageExtensions: nextConfig.pageExtensions,
})
if (
'unsupportedSegmentConfigs' in staticInfo &&
staticInfo.unsupportedSegmentConfigs?.length
) {
pagesWithUnsupportedSegments.set(
pageName,
staticInfo.unsupportedSegmentConfigs
)
}
}
if (routedPages.includes(pageName)) { if (routedPages.includes(pageName)) {
continue continue
} }
...@@ -549,34 +526,6 @@ async function startWatcher(opts: SetupOpts) { ...@@ -549,34 +526,6 @@ async function startWatcher(opts: SetupOpts) {
routedPages.push(pageName) routedPages.push(pageName)
} }
// When dynamicIO is enabled, certain segment configs are not supported as they conflict with dynamicIO behavior.
// This will print all the pages along with the segment configs that were used.
if (nextConfig.experimental.dynamicIO) {
const pagesWithIncompatibleSegmentConfigs: string[] = []
pagesWithUnsupportedSegments.forEach(
(unsupportedSegmentConfigs, page) => {
if (
unsupportedSegmentConfigs &&
unsupportedSegmentConfigs.length > 0
) {
const configs = unsupportedSegmentConfigs.join(', ')
pagesWithIncompatibleSegmentConfigs.push(`${page}: ${configs}`)
}
}
)
if (pagesWithIncompatibleSegmentConfigs.length > 0) {
const errorMessage = `The following pages used segment configs which are not supported with "experimental.dynamicIO" and must be removed to build your application:\n${pagesWithIncompatibleSegmentConfigs.join('\n')}\n`
Log.error(errorMessage)
hotReloader.setHmrServerError(new Error(errorMessage))
previouslyHadSegmentError = true
} else if (previouslyHadSegmentError) {
hotReloader.clearHmrServerError()
previouslyHadSegmentError = false
}
}
const numConflicting = conflictingAppPagePaths.size const numConflicting = conflictingAppPagePaths.size
conflictingPageChange = numConflicting - previousConflictingPagePaths.size conflictingPageChange = numConflicting - previousConflictingPagePaths.size
......
...@@ -13,7 +13,7 @@ import { sandbox } from 'development-sandbox' ...@@ -13,7 +13,7 @@ import { sandbox } from 'development-sandbox'
import { outdent } from 'outdent' import { outdent } from 'outdent'
describe('Dynamic IO Dev Errors', () => { describe('Dynamic IO Dev Errors', () => {
const { next, isTurbopack } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
...@@ -72,9 +72,6 @@ describe('Dynamic IO Dev Errors', () => { ...@@ -72,9 +72,6 @@ describe('Dynamic IO Dev Errors', () => {
expect(stack).toContain('<anonymous> (2:1)') expect(stack).toContain('<anonymous> (2:1)')
}) })
// `setHmrServerError` is not currently implemented in Turbopack
// we will need to enable this after it gets implemented.
if (!isTurbopack) {
it('should clear segment errors after correcting them', async () => { it('should clear segment errors after correcting them', async () => {
const { cleanup, session, browser } = await sandbox( const { cleanup, session, browser } = await sandbox(
next, next,
...@@ -100,10 +97,9 @@ describe('Dynamic IO Dev Errors', () => { ...@@ -100,10 +97,9 @@ describe('Dynamic IO Dev Errors', () => {
} }
expect(redbox.description).toMatchInlineSnapshot(`"Failed to compile"`) expect(redbox.description).toMatchInlineSnapshot(`"Failed to compile"`)
expect(redbox.source).toMatchInlineSnapshot(` expect(redbox.source).toContain(
"The following pages used segment configs which are not supported with "experimental.dynamicIO" and must be removed to build your application: '"revalidate" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
/: revalidate" )
`)
await session.patch( await session.patch(
'app/page.tsx', 'app/page.tsx',
...@@ -122,5 +118,4 @@ describe('Dynamic IO Dev Errors', () => { ...@@ -122,5 +118,4 @@ describe('Dynamic IO Dev Errors', () => {
await cleanup() await cleanup()
}) })
}
}) })
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import {
retry,
assertHasRedbox,
getRedboxDescription,
getRedboxSource,
} from 'next-test-utils'
describe('dynamic-io-segment-configs', () => { describe('dynamic-io-segment-configs', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped, isNextDev, isTurbopack } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
skipDeployment: true, skipDeployment: true,
...@@ -19,16 +24,39 @@ describe('dynamic-io-segment-configs', () => { ...@@ -19,16 +24,39 @@ describe('dynamic-io-segment-configs', () => {
// we expect the build to fail // we expect the build to fail
} }
if (isNextDev) {
const browser = await next.browser('/revalidate')
await assertHasRedbox(browser)
const redbox = {
description: await getRedboxDescription(browser),
source: await getRedboxSource(browser),
}
expect(redbox.description).toMatchInlineSnapshot(`"Failed to compile"`)
expect(redbox.source).toContain(
'"revalidate" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
)
} else {
expect(next.cliOutput).toContain('./app/dynamic-params/[slug]/page.tsx')
expect(next.cliOutput).toContain(
'"dynamicParams" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
)
expect(next.cliOutput).toContain('./app/dynamic/nested/page.tsx')
expect(next.cliOutput).toContain('./app/dynamic/page.tsx')
expect(next.cliOutput).toContain(
'"dynamic" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
)
expect(next.cliOutput).toContain('./app/fetch-cache/page.tsx')
expect(next.cliOutput).toContain(
'"fetchCache" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
)
expect(next.cliOutput).toContain('./app/revalidate/page.tsx')
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
'The following pages used segment configs which are not supported with "experimental.dynamicIO"' '"revalidate" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
) )
expect(next.cliOutput).toContain('/runtime: runtime') }
expect(next.cliOutput).toContain('/multiple: dynamic, fetchCache, runtime')
expect(next.cliOutput).toContain('/dynamic/nested: dynamic')
expect(next.cliOutput).toContain('/dynamic-params/[slug]: dynamicParams')
expect(next.cliOutput).toContain('/fetch-cache: fetchCache')
expect(next.cliOutput).toContain('/dynamic: dynamic')
expect(next.cliOutput).toContain('/revalidate: revalidate')
}) })
it('should propagate configurations from layouts to pages', async () => { it('should propagate configurations from layouts to pages', async () => {
...@@ -38,7 +66,7 @@ describe('dynamic-io-segment-configs', () => { ...@@ -38,7 +66,7 @@ describe('dynamic-io-segment-configs', () => {
'app/layout.tsx', 'app/layout.tsx',
(content) => { (content) => {
return ` return `
export const dynamic = 'force-dynamic'; export const runtime = 'nodejs';
${content} ${content}
` `
}, },
...@@ -49,23 +77,50 @@ describe('dynamic-io-segment-configs', () => { ...@@ -49,23 +77,50 @@ describe('dynamic-io-segment-configs', () => {
// we expect the build to fail // we expect the build to fail
} }
await retry(async () => { if (isNextDev) {
expect(next.cliOutput).toContain( const browser = await next.browser('/revalidate')
'The following pages used segment configs which are not supported with "experimental.dynamicIO"' await assertHasRedbox(browser)
const redbox = {
description: await getRedboxDescription(browser),
source: await getRedboxSource(browser),
}
expect(redbox.description).toMatchInlineSnapshot(
`"Failed to compile"`
) )
expect(next.cliOutput).toContain('/runtime: dynamic, runtime') expect(redbox.source).toContain(
expect(next.cliOutput).toContain( '"runtime" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
'/multiple: dynamic, fetchCache, runtime'
) )
expect(next.cliOutput).toContain('/dynamic/nested: dynamic') } else {
await retry(async () => {
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
'/dynamic-params/[slug]: dynamic, dynamicParams' '"runtime" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
) )
expect(next.cliOutput).toContain('/fetch-cache: dynamic, fetchCache')
expect(next.cliOutput).toContain('/dynamic: dynamic') // the stack trace is different between turbopack/webpack
expect(next.cliOutput).toContain('/revalidate: dynamic, revalidate') if (isTurbopack) {
expectLinesToAppearTogether(next.cliOutput, [
`Page: {"type":"app","side":"server","page":"/fetch-cache/page"}`,
'./app/layout.tsx:2:24',
])
} else {
expectLinesToAppearTogether(next.cliOutput, [
'Import trace for requested module:',
'./app/fetch-cache/page.tsx',
'./app/layout.tsx',
])
}
}) })
} }
}
) )
}) })
}) })
function expectLinesToAppearTogether(output: string, lines: string[]) {
const escapedLines = lines.map((line) =>
line.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
)
const pattern = new RegExp(escapedLines.join('\\s*'), 's')
expect(output).toMatch(pattern)
}
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