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 {
pub server_actions: Option<ServerActionsOrLegacyBool>,
pub sri: Option<SubResourceIntegrity>,
react_compiler: Option<ReactCompilerOptionsOrBoolean>,
#[serde(rename = "dynamicIO")]
pub dynamic_io: Option<bool>,
// ---
// UNSUPPORTED
// ---
......@@ -561,8 +562,6 @@ pub struct ExperimentalConfig {
ppr: Option<ExperimentalPartialPrerendering>,
taint: Option<bool>,
react_owner_stack: Option<bool>,
#[serde(rename = "dynamicIO")]
dynamic_io: Option<bool>,
proxy_timeout: Option<f64>,
/// enables the minification of server code.
server_minification: Option<bool>,
......
......@@ -34,9 +34,15 @@ pub async fn get_next_react_server_components_transform_rule(
app_dir: Option<Vc<FileSystemPath>>,
) -> Result<ModuleRule> {
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(
Box::new(NextJsReactServerComponents::new(
is_react_server_layer,
dynamic_io_enabled,
app_dir,
)),
enable_mdx_rs,
......@@ -47,13 +53,19 @@ pub async fn get_next_react_server_components_transform_rule(
#[derive(Debug)]
struct NextJsReactServerComponents {
is_react_server_layer: bool,
dynamic_io_enabled: bool,
app_dir: Option<Vc<FileSystemPath>>,
}
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 {
is_react_server_layer,
dynamic_io_enabled,
app_dir,
}
}
......@@ -73,6 +85,7 @@ impl CustomTransformer for NextJsReactServerComponents {
file_name,
Config::WithOptions(Options {
is_react_server_layer: self.is_react_server_layer,
dynamic_io_enabled: self.dynamic_io_enabled,
}),
match self.app_dir {
None => None,
......
......@@ -43,6 +43,7 @@ impl Config {
#[serde(rename_all = "camelCase")]
pub struct Options {
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
......@@ -51,6 +52,7 @@ pub struct Options {
/// same purpose, so does not run this transform.
struct ReactServerComponents<C: Comments> {
is_react_server_layer: bool,
dynamic_io_enabled: bool,
filepath: String,
app_dir: Option<PathBuf>,
comments: C,
......@@ -77,6 +79,12 @@ enum RSCErrorKind {
NextRscErrInvalidApi((String, Span)),
NextRscErrDeprecatedApi((String, String, Span)),
NextSsrDynamicFalseNotAllowed(Span),
NextRscErrIncompatibleDynamicIoSegment(Span, String),
}
enum InvalidExportKind {
General,
DynamicIoSegment,
}
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.
let mut validator = ReactServerComponentValidator::new(
self.is_react_server_layer,
self.dynamic_io_enabled,
self.filepath.clone(),
self.app_dir.clone(),
);
......@@ -307,6 +316,10 @@ fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorK
.to_string(),
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())
......@@ -500,6 +513,7 @@ fn collect_top_level_directives_and_imports(
/// A visitor to assert given module file is a valid React server component.
struct ReactServerComponentValidator {
is_react_server_layer: bool,
dynamic_io_enabled: bool,
filepath: String,
app_dir: Option<PathBuf>,
invalid_server_imports: Vec<JsWord>,
......@@ -515,9 +529,15 @@ struct ReactServerComponentValidator {
type RcVec<T> = Rc<Vec<T>>;
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 {
is_react_server_layer,
dynamic_io_enabled,
filepath: filename,
app_dir,
directive_import_collection: None,
......@@ -734,20 +754,28 @@ impl ReactServerComponentValidator {
if is_layout_or_page {
let mut span = DUMMY_SP;
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(
export_name: &str,
invalid_exports: &mut HashMap<String, bool>,
) -> bool {
let mut invalid_exports_matcher = |export_name: &str| -> bool {
match export_name {
"getServerSideProps" | "getStaticProps" | "generateMetadata" | "metadata" => {
invalid_exports.insert(export_name.to_string(), true);
invalid_exports.insert(export_name.to_string(), InvalidExportKind::General);
true
}
"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 {
match export {
......@@ -756,13 +784,13 @@ impl ReactServerComponentValidator {
if let ExportSpecifier::Named(named) = specifier {
match &named.orig {
ModuleExportName::Ident(i) => {
if invalid_exports_matcher(&i.sym, &mut invalid_exports) {
if invalid_exports_matcher(&i.sym) {
span = named.span;
invalid_export_name = i.sym.to_string();
}
}
ModuleExportName::Str(s) => {
if invalid_exports_matcher(&s.value, &mut invalid_exports) {
if invalid_exports_matcher(&s.value) {
span = named.span;
invalid_export_name = s.value.to_string();
}
......@@ -773,7 +801,7 @@ impl ReactServerComponentValidator {
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export)) => match &export.decl {
Decl::Fn(f) => {
if invalid_exports_matcher(&f.ident.sym, &mut invalid_exports) {
if invalid_exports_matcher(&f.ident.sym) {
span = f.ident.span;
invalid_export_name = f.ident.sym.to_string();
}
......@@ -781,7 +809,7 @@ impl ReactServerComponentValidator {
Decl::Var(v) => {
for decl in &v.decls {
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;
invalid_export_name = i.sym.to_string();
}
......@@ -798,38 +826,57 @@ impl ReactServerComponentValidator {
let has_gm_export = invalid_exports.contains_key("generateMetadata");
let has_metadata_export = invalid_exports.contains_key("metadata");
// Client entry can't export `generateMetadata` or `metadata`.
if is_client_entry {
if has_gm_export || has_metadata_export {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrClientMetadataExport((
invalid_export_name.clone(),
span,
)),
);
}
} else {
// Server entry can't export `generateMetadata` and `metadata` together.
if has_gm_export && has_metadata_export {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrConflictMetadataExport(span),
);
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`.
if is_client_entry {
if has_gm_export || has_metadata_export {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrClientMetadataExport((
invalid_export_name.clone(),
span,
)),
);
}
} else {
// Server entry can't export `generateMetadata` and `metadata` together.
if has_gm_export && has_metadata_export {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrConflictMetadataExport(span),
);
}
}
// Assert `getServerSideProps` and `getStaticProps` exports.
if invalid_export_name == "getServerSideProps"
|| invalid_export_name == "getStaticProps"
{
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrInvalidApi((
invalid_export_name.clone(),
span,
)),
);
}
}
}
}
// Assert `getServerSideProps` and `getStaticProps` exports.
if invalid_export_name == "getServerSideProps"
|| invalid_export_name == "getStaticProps"
{
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrInvalidApi((invalid_export_name.clone(), span)),
);
}
}
}
......@@ -946,12 +993,15 @@ pub fn server_components_assert(
Config::WithOptions(x) => x.is_react_server_layer,
_ => false,
};
let dynamic_io_enabled: bool = match &config {
Config::WithOptions(x) => x.dynamic_io_enabled,
_ => false,
};
let filename = match filename {
FileName::Custom(path) => format!("<{path}>"),
_ => 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
......@@ -966,8 +1016,13 @@ pub fn server_components<C: Comments>(
Config::WithOptions(x) => x.is_react_server_layer,
_ => false,
};
let dynamic_io_enabled: bool = match &config {
Config::WithOptions(x) => x.dynamic_io_enabled,
_ => false,
};
as_folder(ReactServerComponents {
is_react_server_layer,
dynamic_io_enabled,
comments,
filepath: match &*filename {
FileName::Custom(path) => format!("<{path}>"),
......
......@@ -96,6 +96,7 @@ fn react_server_components_server_graph_errors(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/layout.js")).into(),
Config::WithOptions(Options {
is_react_server_layer: true,
dynamic_io_enabled: false,
}),
tr.comments.as_ref().clone(),
None,
......@@ -121,6 +122,7 @@ fn react_server_components_client_graph_errors(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/page.js")).into(),
Config::WithOptions(Options {
is_react_server_layer: false,
dynamic_io_enabled: false,
}),
tr.comments.as_ref().clone(),
None,
......@@ -167,7 +169,8 @@ fn react_server_actions_server_errors(input: PathBuf) {
server_components(
FileName::Real(PathBuf::from("/app/item.js")).into(),
Config::WithOptions(Options {
is_react_server_layer: true
is_react_server_layer: true,
dynamic_io_enabled: false
},),
tr.comments.as_ref().clone(),
None,
......@@ -204,7 +207,8 @@ fn react_server_actions_client_errors(input: PathBuf) {
server_components(
FileName::Real(PathBuf::from("/app/item.js")).into(),
Config::WithOptions(Options {
is_react_server_layer: false
is_react_server_layer: false,
dynamic_io_enabled: false
},),
tr.comments.as_ref().clone(),
None,
......
......@@ -321,6 +321,7 @@ fn react_server_components_typescript(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(),
Config::WithOptions(Options {
is_react_server_layer: true,
dynamic_io_enabled: false,
}),
tr.comments.as_ref().clone(),
None,
......@@ -343,6 +344,7 @@ fn react_server_components_server_graph_fixture(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(),
Config::WithOptions(Options {
is_react_server_layer: true,
dynamic_io_enabled: false,
}),
tr.comments.as_ref().clone(),
None,
......@@ -365,6 +367,7 @@ fn react_server_components_client_graph_fixture(input: PathBuf) {
FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(),
Config::WithOptions(Options {
is_react_server_layer: false,
dynamic_io_enabled: false,
}),
tr.comments.as_ref().clone(),
None,
......
......@@ -79,12 +79,6 @@ export interface AppPageStaticInfo {
runtime: AppSegmentConfig['runtime'] | undefined
preferredRegion: AppSegmentConfig['preferredRegion'] | 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 {
......@@ -495,7 +489,6 @@ export async function getAppPageStaticInfo({
runtime: undefined,
preferredRegion: undefined,
maxDuration: undefined,
unsupportedSegmentConfigs: undefined,
}
}
......@@ -535,22 +528,6 @@ export async function getAppPageStaticInfo({
const route = normalizeAppPath(page)
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.
if (isEdgeRuntime(config.runtime) && generateStaticParams) {
......@@ -577,7 +554,6 @@ export async function getAppPageStaticInfo({
runtime: config.runtime,
preferredRegion: config.preferredRegion,
maxDuration: config.maxDuration,
unsupportedSegmentConfigs,
}
}
......
......@@ -160,18 +160,6 @@ export async function getStaticInfoIncludingLayouts({
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)
}
}
......
......@@ -2458,38 +2458,11 @@ export default async function build(
pageDuration: undefined,
ssgPageDurations: 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) {
Log.error(
`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({
serverComponents,
serverReferenceHashSalt,
bundleLayer,
isDynamicIo,
}: {
filename: string
jest?: boolean
......@@ -80,6 +81,7 @@ function getBaseSWCOptions({
serverComponents?: boolean
serverReferenceHashSalt: string
bundleLayer?: WebpackLayerName
isDynamicIo?: boolean
}) {
const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer)
const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer)
......@@ -200,6 +202,7 @@ function getBaseSWCOptions({
serverComponents && !jest
? {
isReactServerLayer,
dynamicIoEnabled: isDynamicIo,
}
: undefined,
serverActions:
......@@ -338,6 +341,7 @@ export function getLoaderSWCOptions({
pagesDir,
appDir,
isPageFile,
isDynamicIo,
hasReactRefresh,
modularizeImports,
optimizeServerReact,
......@@ -362,6 +366,7 @@ export function getLoaderSWCOptions({
hasReactRefresh: boolean
optimizeServerReact?: boolean
modularizeImports: NextConfig['modularizeImports']
isDynamicIo?: boolean
optimizePackageImports?: NonNullable<
NextConfig['experimental']
>['optimizePackageImports']
......@@ -391,6 +396,7 @@ export function getLoaderSWCOptions({
serverComponents,
serverReferenceHashSalt,
esm: !!esm,
isDynamicIo,
})
baseOptions.fontLoaders = {
fontLoaders: ['next/font/local', 'next/font/google'],
......
......@@ -372,7 +372,6 @@ export interface PageInfo {
hasEmptyPrelude?: boolean
hasPostponed?: boolean
isDynamicAppRoute?: boolean
unsupportedSegmentConfigs: string[] | undefined
}
export type PageInfos = Map<string, PageInfo>
......
......@@ -127,6 +127,7 @@ async function loaderTransform(
development:
this.mode === 'development' ||
!!nextConfig.experimental?.allowDevelopmentBuild,
isDynamicIo: nextConfig.experimental?.dynamicIO,
hasReactRefresh,
modularizeImports: nextConfig?.modularizeImports,
optimizePackageImports: nextConfig?.experimental?.optimizePackageImports,
......
......@@ -289,7 +289,6 @@ async function startWatcher(opts: SetupOpts) {
let enabledTypeScript = usingTypeScript
let previousClientRouterFilters: any
let previousConflictingPagePaths: Set<string> = new Set()
let previouslyHadSegmentError = false
wp.on('aggregated', async () => {
let middlewareMatchers: MiddlewareMatcher[] | undefined
......@@ -493,28 +492,6 @@ async function startWatcher(opts: SetupOpts) {
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)) {
continue
}
......@@ -549,34 +526,6 @@ async function startWatcher(opts: SetupOpts) {
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
conflictingPageChange = numConflicting - previousConflictingPagePaths.size
......
......@@ -13,7 +13,7 @@ import { sandbox } from 'development-sandbox'
import { outdent } from 'outdent'
describe('Dynamic IO Dev Errors', () => {
const { next, isTurbopack } = nextTestSetup({
const { next } = nextTestSetup({
files: __dirname,
})
......@@ -72,16 +72,13 @@ describe('Dynamic IO Dev Errors', () => {
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 () => {
const { cleanup, session, browser } = await sandbox(
next,
new Map([
[
'app/page.tsx',
outdent`
it('should clear segment errors after correcting them', async () => {
const { cleanup, session, browser } = await sandbox(
next,
new Map([
[
'app/page.tsx',
outdent`
export const revalidate = 10
export default function Page() {
return (
......@@ -89,38 +86,36 @@ describe('Dynamic IO Dev Errors', () => {
);
}
`,
],
])
)
],
])
)
await assertHasRedbox(browser)
const redbox = {
description: await getRedboxDescription(browser),
source: await getRedboxSource(browser),
}
await assertHasRedbox(browser)
const redbox = {
description: await getRedboxDescription(browser),
source: await getRedboxSource(browser),
}
expect(redbox.description).toMatchInlineSnapshot(`"Failed to compile"`)
expect(redbox.source).toMatchInlineSnapshot(`
"The following pages used segment configs which are not supported with "experimental.dynamicIO" and must be removed to build your application:
/: revalidate"
`)
expect(redbox.description).toMatchInlineSnapshot(`"Failed to compile"`)
expect(redbox.source).toContain(
'"revalidate" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
)
await session.patch(
'app/page.tsx',
outdent`
await session.patch(
'app/page.tsx',
outdent`
export default function Page() {
return (
<div>Hello World</div>
);
}
`
)
await retry(async () => {
assertNoRedbox(browser)
})
)
await cleanup()
await retry(async () => {
assertNoRedbox(browser)
})
}
await cleanup()
})
})
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', () => {
const { next, skipped } = nextTestSetup({
const { next, skipped, isNextDev, isTurbopack } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
......@@ -19,16 +24,39 @@ describe('dynamic-io-segment-configs', () => {
// we expect the build to fail
}
expect(next.cliOutput).toContain(
'The following pages used segment configs which are not supported with "experimental.dynamicIO"'
)
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')
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(
'"revalidate" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
)
}
})
it('should propagate configurations from layouts to pages', async () => {
......@@ -38,7 +66,7 @@ describe('dynamic-io-segment-configs', () => {
'app/layout.tsx',
(content) => {
return `
export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';
${content}
`
},
......@@ -49,23 +77,50 @@ describe('dynamic-io-segment-configs', () => {
// we expect the build to fail
}
await retry(async () => {
expect(next.cliOutput).toContain(
'The following pages used segment configs which are not supported with "experimental.dynamicIO"'
)
expect(next.cliOutput).toContain('/runtime: dynamic, runtime')
expect(next.cliOutput).toContain(
'/multiple: dynamic, fetchCache, runtime'
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(next.cliOutput).toContain('/dynamic/nested: dynamic')
expect(next.cliOutput).toContain(
'/dynamic-params/[slug]: dynamic, dynamicParams'
expect(redbox.source).toContain(
'"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')
expect(next.cliOutput).toContain('/revalidate: dynamic, revalidate')
})
} else {
await retry(async () => {
expect(next.cliOutput).toContain(
'"runtime" is not compatible with `nextConfig.experimental.dynamicIO`. Please remove it.'
)
// the stack trace is different between turbopack/webpack
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