Unverified Commit dea15ec6 authored by Josh Story's avatar Josh Story Committed by GitHub

Require canonical routes for interception routes (#97428)

Interception routes only describe the branch used during a soft
navigation, but every URL they can produce still needs to be handled by
an ordinary App Router page matcher for a direct request or refresh.
Today an interception-only URL can appear to work during client
navigation and then 404 when the same URL is loaded directly. This makes
strict route matching reject that configuration.

For example, this setup is incomplete:

```
app/
  @modal/
    (.)photo/
      [...id]/
        page.tsx
  photo/
    [id]/
      page.tsx
```

The ordinary route handles `/photo/1`, but the interception route also
handles `/photo/1/2`, which has no ordinary page matcher. Widening the
ordinary route makes the setup valid:

```
app/
  @modal/
    (.)photo/
      [...id]/
        page.tsx
  photo/
    [...id]/
      page.tsx
```

The validation checks coverage rather than requiring an identical
matcher. A broader catchall can cover the intercepted pattern, and
multiple ordinary matchers can cover different accepted lengths. For
example, `items/page.tsx` together with `items/[...rest]/page.tsx`
covers an intercepted `items/[[...parts]]` matcher. Route handlers and
generated metadata routes do not count as canonical page matchers.

Webpack and Turbopack now apply the same coverage check and report the
interception matcher and the canonical pattern that is not fully
covered. Existing interception fixtures now include semantically
complete ordinary routes instead of relying on interception-only URLs.

<!-- NEXT_JS_LLM -->
parent 7b7cee30
...@@ -992,6 +992,43 @@ async fn directory_tree_to_entrypoints( ...@@ -992,6 +992,43 @@ async fn directory_tree_to_entrypoints(
} }
} }
let ordinary_routes = retained_entrypoints
.iter()
.filter_map(|(route, entrypoint)| {
(!route.contains_interception() && matches!(entrypoint, Entrypoint::AppPage { .. }))
.then_some(route)
})
.collect::<Vec<_>>();
let missing_canonical_interception_routes = retained_entrypoints
.iter()
.filter_map(|(interception_route, entrypoint)| {
let Entrypoint::AppPage {
participating_page_files,
..
} = entrypoint
else {
return None;
};
let canonical_route = interception_route.intercepted_path()?;
if canonical_route.is_route_pattern_covered_by(ordinary_routes.iter().copied()) {
return None;
}
Some((
interception_route.clone(),
canonical_route,
participating_page_files.first()?.clone(),
))
})
.collect::<Vec<_>>();
if !missing_canonical_interception_routes.is_empty() {
MissingCanonicalInterceptionRoutesIssue {
routes: missing_canonical_interception_routes,
}
.resolved_cell()
.emit();
}
let mut authored_pages = FxIndexSet::default(); let mut authored_pages = FxIndexSet::default();
collect_authored_page_files(&plain_tree, &mut authored_pages); collect_authored_page_files(&plain_tree, &mut authored_pages);
...@@ -1021,6 +1058,52 @@ async fn directory_tree_to_entrypoints( ...@@ -1021,6 +1058,52 @@ async fn directory_tree_to_entrypoints(
Ok(Vc::cell(retained_entrypoints)) Ok(Vc::cell(retained_entrypoints))
} }
#[turbo_tasks::value]
struct MissingCanonicalInterceptionRoutesIssue {
routes: Vec<(AppPath, AppPath, FileSystemPath)>,
}
#[async_trait]
#[turbo_tasks::value_impl]
impl Issue for MissingCanonicalInterceptionRoutesIssue {
async fn file_path(&self) -> Result<FileSystemPath> {
Ok(self.routes[0].2.clone())
}
fn stage(&self) -> IssueStage {
IssueStage::AppStructure
}
fn severity(&self) -> IssueSeverity {
IssueSeverity::Error
}
async fn title(&self) -> Result<StyledString> {
Ok(StyledString::Text(rcstr!(
"Interception routes must have a canonical route"
)))
}
async fn description(&self) -> Result<Option<StyledString>> {
let routes = self
.routes
.iter()
.map(|(interception_route, canonical_route, _)| {
format!("- {interception_route} (expected {canonical_route})")
})
.collect::<Vec<_>>()
.join("\n");
Ok(Some(StyledString::Text(
format!(
"The following interception routes do not have a canonical \
route:\n{routes}\n\nEvery interception route must have a matching \
non-interception route so the URL can be loaded directly or refreshed."
)
.into(),
)))
}
}
fn collect_authored_page_files( fn collect_authored_page_files(
directory_tree: &PlainDirectoryTree, directory_tree: &PlainDirectoryTree,
pages: &mut FxIndexSet<FileSystemPath>, pages: &mut FxIndexSet<FileSystemPath>,
......
...@@ -429,6 +429,165 @@ impl AppPath { ...@@ -429,6 +429,165 @@ impl AppPath {
) )
}) })
} }
/// Returns the ordinary route that an interception route substitutes for.
/// This is the route that must handle a direct request or hard refresh.
pub fn intercepted_path(&self) -> Option<AppPath> {
let (interception_index, segment) =
self.iter().enumerate().find_map(|(index, segment)| {
let PathSegment::Static(segment) = segment else {
return None;
};
let (marker, target) =
["(..)(..)", "(...)", "(..)", "(.)"]
.into_iter()
.find_map(|marker| {
segment.strip_prefix(marker).map(|target| (marker, target))
})?;
Some((index, (marker, target)))
})?;
let (marker, target) = segment;
if target.is_empty() {
return None;
}
let mut canonical_segments = match marker {
"(...)" => Vec::new(),
_ => self.0[..interception_index].to_vec(),
};
let levels_to_pop = match marker {
"(..)(..)" => 2,
"(..)" => 1,
_ => 0,
};
for _ in 0..levels_to_pop {
canonical_segments.pop()?;
}
let target = if let Some(target) = target
.strip_prefix("[[...")
.and_then(|target| target.strip_suffix("]]"))
{
PathSegment::OptionalCatchAll(target.into())
} else if let Some(target) = target
.strip_prefix("[...")
.and_then(|target| target.strip_suffix(']'))
{
PathSegment::CatchAll(target.into())
} else if let Some(target) = target
.strip_prefix('[')
.and_then(|target| target.strip_suffix(']'))
{
PathSegment::Dynamic(target.into())
} else {
PathSegment::Static(target.into())
};
canonical_segments.push(target);
canonical_segments.extend_from_slice(&self.0[interception_index + 1..]);
Some(AppPath(canonical_segments))
}
/// Returns whether the supplied ordinary route patterns cover every URL matched by this
/// route pattern.
pub fn is_route_pattern_covered_by<'a>(
&self,
ordinary_routes: impl IntoIterator<Item = &'a AppPath>,
) -> bool {
let route = RoutePattern::new(self);
let ordinary_routes = ordinary_routes
.into_iter()
.map(RoutePattern::new)
.collect::<Vec<_>>();
if !route.unbounded {
return ordinary_routes
.iter()
.any(|ordinary| pattern_covers_at_length(ordinary, &route, route.min_length));
}
let Some(unbounded_coverage_start) = ordinary_routes
.iter()
.filter(|ordinary| ordinary.unbounded && prefix_covers(ordinary, &route))
.map(|ordinary| ordinary.min_length.max(route.min_length))
.min()
else {
return false;
};
// An optional or required catchall can have its shorter paths covered by fixed routes
// before another catchall takes over the remaining suffix.
(route.min_length..unbounded_coverage_start).all(|length| {
ordinary_routes
.iter()
.any(|ordinary| pattern_covers_at_length(ordinary, &route, length))
})
}
}
struct RoutePattern<'a> {
prefix: &'a [PathSegment],
min_length: usize,
unbounded: bool,
}
impl<'a> RoutePattern<'a> {
fn new(path: &'a AppPath) -> Self {
match path.last() {
Some(PathSegment::CatchAll(_)) => Self {
prefix: &path[..path.len() - 1],
min_length: path.len(),
unbounded: true,
},
Some(PathSegment::OptionalCatchAll(_)) => Self {
prefix: &path[..path.len() - 1],
min_length: path.len() - 1,
unbounded: true,
},
_ => Self {
prefix: path,
min_length: path.len(),
unbounded: false,
},
}
}
}
fn accepts_length(pattern: &RoutePattern<'_>, length: usize) -> bool {
if pattern.unbounded {
length >= pattern.min_length
} else {
length == pattern.min_length
}
}
fn prefix_covers(canonical: &RoutePattern<'_>, intercepted: &RoutePattern<'_>) -> bool {
canonical
.prefix
.iter()
.enumerate()
.all(|(index, canonical_segment)| match canonical_segment {
PathSegment::Dynamic(_) => true,
PathSegment::Static(canonical_segment) => matches!(
intercepted.prefix.get(index),
Some(PathSegment::Static(intercepted_segment))
if canonical_segment == intercepted_segment
),
PathSegment::CatchAll(_) | PathSegment::OptionalCatchAll(_) => {
unreachable!("catchall segments are excluded from the route prefix")
}
})
}
fn pattern_covers_at_length(
canonical: &RoutePattern<'_>,
intercepted: &RoutePattern<'_>,
length: usize,
) -> bool {
accepts_length(canonical, length)
&& accepts_length(intercepted, length)
&& prefix_covers(canonical, intercepted)
} }
impl Deref for AppPath { impl Deref for AppPath {
...@@ -489,7 +648,62 @@ impl From<AppPage> for AppPath { ...@@ -489,7 +648,62 @@ impl From<AppPage> for AppPath {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use crate::next_app::{AppPage, PageSegment, PageType}; use crate::next_app::{AppPage, AppPath, PageSegment, PageType};
#[test]
fn resolves_intercepted_app_paths() {
for (interception, canonical) in [
("/(.)photo/[id]", "/photo/[id]"),
("/feed/(.)photo/[id]", "/feed/photo/[id]"),
("/feed/(..)photo/[id]", "/photo/[id]"),
("/feed/nested/(..)(..)photo/[id]", "/photo/[id]"),
("/feed/(...)photo/[id]", "/photo/[id]"),
("/(.)[username]/[id]", "/[username]/[id]"),
("/(.)[...slug]", "/[...slug]"),
("/(.)[[...slug]]", "/[[...slug]]"),
] {
let interception =
AppPath::from(AppPage::parse(interception.trim_start_matches('/')).unwrap());
let canonical =
AppPath::from(AppPage::parse(canonical.trim_start_matches('/')).unwrap());
assert_eq!(interception.intercepted_path(), Some(canonical));
}
}
#[test]
fn checks_route_pattern_coverage() {
for (route, ordinary_routes, expected) in [
("/photo/[id]", &["/photo/[slug]"][..], true),
("/showcase/[...parts]", &["/[...slug]"][..], true),
(
"/items/[...parts]",
&["/items/[id]", "/items/[id]/[...rest]"][..],
true,
),
(
"/items/[[...parts]]",
&["/items", "/items/[...rest]"][..],
true,
),
("/photo/[id]", &[][..], false),
("/items/[...parts]", &["/items/[id]"][..], false),
("/items/[[...parts]]", &["/items/[...rest]"][..], false),
("/items/[id]", &["/items/one", "/items/two"][..], false),
] {
let route = AppPath::from(AppPage::parse(route.trim_start_matches('/')).unwrap());
let ordinary_routes = ordinary_routes
.iter()
.map(|route| AppPath::from(AppPage::parse(route.trim_start_matches('/')).unwrap()))
.collect::<Vec<_>>();
assert_eq!(
route.is_route_pattern_covered_by(ordinary_routes.iter()),
expected,
"coverage for {route} from {ordinary_routes:?}"
);
}
}
#[test] #[test]
fn test_normalize_metadata_route() { fn test_normalize_metadata_route() {
......
...@@ -47,6 +47,7 @@ import { ...@@ -47,6 +47,7 @@ import {
import { encodeMatchers } from './webpack/loaders/next-middleware-loader' import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
import type { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' import type { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
import { isAppPageRoute } from '../lib/is-app-page-route'
import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader' import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader'
import { import {
isInternalComponent, isInternalComponent,
...@@ -59,6 +60,8 @@ import type { PageExtensions } from './page-extensions-type' ...@@ -59,6 +60,8 @@ import type { PageExtensions } from './page-extensions-type'
import type { MappedPages } from './build-context' import type { MappedPages } from './build-context'
import { PAGE_TYPES } from '../lib/page-types' import { PAGE_TYPES } from '../lib/page-types'
import { UnmatchedAppPagesError } from '../shared/lib/errors/unmatched-app-pages-error' import { UnmatchedAppPagesError } from '../shared/lib/errors/unmatched-app-pages-error'
import { MissingCanonicalInterceptionRoutesError } from '../shared/lib/errors/missing-canonical-interception-routes-error'
import { findMissingCanonicalInterceptionRoutes } from '../shared/lib/router/utils/interception-routes'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts' import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts'
...@@ -431,6 +434,24 @@ export async function createEntrypoints( ...@@ -431,6 +434,24 @@ export async function createEntrypoints(
strictRouteMatching: config.experimental.strictRouteMatching, strictRouteMatching: config.experimental.strictRouteMatching,
defaultAppPaths: Object.keys(appDefaultPaths ?? {}), defaultAppPaths: Object.keys(appDefaultPaths ?? {}),
}) })
// Only App Router pages can make an intercepted URL directly renderable.
// Route handlers and metadata routes may share the pathname, but they
// cannot provide the canonical page shown by an initial request.
const appPagePathsPerRoute = Object.fromEntries(
Object.entries(appPathsPerRoute).flatMap(([route, routeAppPaths]) => {
const pageAppPaths = routeAppPaths.filter(isAppPageRoute)
return pageAppPaths.length > 0 ? [[route, pageAppPaths]] : []
})
)
const missingCanonicalInterceptionRoutes = config.experimental
.strictRouteMatching
? findMissingCanonicalInterceptionRoutes(appPagePathsPerRoute)
: []
if (missingCanonicalInterceptionRoutes.length > 0) {
throw new MissingCanonicalInterceptionRoutesError(
missingCanonicalInterceptionRoutes
)
}
if (unmatchedAppPages.length > 0) { if (unmatchedAppPages.length > 0) {
throw new UnmatchedAppPagesError( throw new UnmatchedAppPagesError(
unmatchedAppPages.map((appPath) => { unmatchedAppPages.map((appPath) => {
......
...@@ -99,6 +99,8 @@ import { isAPIRoute } from '../../../lib/is-api-route' ...@@ -99,6 +99,8 @@ import { isAPIRoute } from '../../../lib/is-api-route'
import { isAppPageRoute } from '../../../lib/is-app-page-route' import { isAppPageRoute } from '../../../lib/is-app-page-route'
import { isAppRouteRoute } from '../../../lib/is-app-route-route' import { isAppRouteRoute } from '../../../lib/is-app-route-route'
import { UnmatchedAppPagesError } from '../../../shared/lib/errors/unmatched-app-pages-error' import { UnmatchedAppPagesError } from '../../../shared/lib/errors/unmatched-app-pages-error'
import { MissingCanonicalInterceptionRoutesError } from '../../../shared/lib/errors/missing-canonical-interception-routes-error'
import { findMissingCanonicalInterceptionRoutes } from '../../../shared/lib/router/utils/interception-routes'
import { import {
createRouteTypesManifest, createRouteTypesManifest,
writeRouteTypesManifest, writeRouteTypesManifest,
...@@ -463,7 +465,7 @@ async function startWatcher( ...@@ -463,7 +465,7 @@ async function startWatcher(
let enabledTypeScript = await verifyTypeScript(opts) let enabledTypeScript = await verifyTypeScript(opts)
let previousClientRouterFilters: any let previousClientRouterFilters: any
let previousConflictingPagePaths: Set<string> = new Set() let previousConflictingPagePaths: Set<string> = new Set()
let hadUnmatchedAppPages = false let previousRouteMatchingError: string | null = null
let hadInitialScan = false let hadInitialScan = false
let previousDuplicatePagePaths: Set<string> = new Set() let previousDuplicatePagePaths: Set<string> = new Set()
...@@ -1097,35 +1099,43 @@ async function startWatcher( ...@@ -1097,35 +1099,43 @@ async function startWatcher(
defaultAppPaths, defaultAppPaths,
} }
) )
const unmatchedAppPagesError = const missingCanonicalInterceptionRoutes = nextConfig.experimental
unmatchedAppPages.length > 0 .strictRouteMatching
? new UnmatchedAppPagesError( ? findMissingCanonicalInterceptionRoutes(appPagePaths)
unmatchedAppPages.map((appPath) => { : []
const filePath = appRouteFilePaths.get(appPath) const routeMatchingError =
return filePath missingCanonicalInterceptionRoutes.length > 0
? normalizePathSep(path.relative(dir, filePath)) ? new MissingCanonicalInterceptionRoutesError(
: appPath missingCanonicalInterceptionRoutes
})
) )
: null : unmatchedAppPages.length > 0
? new UnmatchedAppPagesError(
unmatchedAppPages.map((appPath) => {
const filePath = appRouteFilePaths.get(appPath)
return filePath
? normalizePathSep(path.relative(dir, filePath))
: appPath
})
)
: null
if ( if (
numConflicting === 0 && numConflicting === 0 &&
unmatchedAppPagesError && routeMatchingError &&
!hadUnmatchedAppPages routeMatchingError.message !== previousRouteMatchingError
) { ) {
Log.error(unmatchedAppPagesError.message) Log.error(routeMatchingError.message)
} }
// Turbopack reports unmatched pages as app-structure issues. Webpack // Turbopack reports route-matching failures as app-structure issues.
// needs an HMR server error so dev can finish booting and surface the // Webpack needs an HMR server error so dev can finish booting and surface
// problem to connected clients instead of throwing from this watcher. // the problem to connected clients instead of throwing from this watcher.
if (!opts.turbo) { if (!opts.turbo) {
if (numConflicting === 0 && unmatchedAppPagesError) { if (numConflicting === 0 && routeMatchingError) {
hotReloader.setHmrServerError(unmatchedAppPagesError) hotReloader.setHmrServerError(routeMatchingError)
} else if (numConflicting === 0 && hadUnmatchedAppPages) { } else if (numConflicting === 0 && previousRouteMatchingError) {
hotReloader.clearHmrServerError() hotReloader.clearHmrServerError()
} }
} }
hadUnmatchedAppPages = unmatchedAppPagesError !== null previousRouteMatchingError = routeMatchingError?.message ?? null
for (const pageAppPaths of Object.values(appPagePaths)) { for (const pageAppPaths of Object.values(appPagePaths)) {
pageAppPaths.sort(compareAppPaths) pageAppPaths.sort(compareAppPaths)
} }
......
import type { MissingCanonicalInterceptionRoute } from '../router/utils/interception-routes'
export class MissingCanonicalInterceptionRoutesError extends Error {
constructor(routes: readonly MissingCanonicalInterceptionRoute[]) {
const formattedRoutes = routes
.map(
({ interceptionRoute, canonicalRoute }) =>
`- ${interceptionRoute} (expected ${canonicalRoute})`
)
.join('\n')
super(
`The following interception routes do not have a canonical route:\n${formattedRoutes}\n\nEvery interception route must have a matching non-interception route so the URL can be loaded directly or refreshed.`
)
this.name = 'MissingCanonicalInterceptionRoutesError'
this.stack = undefined
}
}
import { import {
extractInterceptionRouteInformation, extractInterceptionRouteInformation,
findMissingCanonicalInterceptionRoutes,
isInterceptionRouteAppPath, isInterceptionRouteAppPath,
} from './interception-routes' } from './interception-routes'
...@@ -76,4 +77,75 @@ describe('Interception Route helper', () => { ...@@ -76,4 +77,75 @@ describe('Interception Route helper', () => {
) )
}) })
}) })
describe('findMissingCanonicalInterceptionRoutes', () => {
function isCovered(
interceptionRoute: string,
ordinaryRoutes: string[]
): boolean {
return (
findMissingCanonicalInterceptionRoutes(
Object.fromEntries(
[interceptionRoute, ...ordinaryRoutes].map((route) => [
route,
[`${route}/page`],
])
)
).length === 0
)
}
it.each([
{
name: 'an equivalent dynamic matcher',
interception: '/(.)photo/[id]',
ordinary: ['/photo/[slug]'],
},
{
name: 'a broader root catchall',
interception: '/(.)showcase/[...parts]',
ordinary: ['/[...slug]'],
},
{
name: 'a fixed matcher followed by a deeper catchall',
interception: '/(.)items/[...parts]',
ordinary: ['/items/[id]', '/items/[id]/[...rest]'],
},
{
name: 'a fixed matcher and required catchall for an optional catchall',
interception: '/(.)items/[[...parts]]',
ordinary: ['/items', '/items/[...rest]'],
},
])('accepts coverage from $name', ({ interception, ordinary }) => {
expect(isCovered(interception, ordinary)).toBe(true)
})
it.each([
{
name: 'no ordinary matcher',
interception: '/(.)photo/[id]',
ordinary: [],
},
{
name: 'a single dynamic segment for a required catchall',
interception: '/(.)items/[...parts]',
ordinary: ['/items/[id]'],
},
{
name: 'a required catchall for an optional catchall',
interception: '/(.)items/[[...parts]]',
ordinary: ['/items/[...rest]'],
},
{
name: 'a finite set of static values for a dynamic segment',
interception: '/(.)items/[id]',
ordinary: ['/items/one', '/items/two'],
},
])(
'rejects incomplete coverage from $name',
({ interception, ordinary }) => {
expect(isCovered(interception, ordinary)).toBe(false)
}
)
})
}) })
...@@ -10,6 +10,112 @@ export const INTERCEPTION_ROUTE_MARKERS = [ ...@@ -10,6 +10,112 @@ export const INTERCEPTION_ROUTE_MARKERS = [
export type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number] export type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number]
export type MissingCanonicalInterceptionRoute = {
interceptionRoute: string
canonicalRoute: string
}
type RoutePattern = {
prefix: Array<string | null>
minLength: number
unbounded: boolean
}
function parseRoutePattern(route: string): RoutePattern {
const segments = route.split('/').filter(Boolean)
const tail = segments.at(-1)
const isOptionalCatchAll =
tail !== undefined && tail.startsWith('[[...') && tail.endsWith(']]')
const isCatchAll =
tail !== undefined && tail.startsWith('[...') && tail.endsWith(']')
const unbounded = isOptionalCatchAll || isCatchAll
const prefixSegments = unbounded ? segments.slice(0, -1) : segments
return {
prefix: prefixSegments.map((segment) =>
segment.startsWith('[') && segment.endsWith(']') ? null : segment
),
minLength:
prefixSegments.length + (isCatchAll && !isOptionalCatchAll ? 1 : 0),
unbounded,
}
}
function acceptsLength(pattern: RoutePattern, length: number): boolean {
return pattern.unbounded
? length >= pattern.minLength
: length === pattern.minLength
}
function prefixCovers(
canonical: RoutePattern,
intercepted: RoutePattern
): boolean {
return canonical.prefix.every((canonicalSegment, index) => {
if (canonicalSegment === null) return true
const interceptedSegment = intercepted.prefix[index]
return (
interceptedSegment !== undefined &&
interceptedSegment !== null &&
canonicalSegment === interceptedSegment
)
})
}
function patternCoversAtLength(
canonical: RoutePattern,
intercepted: RoutePattern,
length: number
): boolean {
return (
acceptsLength(canonical, length) &&
acceptsLength(intercepted, length) &&
prefixCovers(canonical, intercepted)
)
}
/** Returns whether ordinary route patterns cover every URL in `route`. */
function isRoutePatternCovered(route: string, ordinaryRoutes: RoutePattern[]) {
const intercepted = parseRoutePattern(route)
if (!intercepted.unbounded) {
return ordinaryRoutes.some((pattern) =>
patternCoversAtLength(pattern, intercepted, intercepted.minLength)
)
}
let unboundedCoverageStart = Infinity
for (const pattern of ordinaryRoutes) {
if (pattern.unbounded && prefixCovers(pattern, intercepted)) {
unboundedCoverageStart = Math.min(
unboundedCoverageStart,
Math.max(intercepted.minLength, pattern.minLength)
)
}
}
if (unboundedCoverageStart === Infinity) return false
// An optional or required catchall can have its shorter paths covered by
// fixed routes before another catchall takes over the remaining suffix.
for (
let length = intercepted.minLength;
length < unboundedCoverageStart;
length++
) {
if (
!ordinaryRoutes.some((pattern) =>
patternCoversAtLength(pattern, intercepted, length)
)
) {
return false
}
}
return true
}
export function isInterceptionRouteAppPath(path: string): boolean { export function isInterceptionRouteAppPath(path: string): boolean {
// TODO-APP: add more serious validation // TODO-APP: add more serious validation
return ( return (
...@@ -106,3 +212,31 @@ export function extractInterceptionRouteInformation( ...@@ -106,3 +212,31 @@ export function extractInterceptionRouteInformation(
return { interceptingRoute, interceptedRoute } return { interceptingRoute, interceptedRoute }
} }
/**
* Finds interception matchers that cannot be loaded as an ordinary request.
*
* This must run after catch-all normalization and pruning so `appPaths`
* contains the final matcher set rather than every possible matcher candidate.
*/
export function findMissingCanonicalInterceptionRoutes(
appPaths: Record<string, string[]>
): MissingCanonicalInterceptionRoute[] {
const canonicalRoutes = Object.keys(appPaths).filter(
(route) => !isInterceptionRouteAppPath(route)
)
const canonicalRoutePatterns = canonicalRoutes.map(parseRoutePattern)
return Object.keys(appPaths)
.filter(isInterceptionRouteAppPath)
.map((interceptionRoute) => ({
interceptionRoute,
canonicalRoute:
extractInterceptionRouteInformation(interceptionRoute).interceptedRoute,
}))
.filter(
({ canonicalRoute }) =>
!isRoutePatternCovered(canonicalRoute, canonicalRoutePatterns)
)
.sort((a, b) => a.interceptionRoute.localeCompare(b.interceptionRoute))
}
export default function InterceptedPage() {
return <p>intercepted page</p>
}
import type { ReactNode } from 'react'
export default function Root({
children,
modal,
}: {
children: ReactNode
modal: ReactNode
}) {
return (
<html>
<body>
{children}
{modal}
</body>
</html>
)
}
export default function Page() { export default function Page() {
return 'Canonical slot' return <p>hello world</p>
} }
import { nextTestSetup } from 'e2e-utils'
import stripAnsi from 'strip-ansi'
describe('canonical-interception-routes', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) return
it('requires a canonical hard-navigation route for every interception route', async () => {
if (isNextDev) {
await next.start()
const browser = await next.browser('/')
if (isTurbopack) {
await expect({ browser, next }).toDisplayRedbox(`
{
"description": "Interception routes must have a canonical route",
"environmentLabel": null,
"label": "Build Error",
"source": "./app/@modal/(.)missing/[id]/page.tsx
Error: Interception routes must have a canonical route
The following interception routes do not have a canonical route:
- /(.)missing/[id] (expected /missing/[id])
Every interception route must have a matching non-interception route so the URL can be loaded directly or refreshed.",
"stack": [],
}
`)
} else {
await expect({ browser, next }).toDisplayRedbox(`
{
"description": "- /(.)missing/[id] (expected /missing/[id])",
"environmentLabel": null,
"label": "Build Error",
"source": "The following interception routes do not have a canonical route:
- /(.)missing/[id] (expected /missing/[id])
Every interception route must have a matching non-interception route so the URL can be loaded directly or refreshed.",
"stack": [],
}
`)
}
} else {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(extractMissingCanonicalRoutesError(cliOutput))
.toMatchInlineSnapshot(`
"The following interception routes do not have a canonical route:
- /(.)missing/[id] (expected /missing/[id])
Every interception route must have a matching non-interception route so the URL can be loaded directly or refreshed."
`)
}
})
})
function extractMissingCanonicalRoutesError(output: string): string {
const normalizedOutput = stripAnsi(output)
const start = normalizedOutput.indexOf(
'The following interception routes do not have a canonical route:'
)
const finalLine =
'Every interception route must have a matching non-interception route so the URL can be loaded directly or refreshed.'
const end = normalizedOutput.indexOf(finalLine, start)
expect(start).not.toBe(-1)
expect(end).not.toBe(-1)
return normalizedOutput.slice(start, end + finalLine.length)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
strictRouteMatching: true,
},
}
module.exports = nextConfig
export default function Page() { export default function Page() {
return 'Secondary slot without a default' return <p id="canonical-named-catchall-target">Canonical named catch-all</p>
} }
export default function Page() {
return 'Unreachable canonical catch-all'
}
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}
</>
)
}
...@@ -29,7 +29,6 @@ describe('unmatched-app-pages', () => { ...@@ -29,7 +29,6 @@ describe('unmatched-app-pages', () => {
- app/disagreeing-slots/@first/foo/page.tsx - app/disagreeing-slots/@first/foo/page.tsx
- app/disagreeing-slots/@second/bar/page.tsx - app/disagreeing-slots/@second/bar/page.tsx
- app/disagreeing-slots/[...slug]/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/@outer/[...slug]/page.tsx
- app/nested-parallel/[...slug]/page.tsx - app/nested-parallel/[...slug]/page.tsx
- app/optional-catchall/[[...slug]]/page.tsx - app/optional-catchall/[[...slug]]/page.tsx
...@@ -49,7 +48,6 @@ describe('unmatched-app-pages', () => { ...@@ -49,7 +48,6 @@ describe('unmatched-app-pages', () => {
- app/disagreeing-slots/@first/foo/page.tsx - app/disagreeing-slots/@first/foo/page.tsx
- app/disagreeing-slots/@second/bar/page.tsx - app/disagreeing-slots/@second/bar/page.tsx
- app/disagreeing-slots/[...slug]/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/@outer/[...slug]/page.tsx
- app/nested-parallel/[...slug]/page.tsx - app/nested-parallel/[...slug]/page.tsx
- app/optional-catchall/[[...slug]]/page.tsx - app/optional-catchall/[[...slug]]/page.tsx
...@@ -69,7 +67,6 @@ describe('unmatched-app-pages', () => { ...@@ -69,7 +67,6 @@ describe('unmatched-app-pages', () => {
- app/disagreeing-slots/@first/foo/page.tsx - app/disagreeing-slots/@first/foo/page.tsx
- app/disagreeing-slots/@second/bar/page.tsx - app/disagreeing-slots/@second/bar/page.tsx
- app/disagreeing-slots/[...slug]/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/@outer/[...slug]/page.tsx
- app/nested-parallel/[...slug]/page.tsx - app/nested-parallel/[...slug]/page.tsx
- app/optional-catchall/[[...slug]]/page.tsx - app/optional-catchall/[[...slug]]/page.tsx
......
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