Commit 44e89151 authored by Josh Story's avatar Josh Story

--no commit message

--no commit message
parent beff2f40
...@@ -1180,6 +1180,11 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1180,6 +1180,11 @@ async fn directory_tree_to_loader_tree_internal(
let app_path = AppPath::from(app_page.clone()); let app_path = AppPath::from(app_page.clone());
if !for_app_path.contains(&app_path) { if !for_app_path.contains(&app_path) {
eprintln!(
"[DEBUG loader-tree] PRUNED directory_name={:?} app_path={:?} not contained in \
for_app_path={:?}",
directory_name, app_path, for_app_path
);
return Ok(None); return Ok(None);
} }
...@@ -1267,6 +1272,17 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -1267,6 +1272,17 @@ async fn directory_tree_to_loader_tree_internal(
tree.segment = rcstr!("(__SLOT__)"); tree.segment = rcstr!("(__SLOT__)");
} }
eprintln!(
"[DEBUG loader-tree] directory_name={:?} app_page={:?} app_path={:?} for_app_path={:?} \
is_catchall={} has_page={}",
directory_name,
app_page,
app_path,
for_app_path,
app_path.is_catchall(),
modules.page.is_some()
);
if let Some(page) = (app_path == for_app_path || app_path.is_catchall()) if let Some(page) = (app_path == for_app_path || app_path.is_catchall())
.then_some(modules.page) .then_some(modules.page)
.flatten() .flatten()
......
...@@ -449,11 +449,13 @@ impl AppPath { ...@@ -449,11 +449,13 @@ impl AppPath {
} }
pub fn contains(&self, other: &AppPath) -> bool { pub fn contains(&self, other: &AppPath) -> bool {
// TODO: handle OptionalCatchAll properly.
for (i, segment) in other.0.iter().enumerate() { for (i, segment) in other.0.iter().enumerate() {
let Some(self_segment) = self.0.get(i) else { let Some(self_segment) = self.0.get(i) else {
// other is longer than self // other is longer than self. An optional catch-all as the
return false; // extra trailing segment can match zero URL segments, so
// it's still contained.
return matches!(segment, PathSegment::OptionalCatchAll(_))
&& i == other.0.len() - 1;
}; };
if self_segment == segment { if self_segment == segment {
......
...@@ -1145,5 +1145,6 @@ ...@@ -1145,5 +1145,6 @@
"1144": "Prefetch inlining is enabled but no hints were found for route \"%s\". This is a bug in the Next.js build pipeline — prefetch-hints.json should contain an entry for every route that produces segment data.", "1144": "Prefetch inlining is enabled but no hints were found for route \"%s\". This is a bug in the Next.js build pipeline — prefetch-hints.json should contain an entry for every route that produces segment data.",
"1145": "Internal Next.js Error: Prefetch inlining is enabled but no hints were found for route \"%s\". prefetch-hints.json should contain an entry for every route that produces segment data. This is a bug in Next.js.", "1145": "Internal Next.js Error: Prefetch inlining is enabled but no hints were found for route \"%s\". prefetch-hints.json should contain an entry for every route that produces segment data. This is a bug in Next.js.",
"1146": "Internal Next.js Error: Prefetch inlining is enabled but no hint tree was provided during incremental static revalidation. The prefetch-hints.json manifest should contain an entry for this route. This is a bug in Next.js.", "1146": "Internal Next.js Error: Prefetch inlining is enabled but no hint tree was provided during incremental static revalidation. The prefetch-hints.json manifest should contain an entry for this route. This is a bug in Next.js.",
"1147": "Turbopack database compaction is not supported on this platform" "1147": "Turbopack database compaction is not supported on this platform",
"1148": "Expected conflicting page \"%s\" to have both an app and pages file path but got app: %s, pages: %s"
} }
...@@ -606,7 +606,28 @@ async function createTreeCodeFromPath( ...@@ -606,7 +606,28 @@ async function createTreeCodeFromPath(
// This also handles route groups correctly by filtering them out. // This also handles route groups correctly by filtering them out.
const isLeafSegment = !hasChildRoutesForSegment(segmentPath) const isLeafSegment = !hasChildRoutesForSegment(segmentPath)
if (!isInsideCatchAll && !isLeafSegment) { // Check if the slot itself contains an optional catch-all route.
// An optional catch-all ([[...slug]]) matches all URL paths
// including the parent, so default.js is not required. A
// regular catch-all ([...slug]) still requires default.js
// because it doesn't match the parent path.
let slotHasOptionalCatchAll = false
const absoluteSlotPath = resolveDir(fullSegmentPath)
if (absoluteSlotPath && (await isDirectory(absoluteSlotPath))) {
const slotFiles = await fs.opendir(absoluteSlotPath)
for await (const dirent of slotFiles) {
if (dirent.isDirectory() && dirent.name.startsWith('[[...')) {
slotHasOptionalCatchAll = true
break
}
}
}
if (
!isInsideCatchAll &&
!isLeafSegment &&
!slotHasOptionalCatchAll
) {
// Replace internal webpack alias with user-facing directory name // Replace internal webpack alias with user-facing directory name
const userFacingPath = fullSegmentPath.replace( const userFacingPath = fullSegmentPath.replace(
APP_DIR_ALIAS, APP_DIR_ALIAS,
......
...@@ -7,6 +7,7 @@ import type { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/midd ...@@ -7,6 +7,7 @@ import type { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/midd
import type { PropagateToWorkersField } from './types' import type { PropagateToWorkersField } from './types'
import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types' import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types'
import { InvariantError } from '../../../shared/lib/invariant-error'
import { createDefineEnv } from '../../../build/swc' import { createDefineEnv } from '../../../build/swc'
import { installBindings } from '../../../build/swc/install-bindings' import { installBindings } from '../../../build/swc/install-bindings'
import fs from 'fs' import fs from 'fs'
...@@ -96,6 +97,7 @@ import { ...@@ -96,6 +97,7 @@ import {
} from '../../../build/file-classifier' } from '../../../build/file-classifier'
import { import {
normalizeAppPath, normalizeAppPath,
normalizeAppPathWithSlots,
compareAppPaths, compareAppPaths,
} from '../../../shared/lib/router/utils/app-paths' } from '../../../shared/lib/router/utils/app-paths'
import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash' import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash'
...@@ -418,6 +420,7 @@ async function startWatcher( ...@@ -418,6 +420,7 @@ async function startWatcher(
let initialWatchTime = performance.now() + performance.timeOrigin let initialWatchTime = performance.now() + performance.timeOrigin
wp.on('aggregated', async () => { wp.on('aggregated', async () => {
console.log('[DEBUG] aggregated callback started')
let writeEnvDefinitions = false let writeEnvDefinitions = false
let typescriptStatusFromLastAggregation = enabledTypeScript let typescriptStatusFromLastAggregation = enabledTypeScript
let middlewareMatchers: ProxyMatcher[] | undefined let middlewareMatchers: ProxyMatcher[] | undefined
...@@ -643,6 +646,8 @@ async function startWatcher( ...@@ -643,6 +646,8 @@ async function startWatcher(
continue continue
} }
let routedPageName = pageName
if (isAppPath) { if (isAppPath) {
// Track root not-found // Track root not-found
if (validFileMatcher.isRootNotFound(fileName)) { if (validFileMatcher.isRootNotFound(fileName)) {
...@@ -706,7 +711,35 @@ async function startWatcher( ...@@ -706,7 +711,35 @@ async function startWatcher(
appRoutes.push(routeEntry) appRoutes.push(routeEntry)
} }
if (routedPages.includes(pageName)) continue routedPageName = normalizeAppPathWithSlots(originalPageName).replace(
/%5F/g,
'_'
)
console.log('[DEBUG] app route:', {
pageName,
routedPageName,
originalPageName,
})
if (routedPages.includes(routedPageName)) {
console.log(
'[DEBUG] skipping duplicate routedPageName:',
routedPageName
)
continue
}
// If this normalized pageName was already processed from another
// parallel slot, skip the rest of the loop (which includes
// conflict detection) but still add the slot-preserving name
// to routedPages for route sorting.
if (appPageFilePaths.has(pageName)) {
console.log('[DEBUG] skipping already-processed slot route:', {
pageName,
routedPageName,
})
routedPages.push(routedPageName)
continue
}
} else { } else {
// Pages router // Pages router
if (useFileSystemPublicRoutes) { if (useFileSystemPublicRoutes) {
...@@ -745,8 +778,9 @@ async function startWatcher( ...@@ -745,8 +778,9 @@ async function startWatcher(
continue continue
} }
routedPages.push(pageName) routedPages.push(routedPageName)
} }
console.log('[DEBUG] loop done, routedPages:', routedPages)
const numConflicting = conflictingAppPagePaths.size const numConflicting = conflictingAppPagePaths.size
conflictingPageChange = numConflicting - previousConflictingPagePaths.size conflictingPageChange = numConflicting - previousConflictingPagePaths.size
...@@ -758,8 +792,15 @@ async function startWatcher( ...@@ -758,8 +792,15 @@ async function startWatcher(
} found, please remove the conflicting files to continue:\n` } found, please remove the conflicting files to continue:\n`
for (const p of conflictingAppPagePaths) { for (const p of conflictingAppPagePaths) {
const appPath = path.relative(dir, appPageFilePaths.get(p)!) const appFile = appPageFilePaths.get(p)
const pagesPath = path.relative(dir, pagesPageFilePaths.get(p)!) const pagesFile = pagesPageFilePaths.get(p)
if (typeof appFile !== 'string' || typeof pagesFile !== 'string') {
throw new InvariantError(
`Expected conflicting page "${p}" to have both an app and pages file path but got app: ${appFile}, pages: ${pagesFile}`
)
}
const appPath = path.relative(dir, appFile)
const pagesPath = path.relative(dir, pagesFile)
errorMessage += ` "${pagesPath}" - "${appPath}"\n` errorMessage += ` "${pagesPath}" - "${appPath}"\n`
} }
hotReloader.setHmrServerError(new Error(errorMessage)) hotReloader.setHmrServerError(new Error(errorMessage))
...@@ -1028,8 +1069,23 @@ async function startWatcher( ...@@ -1028,8 +1069,23 @@ async function startWatcher(
try { try {
// we serve a separate manifest with all pages for the client in // we serve a separate manifest with all pages for the client in
// dev mode so that we can match a page after a rewrite on the client // dev mode so that we can match a page after a rewrite on the client
// before it has been built and is populated in the _buildManifest // before it has been built and is populated in the _buildManifest.
const sortedRoutes = getSortedRoutes(routedPages) // routedPages includes @slot segments so getSortedRoutes can
// validate and sort routes per slot independently. The output
// has @slot segments stripped. Deduplicate in case multiple
// slots produce the same URL path.
console.log('[DEBUG] routedPages:', routedPages)
const sortedRoutesWithDups = getSortedRoutes(routedPages)
console.log('[DEBUG] sortedRoutesWithDups:', sortedRoutesWithDups)
const sortedRoutes: string[] = []
const seen = new Set<string>()
for (const route of sortedRoutesWithDups) {
if (!seen.has(route)) {
seen.add(route)
sortedRoutes.push(route)
}
}
console.log('[DEBUG] sortedRoutes:', sortedRoutes)
opts.fsChecker.dynamicRoutes = sortedRoutes.map( opts.fsChecker.dynamicRoutes = sortedRoutes.map(
(page): FilesystemDynamicRoute => { (page): FilesystemDynamicRoute => {
......
...@@ -51,6 +51,35 @@ export function normalizeAppPath(route: string) { ...@@ -51,6 +51,35 @@ export function normalizeAppPath(route: string) {
) )
} }
/**
* Like `normalizeAppPath` but keeps parallel slot segments (`@slot`).
* Used for route conflict detection where `@slot` segments separate
* routes into independent parallel slots that can't conflict with
* each other.
*/
export function normalizeAppPathWithSlots(route: string) {
return ensureLeadingSlash(
route.split('/').reduce((pathname, segment, index, segments) => {
if (!segment) {
return pathname
}
if (isGroupSegment(segment)) {
return pathname
}
if (
(segment === 'page' || segment === 'route') &&
index === segments.length - 1
) {
return pathname
}
return `${pathname}/${segment}`
}, '')
)
}
/** /**
* Comparator for sorting app paths so that parallel slot paths (containing * Comparator for sorting app paths so that parallel slot paths (containing
* `/@`) come before the children/root page path. This ensures the last item * `/@`) come before the children/root page path. This ensures the last item
......
...@@ -5,8 +5,11 @@ class UrlNode { ...@@ -5,8 +5,11 @@ class UrlNode {
restSlugName: string | null = null restSlugName: string | null = null
optionalRestSlugName: string | null = null optionalRestSlugName: string | null = null
private placeholderSlot: string | null = null
private optionalRestSlugSlot: string | null = null
insert(urlPath: string): void { insert(urlPath: string): void {
this._insert(urlPath.split('/').filter(Boolean), [], false) this._insert(urlPath.split('/').filter(Boolean), [], false, null)
} }
smoosh(): string[] { smoosh(): string[] {
...@@ -37,7 +40,10 @@ class UrlNode { ...@@ -37,7 +40,10 @@ class UrlNode {
if (!this.placeholder) { if (!this.placeholder) {
const r = prefix === '/' ? '/' : prefix.slice(0, -1) const r = prefix === '/' ? '/' : prefix.slice(0, -1)
if (this.optionalRestSlugName != null) { if (
this.optionalRestSlugName != null &&
this.placeholderSlot === this.optionalRestSlugSlot
) {
throw new Error( throw new Error(
`You cannot define a route with the same specificity as a optional catch-all route ("${r}" and "${r}[[...${this.optionalRestSlugName}]]").` `You cannot define a route with the same specificity as a optional catch-all route ("${r}" and "${r}[[...${this.optionalRestSlugName}]]").`
) )
...@@ -68,10 +74,26 @@ class UrlNode { ...@@ -68,10 +74,26 @@ class UrlNode {
private _insert( private _insert(
urlPaths: string[], urlPaths: string[],
slugNames: string[], slugNames: string[],
isCatchAll: boolean isCatchAll: boolean,
slot: string | null
): void { ): void {
if (urlPaths.length === 0) { if (urlPaths.length === 0) {
this.placeholder = false this.placeholder = false
this.placeholderSlot = slot
return
}
// The next segment in the urlPaths list
let nextSegment = urlPaths[0]
// Parallel slot segments (@slot) are transparent — skip them
// without creating a trie node. The slot name is tracked as
// metadata so validation only flags conflicts within the same slot.
// This must come before the isCatchAll check because @slot segments
// can appear after a catchall (e.g., /[...slug]/@header).
if (nextSegment.startsWith('@')) {
const nestedSlot = slot ? `${slot}/${nextSegment}` : nextSegment
this._insert(urlPaths.slice(1), slugNames, isCatchAll, nestedSlot)
return return
} }
...@@ -79,9 +101,6 @@ class UrlNode { ...@@ -79,9 +101,6 @@ class UrlNode {
throw new Error(`Catch-all must be the last part of the URL.`) throw new Error(`Catch-all must be the last part of the URL.`)
} }
// The next segment in the urlPaths list
let nextSegment = urlPaths[0]
// Check if the segment matches `[something]` // Check if the segment matches `[something]`
if (nextSegment.startsWith('[') && nextSegment.endsWith(']')) { if (nextSegment.startsWith('[') && nextSegment.endsWith(']')) {
// Strip `[` and `]`, leaving only `something` // Strip `[` and `]`, leaving only `something`
...@@ -161,6 +180,7 @@ class UrlNode { ...@@ -161,6 +180,7 @@ class UrlNode {
handleSlug(this.optionalRestSlugName, segmentName) handleSlug(this.optionalRestSlugName, segmentName)
// slugName is kept as it can only be one particular slugName // slugName is kept as it can only be one particular slugName
this.optionalRestSlugName = segmentName this.optionalRestSlugName = segmentName
this.optionalRestSlugSlot = slot
// nextSegment is overwritten to [[...]] so that it can later be sorted specifically // nextSegment is overwritten to [[...]] so that it can later be sorted specifically
nextSegment = '[[...]]' nextSegment = '[[...]]'
} else { } else {
...@@ -197,7 +217,7 @@ class UrlNode { ...@@ -197,7 +217,7 @@ class UrlNode {
this.children this.children
.get(nextSegment)! .get(nextSegment)!
._insert(urlPaths.slice(1), slugNames, isCatchAll) ._insert(urlPaths.slice(1), slugNames, isCatchAll, slot)
} }
} }
......
export default function Page() {
return (
<div>
<h2>Slot With Optional Catchall Page</h2>
<p>
The @breadcrumbs slot uses [[...catchall]] which matches all routes
including the root. No default.tsx should be required.
</p>
</div>
)
}
export default function Page() {
return (
<div>
<h2>Root Page</h2>
</div>
)
}
...@@ -69,13 +69,6 @@ describe('parallel-routes-leaf-segments-no-build-error', () => { ...@@ -69,13 +69,6 @@ describe('parallel-routes-leaf-segments-no-build-error', () => {
describe('parallel slot with optional catchall', () => { describe('parallel slot with optional catchall', () => {
it('should not require default.tsx when slot contains [[...catchall]]', async () => { it('should not require default.tsx when slot contains [[...catchall]]', async () => {
const $ = await next.render$('/slot-with-optional-catchall')
expect($('h2').text()).toBe('Slot With Optional Catchall Page')
expect($('.breadcrumbs-content h3').text()).toBe('Breadcrumbs')
})
it('should render the optional catchall slot for nested routes', async () => {
const $ = await next.render$('/slot-with-optional-catchall/nested') const $ = await next.render$('/slot-with-optional-catchall/nested')
expect($('h2').text()).toBe('Nested Page') expect($('h2').text()).toBe('Nested Page')
......
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