Unverified Commit eba236b5 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

[backport] Scope app-entry export validation to files inside the app directory (#97357)

Backports [Scope app-entry export validation to files inside the app
directory (#97350)](https://github.com/vercel/next.js/pull/97350) to
`next-16-3`.

Fixes #96859 on the 16.3 line. The regression came from #94962, which is
present in `next-16-3` (16.3.1) and absent from `next-16-2`, so 16.3 is
the only release branch that needs it.

Clean cherry-pick with no conflicts; every touched file is
byte-identical to the merged canary commit. `cargo test -p
next-custom-transforms --test errors react_server_components` passes on
this branch (33 fixtures). The end-to-end suite is left to CI.

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarRodrigo Arias <rodrigo@arias.me>
parent 3d32eb87
......@@ -281,6 +281,24 @@ fn join_atoms(atoms: &[Atom]) -> String {
.join(",")
}
/// Returns whether `filepath` is a file inside `app_dir`.
///
/// The App Router file conventions are matched by filename. The same filenames
/// are also valid Pages Router routes, where the conventions do not apply.
/// `pages/sitemap.js` is an ordinary page, not a sitemap. Gate App Router
/// checks on this function to keep them out of the Pages Router.
fn is_in_app_dir(app_dir: &Option<PathBuf>, filepath: &str) -> bool {
let Some(app_dir) = app_dir.as_ref().and_then(|app_dir| app_dir.to_str()) else {
return false;
};
// The rest of the path must start with a separator. A plain prefix match
// would also accept a sibling directory such as `apparel` for `app`.
filepath
.strip_prefix(app_dir.trim_end_matches(['/', '\\']))
.is_some_and(|rest| rest.starts_with(['/', '\\']))
}
/// Consolidated place to parse, generate error messages for the RSC parsing
/// errors.
fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorKind) {
......@@ -315,18 +333,7 @@ fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorK
(msg, vec![span])
}
RSCErrorKind::NextRscErrClientImport((source, span)) => {
let is_app_dir = app_dir
.as_ref()
.map(|app_dir| {
if let Some(app_dir) = app_dir.as_os_str().to_str() {
filepath.starts_with(app_dir)
} else {
false
}
})
.unwrap_or_default();
let msg = if !is_app_dir {
let msg = if !is_in_app_dir(app_dir, filepath) {
format!("You're importing a module that depends on \"{source}\". This API is only available in Server Components in the App Router, but you are using it in the Pages Router.\nLearn more: https://nextjs.org/docs/app/building-your-application/rendering/server-components\n\n")
} else {
format!("You're importing a module that depends on \"{source}\" into a React Client Component module. This API is only available in Server Components but one of its parents is marked with \"use client\", so this module is also a Client Component.\nLearn more: https://nextjs.org/docs/app/building-your-application/rendering\n\n")
......@@ -842,11 +849,7 @@ impl ReactServerComponentValidator {
let is_error_file = re.is_match(&self.filepath);
if is_error_file
&& let Some(app_dir) = &self.app_dir
&& let Some(app_dir) = app_dir.to_str()
&& self.filepath.starts_with(app_dir)
{
if is_error_file && is_in_app_dir(&self.app_dir, &self.filepath) {
let span = if let Some(first_item) = module.body.first() {
first_item.span()
} else {
......@@ -910,7 +913,8 @@ impl ReactServerComponentValidator {
r"[\\/](page|layout|route|icon\d?|apple-icon\d?|opengraph-image\d?|twitter-image\d?|sitemap|robots|manifest)\.{ext_pattern}$",
))
.unwrap();
let is_app_entry = re.is_match(&self.filepath);
let is_app_entry =
re.is_match(&self.filepath) && is_in_app_dir(&self.app_dir, &self.filepath);
if is_app_entry {
let mut possibly_invalid_exports: FxIndexMap<Atom, (InvalidExportKind, Span)> =
......
......@@ -92,6 +92,7 @@ fn next_ssg_errors(input: PathBuf) {
#[fixture("tests/errors/react-server-components/**/input.js")]
#[fixture("tests/errors/react-server-components/**/page.js")]
#[fixture("tests/errors/react-server-components/**/route.js")]
#[fixture("tests/errors/react-server-components/**/sitemap.js")]
fn react_server_components_errors(input: PathBuf) {
use next_custom_transforms::transforms::react_server_components::{Config, Options};
let is_react_server_layer = input.iter().any(|s| s.to_str() == Some("server-graph"));
......@@ -99,6 +100,10 @@ fn react_server_components_errors(input: PathBuf) {
let use_cache_enabled = input.iter().any(|s| s.to_str() == Some("use-cache"));
let taint_enabled = input.iter().any(|s| s.to_str() == Some("taint-enabled"));
// A path segment named `app-dir` marks the fixture as an App Router file.
// Everything up to and including that segment becomes `appDir`. A fixture
// without the segment compiles as a Pages Router file, so the checks that
// only apply inside `appDir` do not run for it.
let app_dir = input
.iter()
.position(|s| s.to_str() == Some("app-dir"))
......
export function getStaticProps() {}
export default function() {
return null;
}
export function getStaticProps() {}
export default function () {
return null
}
import { nextTestSetup } from 'e2e-utils'
describe('pages-app-router-filenames', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should support getStaticProps in a page named sitemap', async () => {
const $ = await next.render$('/sitemap')
expect($('#page').text()).toBe('sitemap')
})
it('should support getServerSideProps in a page named robots', async () => {
const $ = await next.render$('/robots')
expect($('#page').text()).toBe('robots')
})
it('should support getStaticProps in a page named page', async () => {
const $ = await next.render$('/page')
expect($('#page').text()).toBe('page')
})
})
export function getStaticProps() {
return { props: { name: 'page' } }
}
export default function Page({ name }) {
return <p id="page">{name}</p>
}
export function getServerSideProps() {
return { props: { name: 'robots' } }
}
export default function Robots({ name }) {
return <p id="page">{name}</p>
}
export function getStaticProps() {
return { props: { name: 'sitemap' } }
}
export default function Sitemap({ name }) {
return <p id="page">{name}</p>
}
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