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