Unverified Commit 6b766f9c authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Brand internal page identifiers and route pathnames

Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 9ec56531
import { pageToRoute } from '../utils' import { pageToRoute } from '../utils'
import { collectFallbackShellRuns } from './fallback-shell-runs' import { collectFallbackShellRuns } from './fallback-shell-runs'
import type { RoutesManifest } from '..' import type { RoutesManifest } from '..'
import type { Route } from '../../shared/lib/route-types'
// The suites in `test/production/app-dir/adapter-dynamic-routes` cover the // The suites in `test/production/app-dir/adapter-dynamic-routes` cover the
// shapes that a build produces, and they pin the entries that come out of them. // shapes that a build produces, and they pin the entries that come out of them.
...@@ -13,17 +14,17 @@ import type { RoutesManifest } from '..' ...@@ -13,17 +14,17 @@ import type { RoutesManifest } from '..'
// shape of a result. // shape of a result.
/** /**
* A fallback shell, which the build derives from a source page. * A fallback shell, which the build derives from a normalized source URL pattern.
*/ */
function shell(page: string, sourcePage: string) { function shell(page: string, sourcePage: string) {
return pageToRoute(page, sourcePage) return pageToRoute(page as Route, sourcePage as Route)
} }
/** /**
* Any other dynamic route, which carries no source page. * Any other dynamic route, which carries no source page.
*/ */
function plain(page: string) { function plain(page: string) {
return pageToRoute(page, undefined) return pageToRoute(page as Route, undefined)
} }
function collect( function collect(
......
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
* place relative to the routes around it. * place relative to the routes around it.
*/ */
import type { Route } from '../../shared/lib/route-types'
import type { RoutesManifest } from '..' import type { RoutesManifest } from '..'
import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { escapeStringRegexp } from '../../shared/lib/escape-regexp' import { escapeStringRegexp } from '../../shared/lib/escape-regexp'
...@@ -37,12 +38,12 @@ export type FallbackShellRuns = { ...@@ -37,12 +38,12 @@ export type FallbackShellRuns = {
/** /**
* The runs, keyed by the page of the representative of each. * The runs, keyed by the page of the representative of each.
*/ */
byRepresentativePage: Map<string, FallbackShellRun> byRepresentativePage: Map<Route, FallbackShellRun>
/** /**
* The pages of the shells that a run serves, apart from the representative * The pages of the shells that a run serves, apart from the representative
* that keys it. The caller emits no entry of its own for these. * that keys it. The caller emits no entry of its own for these.
*/ */
replacedPages: Set<string> replacedPages: Set<Route>
} }
/** /**
...@@ -53,7 +54,7 @@ type PendingRun = { ...@@ -53,7 +54,7 @@ type PendingRun = {
/** /**
* The source page that every shell of the run repeats. * The source page that every shell of the run repeats.
*/ */
sourcePage: string sourcePage: Route
/** /**
* The path that every shell of the run has after its prefix. * The path that every shell of the run has after its prefix.
*/ */
...@@ -70,7 +71,7 @@ type PendingRun = { ...@@ -70,7 +71,7 @@ type PendingRun = {
/** /**
* The page of the shell. * The page of the shell.
*/ */
page: string page: Route
/** /**
* The leading part of that page, which holds the values that the shell * The leading part of that page, which holds the values that the shell
* resolves for the params of the source page. * resolves for the params of the source page.
...@@ -87,8 +88,8 @@ type PendingRun = { ...@@ -87,8 +88,8 @@ type PendingRun = {
* segments are not consecutive from the first segment onwards. * segments are not consecutive from the first segment onwards.
*/ */
function splitShellPage( function splitShellPage(
page: string, page: Route,
sourcePage: string sourcePage: Route
): { prefix: string; tail: string } | undefined { ): { prefix: string; tail: string } | undefined {
const pageSegments = page.split('/') const pageSegments = page.split('/')
const sourceSegments = sourcePage.split('/') const sourceSegments = sourcePage.split('/')
...@@ -177,7 +178,7 @@ function splitShellPage( ...@@ -177,7 +178,7 @@ function splitShellPage(
*/ */
export function collectFallbackShellRuns( export function collectFallbackShellRuns(
dynamicRoutes: RoutesManifest['dynamicRoutes'], dynamicRoutes: RoutesManifest['dynamicRoutes'],
hasFallbackFalse: (page: string) => boolean hasFallbackFalse: (page: Route) => boolean
): FallbackShellRuns { ): FallbackShellRuns {
const runs: PendingRun[] = [] const runs: PendingRun[] = []
let current: PendingRun | undefined let current: PendingRun | undefined
...@@ -224,8 +225,8 @@ export function collectFallbackShellRuns( ...@@ -224,8 +225,8 @@ export function collectFallbackShellRuns(
current.shells.push({ page: route.page, prefix: split.prefix }) current.shells.push({ page: route.page, prefix: split.prefix })
} }
const byRepresentativePage = new Map<string, FallbackShellRun>() const byRepresentativePage = new Map<Route, FallbackShellRun>()
const replacedPages = new Set<string>() const replacedPages = new Set<Route>()
for (const run of runs) { for (const run of runs) {
if (run.shells.length < 2) { if (run.shells.length < 2) {
......
import type { Page } from '../../shared/lib/route-types'
import type { NextConfig } from '../../server/config-shared' import type { NextConfig } from '../../server/config-shared'
import type { RouteHas } from '../../lib/load-custom-routes' import type { RouteHas } from '../../lib/load-custom-routes'
...@@ -174,7 +175,7 @@ export function getRSCModuleInformation( ...@@ -174,7 +175,7 @@ export function getRSCModuleInformation(
function checkExports( function checkExports(
ast: any, ast: any,
expectedExports: string[], expectedExports: string[],
page: string page: Page
): { ): {
getStaticProps?: boolean getStaticProps?: boolean
getServerSideProps?: boolean getServerSideProps?: boolean
...@@ -342,7 +343,7 @@ function validateMiddlewareProxyExports({ ...@@ -342,7 +343,7 @@ function validateMiddlewareProxyExports({
isDev, isDev,
}: { }: {
ast: any ast: any
page: string page: Page
pageFilePath: string pageFilePath: string
isDev: boolean isDev: boolean
}): void { }): void {
...@@ -536,7 +537,7 @@ export function getMiddlewareMatchers( ...@@ -536,7 +537,7 @@ export function getMiddlewareMatchers(
} }
function parseMiddlewareConfig( function parseMiddlewareConfig(
page: string, page: Page,
rawConfig: unknown, rawConfig: unknown,
nextConfig: NextConfig nextConfig: NextConfig
): ProxyConfig { ): ProxyConfig {
...@@ -575,7 +576,7 @@ function parseMiddlewareConfig( ...@@ -575,7 +576,7 @@ function parseMiddlewareConfig(
} }
const apiRouteWarnings = new LRUCache(250) const apiRouteWarnings = new LRUCache(250)
function warnAboutExperimentalEdge(apiRoute: string | null) { function warnAboutExperimentalEdge(apiRoute: Page | null) {
if ( if (
process.env.NODE_ENV === 'production' && process.env.NODE_ENV === 'production' &&
process.env.NEXT_PRIVATE_BUILD_WORKER === '1' process.env.NEXT_PRIVATE_BUILD_WORKER === '1'
...@@ -603,7 +604,7 @@ const warnedUnsupportedValueMap = new LRUCache<boolean>(250, () => 1) ...@@ -603,7 +604,7 @@ const warnedUnsupportedValueMap = new LRUCache<boolean>(250, () => 1)
function warnAboutUnsupportedValue( function warnAboutUnsupportedValue(
pageFilePath: string, pageFilePath: string,
page: string | undefined, page: Page | undefined,
result: { unsupported: string; path?: string } result: { unsupported: string; path?: string }
) { ) {
hadUnsupportedValue = true hadUnsupportedValue = true
...@@ -641,7 +642,7 @@ type GetPageStaticInfoParams = { ...@@ -641,7 +642,7 @@ type GetPageStaticInfoParams = {
pageFilePath: string pageFilePath: string
nextConfig: Partial<NextConfig> nextConfig: Partial<NextConfig>
isDev: boolean isDev: boolean
page: string page: Page
pageType: PAGE_TYPES pageType: PAGE_TYPES
} }
......
import type { Route } from '../../shared/lib/route-types'
import { readFileSync, writeSync } from 'node:fs' import { readFileSync, writeSync } from 'node:fs'
import { join, resolve, sep } from 'node:path' import { join, resolve, sep } from 'node:path'
...@@ -145,7 +146,7 @@ function sourcePaths(sources: Source[]): string[] { ...@@ -145,7 +146,7 @@ function sourcePaths(sources: Source[]): string[] {
return sources.map((_, i) => path(i)) return sources.map((_, i) => path(i))
} }
function routeFile(directory: string, route: string): string { function routeFile(directory: string, route: Route): string {
if ( if (
!route.startsWith('/') || !route.startsWith('/') ||
route.includes('\\') || route.includes('\\') ||
...@@ -333,9 +334,11 @@ export function dumpAnalyzeGraph( ...@@ -333,9 +334,11 @@ export function dumpAnalyzeGraph(
// @ts-ignore Node's internal handle, also used by the native bindings loader. // @ts-ignore Node's internal handle, also used by the native bindings loader.
process.stdout._handle.setBlocking?.(true) process.stdout._handle.setBlocking?.(true)
} }
// Native serialized collectRoutesForAnalyze URL patterns; existing guards
// remain unchanged. The public CLI filter is only a string equality probe.
const routes = JSON.parse( const routes = JSON.parse(
readFileSync(join(directory, 'routes.json'), 'utf8') readFileSync(join(directory, 'routes.json'), 'utf8')
) as string[] ) as Route[]
if ( if (
!Array.isArray(routes) || !Array.isArray(routes) ||
routes.some((route) => typeof route !== 'string') routes.some((route) => typeof route !== 'string')
......
import type { Page, Route } from '../../shared/lib/route-types'
import type { NextConfigComplete } from '../../server/config-shared' import type { NextConfigComplete } from '../../server/config-shared'
import type { __ApiPreviewProps } from '../../server/api-utils' import type { __ApiPreviewProps } from '../../server/api-utils'
...@@ -172,7 +173,7 @@ async function collectRoutesForAnalyze( ...@@ -172,7 +173,7 @@ async function collectRoutesForAnalyze(
dir: string, dir: string,
config: NextConfigComplete, config: NextConfigComplete,
appDirOnly: boolean appDirOnly: boolean
): Promise<string[]> { ): Promise<Route[]> {
const { pagesDir, appDir } = findPagesDir(dir) const { pagesDir, appDir } = findPagesDir(dir)
let appType: RoutesManifest['appType'] let appType: RoutesManifest['appType']
...@@ -197,9 +198,10 @@ async function collectRoutesForAnalyze( ...@@ -197,9 +198,10 @@ async function collectRoutesForAnalyze(
}) })
const pageKeys = { const pageKeys = {
pages: Object.keys(discovery.mappedPages || {}), // Discovered Pages keys are URL patterns in the Pages module namespace.
pages: Object.keys(discovery.mappedPages || {}) as Route[],
app: discovery.mappedAppPages app: discovery.mappedAppPages
? Object.keys(discovery.mappedAppPages).map((key) => ? (Object.keys(discovery.mappedAppPages) as Page[]).map((key) =>
normalizeAppPath(key) normalizeAppPath(key)
) )
: [], : [],
......
import type { Page } from '../shared/lib/route-types'
import type { LoadedEnvFiles } from '@next/env' import type { LoadedEnvFiles } from '@next/env'
import type { Rewrite } from '../lib/load-custom-routes' import type { Rewrite } from '../lib/load-custom-routes'
import type { __ApiPreviewProps } from '../server/api-utils' import type { __ApiPreviewProps } from '../server/api-utils'
...@@ -40,9 +41,7 @@ export function getPluginState() { ...@@ -40,9 +41,7 @@ export function getPluginState() {
return pluginState return pluginState
} }
export interface MappedPages { export type MappedPages = Record<Page, string>
[page: string]: string
}
// a global object to store context for the current build // a global object to store context for the current build
// this is used to pass data between different steps of the build without having // this is used to pass data between different steps of the build without having
......
import type { Page, Route } from '../shared/lib/route-types'
import type { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader' import type { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader'
import type { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader' import type { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader'
import type { EdgeSSRLoaderQuery } from './webpack/loaders/next-edge-ssr-loader' import type { EdgeSSRLoaderQuery } from './webpack/loaders/next-edge-ssr-loader'
...@@ -126,6 +127,8 @@ export interface CreateEntrypointsParams { ...@@ -126,6 +127,8 @@ export interface CreateEntrypointsParams {
* @param deferredEntries - Array of path patterns to match against * @param deferredEntries - Array of path patterns to match against
* @returns true if the page matches a deferred entry pattern * @returns true if the page matches a deferred entry pattern
*/ */
// Pattern matching also receives filesystem-derived paths (with extensions)
// during dev entry disposal. It does not require a module Page or URL Route.
export function isDeferredEntry( export function isDeferredEntry(
page: string, page: string,
deferredEntries: string[] | undefined deferredEntries: string[] | undefined
...@@ -163,7 +166,7 @@ export function getEdgeServerEntry(opts: { ...@@ -163,7 +166,7 @@ export function getEdgeServerEntry(opts: {
config: NextConfigComplete config: NextConfigComplete
isDev: boolean isDev: boolean
isServerComponent: boolean isServerComponent: boolean
page: string page: Page
pages: MappedPages pages: MappedPages
middleware?: Partial<ProxyConfig> middleware?: Partial<ProxyConfig>
pagesType: PAGE_TYPES pagesType: PAGE_TYPES
...@@ -238,10 +241,10 @@ export function getEdgeServerEntry(opts: { ...@@ -238,10 +241,10 @@ export function getEdgeServerEntry(opts: {
} }
const loaderParams: EdgeSSRLoaderQuery = { const loaderParams: EdgeSSRLoaderQuery = {
absolute500Path: opts.pages['/500'] || '', absolute500Path: opts.pages['/500' as Page] || '',
absoluteAppPath: opts.pages['/_app'], absoluteAppPath: opts.pages['/_app' as Page],
absoluteDocumentPath: opts.pages['/_document'], absoluteDocumentPath: opts.pages['/_document' as Page],
absoluteErrorPath: opts.pages['/_error'], absoluteErrorPath: opts.pages['/_error' as Page],
absolutePagePath: opts.absolutePagePath, absolutePagePath: opts.absolutePagePath,
dev: opts.isDev, dev: opts.isDev,
isServerComponent: opts.isServerComponent, isServerComponent: opts.isServerComponent,
...@@ -300,13 +303,12 @@ export function getAppEntry(opts: Readonly<AppLoaderOptions>) { ...@@ -300,13 +303,12 @@ export function getAppEntry(opts: Readonly<AppLoaderOptions>) {
} }
} }
export function getClientEntry(opts: { export function getClientEntry(opts: { absolutePagePath: string; page: Page }) {
absolutePagePath: string
page: string
}) {
const loaderOptions: ClientPagesLoaderOptions = { const loaderOptions: ClientPagesLoaderOptions = {
absolutePagePath: opts.absolutePagePath, absolutePagePath: opts.absolutePagePath,
page: opts.page, // Pages-router discovery keys share the client URL namespace; raw module
// definition.page instead uses normalizePagePath's file encoding.
page: opts.page as unknown as Route,
} }
const pageLoader = `next-client-pages-loader?${stringify(loaderOptions)}!` const pageLoader = `next-client-pages-loader?${stringify(loaderOptions)}!`
...@@ -323,7 +325,7 @@ export function runDependingOnPageType<T>(params: { ...@@ -323,7 +325,7 @@ export function runDependingOnPageType<T>(params: {
onClient: () => T onClient: () => T
onEdgeServer: () => T onEdgeServer: () => T
onServer: () => T onServer: () => T
page: string page: Page
pageRuntime: ServerRuntime pageRuntime: ServerRuntime
pageType?: PAGE_TYPES pageType?: PAGE_TYPES
}): void { }): void {
...@@ -415,12 +417,12 @@ export async function createEntrypoints( ...@@ -415,12 +417,12 @@ export async function createEntrypoints(
const entrySourceDirectories = new Set<string>() const entrySourceDirectories = new Set<string>()
let middlewareMatchers: ProxyMatcher[] | undefined = undefined let middlewareMatchers: ProxyMatcher[] | undefined = undefined
let appPathsPerRoute: Record<string, string[]> = {} let appPathsPerRoute: Record<Route, Page[]> = {}
if (appDir && appPaths) { if (appDir && appPaths) {
const appPageFiles = new Map<string, string>() const appPageFiles = new Map<Page, string>()
for (const pathname in appPaths) { for (const pathname in appPaths) {
const normalizedPath = normalizeAppPath(pathname) const normalizedPath = normalizeAppPath(pathname as Page)
const actualPath = appPaths[pathname] const actualPath = appPaths[pathname as Page]
if (!appPathsPerRoute[normalizedPath]) { if (!appPathsPerRoute[normalizedPath]) {
appPathsPerRoute[normalizedPath] = [] appPathsPerRoute[normalizedPath] = []
} }
...@@ -428,7 +430,7 @@ export async function createEntrypoints( ...@@ -428,7 +430,7 @@ export async function createEntrypoints(
const appPath = getPageFromPath(actualPath, pageExtensions).replace( const appPath = getPageFromPath(actualPath, pageExtensions).replace(
APP_DIR_ALIAS, APP_DIR_ALIAS,
'' ''
) ) as Page
appPathsPerRoute[normalizedPath].push(appPath) appPathsPerRoute[normalizedPath].push(appPath)
appPageFiles.set(appPath, actualPath) appPageFiles.set(appPath, actualPath)
} }
...@@ -437,7 +439,7 @@ export async function createEntrypoints( ...@@ -437,7 +439,7 @@ export async function createEntrypoints(
const { unmatchedAppPages, incompatibleParallelRouteSlots } = const { unmatchedAppPages, incompatibleParallelRouteSlots } =
normalizeCatchAllRoutes(appPathsPerRoute, { normalizeCatchAllRoutes(appPathsPerRoute, {
strictRouteMatching: config.experimental.strictRouteMatching, strictRouteMatching: config.experimental.strictRouteMatching,
defaultAppPaths: Object.keys(appDefaultPaths ?? {}), defaultAppPaths: Object.keys(appDefaultPaths ?? {}) as Page[],
}) })
// Only App Router pages can make an intercepted URL directly renderable. // Only App Router pages can make an intercepted URL directly renderable.
// Route handlers and metadata routes may share the pathname, but they // Route handlers and metadata routes may share the pathname, but they
...@@ -447,7 +449,7 @@ export async function createEntrypoints( ...@@ -447,7 +449,7 @@ export async function createEntrypoints(
const pageAppPaths = routeAppPaths.filter(isAppPageRoute) const pageAppPaths = routeAppPaths.filter(isAppPageRoute)
return pageAppPaths.length > 0 ? [[route, pageAppPaths]] : [] return pageAppPaths.length > 0 ? [[route, pageAppPaths]] : []
}) })
) ) as Record<Route, Page[]>
const missingCanonicalInterceptionRoutes = config.experimental const missingCanonicalInterceptionRoutes = config.experimental
.strictRouteMatching .strictRouteMatching
? findMissingCanonicalInterceptionRoutes(appPagePathsPerRoute) ? findMissingCanonicalInterceptionRoutes(appPagePathsPerRoute)
...@@ -468,7 +470,7 @@ export async function createEntrypoints( ...@@ -468,7 +470,7 @@ export async function createEntrypoints(
const layoutPagePath = posix.join( const layoutPagePath = posix.join(
incompatibleRoute.layoutPath, incompatibleRoute.layoutPath,
'layout' 'layout'
) ) as Page
const layoutFile = await findPageFile( const layoutFile = await findPageFile(
appDir, appDir,
layoutPagePath, layoutPagePath,
...@@ -531,11 +533,11 @@ export async function createEntrypoints( ...@@ -531,11 +533,11 @@ export async function createEntrypoints(
k, k,
v.sort(compareAppPaths), v.sort(compareAppPaths),
]) ])
) ) as Record<Route, Page[]>
} }
const getEntryHandler = const getEntryHandler =
(mappings: MappedPages, pagesType: PAGE_TYPES): ((page: string) => void) => (mappings: MappedPages, pagesType: PAGE_TYPES): ((page: Page) => void) =>
async (page) => { async (page) => {
if ( if (
pagesType === PAGE_TYPES.APP && pagesType === PAGE_TYPES.APP &&
...@@ -645,7 +647,7 @@ export async function createEntrypoints( ...@@ -645,7 +647,7 @@ export async function createEntrypoints(
pagePath: absolutePagePath, pagePath: absolutePagePath,
appDir, appDir,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
allNormalizedAppPaths: Object.keys(appPathsPerRoute), allNormalizedAppPaths: Object.keys(appPathsPerRoute) as Route[],
pageExtensions, pageExtensions,
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
...@@ -731,7 +733,7 @@ export async function createEntrypoints( ...@@ -731,7 +733,7 @@ export async function createEntrypoints(
pagePath: absolutePagePath, pagePath: absolutePagePath,
appDir: appDir!, appDir: appDir!,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
allNormalizedAppPaths: Object.keys(appPathsPerRoute), allNormalizedAppPaths: Object.keys(appPathsPerRoute) as Route[],
pageExtensions, pageExtensions,
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
...@@ -778,18 +780,24 @@ export async function createEntrypoints( ...@@ -778,18 +780,24 @@ export async function createEntrypoints(
if (appPaths) { if (appPaths) {
const entryHandler = getEntryHandler(appPaths, PAGE_TYPES.APP) const entryHandler = getEntryHandler(appPaths, PAGE_TYPES.APP)
promises.push(Promise.all(Object.keys(appPaths).map(entryHandler))) promises.push(
Promise.all((Object.keys(appPaths) as Page[]).map(entryHandler))
)
} }
if (rootPaths) { if (rootPaths) {
promises.push( promises.push(
Promise.all( Promise.all(
Object.keys(rootPaths).map(getEntryHandler(rootPaths, PAGE_TYPES.ROOT)) (Object.keys(rootPaths) as Page[]).map(
getEntryHandler(rootPaths, PAGE_TYPES.ROOT)
)
) )
) )
} }
promises.push( promises.push(
Promise.all( Promise.all(
Object.keys(pages).map(getEntryHandler(pages, PAGE_TYPES.PAGES)) (Object.keys(pages) as Page[]).map(
getEntryHandler(pages, PAGE_TYPES.PAGES)
)
) )
) )
......
import type { Page, Route } from '../shared/lib/route-types'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { isParallelRouteSegment } from '../shared/lib/segment' import { isParallelRouteSegment } from '../shared/lib/segment'
// Slot information for parallel routes // Slot information for parallel routes
export type SlotInfo = { name: string; parent: string } export type SlotInfo = { name: string; parent: Route }
// Route information for route manifests // Route information for route manifests
export type RouteInfo = { route: string; filePath: string } export type RouteInfo = { route: Route; filePath: string }
/** /**
* Extract slot info from a page path if it contains a parallel route * Extract slot info from a page path if it contains a parallel route
*/ */
export function extractSlotFromPath(pagePath: string): SlotInfo | undefined { export function extractSlotFromPath(pagePath: Page): SlotInfo | undefined {
const segments = pagePath.split('/') const segments = pagePath.split('/')
for (let i = segments.length - 1; i >= 0; i--) { for (let i = segments.length - 1; i >= 0; i--) {
const segment = segments[i] const segment = segments[i]
if (isParallelRouteSegment(segment)) { if (isParallelRouteSegment(segment)) {
return { return {
name: segment.slice(1), name: segment.slice(1),
parent: normalizeAppPath(segments.slice(0, i).join('/')), parent: normalizeAppPath(segments.slice(0, i).join('/') as Page),
} }
} }
} }
...@@ -27,7 +28,7 @@ export function extractSlotFromPath(pagePath: string): SlotInfo | undefined { ...@@ -27,7 +28,7 @@ export function extractSlotFromPath(pagePath: string): SlotInfo | undefined {
/** /**
* Add a slot to the slots array if it doesn't already exist * Add a slot to the slots array if it doesn't already exist
*/ */
export function addSlotIfNew(slots: SlotInfo[], pagePath: string): boolean { export function addSlotIfNew(slots: SlotInfo[], pagePath: Page): boolean {
const slot = extractSlotFromPath(pagePath) const slot = extractSlotFromPath(pagePath)
if (!slot) return false if (!slot) return false
if (slots.some((s) => s.name === slot.name && s.parent === slot.parent)) if (slots.some((s) => s.name === slot.name && s.parent === slot.parent))
...@@ -40,11 +41,11 @@ export function addSlotIfNew(slots: SlotInfo[], pagePath: string): boolean { ...@@ -40,11 +41,11 @@ export function addSlotIfNew(slots: SlotInfo[], pagePath: string): boolean {
* Extract slots from a route mapping object * Extract slots from a route mapping object
*/ */
export function extractSlotsFromRoutes( export function extractSlotsFromRoutes(
routes: { [page: string]: string }, routes: Record<Page, string>,
skipRoutes?: Set<string> skipRoutes?: Set<Page>
): SlotInfo[] { ): SlotInfo[] {
const slots: SlotInfo[] = [] const slots: SlotInfo[] = []
for (const [route] of Object.entries(routes)) { for (const [route] of Object.entries(routes) as [Page, string][]) {
if (skipRoutes?.has(route)) continue if (skipRoutes?.has(route)) continue
addSlotIfNew(slots, route) addSlotIfNew(slots, route)
} }
......
import type { Route } from '../shared/lib/route-types'
import type { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
import type { CustomRoutes } from '../lib/load-custom-routes' import type { CustomRoutes } from '../lib/load-custom-routes'
import { import {
...@@ -25,8 +26,8 @@ import { sortPages } from '../shared/lib/router/utils/sortable-routes' ...@@ -25,8 +26,8 @@ import { sortPages } from '../shared/lib/router/utils/sortable-routes'
export interface GenerateRoutesManifestOptions { export interface GenerateRoutesManifestOptions {
pageKeys: { pageKeys: {
pages: string[] pages: Route[]
app?: string[] app?: Route[]
} }
config: NextConfigComplete config: NextConfigComplete
redirects: CustomRoutes['redirects'] redirects: CustomRoutes['redirects']
...@@ -42,7 +43,7 @@ export interface GenerateRoutesManifestOptions { ...@@ -42,7 +43,7 @@ export interface GenerateRoutesManifestOptions {
export interface GenerateRoutesManifestResult { export interface GenerateRoutesManifestResult {
routesManifest: RoutesManifest routesManifest: RoutesManifest
dynamicRoutes: Array<DynamicManifestRoute> dynamicRoutes: Array<DynamicManifestRoute>
sourcePages: Map<string, string> sourcePages: Map<Route, Route>
} }
/** /**
...@@ -71,10 +72,11 @@ export function generateRoutesManifest( ...@@ -71,10 +72,11 @@ export function generateRoutesManifest(
const dynamicRoutes: Array<DynamicManifestRoute> = [] const dynamicRoutes: Array<DynamicManifestRoute> = []
/** /**
* A map of all the pages to their sourcePage value. This is only used for * A map of URL route patterns to their normalized source URL route pattern.
* This is only used for
* routes that have PPR enabled and clientSegmentEnabled is true. * routes that have PPR enabled and clientSegmentEnabled is true.
*/ */
const sourcePages = new Map<string, string>() const sourcePages = new Map<Route, Route>()
for (const route of sortedRoutes) { for (const route of sortedRoutes) {
if (isDynamicRoute(route)) { if (isDynamicRoute(route)) {
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
getPageStaticInfo, getPageStaticInfo,
} from './analysis/get-page-static-info' } from './analysis/get-page-static-info'
import type { PageExtensions } from './page-extensions-type' import type { PageExtensions } from './page-extensions-type'
import type { Page } from '../shared/lib/route-types'
import { PAGE_TYPES } from '../lib/page-types' import { PAGE_TYPES } from '../lib/page-types'
import { isAppPageRoute } from '../lib/is-app-page-route' import { isAppPageRoute } from '../lib/is-app-page-route'
...@@ -30,7 +31,7 @@ export async function getStaticInfoIncludingLayouts({ ...@@ -30,7 +31,7 @@ export async function getStaticInfoIncludingLayouts({
appDir: string | undefined appDir: string | undefined
config: NextConfigComplete config: NextConfigComplete
isDev: boolean isDev: boolean
page: string page: Page
}): Promise<Omit<PageStaticInfo, 'config'>> { }): Promise<Omit<PageStaticInfo, 'config'>> {
// TODO: sync types for pages: PAGE_TYPES, ROUTER_TYPE, 'app' | 'pages', etc. // TODO: sync types for pages: PAGE_TYPES, ROUTER_TYPE, 'app' | 'pages', etc.
const pageType = isInsideAppDir ? PAGE_TYPES.APP : PAGE_TYPES.PAGES const pageType = isInsideAppDir ? PAGE_TYPES.APP : PAGE_TYPES.PAGES
......
import type { Page } from '../shared/lib/route-types'
import type { TurbopackManifestLoader } from '../shared/lib/turbopack/manifest-loader' import type { TurbopackManifestLoader } from '../shared/lib/turbopack/manifest-loader'
import type { import type {
Entrypoints, Entrypoints,
...@@ -11,14 +12,16 @@ import * as Log from './output/log' ...@@ -11,14 +12,16 @@ import * as Log from './output/log'
export async function rawEntrypointsToEntrypoints( export async function rawEntrypointsToEntrypoints(
entrypointsOp: RawEntrypoints entrypointsOp: RawEntrypoints
): Promise<Entrypoints> { ): Promise<Entrypoints> {
const page = new Map() const page: Entrypoints['page'] = new Map()
const app = new Map() const app: Entrypoints['app'] = new Map()
for (const [pathname, route] of entrypointsOp.routes) { for (const [pathname, route] of entrypointsOp.routes) {
switch (route.type) { switch (route.type) {
case 'page': case 'page':
case 'page-api': case 'page-api':
page.set(pathname, route) // At the native pages-router boundary, a URL pathname also identifies
// the page; there are no app modifiers or leaf suffixes to preserve.
page.set(pathname as string as Page, route)
break break
case 'app-page': { case 'app-page': {
for (const p of route.pages) { for (const p of route.pages) {
...@@ -59,7 +62,7 @@ export async function handleRouteType({ ...@@ -59,7 +62,7 @@ export async function handleRouteType({
route, route,
manifestLoader, manifestLoader,
}: { }: {
page: string page: Page
route: PageRoute | AppRoute route: PageRoute | AppRoute
manifestLoader: TurbopackManifestLoader manifestLoader: TurbopackManifestLoader
}) { }) {
...@@ -77,7 +80,7 @@ export async function handleRouteType({ ...@@ -77,7 +80,7 @@ export async function handleRouteType({
manifestLoader.deleteMiddlewareManifest(serverKey) manifestLoader.deleteMiddlewareManifest(serverKey)
} }
await manifestLoader.loadFontManifest('/_app', 'pages') await manifestLoader.loadFontManifest('/_app' as Page, 'pages')
await manifestLoader.loadFontManifest(page, 'pages') await manifestLoader.loadFontManifest(page, 'pages')
await manifestLoader.loadSriManifest(page, 'pages') await manifestLoader.loadSriManifest(page, 'pages')
......
This diff is collapsed.
import type { Page, Route } from '../shared/lib/route-types'
import { import {
findIncompatibleParallelRouteSlots, findIncompatibleParallelRouteSlots,
normalizeCatchAllRoutes as normalizeCatchAllRoutesInternal, normalizeCatchAllRoutes as normalizeCatchAllRoutesInternal,
...@@ -7,7 +8,7 @@ import { ...@@ -7,7 +8,7 @@ import {
export { findIncompatibleParallelRouteSlots } export { findIncompatibleParallelRouteSlots }
export function normalizeCatchAllRoutes( export function normalizeCatchAllRoutes(
appPaths: Record<string, string[]>, appPaths: Record<Route, Page[]>,
options: NormalizeCatchAllRoutesOptions = {} options: NormalizeCatchAllRoutesOptions = {}
) { ) {
return normalizeCatchAllRoutesInternal(appPaths, undefined, options) return normalizeCatchAllRoutesInternal(appPaths, undefined, options)
......
import type { Page, Route } from '../shared/lib/route-types'
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import path from 'path' import path from 'path'
import { promises as fs, statSync } from 'fs' import { promises as fs, statSync } from 'fs'
import { import {
...@@ -11,7 +13,7 @@ import { filterAndSortList } from './utils' ...@@ -11,7 +13,7 @@ import { filterAndSortList } from './utils'
const ROUTE_BUNDLE_STATS_FILE = 'route-bundle-stats.json' const ROUTE_BUNDLE_STATS_FILE = 'route-bundle-stats.json'
type RouteBundleStat = { type RouteBundleStat = {
route: string route: Route
firstLoadUncompressedJsBytes: number firstLoadUncompressedJsBytes: number
firstLoadChunkPaths: string[] firstLoadChunkPaths: string[]
} }
...@@ -48,14 +50,14 @@ function toProjectRelativePaths( ...@@ -48,14 +50,14 @@ function toProjectRelativePaths(
} }
function buildRouteToAppPathsMap( function buildRouteToAppPathsMap(
appPathsManifest: Record<string, string> appPathsManifest: PagesManifest
): Map<string, string[]> { ): Map<Route, Page[]> {
const { normalizeAppPath } = const { normalizeAppPath } =
require('../shared/lib/router/utils/app-paths') as typeof import('../shared/lib/router/utils/app-paths') require('../shared/lib/router/utils/app-paths') as typeof import('../shared/lib/router/utils/app-paths')
// Keys in appPathsManifest are app paths like /blog/[slug]/page; // Keys in appPathsManifest are app paths like /blog/[slug]/page;
// values are server bundle file paths. Normalize the key to get the route. // values are server bundle file paths. Normalize the key to get the route.
const routeToAppPaths = new Map<string, string[]>() const routeToAppPaths = new Map<Route, Page[]>()
for (const appPath of Object.keys(appPathsManifest)) { for (const appPath of Object.keys(appPathsManifest) as Page[]) {
const route = normalizeAppPath(appPath) const route = normalizeAppPath(appPath)
const existing = routeToAppPaths.get(route) const existing = routeToAppPaths.get(route)
if (existing) { if (existing) {
...@@ -72,8 +74,8 @@ function buildRouteToAppPathsMap( ...@@ -72,8 +74,8 @@ function buildRouteToAppPathsMap(
// it with a save/restore of the global // it with a save/restore of the global
function readEntryJSFiles( function readEntryJSFiles(
distDir: string, distDir: string,
pagePath: string, pagePath: Page,
appRoute: string appRoute: Route
): Record<string, string[]> | undefined { ): Record<string, string[]> | undefined {
const manifestFile = path.join( const manifestFile = path.join(
distDir, distDir,
...@@ -87,11 +89,12 @@ function readEntryJSFiles( ...@@ -87,11 +89,12 @@ function readEntryJSFiles(
g.__RSC_MANIFEST = undefined g.__RSC_MANIFEST = undefined
require(manifestFile) require(manifestFile)
const rscManifest = g.__RSC_MANIFEST as const rscManifest = g.__RSC_MANIFEST as
| Record<string, { entryJSFiles?: Record<string, string[]> }> | Record<Page, { entryJSFiles?: Record<string, string[]> }>
| undefined | undefined
g.__RSC_MANIFEST = prev g.__RSC_MANIFEST = prev
// The key in __RSC_MANIFEST is the app path (e.g. /blog/[slug]/page) // The key in __RSC_MANIFEST is the app path (e.g. /blog/[slug]/page)
// @ts-ignore -- Human review: the fallback probe uses a normalized App URL in a raw App-module-keyed RSC manifest. This may be an intentional legacy miss; preserve it without claiming the URL is a raw Page.
const manifestEntry = rscManifest?.[pagePath] ?? rscManifest?.[appRoute] const manifestEntry = rscManifest?.[pagePath] ?? rscManifest?.[appRoute]
return manifestEntry?.entryJSFiles return manifestEntry?.entryJSFiles
} catch { } catch {
...@@ -100,7 +103,7 @@ function readEntryJSFiles( ...@@ -100,7 +103,7 @@ function readEntryJSFiles(
} }
function collectPagesRouterStats( function collectPagesRouterStats(
pages: ReadonlyArray<string>, pages: ReadonlyArray<Route>,
buildManifest: BuildManifest, buildManifest: BuildManifest,
distDir: string, distDir: string,
dir: string, dir: string,
...@@ -113,8 +116,9 @@ function collectPagesRouterStats( ...@@ -113,8 +116,9 @@ function collectPagesRouterStats(
// Don't report on layouts directly // Don't report on layouts directly
continue continue
const allFiles = (buildManifest.pages[page] ?? []).filter((f) => // This list contains only Pages-router URL keys, sharing the module namespace.
f.endsWith('.js') const allFiles = (buildManifest.pages[page as string as Page] ?? []).filter(
(f) => f.endsWith('.js')
) )
const sharedJs = sharedFiles.filter((f) => f.endsWith('.js')) const sharedJs = sharedFiles.filter((f) => f.endsWith('.js'))
const chunks = [...new Set([...allFiles, ...sharedJs])] const chunks = [...new Set([...allFiles, ...sharedJs])]
...@@ -129,13 +133,13 @@ function collectPagesRouterStats( ...@@ -129,13 +133,13 @@ function collectPagesRouterStats(
} }
async function collectAppRouterStats( async function collectAppRouterStats(
appRoutes: ReadonlyArray<string>, appRoutes: ReadonlyArray<Route>,
buildManifest: BuildManifest, buildManifest: BuildManifest,
distDir: string, distDir: string,
dir: string, dir: string,
cache: Map<string, number> cache: Map<string, number>
): Promise<RouteBundleStat[]> { ): Promise<RouteBundleStat[]> {
let appPathsManifest: Record<string, string> = {} let appPathsManifest: PagesManifest = {}
try { try {
const manifestPath = path.join( const manifestPath = path.join(
distDir, distDir,
...@@ -184,8 +188,8 @@ async function collectAppRouterStats( ...@@ -184,8 +188,8 @@ async function collectAppRouterStats(
export async function writeRouteBundleStats( export async function writeRouteBundleStats(
lists: { lists: {
pages: ReadonlyArray<string> pages: ReadonlyArray<Route>
app: ReadonlyArray<string> | undefined app: ReadonlyArray<Route> | undefined
}, },
buildManifest: BuildManifest, buildManifest: BuildManifest,
distDir: string, distDir: string,
......
import type { Page, Route } from '../shared/lib/route-types'
import { join } from 'path' import { join } from 'path'
import { createValidFileMatcher } from '../server/lib/find-page-file' import { createValidFileMatcher } from '../server/lib/find-page-file'
import { recursiveReadDir } from '../lib/recursive-readdir' import { recursiveReadDir } from '../lib/recursive-readdir'
...@@ -47,7 +48,7 @@ const PAGES_SUPPORT_ROUTES = new Set([ ...@@ -47,7 +48,7 @@ const PAGES_SUPPORT_ROUTES = new Set([
]) ])
const PAGES_FRAMEWORK_ROUTES = new Set(['/_app', '/_document', '/_error']) const PAGES_FRAMEWORK_ROUTES = new Set(['/_app', '/_document', '/_error'])
function isRenderablePagesRoute(page: string): boolean { function isRenderablePagesRoute(page: Page): boolean {
return ( return (
!PAGES_FRAMEWORK_ROUTES.has(page) && !PAGES_FRAMEWORK_ROUTES.has(page) &&
page !== '/api' && page !== '/api' &&
...@@ -60,14 +61,17 @@ function removeSuffix(value: string, suffix: string): string { ...@@ -60,14 +61,17 @@ function removeSuffix(value: string, suffix: string): string {
} }
/** Normalize a route for the app router */ /** Normalize a route for the app router */
function normalizeAppRoute(pageName: string): string { function normalizeAppRoute(pageName: Page): Route {
return normalizeAppPath(normalizePathSep(pageName)) return normalizeAppPath(normalizePathSep(pageName))
} }
/** Normalize a layout route (strip /layout suffix) */ /** Normalize a layout route (strip /layout suffix) */
function normalizeLayoutRoute(pageName: string): string { function normalizeLayoutRoute(pageName: Page): Route {
return ensureLeadingSlash( return ensureLeadingSlash(
removeSuffix(normalizeAppPath(normalizePathSep(pageName)), '/layout') removeSuffix(
normalizeAppPath(normalizePathSep(pageName)),
'/layout'
) as Route
) )
} }
...@@ -77,7 +81,7 @@ function normalizeLayoutRoute(pageName: string): string { ...@@ -77,7 +81,7 @@ function normalizeLayoutRoute(pageName: string): string {
export function getPageFromPath( export function getPageFromPath(
pagePath: string, pagePath: string,
pageExtensions: PageExtensions pageExtensions: PageExtensions
) { ): Page {
let page = normalizePathSep(pagePath) let page = normalizePathSep(pagePath)
// Try longer extensions first so compound extensions like 'page.js' // Try longer extensions first so compound extensions like 'page.js'
// match before shorter ones like 'js' // match before shorter ones like 'js'
...@@ -92,11 +96,13 @@ export function getPageFromPath( ...@@ -92,11 +96,13 @@ export function getPageFromPath(
page = removeSuffix(page, '/index') page = removeSuffix(page, '/index')
return page === '' ? '/' : page return (page === '' ? '/' : page) as Page
} }
/** /**
* Collect app pages, layouts, and default files from the app directory * Collect app pages, layouts, and default files from the app directory.
* These arrays hold discovered filenames, including extensions, not Page
* identifiers; createPagesMapping performs that boundary conversion later.
*/ */
export async function collectAppFiles( export async function collectAppFiles(
appDir: string, appDir: string,
...@@ -164,7 +170,7 @@ export function createRelativeFilePath( ...@@ -164,7 +170,7 @@ export function createRelativeFilePath(
* Process pages routes from mapped pages * Process pages routes from mapped pages
*/ */
export function processPageRoutes( export function processPageRoutes(
mappedPages: { [page: string]: string }, mappedPages: MappedPages,
baseDir: string, baseDir: string,
isSrcDir: boolean isSrcDir: boolean
): { ): {
...@@ -174,7 +180,12 @@ export function processPageRoutes( ...@@ -174,7 +180,12 @@ export function processPageRoutes(
const pageRoutes: RouteInfo[] = [] const pageRoutes: RouteInfo[] = []
const pageApiRoutes: RouteInfo[] = [] const pageApiRoutes: RouteInfo[] = []
for (const [route, filePath] of Object.entries(mappedPages)) { // Pages-router mapping keys already spell the URL pathname; unlike app
// keys, they have no groups, slots or leaf suffixes to remove.
for (const [route, filePath] of Object.entries(mappedPages) as [
Page,
string,
][]) {
const relativeFilePath = createRelativeFilePath( const relativeFilePath = createRelativeFilePath(
baseDir, baseDir,
filePath, filePath,
...@@ -184,14 +195,14 @@ export function processPageRoutes( ...@@ -184,14 +195,14 @@ export function processPageRoutes(
if (route.startsWith('/api/')) { if (route.startsWith('/api/')) {
pageApiRoutes.push({ pageApiRoutes.push({
route: normalizePathSep(route), route: normalizePathSep(route) as string as Route,
filePath: relativeFilePath, filePath: relativeFilePath,
}) })
} else { } else {
if (isReservedPage(route)) continue if (isReservedPage(route)) continue
pageRoutes.push({ pageRoutes.push({
route: normalizePathSep(route), route: normalizePathSep(route) as string as Route,
filePath: relativeFilePath, filePath: relativeFilePath,
}) })
} }
...@@ -204,7 +215,7 @@ export function processPageRoutes( ...@@ -204,7 +215,7 @@ export function processPageRoutes(
* Process app routes from mapped app pages * Process app routes from mapped app pages
*/ */
export function processAppRoutes( export function processAppRoutes(
mappedAppPages: { [page: string]: string }, mappedAppPages: MappedPages,
validFileMatcher: ReturnType<typeof createValidFileMatcher>, validFileMatcher: ReturnType<typeof createValidFileMatcher>,
baseDir: string, baseDir: string,
isSrcDir: boolean isSrcDir: boolean
...@@ -215,7 +226,10 @@ export function processAppRoutes( ...@@ -215,7 +226,10 @@ export function processAppRoutes(
const appRoutes: RouteInfo[] = [] const appRoutes: RouteInfo[] = []
const appRouteHandlers: RouteInfo[] = [] const appRouteHandlers: RouteInfo[] = []
for (const [page, filePath] of Object.entries(mappedAppPages)) { for (const [page, filePath] of Object.entries(mappedAppPages) as [
Page,
string,
][]) {
if ( if (
page === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY || page === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY ||
page === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY page === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY
...@@ -245,14 +259,16 @@ export function processAppRoutes( ...@@ -245,14 +259,16 @@ export function processAppRoutes(
* Process layout routes from mapped app layouts * Process layout routes from mapped app layouts
*/ */
export function processLayoutRoutes( export function processLayoutRoutes(
mappedAppLayouts: { [page: string]: string }, mappedAppLayouts: MappedPages,
baseDir: string, baseDir: string,
isSrcDir: boolean isSrcDir: boolean
): RouteInfo[] { ): RouteInfo[] {
return Object.entries(mappedAppLayouts).map(([route, filePath]) => ({ return (Object.entries(mappedAppLayouts) as [Page, string][]).map(
route: normalizeLayoutRoute(route), ([route, filePath]) => ({
filePath: createRelativeFilePath(baseDir, filePath, 'app', isSrcDir), route: normalizeLayoutRoute(route),
})) filePath: createRelativeFilePath(baseDir, filePath, 'app', isSrcDir),
})
)
} }
/** /**
...@@ -277,7 +293,7 @@ export async function createPagesMapping({ ...@@ -277,7 +293,7 @@ export async function createPagesMapping({
}): Promise<MappedPages> { }): Promise<MappedPages> {
const isAppRoute = pagesType === 'app' const isAppRoute = pagesType === 'app'
const promises = pagePaths.map<Promise<[string, string] | undefined>>( const promises = pagePaths.map<Promise<[Page, string] | undefined>>(
async (pagePath) => { async (pagePath) => {
if (pagePath.endsWith('.d.ts') && pageExtensions.includes('ts')) { if (pagePath.endsWith('.d.ts') && pageExtensions.includes('ts')) {
return return
...@@ -286,7 +302,7 @@ export async function createPagesMapping({ ...@@ -286,7 +302,7 @@ export async function createPagesMapping({
let pageKey = getPageFromPath(pagePath, pageExtensions) let pageKey = getPageFromPath(pagePath, pageExtensions)
if (isAppRoute) { if (isAppRoute) {
// Turbopack encodes '_' as '%5F' in app paths; normalize to underscores. // Turbopack encodes '_' as '%5F' in app paths; normalize to underscores.
pageKey = pageKey.replace(/%5F/g, '_') pageKey = pageKey.replace(/%5F/g, '_') as Page
if (pageKey === UNDERSCORE_NOT_FOUND_ROUTE) { if (pageKey === UNDERSCORE_NOT_FOUND_ROUTE) {
pageKey = UNDERSCORE_NOT_FOUND_ROUTE_ENTRY pageKey = UNDERSCORE_NOT_FOUND_ROUTE_ENTRY
} }
...@@ -359,9 +375,9 @@ export async function createPagesMapping({ ...@@ -359,9 +375,9 @@ export async function createPagesMapping({
} }
case PAGE_TYPES.PAGES: { case PAGE_TYPES.PAGES: {
if (isDev) { if (isDev) {
delete pages['/_app'] delete pages['/_app' as Page]
delete pages['/_error'] delete pages['/_error' as Page]
delete pages['/_document'] delete pages['/_document' as Page]
} }
const root = isDev && pagesDir ? PAGES_DIR_ALIAS : 'next/dist/pages' const root = isDev && pagesDir ? PAGES_DIR_ALIAS : 'next/dist/pages'
...@@ -449,7 +465,8 @@ export async function discoverRoutes( ...@@ -449,7 +465,8 @@ export async function discoverRoutes(
appDirOnly, appDirOnly,
}) })
// Helper to apply debugBuildPaths filtering // Helper to apply debugBuildPaths filtering. Both arrays contain filesystem
// names resolved from CLI globs, not normalized route identities.
const applyDebugFilter = ( const applyDebugFilter = (
paths: string[], paths: string[],
debugPaths: string[] debugPaths: string[]
......
import { z } from 'next/dist/compiled/zod' import { z } from 'next/dist/compiled/zod'
import { formatZodError } from '../../../shared/lib/zod' import { formatZodError } from '../../../shared/lib/zod'
import type { Route } from '../../../shared/lib/route-types'
const CookieSchema = z const CookieSchema = z
.object({ .object({
...@@ -175,12 +176,12 @@ const AppSegmentConfigSchema = z.object({ ...@@ -175,12 +176,12 @@ const AppSegmentConfigSchema = z.object({
/** /**
* Parse the app segment config. * Parse the app segment config.
* @param data - The data to parse. * @param data - The data to parse.
* @param route - The route of the app. * @param route - The normalized URL route used in configuration diagnostics.
* @returns The parsed app segment config. * @returns The parsed app segment config.
*/ */
export function parseAppSegmentConfig( export function parseAppSegmentConfig(
data: unknown, data: unknown,
route: string route: Route
): AppSegmentConfig { ): AppSegmentConfig {
const parsed = AppSegmentConfigSchema.safeParse(data, { const parsed = AppSegmentConfigSchema.safeParse(data, {
errorMap: (issue, ctx) => { errorMap: (issue, ctx) => {
......
import type { Route } from '../../../shared/lib/route-types'
import type { Params } from '../../../server/request/params' import type { Params } from '../../../server/request/params'
import type { AppPageRouteModule } from '../../../server/route-modules/app-page/module.compiled' import type { AppPageRouteModule } from '../../../server/route-modules/app-page/module.compiled'
import type { AppRouteRouteModule } from '../../../server/route-modules/app-route/module.compiled' import type { AppRouteRouteModule } from '../../../server/route-modules/app-route/module.compiled'
...@@ -36,7 +37,7 @@ export type ParamMatchingMode = (typeof PARAM_MATCHING_MODES)[number] ...@@ -36,7 +37,7 @@ export type ParamMatchingMode = (typeof PARAM_MATCHING_MODES)[number]
export type ParamMatching = Record<string, ParamMatchingMode> export type ParamMatching = Record<string, ParamMatchingMode>
function validateParamMatchingExport( function validateParamMatchingExport(
route: string, route: Route,
filePath: string | undefined, filePath: string | undefined,
exportName: string, exportName: string,
value: unknown, value: unknown,
...@@ -76,7 +77,7 @@ function validateParamMatchingExport( ...@@ -76,7 +77,7 @@ function validateParamMatchingExport(
function attach( function attach(
segment: AppSegment, segment: AppSegment,
userland: unknown, userland: unknown,
route: string, route: Route,
visibleParamNames: readonly string[] visibleParamNames: readonly string[]
) { ) {
// If the userland is not an object, then we can't do anything with it. // If the userland is not an object, then we can't do anything with it.
......
import { z } from 'next/dist/compiled/zod' import { z } from 'next/dist/compiled/zod'
import { formatZodError } from '../../../shared/lib/zod' import { formatZodError } from '../../../shared/lib/zod'
import type { Page } from '../../../shared/lib/route-types'
/** /**
* The schema for the page segment config. * The schema for the page segment config.
...@@ -36,12 +37,12 @@ const PagesSegmentConfigSchema = z.object({ ...@@ -36,12 +37,12 @@ const PagesSegmentConfigSchema = z.object({
/** /**
* Parse the page segment config. * Parse the page segment config.
* @param data - The data to parse. * @param data - The data to parse.
* @param route - The route of the page. * @param route - The Pages module's file counterpart used in configuration diagnostics.
* @returns The parsed page segment config. * @returns The parsed page segment config.
*/ */
export function parsePagesSegmentConfig( export function parsePagesSegmentConfig(
data: unknown, data: unknown,
route: string route: Page
): PagesSegmentConfig { ): PagesSegmentConfig {
const parsed = PagesSegmentConfigSchema.safeParse(data, {}) const parsed = PagesSegmentConfigSchema.safeParse(data, {})
if (!parsed.success) { if (!parsed.success) {
......
import type { Page, Route } from '../../shared/lib/route-types'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import type { AppPageModule } from '../../server/route-modules/app-page/module' import type { AppPageModule } from '../../server/route-modules/app-page/module'
import type { import type {
...@@ -331,7 +332,7 @@ export function calculateFallbackMode( ...@@ -331,7 +332,7 @@ export function calculateFallbackMode(
* @returns The list of validated parameters. * @returns The list of validated parameters.
*/ */
function validateParams( function validateParams(
page: string, page: Route,
isRoutePPREnabled: boolean, isRoutePPREnabled: boolean,
pathnameSegments: ReadonlyArray<{ pathnameSegments: ReadonlyArray<{
readonly paramName: string readonly paramName: string
...@@ -657,7 +658,7 @@ function getValueType(value: unknown): string { ...@@ -657,7 +658,7 @@ function getValueType(value: unknown): string {
* making root param getters available during static param generation. * making root param getters available during static param generation.
*/ */
async function callGenerateStaticParams( async function callGenerateStaticParams(
route: string, route: Route,
generateStaticParams: NonNullable<AppSegment['generateStaticParams']>, generateStaticParams: NonNullable<AppSegment['generateStaticParams']>,
parentParams: Params, parentParams: Params,
rootParamKeys: readonly string[], rootParamKeys: readonly string[],
...@@ -890,7 +891,7 @@ export async function buildAppStaticPaths({ ...@@ -890,7 +891,7 @@ export async function buildAppStaticPaths({
rootParamKeys, rootParamKeys,
}: { }: {
dir: string dir: string
page: string page: Route
route: NormalizedAppRoute route: NormalizedAppRoute
cacheComponents: boolean cacheComponents: boolean
authInterrupts: boolean authInterrupts: boolean
...@@ -1198,17 +1199,17 @@ export async function buildAppStaticPaths({ ...@@ -1198,17 +1199,17 @@ export async function buildAppStaticPaths({
) )
} }
const prerenderedRoutesByPathname = new Map<string, PrerenderedRoute>() const prerenderedRoutesByPathname = new Map<Route, PrerenderedRoute>()
const blockingCandidatesByPathname = new Map<string, PrerenderedRoute>() const blockingCandidatesByPathname = new Map<Route, PrerenderedRoute>()
const prerenderRouteMatchersByPathname = new Map< const prerenderRouteMatchersByPathname = new Map<
string, Route,
PrerenderRouteMatcher PrerenderRouteMatcher
>() >()
const addPrerenderCandidate = ( const addPrerenderCandidate = (
params: Params, params: Params,
pathname: string, pathname: Route,
encodedPathname: string, encodedPathname: Route,
fallbackRouteParams: readonly FallbackRouteParam[], fallbackRouteParams: readonly FallbackRouteParam[],
fallbackRootParams: readonly string[] fallbackRootParams: readonly string[]
): void => { ): void => {
...@@ -1377,14 +1378,14 @@ export async function buildAppStaticPaths({ ...@@ -1377,14 +1378,14 @@ export async function buildAppStaticPaths({
// We're replacing the segment name with the replacement pathname // We're replacing the segment name with the replacement pathname
// which will include the interception marker prefix if it exists. // which will include the interception marker prefix if it exists.
replacements.pathname replacements.pathname
) ) as Route
encodedPathname = encodedPathname.replace( encodedPathname = encodedPathname.replace(
name, name,
// We're replacing the segment name with the replacement encoded // We're replacing the segment name with the replacement encoded
// pathname which will include the encoded param value. // pathname which will include the encoded param value.
replacements.encodedPathname replacements.encodedPathname
) ) as Route
} }
// Resolve all route params from the loader tree if this is from an // Resolve all route params from the loader tree if this is from an
......
import type { Route } from '../../shared/lib/route-types'
import type { GetStaticPaths } from '../../types' import type { GetStaticPaths } from '../../types'
import type { PrerenderedRoute, StaticPathsResult } from './types' import type { PrerenderedRoute, StaticPathsResult } from './types'
...@@ -16,13 +17,13 @@ export async function buildPagesStaticPaths({ ...@@ -16,13 +17,13 @@ export async function buildPagesStaticPaths({
locales, locales,
defaultLocale, defaultLocale,
}: { }: {
page: string page: Route
getStaticPaths: GetStaticPaths getStaticPaths: GetStaticPaths
configFileName: string configFileName: string
locales?: readonly string[] locales?: readonly string[]
defaultLocale?: string defaultLocale?: string
}): Promise<StaticPathsResult> { }): Promise<StaticPathsResult> {
const prerenderedRoutesByPathname = new Map<string, PrerenderedRoute>() const prerenderedRoutesByPathname = new Map<Route, PrerenderedRoute>()
const _routeRegex = getRouteRegex(page) const _routeRegex = getRouteRegex(page)
const _routeMatcher = getRouteMatcher(_routeRegex) const _routeMatcher = getRouteMatcher(_routeRegex)
...@@ -98,7 +99,7 @@ export async function buildPagesStaticPaths({ ...@@ -98,7 +99,7 @@ export async function buildPagesStaticPaths({
entry = `/${defaultLocale}${entry}` entry = `/${defaultLocale}${entry}`
} }
const params = _routeMatcher(cleanedEntry) const params = _routeMatcher(cleanedEntry as Route)
if (!params) { if (!params) {
throw new Error( throw new Error(
`The provided path \`${cleanedEntry}\` does not match the page: \`${page}\`.` `The provided path \`${cleanedEntry}\` does not match the page: \`${page}\`.`
...@@ -113,13 +114,13 @@ export async function buildPagesStaticPaths({ ...@@ -113,13 +114,13 @@ export async function buildPagesStaticPaths({
.map((segment) => .map((segment) =>
escapePathDelimiters(decodeURIComponent(segment), true) escapePathDelimiters(decodeURIComponent(segment), true)
) )
.join('/') .join('/') as Route
if (!prerenderedRoutesByPathname.has(pathname)) { if (!prerenderedRoutesByPathname.has(pathname)) {
prerenderedRoutesByPathname.set(pathname, { prerenderedRoutesByPathname.set(pathname, {
params, params,
pathname, pathname,
encodedPathname: entry, encodedPathname: entry as Route,
fallbackRouteParams: undefined, fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback), fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
fallbackRootParams: undefined, fallbackRootParams: undefined,
...@@ -182,12 +183,12 @@ export async function buildPagesStaticPaths({ ...@@ -182,12 +183,12 @@ export async function buildPagesStaticPaths({
builtPage = builtPage.replace( builtPage = builtPage.replace(
replaced, replaced,
encodeParam(paramValue, (value) => escapePathDelimiters(value, true)) encodeParam(paramValue, (value) => escapePathDelimiters(value, true))
) ) as Route
encodedBuiltPage = encodedBuiltPage.replace( encodedBuiltPage = encodedBuiltPage.replace(
replaced, replaced,
encodeParam(paramValue, encodeURIComponent) encodeParam(paramValue, encodeURIComponent)
) ) as Route
}) })
if (!builtPage && !encodedBuiltPage) { if (!builtPage && !encodedBuiltPage) {
...@@ -202,7 +203,7 @@ export async function buildPagesStaticPaths({ ...@@ -202,7 +203,7 @@ export async function buildPagesStaticPaths({
const curLocale = entry.locale || defaultLocale || '' const curLocale = entry.locale || defaultLocale || ''
const pathname = normalizePathname( const pathname = normalizePathname(
`${curLocale ? `/${curLocale}` : ''}${curLocale && builtPage === '/' ? '' : builtPage}` `${curLocale ? `/${curLocale}` : ''}${curLocale && builtPage === '/' ? '' : builtPage}` as Route
) )
if (!prerenderedRoutesByPathname.has(pathname)) { if (!prerenderedRoutesByPathname.has(pathname)) {
...@@ -212,7 +213,7 @@ export async function buildPagesStaticPaths({ ...@@ -212,7 +213,7 @@ export async function buildPagesStaticPaths({
encodedPathname: normalizePathname( encodedPathname: normalizePathname(
`${curLocale ? `/${curLocale}` : ''}${ `${curLocale ? `/${curLocale}` : ''}${
curLocale && encodedBuiltPage === '/' ? '' : encodedBuiltPage curLocale && encodedBuiltPage === '/' ? '' : encodedBuiltPage
}` }` as Route
), ),
fallbackRouteParams: undefined, fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback), fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
......
import type { Page, Route } from '../../shared/lib/route-types'
import { import {
PARAM_MATCHING_MODES, PARAM_MATCHING_MODES,
type AppSegment, type AppSegment,
...@@ -16,7 +17,7 @@ type PolicyCandidate = { ...@@ -16,7 +17,7 @@ type PolicyCandidate = {
} }
export async function resolveParamMatching( export async function resolveParamMatching(
page: string, page: Route,
segmentTree: readonly AppSegmentTree[], segmentTree: readonly AppSegmentTree[],
pathnameSegments: ReadonlyArray<{ readonly paramName: string }> pathnameSegments: ReadonlyArray<{ readonly paramName: string }>
): Promise<ParamMatching | undefined> { ): Promise<ParamMatching | undefined> {
...@@ -159,9 +160,9 @@ export async function resolveParamMatching( ...@@ -159,9 +160,9 @@ export async function resolveParamMatching(
* definition when their URL prefixes match. * definition when their URL prefixes match.
*/ */
export function validateParamMatchingCoherence( export function validateParamMatchingCoherence(
paramMatchingByRoute: ReadonlyMap<string, ParamMatching | undefined> paramMatchingByRoute: ReadonlyMap<Page, ParamMatching | undefined>
): void { ): void {
const parameters = new Map<string, [route: string, notFound: boolean]>() const parameters = new Map<string, [route: Route, notFound: boolean]>()
for (const [appPath, paramMatching] of [...paramMatchingByRoute].sort( for (const [appPath, paramMatching] of [...paramMatchingByRoute].sort(
([a], [b]) => a.localeCompare(b) ([a], [b]) => a.localeCompare(b)
...@@ -221,7 +222,7 @@ export function getParamMatchingFallbackMode( ...@@ -221,7 +222,7 @@ export function getParamMatchingFallbackMode(
} }
export function validateParamMatchingParams( export function validateParamMatchingParams(
page: string, page: Route,
paramMatching: Readonly<ParamMatching>, paramMatching: Readonly<ParamMatching>,
generatedParamNames: ReadonlySet<string>, generatedParamNames: ReadonlySet<string>,
missingParamNames: ReadonlySet<string>, missingParamNames: ReadonlySet<string>,
......
import type { Route } from '../../shared/lib/route-types'
import type { FallbackMode } from '../../lib/fallback' import type { FallbackMode } from '../../lib/fallback'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import type { DynamicParamTypes } from '../../shared/lib/app-router-types' import type { DynamicParamTypes } from '../../shared/lib/app-router-types'
...@@ -5,8 +6,8 @@ import type { ParamMatching } from '../segment-config/app/app-segments' ...@@ -5,8 +6,8 @@ import type { ParamMatching } from '../segment-config/app/app-segments'
type StaticPrerenderedRoute = { type StaticPrerenderedRoute = {
readonly params: Params readonly params: Params
readonly pathname: string readonly pathname: Route
readonly encodedPathname: string readonly encodedPathname: Route
readonly fallbackRouteParams: undefined readonly fallbackRouteParams: undefined
readonly fallbackMode: FallbackMode | undefined readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: undefined readonly fallbackRootParams: undefined
...@@ -34,8 +35,8 @@ export type FallbackRouteParam = { ...@@ -34,8 +35,8 @@ export type FallbackRouteParam = {
type FallbackPrerenderedRoute = { type FallbackPrerenderedRoute = {
readonly params: Params readonly params: Params
readonly pathname: string readonly pathname: Route
readonly encodedPathname: string readonly encodedPathname: Route
/** /**
* The fallback route params for the route. This includes all route parameters * The fallback route params for the route. This includes all route parameters
...@@ -82,7 +83,7 @@ export type PrerenderedRoute = StaticPrerenderedRoute | FallbackPrerenderedRoute ...@@ -82,7 +83,7 @@ export type PrerenderedRoute = StaticPrerenderedRoute | FallbackPrerenderedRoute
* must not assume pathname identifies a single candidate or render result. * must not assume pathname identifies a single candidate or render result.
*/ */
export type PrerenderRouteMatcher = { export type PrerenderRouteMatcher = {
readonly pathname: string readonly pathname: Route
readonly fallbackRouteParams: readonly FallbackRouteParam[] readonly fallbackRouteParams: readonly FallbackRouteParam[]
readonly fallbackMode: FallbackMode | undefined readonly fallbackMode: FallbackMode | undefined
/** /**
......
import type { Route } from '../../shared/lib/route-types'
import type { LoaderTree } from '../../server/lib/app-dir-module' import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import type { AppPageRouteModule } from '../../server/route-modules/app-page/module.compiled' import type { AppPageRouteModule } from '../../server/route-modules/app-page/module.compiled'
...@@ -41,8 +42,8 @@ export function encodeParam( ...@@ -41,8 +42,8 @@ export function encodeParam(
* @param pathname - The pathname to normalize. * @param pathname - The pathname to normalize.
* @returns The normalized pathname. * @returns The normalized pathname.
*/ */
export function normalizePathname(pathname: string) { export function normalizePathname(pathname: Route): Route {
return pathname.replace(/\\/g, '/').replace(/(?!^)\/$/, '') return pathname.replace(/\\/g, '/').replace(/(?!^)\/$/, '') as Route
} }
/** /**
......
...@@ -43,6 +43,7 @@ import type { ...@@ -43,6 +43,7 @@ import type {
WrittenEndpoint, WrittenEndpoint,
} from './types' } from './types'
import { runLoaderWorkerPool } from './loaderWorkerPool' import { runLoaderWorkerPool } from './loaderWorkerPool'
import type { Page, Route as RoutePathname } from '../../shared/lib/route-types'
type RawBindings = typeof import('./generated-native') type RawBindings = typeof import('./generated-native')
type RawWasmBindings = typeof import('./generated-wasm') & { type RawWasmBindings = typeof import('./generated-wasm') & {
...@@ -1214,7 +1215,9 @@ function bindingToApi( ...@@ -1214,7 +1215,9 @@ function bindingToApi(
function napiEntrypointsToRawEntrypoints( function napiEntrypointsToRawEntrypoints(
entrypoints: TurbopackResult<NapiEntrypoints> entrypoints: TurbopackResult<NapiEntrypoints>
): TurbopackResult<RawEntrypoints> { ): TurbopackResult<RawEntrypoints> {
const routes = new Map() // NAPI publishes normalized pathname keys and raw app originalName module
// identifiers. Establish the internal namespaces at this native boundary.
const routes = new Map<RoutePathname, Route>()
for (const { pathname, ...nativeRoute } of entrypoints.value.routes) { for (const { pathname, ...nativeRoute } of entrypoints.value.routes) {
let route: Route let route: Route
const routeType = nativeRoute.type const routeType = nativeRoute.type
...@@ -1236,7 +1239,7 @@ function bindingToApi( ...@@ -1236,7 +1239,7 @@ function bindingToApi(
route = { route = {
type: 'app-page', type: 'app-page',
pages: nativeRoute.pages.map((page) => ({ pages: nativeRoute.pages.map((page) => ({
originalName: page.originalName, originalName: page.originalName as Page,
htmlEndpoint: new EndpointImpl(page.htmlEndpoint), htmlEndpoint: new EndpointImpl(page.htmlEndpoint),
rscHmrEndpoint: new EndpointImpl(page.rscHmrEndpoint), rscHmrEndpoint: new EndpointImpl(page.rscHmrEndpoint),
})), })),
...@@ -1245,7 +1248,7 @@ function bindingToApi( ...@@ -1245,7 +1248,7 @@ function bindingToApi(
case 'app-route': case 'app-route':
route = { route = {
type: 'app-route', type: 'app-route',
originalName: nativeRoute.originalName, originalName: nativeRoute.originalName as Page,
hasActionManifest: nativeRoute.hasActionManifest, hasActionManifest: nativeRoute.hasActionManifest,
endpoint: new EndpointImpl(nativeRoute.endpoint), endpoint: new EndpointImpl(nativeRoute.endpoint),
} }
...@@ -1263,7 +1266,7 @@ function bindingToApi( ...@@ -1263,7 +1266,7 @@ function bindingToApi(
) )
} }
} }
routes.set(pathname, route) routes.set(pathname as RoutePathname, route)
} }
const napiMiddlewareToMiddleware = (middleware: NapiMiddleware) => ({ const napiMiddlewareToMiddleware = (middleware: NapiMiddleware) => ({
endpoint: new EndpointImpl(middleware.endpoint), endpoint: new EndpointImpl(middleware.endpoint),
......
import type { Page, Route as RoutePathname } from '../../shared/lib/route-types'
import type { NextConfigComplete } from '../../server/config-shared' import type { NextConfigComplete } from '../../server/config-shared'
import type { __ApiPreviewProps } from '../../server/api-utils' import type { __ApiPreviewProps } from '../../server/api-utils'
import type { import type {
...@@ -202,7 +203,7 @@ export interface Instrumentation { ...@@ -202,7 +203,7 @@ export interface Instrumentation {
} }
export interface RawEntrypoints { export interface RawEntrypoints {
routes: Map<string, Route> routes: Map<RoutePathname, Route>
middleware?: Middleware middleware?: Middleware
instrumentation?: Instrumentation instrumentation?: Instrumentation
pagesDocumentEndpoint: Endpoint pagesDocumentEndpoint: Endpoint
...@@ -405,14 +406,14 @@ export type Route = ...@@ -405,14 +406,14 @@ export type Route =
| { | {
type: 'app-page' type: 'app-page'
pages: { pages: {
originalName: string originalName: Page
htmlEndpoint: Endpoint htmlEndpoint: Endpoint
rscHmrEndpoint: Endpoint rscHmrEndpoint: Endpoint
}[] }[]
} }
| { | {
type: 'app-route' type: 'app-route'
originalName: string originalName: Page
hasActionManifest: boolean hasActionManifest: boolean
endpoint: Endpoint endpoint: Endpoint
} }
...@@ -564,11 +565,11 @@ export type AppRoute = ...@@ -564,11 +565,11 @@ export type AppRoute =
endpoint: Endpoint endpoint: Endpoint
} }
// pathname -> route // Pages-router page identifiers use the same spelling as their URL pathname.
export type PageEntrypoints = Map<string, PageRoute> export type PageEntrypoints = Map<Page, PageRoute>
// originalName / page -> route // originalName / page -> route
export type AppEntrypoints = Map<string, AppRoute> export type AppEntrypoints = Map<Page, AppRoute>
export type Entrypoints = { export type Entrypoints = {
global: GlobalEntrypoints global: GlobalEntrypoints
......
import type { Page, Route } from '../../shared/lib/route-types'
import type { LoaderTree } from '../../server/lib/app-dir-module' import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { IncomingMessage, ServerResponse } from 'node:http' import type { IncomingMessage, ServerResponse } from 'node:http'
import type { FallbackRouteParam } from '../static-paths/types' import type { FallbackRouteParam } from '../static-paths/types'
...@@ -164,8 +165,8 @@ export function createAppPageEntrypoint({ ...@@ -164,8 +165,8 @@ export function createAppPageEntrypoint({
interopDefault, interopDefault,
}: { }: {
tree: LoaderTree tree: LoaderTree
page: string page: Page
pathname: string pathname: Route
require: (id: string | number) => unknown require: (id: string | number) => unknown
loadChunk: (id: string | number) => Promise<unknown> loadChunk: (id: string | number) => Promise<unknown>
interopDefault: typeof import('../../server/app-render/interop-default').interopDefault interopDefault: typeof import('../../server/app-render/interop-default').interopDefault
...@@ -197,10 +198,10 @@ export function createAppPageEntrypoint({ ...@@ -197,10 +198,10 @@ export function createAppPageEntrypoint({
// so we need to to process dynamic routes properly // so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack // TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
srcPage = srcPage.replace(/\/index$/, '') || '/' srcPage = (srcPage.replace(/\/index$/, '') || '/') as Page
} else if (srcPage === '/index') { } else if (srcPage === '/index') {
// we always normalize /index specifically // we always normalize /index specifically
srcPage = '/' srcPage = '/' as Page
} }
const normalizedSrcPage = normalizeAppPath(srcPage) const normalizedSrcPage = normalizeAppPath(srcPage)
......
import type { Page, Route } from '../../shared/lib/route-types'
import type { LoaderTree } from '../../server/lib/app-dir-module' import type { LoaderTree } from '../../server/lib/app-dir-module'
import { createAppPageEntrypoint } from './app-page-runtime' import { createAppPageEntrypoint } from './app-page-runtime'
import { interopDefault } from '../../server/app-render/interop-default' with { 'turbopack-transition': 'next-server-utility' } import { interopDefault } from '../../server/app-render/interop-default' with { 'turbopack-transition': 'next-server-utility' }
...@@ -21,8 +22,8 @@ declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown> ...@@ -21,8 +22,8 @@ declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown>
const entrypoint = createAppPageEntrypoint({ const entrypoint = createAppPageEntrypoint({
tree, tree,
page: 'VAR_DEFINITION_PAGE', page: 'VAR_DEFINITION_PAGE' as Page,
pathname: 'VAR_DEFINITION_PATHNAME', pathname: 'VAR_DEFINITION_PATHNAME' as Route,
require: __next_app_require__, require: __next_app_require__,
loadChunk: __next_app_load_chunk__, loadChunk: __next_app_load_chunk__,
interopDefault, interopDefault,
......
import type { Page, Route } from '../../shared/lib/route-types'
import { import {
AppRouteRouteModule, AppRouteRouteModule,
type AppRouteRouteHandlerContext, type AppRouteRouteHandlerContext,
...@@ -54,8 +55,8 @@ declare const nextConfigOutput: AppRouteRouteModuleOptions['nextConfigOutput'] ...@@ -54,8 +55,8 @@ declare const nextConfigOutput: AppRouteRouteModuleOptions['nextConfigOutput']
const routeModule = new AppRouteRouteModule({ const routeModule = new AppRouteRouteModule({
definition: { definition: {
kind: RouteKind.APP_ROUTE, kind: RouteKind.APP_ROUTE,
page: 'VAR_DEFINITION_PAGE', page: 'VAR_DEFINITION_PAGE' as Page,
pathname: 'VAR_DEFINITION_PATHNAME', pathname: 'VAR_DEFINITION_PATHNAME' as Route,
filename: 'VAR_DEFINITION_FILENAME', filename: 'VAR_DEFINITION_FILENAME',
bundlePath: 'VAR_DEFINITION_BUNDLE_PATH', bundlePath: 'VAR_DEFINITION_BUNDLE_PATH',
}, },
...@@ -117,16 +118,16 @@ export async function handler( ...@@ -117,16 +118,16 @@ export async function handler(
if (routeModule.isDev) { if (routeModule.isDev) {
addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint()) addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())
} }
let srcPage = 'VAR_DEFINITION_PAGE' let srcPage = 'VAR_DEFINITION_PAGE' as Page
// turbopack doesn't normalize `/index` in the page name // turbopack doesn't normalize `/index` in the page name
// so we need to to process dynamic routes properly // so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack // TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
srcPage = srcPage.replace(/\/index$/, '') || '/' srcPage = (srcPage.replace(/\/index$/, '') || '/') as Page
} else if (srcPage === '/index') { } else if (srcPage === '/index') {
// we always normalize /index specifically // we always normalize /index specifically
srcPage = '/' srcPage = '/' as Page
} }
const multiZoneDraftMode = process.env const multiZoneDraftMode = process.env
.__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean .__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean
......
import type { Page } from '../../shared/lib/route-types'
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import type { RequestMeta } from '../../server/request-meta' import type { RequestMeta } from '../../server/request-meta'
import type { EdgeHandler } from '../../server/web/adapter' import type { EdgeHandler } from '../../server/web/adapter'
...@@ -19,7 +20,7 @@ const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST) ...@@ -19,7 +20,7 @@ const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)
if (rscManifest && rscServerManifest) { if (rscManifest && rscServerManifest) {
setManifestsSingleton({ setManifestsSingleton({
page: 'VAR_PAGE', page: 'VAR_PAGE' as Page,
clientReferenceManifest: rscManifest, clientReferenceManifest: rscManifest,
serverActionsManifest: rscServerManifest, serverActionsManifest: rscServerManifest,
}) })
...@@ -33,7 +34,7 @@ const edgeCacheHandlers: any = {} ...@@ -33,7 +34,7 @@ const edgeCacheHandlers: any = {}
const internalHandler: EdgeHandler = EdgeRouteModuleWrapper.wrap( const internalHandler: EdgeHandler = EdgeRouteModuleWrapper.wrap(
module.routeModule, module.routeModule,
{ {
page: 'VAR_PAGE', page: 'VAR_PAGE' as Page,
cacheHandlers: edgeCacheHandlers, cacheHandlers: edgeCacheHandlers,
incrementalCacheHandler, incrementalCacheHandler,
} }
...@@ -66,7 +67,7 @@ export async function handler( ...@@ -66,7 +67,7 @@ export async function handler(
}, },
}, },
page: { page: {
name: 'VAR_PAGE', name: 'VAR_PAGE' as Page,
}, },
body: body:
request.method !== 'GET' && request.method !== 'HEAD' request.method !== 'GET' && request.method !== 'HEAD'
......
import type { Page } from '../../shared/lib/route-types'
import '../../server/web/globals' import '../../server/web/globals'
import { import {
adapter, adapter,
...@@ -54,7 +55,7 @@ const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST) ...@@ -54,7 +55,7 @@ const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)
if (rscManifest && rscServerManifest) { if (rscManifest && rscServerManifest) {
setManifestsSingleton({ setManifestsSingleton({
page: 'VAR_PAGE', page: 'VAR_PAGE' as Page,
clientReferenceManifest: rscManifest, clientReferenceManifest: rscManifest,
serverActionsManifest: rscServerManifest, serverActionsManifest: rscServerManifest,
}) })
...@@ -66,7 +67,7 @@ async function requestHandler( ...@@ -66,7 +67,7 @@ async function requestHandler(
req: NextRequestHint, req: NextRequestHint,
event: NextFetchEvent event: NextFetchEvent
): Promise<Response> { ): Promise<Response> {
let srcPage = 'VAR_PAGE' let srcPage = 'VAR_PAGE' as Page
const normalizedSrcPage = normalizeAppPath(srcPage) const normalizedSrcPage = normalizeAppPath(srcPage)
const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}` const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`
...@@ -440,7 +441,7 @@ const internalHandler: EdgeHandler = (opts) => { ...@@ -440,7 +441,7 @@ const internalHandler: EdgeHandler = (opts) => {
IncrementalCache, IncrementalCache,
handler: requestHandler, handler: requestHandler,
incrementalCacheHandler, incrementalCacheHandler,
page: 'VAR_PAGE', page: 'VAR_PAGE' as Page,
}) })
} }
...@@ -471,7 +472,7 @@ export async function handler( ...@@ -471,7 +472,7 @@ export async function handler(
}, },
}, },
page: { page: {
name: 'VAR_PAGE', name: 'VAR_PAGE' as Page,
}, },
body: body:
request.method !== 'GET' && request.method !== 'HEAD' request.method !== 'GET' && request.method !== 'HEAD'
......
import type { Route } from '../../shared/lib/route-types'
import '../../server/web/globals' import '../../server/web/globals'
import { import {
adapter, adapter,
...@@ -96,12 +97,13 @@ async function requestHandler( ...@@ -96,12 +97,13 @@ async function requestHandler(
req: NextRequestHint, req: NextRequestHint,
_event: NextFetchEvent _event: NextFetchEvent
): Promise<Response> { ): Promise<Response> {
let srcPage = 'VAR_DEFINITION_PATHNAME' let srcPage = 'VAR_DEFINITION_PATHNAME' as Route
const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}` const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`
const baseReq = new WebNextRequest(req) const baseReq = new WebNextRequest(req)
const pageRouteModule = pageMod.routeModule as RouteModule const pageRouteModule = pageMod.routeModule as RouteModule
const prepareResult = await pageRouteModule.prepare(baseReq, null, { const prepareResult = await pageRouteModule.prepare(baseReq, null, {
// @ts-ignore -- Human review: edge Pages preparation receives the normalized pathname, not the raw definition.page used by the Node template. Preserve the existing normalization assumption.
srcPage, srcPage,
multiZoneDraftMode: false, multiZoneDraftMode: false,
}) })
...@@ -149,6 +151,7 @@ async function requestHandler( ...@@ -149,6 +151,7 @@ async function requestHandler(
renderOpts: { renderOpts: {
params, params,
// @ts-ignore -- Human review: renderOpts.page expects the raw Page, but edge Pages rendering forwards its normalized pathname. Preserve existing behavior.
page: srcPage, page: srcPage,
supportsDynamicResponse: true, supportsDynamicResponse: true,
Component: pageMod.Component, Component: pageMod.Component,
......
import type { Page, Route } from '../../shared/lib/route-types'
import type { NextApiResponse } from '../../types' import type { NextApiResponse } from '../../types'
import type { IncomingMessage, ServerResponse } from 'node:http' import type { IncomingMessage, ServerResponse } from 'node:http'
...@@ -33,8 +34,8 @@ export const config = hoist(userland, 'config') ...@@ -33,8 +34,8 @@ export const config = hoist(userland, 'config')
const routeModule = new PagesAPIRouteModule({ const routeModule = new PagesAPIRouteModule({
definition: { definition: {
kind: RouteKind.PAGES_API, kind: RouteKind.PAGES_API,
page: 'VAR_DEFINITION_PAGE', page: 'VAR_DEFINITION_PAGE' as Page,
pathname: 'VAR_DEFINITION_PATHNAME', pathname: 'VAR_DEFINITION_PATHNAME' as Route,
// The following aren't used in production. // The following aren't used in production.
bundlePath: '', bundlePath: '',
filename: '', filename: '',
...@@ -58,13 +59,13 @@ export async function handler( ...@@ -58,13 +59,13 @@ export async function handler(
if (routeModule.isDev) { if (routeModule.isDev) {
addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint()) addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())
} }
let srcPage = 'VAR_DEFINITION_PAGE' let srcPage = 'VAR_DEFINITION_PAGE' as Page
// turbopack doesn't normalize `/index` in the page name // turbopack doesn't normalize `/index` in the page name
// so we need to to process dynamic routes properly // so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack // TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
srcPage = srcPage.replace(/\/index$/, '') || '/' srcPage = (srcPage.replace(/\/index$/, '') || '/') as Page
} }
const prepareResult = await routeModule.prepare(req, res, { srcPage }) const prepareResult = await routeModule.prepare(req, res, { srcPage })
...@@ -108,7 +109,7 @@ export async function handler( ...@@ -108,7 +109,7 @@ export async function handler(
previewProps, previewProps,
propagateError: false, propagateError: false,
dev: routeModule.isDev, dev: routeModule.isDev,
page: 'VAR_DEFINITION_PAGE', page: 'VAR_DEFINITION_PAGE' as Page,
internalRevalidate: routerServerContext?.revalidate, internalRevalidate: routerServerContext?.revalidate,
......
import type { Page } from '../../shared/lib/route-types'
import type { EdgeHandler } from '../../server/web/adapter' import type { EdgeHandler } from '../../server/web/adapter'
import '../../server/web/globals' import '../../server/web/globals'
...@@ -13,7 +14,7 @@ import handlerUserland from 'VAR_USERLAND' ...@@ -13,7 +14,7 @@ import handlerUserland from 'VAR_USERLAND'
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils' import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
import type { RequestMeta } from '../../server/request-meta' import type { RequestMeta } from '../../server/request-meta'
const page = 'VAR_DEFINITION_PAGE' const page = 'VAR_DEFINITION_PAGE' as Page
if (typeof handlerUserland !== 'function') { if (typeof handlerUserland !== 'function') {
throw new Error( throw new Error(
......
import type { Page, Route } from '../../shared/lib/route-types'
import { PagesRouteModule } from '../../server/route-modules/pages/module.compiled' import { PagesRouteModule } from '../../server/route-modules/pages/module.compiled'
import { RouteKind } from '../../server/route-kind' import { RouteKind } from '../../server/route-kind'
...@@ -47,8 +48,8 @@ export const unstable_getServerSideProps = hoist( ...@@ -47,8 +48,8 @@ export const unstable_getServerSideProps = hoist(
export const routeModule = new PagesRouteModule({ export const routeModule = new PagesRouteModule({
definition: { definition: {
kind: RouteKind.PAGES, kind: RouteKind.PAGES,
page: 'VAR_DEFINITION_PAGE', page: 'VAR_DEFINITION_PAGE' as Page,
pathname: 'VAR_DEFINITION_PATHNAME', pathname: 'VAR_DEFINITION_PATHNAME' as Route,
// The following aren't used in production. // The following aren't used in production.
bundlePath: '', bundlePath: '',
filename: '', filename: '',
...@@ -64,7 +65,7 @@ export const routeModule = new PagesRouteModule({ ...@@ -64,7 +65,7 @@ export const routeModule = new PagesRouteModule({
}) })
export const handler = getHandler({ export const handler = getHandler({
srcPage: 'VAR_DEFINITION_PAGE', srcPage: 'VAR_DEFINITION_PAGE' as Page,
config, config,
userland, userland,
routeModule, routeModule,
......
...@@ -18,6 +18,7 @@ import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compi ...@@ -18,6 +18,7 @@ import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compi
import { getSupportedBrowsers } from '../get-supported-browsers' import { getSupportedBrowsers } from '../get-supported-browsers'
import { printBuildErrors } from '../print-build-errors' import { printBuildErrors } from '../print-build-errors'
import { normalizePath } from '../../lib/normalize-path' import { normalizePath } from '../../lib/normalize-path'
import type { Page } from '../../shared/lib/route-types'
import type { ProjectOptions, RawEntrypoints } from '../swc/types' import type { ProjectOptions, RawEntrypoints } from '../swc/types'
import { Bundler } from '../../lib/bundler' import { Bundler } from '../../lib/bundler'
import { getStrictRouteMatchingDefaultWarning } from '../../server/lib/router-utils/strict-route-matching-config' import { getStrictRouteMatchingDefaultWarning } from '../../server/lib/router-utils/strict-route-matching-config'
...@@ -266,14 +267,14 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{ ...@@ -266,14 +267,14 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{
// Only load pages router manifests if not app-only // Only load pages router manifests if not app-only
...(!appDirOnly ...(!appDirOnly
? [ ? [
manifestLoader.loadBuildManifest('_app'), manifestLoader.loadBuildManifest('_app' as Page),
manifestLoader.loadPagesManifest('_app'), manifestLoader.loadPagesManifest('_app' as Page),
manifestLoader.loadFontManifest('_app'), manifestLoader.loadFontManifest('_app' as Page),
manifestLoader.loadPagesManifest('_document'), manifestLoader.loadPagesManifest('_document' as Page),
manifestLoader.loadClientBuildManifest('_error'), manifestLoader.loadClientBuildManifest('_error' as Page),
manifestLoader.loadBuildManifest('_error'), manifestLoader.loadBuildManifest('_error' as Page),
manifestLoader.loadPagesManifest('_error'), manifestLoader.loadPagesManifest('_error' as Page),
manifestLoader.loadFontManifest('_error'), manifestLoader.loadFontManifest('_error' as Page),
] ]
: []), : []),
entrypoints.value.instrumentation && entrypoints.value.instrumentation &&
......
This diff is collapsed.
import type { Route } from '../shared/lib/route-types'
import { import {
getParamProperties, getParamProperties,
type SegmentParam, type SegmentParam,
...@@ -58,7 +59,8 @@ function validateSegmentParam(param: SegmentParam, pathname: string): void { ...@@ -58,7 +59,8 @@ function validateSegmentParam(param: SegmentParam, pathname: string): void {
* For interception routes, validates both the intercepting and intercepted routes separately. * For interception routes, validates both the intercepting and intercepted routes separately.
* Returns the validated segment parameters. * Returns the validated segment parameters.
*/ */
function validateAppRoute(route: NormalizedAppRoute): void { // This also validates relative intercepted fragments, not only whole Routes.
function validateAppRoute(route: NormalizedAppRoute<string>): void {
// For interception routes, validate the intercepting and intercepted routes separately // For interception routes, validate the intercepting and intercepted routes separately
// This allows the same parameter name to appear in both parts // This allows the same parameter name to appear in both parts
if (isInterceptionAppRoute(route)) { if (isInterceptionAppRoute(route)) {
...@@ -141,7 +143,7 @@ function validateAppRoute(route: NormalizedAppRoute): void { ...@@ -141,7 +143,7 @@ function validateAppRoute(route: NormalizedAppRoute): void {
/** /**
* Validates a single path for internal consistency and returns its segment parameters. * Validates a single path for internal consistency and returns its segment parameters.
*/ */
function parseAndValidateAppPath(path: string): NormalizedAppRoute { function parseAndValidateAppPath(path: Route): NormalizedAppRoute {
// Fast parse the route information. We're expecting this to be a normalized // Fast parse the route information. We're expecting this to be a normalized
// route. // route.
const route = parseNormalizedAppRoute(path) const route = parseNormalizedAppRoute(path)
...@@ -200,16 +202,16 @@ function normalizeSegments( ...@@ -200,16 +202,16 @@ function normalizeSegments(
* @throws Error if validation fails * @throws Error if validation fails
*/ */
export function validateAppPaths( export function validateAppPaths(
appPaths: readonly string[] appPaths: readonly Route[]
): NormalizedAppRoute[] { ): NormalizedAppRoute[] {
// First, validate each path individually // First, validate each path individually
const paramsByPath = new Map<string, NormalizedAppRoute>() const paramsByPath = new Map<Route, NormalizedAppRoute>()
for (const path of appPaths) { for (const path of appPaths) {
paramsByPath.set(path, parseAndValidateAppPath(path)) paramsByPath.set(path, parseAndValidateAppPath(path))
} }
// Group paths by their normalized structure for ambiguity detection // Group paths by their normalized structure for ambiguity detection
const structureMap = new Map<string, string[]>() const structureMap = new Map<string, Route[]>()
for (const [path, route] of paramsByPath) { for (const [path, route] of paramsByPath) {
// Check if the last segment is an optional catch-all and check to see if // Check if the last segment is an optional catch-all and check to see if
...@@ -252,7 +254,7 @@ export function validateAppPaths( ...@@ -252,7 +254,7 @@ export function validateAppPaths(
} }
// Check for ambiguous routes (different slug names, same structure) // Check for ambiguous routes (different slug names, same structure)
const conflicts: Array<{ paths: string[]; normalizedPath: string }> = [] const conflicts: Array<{ paths: Route[]; normalizedPath: string }> = []
for (const [structure, paths] of structureMap) { for (const [structure, paths] of structureMap) {
if (paths.length > 1) { if (paths.length > 1) {
......
import type { Page, Route } from '../../../shared/lib/route-types'
import type { import type {
ProxyConfig, ProxyConfig,
ProxyMatcher, ProxyMatcher,
...@@ -6,7 +7,7 @@ import type { ...@@ -6,7 +7,7 @@ import type {
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
export type ModuleBuildInfo = { export type ModuleBuildInfo = {
nextEdgeMiddleware?: EdgeMiddlewareMeta nextEdgeMiddleware?: EdgeMiddlewareMeta<Route>
nextEdgeApiFunction?: EdgeMiddlewareMeta nextEdgeApiFunction?: EdgeMiddlewareMeta
nextEdgeSSR?: EdgeSSRMeta nextEdgeSSR?: EdgeSSRMeta
nextWasmMiddlewareBinding?: AssetBinding nextWasmMiddlewareBinding?: AssetBinding
...@@ -53,7 +54,7 @@ export interface RSCMeta { ...@@ -53,7 +54,7 @@ export interface RSCMeta {
} }
export interface RouteMeta { export interface RouteMeta {
page: string page: Page
absolutePagePath: string absolutePagePath: string
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
middlewareConfig: ProxyConfig middlewareConfig: ProxyConfig
...@@ -62,15 +63,16 @@ export interface RouteMeta { ...@@ -62,15 +63,16 @@ export interface RouteMeta {
relatedModules?: string[] relatedModules?: string[]
} }
export interface EdgeMiddlewareMeta { // Proxy entries carry a URL scope prefix; API entries carry a raw module key.
page: string export interface EdgeMiddlewareMeta<Path extends string = Page> {
page: Path
matchers?: ProxyMatcher[] matchers?: ProxyMatcher[]
} }
export interface EdgeSSRMeta { export interface EdgeSSRMeta {
isServerComponent: boolean isServerComponent: boolean
isAppDir?: boolean isAppDir?: boolean
page: string page: Page
} }
export interface AssetBinding { export interface AssetBinding {
......
import type { Page } from '../../../../shared/lib/route-types'
import path from 'path' import path from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
...@@ -23,7 +24,7 @@ export async function createAppRouteCode({ ...@@ -23,7 +24,7 @@ export async function createAppRouteCode({
}: { }: {
appDir: string appDir: string
name: string name: string
page: string page: Page
pagePath: string pagePath: string
resolveAppRoute: ( resolveAppRoute: (
pathname: string pathname: string
......
import type { Page, Route } from '../../../../shared/lib/route-types'
import type webpack from 'next/dist/compiled/webpack/webpack' import type webpack from 'next/dist/compiled/webpack/webpack'
import { import {
UNDERSCORE_GLOBAL_ERROR_ROUTE, UNDERSCORE_GLOBAL_ERROR_ROUTE,
...@@ -47,13 +48,13 @@ import { installBindings } from '../../../swc/install-bindings' ...@@ -47,13 +48,13 @@ import { installBindings } from '../../../swc/install-bindings'
export type AppLoaderOptions = { export type AppLoaderOptions = {
name: string name: string
page: string page: Page
pagePath: string pagePath: string
appDir: string appDir: string
appPaths: readonly string[] | null appPaths: readonly Page[] | Page | null
// All normalized app paths across the entire app, used for computing // Normalized URL paths across the entire app, used for computing
// static siblings for dynamic segments // static siblings for dynamic segments.
allNormalizedAppPaths: readonly string[] | null allNormalizedAppPaths: readonly Route[] | null
preferredRegion: string | string[] | undefined preferredRegion: string | string[] | undefined
pageExtensions: PageExtensions pageExtensions: PageExtensions
assetPrefix: string assetPrefix: string
...@@ -172,7 +173,7 @@ async function createTreeCodeFromPath( ...@@ -172,7 +173,7 @@ async function createTreeCodeFromPath(
isFinalRouteMatcher, isFinalRouteMatcher,
isDev, isDev,
}: { }: {
page: string page: Page
resolveDir: DirResolver resolveDir: DirResolver
resolver: PathResolver resolver: PathResolver
metadataResolver: MetadataResolver metadataResolver: MetadataResolver
...@@ -1056,7 +1057,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -1056,7 +1057,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const getStaticSiblingSegments = (segmentPath: string): string[] => { const getStaticSiblingSegments = (segmentPath: string): string[] => {
// Normalize the current path to URL space // Normalize the current path to URL space
// Add a trailing /page so normalizeAppPath strips it properly // Add a trailing /page so normalizeAppPath strips it properly
const currentUrlPath = normalizeAppPath(segmentPath + '/page') const currentUrlPath = normalizeAppPath((segmentPath + '/page') as Page)
const currentUrlSegments = currentUrlPath.split('/').filter(Boolean) const currentUrlSegments = currentUrlPath.split('/').filter(Boolean)
// If the path is empty (root level), there are no siblings // If the path is empty (root level), there are no siblings
...@@ -1083,6 +1084,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -1083,6 +1084,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
for (const appPath of allNormalizedAppPaths) { for (const appPath of allNormalizedAppPaths) {
// Normalize each path to URL space (strip route groups, parallel routes, and /page suffix) // Normalize each path to URL space (strip route groups, parallel routes, and /page suffix)
// @ts-ignore -- Human review: these keys are already Routes from appPathsPerRoute; normalizing again as raw Pages may strip a real URL /page or /route segment. Preserve sibling computation.
const urlPath = normalizeAppPath(appPath) const urlPath = normalizeAppPath(appPath)
const urlSegments = urlPath.split('/').filter(Boolean) const urlSegments = urlPath.split('/').filter(Boolean)
......
import type { Route } from '../../../shared/lib/route-types'
import { stringifyRequest } from '../stringify-request' import { stringifyRequest } from '../stringify-request'
export type ClientPagesLoaderOptions = { export type ClientPagesLoaderOptions = {
absolutePagePath: string absolutePagePath: string
page: string page: Route
} }
// this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters // this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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