Unverified Commit 7b7cee30 authored by Josh Story's avatar Josh Story Committed by GitHub

Error when app pages do not match any route (#97401)

## What?

This reports an error under `experimental.strictRouteMatching` when a
`page.tsx` is left out of every retained matcher. A page can lose its
own broad catchall matcher and still be valid if it participates in a
more specific matcher, so this checks the final matcher set instead of
treating every pruned candidate as an error.

Both Webpack and Turbopack report every unmatched page in development
and production builds.

## Why?

Pages that are never selected by any complete loader tree are
unreachable by construction. This usually means parallel slots define
incompatible paths without matching pages or defaults, and silently
ignoring those files makes the project look like it has routes that
cannot actually exist.

For example:

```text
app/disagreeing-slots/
├── layout.tsx
├── @first/foo/page.tsx
├── @second/bar/page.tsx
└── [...slug]/page.tsx
```

Every candidate is incomplete: `/foo` has no match in `@second`, `/bar`
has no match in `@first`, and URLs handled only by the catchall have no
matching page or applicable default in either named slot. Strict route
matching prunes all three matchers, and this change reports all three
page files instead of silently leaving them out of the build.

The same validation catches a real `children` branch that only becomes
incomplete below its page:

```text
app/declared-children/
├── layout.tsx
├── page.tsx
└── @panel/
    ├── default.tsx
    └── details/page.tsx
```

`/declared-children` is valid, but `/declared-children/details` only has
a page in `@panel`. Because the declared `children` slot has no matching
page or default at `/details`, that matcher is pruned and
`@panel/details/page.tsx` is reported as unreachable. The root
`page.tsx` is still part of the valid `/declared-children` matcher and
is not reported.

A pruned matcher is not automatically an error. If
`@slot/[...parts]/page.tsx` is combined into retained `/foo` and `/bar`
matchers, that page still participates in routes and remains valid.

## How?

Webpack snapshots the authored app page paths before pruning and
compares them with the pages used by the retained app paths. Turbopack
collects authored page source files from the directory tree and compares
them with the files referenced by the final accepted loader trees. The
tests cover disagreeing named slots, declared `children`, optional
catchalls, route groups, nested slots, and the valid case where a pruned
catchall is still used by more specific matchers.

## Verification

- `pnpm test-start-turbo
test/e2e/app-dir/unmatched-app-pages/unmatched-app-pages.test.ts`
- `pnpm test-start-webpack
test/e2e/app-dir/unmatched-app-pages/unmatched-app-pages.test.ts`
- `pnpm test-dev-turbo
test/e2e/app-dir/unmatched-app-pages/unmatched-app-pages.test.ts`
- `pnpm test-dev-webpack
test/e2e/app-dir/unmatched-app-pages/unmatched-app-pages.test.ts`
- `pnpm test-start-turbo
test/e2e/app-dir/parallel-routes-pruned-matchers/parallel-routes-pruned-matchers.test.ts`
- `pnpm test-start-webpack
test/e2e/app-dir/parallel-routes-pruned-matchers/parallel-routes-pruned-matchers.test.ts`

<!-- NEXT_JS_LLM -->
parent ec62d6a4
......@@ -486,6 +486,16 @@ pub struct AppPageLoaderTree {
}
impl AppPageLoaderTree {
fn collect_page_files(&self, pages: &mut FxIndexSet<FileSystemPath>) {
if let Some(page) = &self.modules.page {
pages.insert(page.clone());
}
for tree in self.parallel_routes.values() {
tree.collect_page_files(pages);
}
}
/// Returns true if there's a page match in this loader tree.
pub fn has_page(&self) -> bool {
if &*self.segment == "__PAGE__" {
......@@ -613,6 +623,7 @@ pub enum Entrypoint {
AppPage {
pages: Vec<AppPage>,
loader_tree: ResolvedVc<AppPageLoaderTree>,
participating_page_files: Vec<FileSystemPath>,
root_params: ResolvedVc<RootParamVecOption>,
},
AppRoute {
......@@ -709,6 +720,7 @@ fn add_app_page(
result: &mut FxIndexMap<AppPath, Entrypoint>,
page: AppPage,
loader_tree: ResolvedVc<AppPageLoaderTree>,
participating_page_files: Vec<FileSystemPath>,
root_params: ResolvedVc<RootParamVecOption>,
) {
let mut e = match result.entry(page.clone().into()) {
......@@ -717,6 +729,7 @@ fn add_app_page(
e.insert(Entrypoint::AppPage {
pages: vec![page],
loader_tree,
participating_page_files,
root_params,
});
return;
......@@ -742,6 +755,7 @@ fn add_app_page(
let Entrypoint::AppPage {
pages: stored_pages,
participating_page_files: stored_page_files,
..
} = e.get_mut()
else {
......@@ -750,6 +764,11 @@ fn add_app_page(
stored_pages.push(page);
stored_pages.sort();
for page_file in participating_page_files {
if !stored_page_files.contains(&page_file) {
stored_page_files.push(page_file);
}
}
}
Entrypoint::AppRoute {
page: existing_page,
......@@ -972,9 +991,98 @@ async fn directory_tree_to_entrypoints(
);
}
}
let mut authored_pages = FxIndexSet::default();
collect_authored_page_files(&plain_tree, &mut authored_pages);
let mut matched_pages = FxIndexSet::default();
for entrypoint in retained_entrypoints.values() {
if let Entrypoint::AppPage {
participating_page_files,
..
} = entrypoint
{
matched_pages.extend(participating_page_files.iter().cloned());
}
}
let unmatched_pages = authored_pages
.into_iter()
.filter(|page| !matched_pages.contains(page))
.collect::<Vec<_>>();
if !unmatched_pages.is_empty() {
UnmatchedAppPagesIssue {
app_dir,
pages: unmatched_pages,
}
.resolved_cell()
.emit();
}
Ok(Vc::cell(retained_entrypoints))
}
fn collect_authored_page_files(
directory_tree: &PlainDirectoryTree,
pages: &mut FxIndexSet<FileSystemPath>,
) {
if let Some(page) = &directory_tree.modules.page {
pages.insert(page.clone());
}
for subdirectory in directory_tree.subdirectories.values() {
collect_authored_page_files(subdirectory, pages);
}
}
#[turbo_tasks::value]
struct UnmatchedAppPagesIssue {
app_dir: FileSystemPath,
pages: Vec<FileSystemPath>,
}
#[async_trait]
#[turbo_tasks::value_impl]
impl Issue for UnmatchedAppPagesIssue {
async fn file_path(&self) -> Result<FileSystemPath> {
Ok(self.pages[0].clone())
}
fn stage(&self) -> IssueStage {
IssueStage::AppStructure
}
fn severity(&self) -> IssueSeverity {
IssueSeverity::Error
}
async fn title(&self) -> Result<StyledString> {
Ok(StyledString::Text(rcstr!("Unmatched app pages")))
}
async fn description(&self) -> Result<Option<StyledString>> {
let page_paths = self
.pages
.iter()
.map(|page| {
let relative_path = self
.app_dir
.get_path_to(page)
.expect("authored page should be within the app directory");
format!("- app/{}", relative_path)
})
.collect::<Vec<_>>()
.join("\n");
Ok(Some(StyledString::Text(
format!(
"The following page files do not match any complete route:\n{page_paths}\n\nEvery \
page must be part of at least one complete route. Add matching pages or default \
files for the sibling parallel route slots, or remove the unreachable pages."
)
.into(),
)))
}
}
#[turbo_tasks::value]
struct DuplicateParallelRouteIssue {
app_dir: FileSystemPath,
......@@ -1852,11 +1960,18 @@ async fn directory_tree_to_entrypoints_internal_untraced(
)
.await?;
let loader_tree =
loader_tree.context("loader tree should be created for a page/default")?;
let mut participating_page_files = FxIndexSet::default();
loader_tree
.await?
.collect_page_files(&mut participating_page_files);
add_app_page(
app_dir.clone(),
&mut result,
app_page.complete(PageType::Page)?,
loader_tree.context("loader tree should be created for a page/default")?,
loader_tree,
participating_page_files.into_iter().collect(),
root_params,
);
}
......@@ -2052,6 +2167,7 @@ async fn directory_tree_to_entrypoints_internal_untraced(
&mut result,
app_page,
not_found_tree,
Vec::new(),
root_params,
);
}
......@@ -2100,6 +2216,7 @@ async fn directory_tree_to_entrypoints_internal_untraced(
&mut result,
app_global_error_page,
global_error_tree,
Vec::new(),
root_params,
);
}
......@@ -2178,18 +2295,27 @@ async fn directory_tree_to_entrypoints_internal_untraced(
Entrypoint::AppPage {
pages,
loader_tree: _,
participating_page_files: child_participating_page_files,
root_params,
} => {
for page in pages {
let loader_tree = *loader_trees[i].await?;
i += 1;
let loader_tree = loader_tree
.context("loader tree should be created for a page/default")?;
let mut participating_page_files = FxIndexSet::default();
loader_tree
.await?
.collect_page_files(&mut participating_page_files);
participating_page_files
.extend(child_participating_page_files.iter().cloned());
add_app_page(
app_dir.clone(),
&mut result,
page.clone(),
loader_tree
.context("loader tree should be created for a page/default")?,
loader_tree,
participating_page_files.into_iter().collect(),
*root_params,
);
}
......
......@@ -8,7 +8,7 @@ import type { ProxyConfig, ProxyMatcher } from './analysis/get-page-static-info'
import type { LoadedEnvFiles } from '@next/env'
import type { AppLoaderOptions } from './webpack/loaders/next-app-loader'
import { dirname, posix, join, normalize } from 'path'
import { dirname, posix, join, normalize, relative } from 'path'
import { stringify } from 'querystring'
import {
PAGES_DIR_ALIAS,
......@@ -58,6 +58,7 @@ import { normalizeCatchAllRoutes } from './normalize-catchall-routes'
import type { PageExtensions } from './page-extensions-type'
import type { MappedPages } from './build-context'
import { PAGE_TYPES } from '../lib/page-types'
import { UnmatchedAppPagesError } from '../shared/lib/errors/unmatched-app-pages-error'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts'
......@@ -409,23 +410,45 @@ export async function createEntrypoints(
let appPathsPerRoute: Record<string, string[]> = {}
if (appDir && appPaths) {
const appPageFiles = new Map<string, string>()
for (const pathname in appPaths) {
const normalizedPath = normalizeAppPath(pathname)
const actualPath = appPaths[pathname]
if (!appPathsPerRoute[normalizedPath]) {
appPathsPerRoute[normalizedPath] = []
}
appPathsPerRoute[normalizedPath].push(
// TODO-APP: refactor to pass the page path from createPagesMapping instead.
getPageFromPath(actualPath, pageExtensions).replace(APP_DIR_ALIAS, '')
// TODO-APP: refactor to pass the page path from createPagesMapping instead.
const appPath = getPageFromPath(actualPath, pageExtensions).replace(
APP_DIR_ALIAS,
''
)
appPathsPerRoute[normalizedPath].push(appPath)
appPageFiles.set(appPath, actualPath)
}
// TODO: find a better place to do this
normalizeCatchAllRoutes(appPathsPerRoute, {
const unmatchedAppPages = normalizeCatchAllRoutes(appPathsPerRoute, {
strictRouteMatching: config.experimental.strictRouteMatching,
defaultAppPaths: Object.keys(appDefaultPaths ?? {}),
})
if (unmatchedAppPages.length > 0) {
throw new UnmatchedAppPagesError(
unmatchedAppPages.map((appPath) => {
const absolutePagePath = appPageFiles.get(appPath)
if (!absolutePagePath) return appPath
return relative(
rootDir,
getPageFilePath({
absolutePagePath,
pagesDir,
appDir,
rootDir,
})
)
})
)
}
// Make sure to sort parallel routes to make the result deterministic.
appPathsPerRoute = Object.fromEntries(
......
......@@ -221,6 +221,18 @@ describe('normalizeCatchallRoutes', () => {
})
describe('strictRouteMatching pruning', () => {
it('does not report pages when strict route matching is disabled', () => {
const appPaths = {
'/[...slug]': ['/[...slug]/page'],
'/foo': ['/@first/foo/page'],
'/bar': ['/@second/bar/page'],
}
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths)
expect(unmatchedAppPages).toEqual([])
})
it('does not require an implicit children slot with no routes', () => {
const appPaths = {
'/[...slug]': ['/@catchall/[...slug]/page'],
......@@ -299,9 +311,16 @@ describe('normalizeCatchallRoutes', () => {
'/bar': ['/@second/bar/page'],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
})
expect(appPaths).toEqual({})
expect(unmatchedAppPages).toEqual([
'/@first/foo/page',
'/@second/bar/page',
'/[...slug]/page',
])
})
it('prunes an optional children catch-all when a named slot is missing', () => {
......@@ -310,11 +329,14 @@ describe('normalizeCatchallRoutes', () => {
'/specific': ['/specific/page', '/@slot/specific/page'],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
})
expect(appPaths).toEqual({
'/specific': ['/specific/page', '/@slot/specific/page'],
})
expect(unmatchedAppPages).toEqual(['/[[...slug]]/page'])
})
it('prunes a catch-all with an incomplete nested parallel route', () => {
......@@ -502,9 +524,29 @@ describe('normalizeCatchallRoutes', () => {
'/photo/specific': ['/@modal/(.)photo/@specific/specific/page'],
}
normalizeCatchAllRoutes(appPaths, { strictRouteMatching: true })
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
})
expect(appPaths).toEqual({})
expect(unmatchedAppPages).toEqual([
'/@modal/(.)photo/@catchall/[...slug]/page',
'/@modal/(.)photo/@specific/specific/page',
])
})
it('does not report a catch-all page used by more specific matchers', () => {
const appPaths = {
'/foo': ['/foo/page'],
'/bar': ['/bar/page'],
'/[...parts]': ['/@slot/[...parts]/page'],
}
const unmatchedAppPages = normalizeCatchAllRoutes(appPaths, {
strictRouteMatching: true,
})
expect(unmatchedAppPages).toEqual([])
})
})
})
......@@ -6,6 +6,6 @@ import {
export function normalizeCatchAllRoutes(
appPaths: Record<string, string[]>,
options: NormalizeCatchAllRoutesOptions = {}
) {
): string[] {
return normalizeCatchAllRoutesInternal(appPaths, undefined, options)
}
......@@ -36,6 +36,7 @@ const defaultNormalizer: AppPathNormalizer = {
* the catch-all. If it finds a match, it will add the catch-all to the parallel route's list of possible routes.
*
* @param appPaths The appPaths to transform
* @returns Page app paths that are not present in any retained matcher.
*/
export function normalizeCatchAllRoutes(
appPaths: Record<string, string[]>,
......@@ -44,7 +45,14 @@ export function normalizeCatchAllRoutes(
strictRouteMatching = false,
defaultAppPaths = [],
}: NormalizeCatchAllRoutesOptions = {}
) {
): string[] {
const pageAppPaths = strictRouteMatching
? new Set(
Object.values(appPaths)
.flat()
.filter((appPath) => appPath.endsWith('/page'))
)
: undefined
const catchAllRoutes = [
...new Set(
Object.values(appPaths)
......@@ -95,7 +103,14 @@ export function normalizeCatchAllRoutes(
if (strictRouteMatching) {
pruneUnrenderableRoutes(appPaths, defaultAppPaths)
const matchedAppPaths = new Set(Object.values(appPaths).flat())
return [...pageAppPaths!]
.filter((appPath) => !matchedAppPaths.has(appPath))
.sort()
}
return []
}
/**
......
......@@ -98,6 +98,7 @@ import { parseUrl } from '../../../lib/url'
import { isAPIRoute } from '../../../lib/is-api-route'
import { isAppPageRoute } from '../../../lib/is-app-page-route'
import { isAppRouteRoute } from '../../../lib/is-app-route-route'
import { UnmatchedAppPagesError } from '../../../shared/lib/errors/unmatched-app-pages-error'
import {
createRouteTypesManifest,
writeRouteTypesManifest,
......@@ -462,6 +463,7 @@ async function startWatcher(
let enabledTypeScript = await verifyTypeScript(opts)
let previousClientRouterFilters: any
let previousConflictingPagePaths: Set<string> = new Set()
let hadUnmatchedAppPages = false
let hadInitialScan = false
let previousDuplicatePagePaths: Set<string> = new Set()
......@@ -1087,10 +1089,43 @@ async function startWatcher(
}
}
normalizeCatchAllRoutes(appPagePaths, undefined, {
strictRouteMatching: nextConfig.experimental.strictRouteMatching,
defaultAppPaths,
})
const unmatchedAppPages = normalizeCatchAllRoutes(
appPagePaths,
undefined,
{
strictRouteMatching: nextConfig.experimental.strictRouteMatching,
defaultAppPaths,
}
)
const unmatchedAppPagesError =
unmatchedAppPages.length > 0
? new UnmatchedAppPagesError(
unmatchedAppPages.map((appPath) => {
const filePath = appRouteFilePaths.get(appPath)
return filePath
? normalizePathSep(path.relative(dir, filePath))
: appPath
})
)
: null
if (
numConflicting === 0 &&
unmatchedAppPagesError &&
!hadUnmatchedAppPages
) {
Log.error(unmatchedAppPagesError.message)
}
// Turbopack reports unmatched pages as app-structure issues. Webpack
// needs an HMR server error so dev can finish booting and surface the
// problem to connected clients instead of throwing from this watcher.
if (!opts.turbo) {
if (numConflicting === 0 && unmatchedAppPagesError) {
hotReloader.setHmrServerError(unmatchedAppPagesError)
} else if (numConflicting === 0 && hadUnmatchedAppPages) {
hotReloader.clearHmrServerError()
}
}
hadUnmatchedAppPages = unmatchedAppPagesError !== null
for (const pageAppPaths of Object.values(appPagePaths)) {
pageAppPaths.sort(compareAppPaths)
}
......
export class UnmatchedAppPagesError extends Error {
constructor(pagePaths: readonly string[]) {
const formattedPagePaths = pagePaths
.map((pagePath) => `- ${pagePath}`)
.join('\n')
super(
`The following page files do not match any complete route:\n${formattedPagePaths}\n\nEvery page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages.`
)
this.name = 'UnmatchedAppPagesError'
this.stack = undefined
}
}
import type { ReactNode } from 'react'
// `content` is a real children branch even though its route targets are all
// below named slots. A match for only `sidebar` must therefore be incomplete.
// below named slots.
export default function Layout({
children,
sidebar,
......
......@@ -16,13 +16,6 @@ describe('explicit-parallel-route-children-detection', () => {
})
it('finds route targets nested beneath an ordinary children branch', async () => {
// The sidebar matches, but the discovered children branch does not. This
// route must be incomplete rather than rendering only the sidebar.
const incompleteResponse = await next.fetch('/nested/incomplete')
expect(await incompleteResponse.text()).toContain(
'This page could not be found'
)
const browser = await next.browser('/nested/content/anything')
expect(await browser.elementById('nested-sidebar').text()).toBe(
'nested sidebar'
......
......@@ -3,7 +3,7 @@ import { cookies } from 'next/headers'
// @slot has NO config but blocks with cookies(). The cause must
// come from the children slot's configs. The deepest config
// (still/deep/page.tsx) should be preferred over the shallower
// one (@anotherSlot/page.tsx).
// one (@anotherSlot/default.tsx).
export default async function CatchallSlotPage() {
await cookies()
return <p>Slot catchall page — no config, blocks with cookies()</p>
......
// Shallow config in a named slot. The deeper config in the children slot's
// still/deep/page.tsx should be preferred over this one.
export const instant = { level: 'experimental-error' }
export default function AnotherSlotDefault() {
return <p>Another slot default</p>
return <p>Another slot default — shallow config, no blocking</p>
}
// Shallow config in a named slot. The deeper config in
// still/deep/page.tsx should be preferred over this one.
export const instant = { level: 'experimental-error' }
export default function AnotherSlotPage() {
return <p>Another slot page — shallow config, no blocking</p>
}
export default function PanelPage() {
return <p>Panel page — no config, no blocking</p>
}
......@@ -895,7 +895,7 @@ export function registerSlotsAndGroupsTests(ctx: InstantValidationCaseContext) {
it('invalid - deeper children config preferred over shallower slot config', async () => {
// children has config deep (deeper/still/deep/page.tsx, depth 2)
// @anotherSlot has config shallow (page.tsx, depth 0)
// @anotherSlot has config shallow (default.tsx, depth 0)
// @slot blocks with no config — cause should be children's deep config
if (isNextDev) {
const browser = await navigateTo(
......
export default function Page() {
return <div>Children</div>
}
import { notFound } from 'next/navigation'
export default function Default() {
notFound()
}
export default function GroupedCatchallPage() {
return <p id="grouped-catchall-page">grouped catch-all page</p>
}
export default function FirstSlot() {
return <p id="first-slot-page">first slot</p>
}
export default function SecondSlot() {
return <p id="second-slot-page">second slot</p>
}
export default function ChildrenCatchall() {
return <p id="children-catchall-page">children catch-all</p>
}
export default function NestedOuterCatchallPage() {
return <p id="nested-outer-catchall-page">nested outer catch-all page</p>
}
export default function NestedCatchallPage() {
return <p id="nested-catchall-page">nested catch-all page</p>
}
export default function OptionalCatchallPage() {
return <p id="optional-catchall-page">optional catch-all page</p>
}
/**
* The optional children catch-all can match the segment root or any suffix,
* while @slot only matches /specific. The broad optional matcher is pruned,
* but /specific remains because both slots have an exact page for that URL.
* /specific has an exact page in both children and @slot, so it remains a
* complete matcher regardless of catch-all pruning elsewhere in the app.
*/
export default function OptionalChildrenCatchallLayout({
children,
......
......@@ -5,13 +5,7 @@ import stripAnsi from 'strip-ansi'
const prunedRoutes: Array<[path: string, layoutId: string]> = [
['/named-catchall/anything', 'named-catchall-layout'],
['/children-catchall/foo', 'children-catchall-layout'],
['/children-catchall/bar', 'children-catchall-layout'],
['/optional-children-catchall', 'optional-children-catchall-layout'],
['/optional-children-catchall/anything', 'optional-children-catchall-layout'],
['/split-matcher/anything', 'split-matcher-layout'],
['/nested-parallel/anything', 'nested-parallel-layout'],
['/grouped/anything', 'grouped-layout'],
]
function getAppRoutes(cliOutput: string): string[] {
......@@ -147,7 +141,7 @@ describe('parallel-routes-pruned-matchers', () => {
expect($('#valid-slot-page').text()).toBe('valid slot page')
})
it('keeps the specific sibling of a pruned optional catch-all', async () => {
it('keeps a complete specific matcher', async () => {
const $ = await next.render$('/optional-children-catchall/specific')
expect($('#optional-specific-page').text()).toBe('optional specific page')
......@@ -170,7 +164,7 @@ describe('parallel-routes-pruned-matchers', () => {
expect(response.status).toBe(404)
})
it('prunes a matcher with an incomplete nested parallel route', async () => {
it('keeps a complete nested parallel route matcher', async () => {
const $ = await next.render$('/nested-parallel/specific')
expect($('#nested-specific-page').text()).toBe('nested specific page')
......@@ -182,7 +176,7 @@ describe('parallel-routes-pruned-matchers', () => {
)
})
it('keeps the specific sibling of a pruned route-group matcher', async () => {
it('keeps a complete matcher through a route group', async () => {
const $ = await next.render$('/grouped/specific')
expect($('#grouped-specific-page').text()).toBe('grouped specific page')
......@@ -194,11 +188,7 @@ describe('parallel-routes-pruned-matchers', () => {
const appRoutes = getAppRoutes(next.cliOutput)
const omittedRoutes = [
'/named-catchall/[...slug]',
'/children-catchall/[...slug]',
'/optional-children-catchall/[[...slug]]',
'/split-matcher/[...parts]',
'/nested-parallel/[...slug]',
'/grouped/[...slug]',
]
expect(
......
export default function GroupedSlotPage() {
return <p>grouped slot</p>
}
export default function GroupedCatchAllPage() {
return <p>grouped catch-all</p>
}
import type { ReactNode } from 'react'
/** Route groups are transparent to both pruning and unmatched-page reporting. */
export default function GroupedLayout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<>
{children}
{slot}
</>
)
}
export default function GroupedSpecificPage() {
return <p>grouped specific</p>
}
export default function PanelDefault() {
return <p>panel default</p>
}
export default function PanelDetailsPage() {
return <p>panel details</p>
}
import type { ReactNode } from 'react'
/**
* /declared-children can render children/page with @panel/default. However,
* /declared-children/details only has a page in @panel, so its declared
* children slot would use Next.js' built-in not-found default. Strict route
* matching prunes that incomplete matcher and reports the panel page as
* unreachable.
*/
export default function DeclaredChildrenLayout({
children,
panel,
}: {
children: ReactNode
panel: ReactNode
}) {
return (
<>
{children}
{panel}
</>
)
}
export default function DeclaredChildrenPage() {
return <p>declared children</p>
}
export default function FirstFooPage() {
return <p>first foo</p>
}
export default function SecondBarPage() {
return <p>second bar</p>
}
export default function CatchAllPage() {
return <p>catch-all</p>
}
import type { ReactNode } from 'react'
/**
* `children` matches every non-empty path, but @first only matches /foo and
* @second only matches /bar. Every candidate therefore synthesizes a
* not-found default for at least one named slot, so this route emits no
* matchers when pruning is enabled.
* The children catch-all is combined with @first/foo and @second/bar, but each
* candidate is still missing the other named slot. All three pages are left
* out of the matcher set, so strict matching reports each one as unreachable.
*/
export default function ChildrenCatchallLayout({
export default function DisagreeingSlotsLayout({
children,
first,
second,
......@@ -16,10 +15,10 @@ export default function ChildrenCatchallLayout({
second: ReactNode
}) {
return (
<div id="children-catchall-layout">
<>
{children}
{first}
{second}
</div>
</>
)
}
export default function Page() {
return 'Unreachable canonical catch-all'
}
export default function Page() {
return 'Canonical slot'
}
export default function Page() {
return 'Secondary slot without a default'
}
import type { ReactNode } from 'react'
/**
* The interception matcher may retain every active host slot, so it remains
* valid even though @secondary cannot match /intercepted/*. The ordinary
* @canonical catch-all cannot retain slots and is therefore unreachable.
*/
export default function InterceptionHostLayout({
canonical,
modal,
secondary,
}: {
canonical: ReactNode
modal: ReactNode
secondary: ReactNode
}) {
return (
<>
{canonical}
{modal}
{secondary}
</>
)
}
import type { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function InnerSpecificPage() {
return <p>inner specific</p>
}
export default function OuterCatchAllPage() {
return <p>outer catch-all</p>
}
import type { ReactNode } from 'react'
export default function OuterLayout({
children,
inner,
}: {
children: ReactNode
inner: ReactNode
}) {
return (
<>
{children}
{inner}
</>
)
}
export default function OuterSpecificPage() {
return <p>outer specific</p>
}
export default function NestedCatchAllPage() {
return <p>nested catch-all</p>
}
import type { ReactNode } from 'react'
/** Incomplete catch-alls can be unreachable at more than one slot depth. */
export default function NestedLayout({
children,
outer,
}: {
children: ReactNode
outer: ReactNode
}) {
return (
<>
{children}
{outer}
</>
)
}
export default function NestedSpecificPage() {
return <p>nested specific</p>
}
export default function SlotSpecificPage() {
return <p>slot specific</p>
}
export default function OptionalCatchAllPage() {
return <p>optional catch-all</p>
}
import type { ReactNode } from 'react'
/**
* The optional catch-all's broad matcher cannot satisfy @slot and is pruned.
* /specific remains complete, but its exact children page wins there, so the
* optional catch-all page does not participate in that matcher either.
*/
export default function OptionalCatchallLayout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<>
{children}
{slot}
</>
)
}
export default function SpecificPage() {
return <p>specific</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
strictRouteMatching: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import stripAnsi from 'strip-ansi'
describe('unmatched-app-pages', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
it('reports every page excluded from all complete routes', async () => {
if (isNextDev) {
await next.start()
const browser = await next.browser('/')
if (isTurbopack) {
await expect({ browser, next }).toDisplayRedbox(`
{
"description": "Unmatched app pages",
"environmentLabel": null,
"label": "Build Error",
"source": "./app/(pruning-group)/grouped/[...slug]/page.tsx
Error: Unmatched app pages
The following page files do not match any complete route:
- app/(pruning-group)/grouped/[...slug]/page.tsx
- app/declared-children/@panel/details/page.tsx
- app/disagreeing-slots/@first/foo/page.tsx
- app/disagreeing-slots/@second/bar/page.tsx
- app/disagreeing-slots/[...slug]/page.tsx
- app/interception-host/@canonical/intercepted/[...slug]/page.tsx
- app/nested-parallel/@outer/[...slug]/page.tsx
- app/nested-parallel/[...slug]/page.tsx
- app/optional-catchall/[[...slug]]/page.tsx
Every page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages.",
"stack": [],
}
`)
} else {
await expect({ browser, next }).toDisplayRedbox(`
{
"description": "- app/(pruning-group)/grouped/[...slug]/page.tsx",
"environmentLabel": null,
"label": "Build Error",
"source": "The following page files do not match any complete route:
- app/(pruning-group)/grouped/[...slug]/page.tsx
- app/declared-children/@panel/details/page.tsx
- app/disagreeing-slots/@first/foo/page.tsx
- app/disagreeing-slots/@second/bar/page.tsx
- app/disagreeing-slots/[...slug]/page.tsx
- app/interception-host/@canonical/intercepted/[...slug]/page.tsx
- app/nested-parallel/@outer/[...slug]/page.tsx
- app/nested-parallel/[...slug]/page.tsx
- app/optional-catchall/[[...slug]]/page.tsx
Every page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages.",
"stack": [],
}
`)
}
} else {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(extractUnmatchedPagesError(cliOutput)).toMatchInlineSnapshot(`
"The following page files do not match any complete route:
- app/(pruning-group)/grouped/[...slug]/page.tsx
- app/declared-children/@panel/details/page.tsx
- app/disagreeing-slots/@first/foo/page.tsx
- app/disagreeing-slots/@second/bar/page.tsx
- app/disagreeing-slots/[...slug]/page.tsx
- app/interception-host/@canonical/intercepted/[...slug]/page.tsx
- app/nested-parallel/@outer/[...slug]/page.tsx
- app/nested-parallel/[...slug]/page.tsx
- app/optional-catchall/[[...slug]]/page.tsx
Every page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages."
`)
}
})
})
function extractUnmatchedPagesError(output: string): string {
const normalizedOutput = stripAnsi(output)
const start = normalizedOutput.indexOf(
'The following page files do not match any complete route:'
)
const finalLine =
'Every page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages.'
const end = normalizedOutput.indexOf(finalLine, start)
expect(start).not.toBe(-1)
expect(end).not.toBe(-1)
return normalizedOutput.slice(start, end + finalLine.length)
}
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