Unverified Commit 44f436b9 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add initial handling for routing tests (#36635)

x-ref: https://github.com/vercel/next.js/pull/36618
parent 837e0a6a
...@@ -10,8 +10,20 @@ import fs from 'fs' ...@@ -10,8 +10,20 @@ import fs from 'fs'
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
import { posix, join } from 'path' import { posix, join } from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { API_ROUTE, DOT_NEXT_ALIAS, PAGES_DIR_ALIAS } from '../lib/constants' import {
import { EDGE_RUNTIME_WEBPACK } from '../shared/lib/constants' API_ROUTE,
DOT_NEXT_ALIAS,
PAGES_DIR_ALIAS,
ROOT_ALIAS,
ROOT_DIR_ALIAS,
} from '../lib/constants'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
EDGE_RUNTIME_WEBPACK,
} from '../shared/lib/constants'
import { MIDDLEWARE_ROUTE } from '../lib/constants' import { MIDDLEWARE_ROUTE } from '../lib/constants'
import { __ApiPreviewProps } from '../server/api-utils' import { __ApiPreviewProps } from '../server/api-utils'
import { isTargetLikeServerless } from '../server/utils' import { isTargetLikeServerless } from '../server/utils'
...@@ -28,14 +40,22 @@ type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never ...@@ -28,14 +40,22 @@ type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
* special case because it is the only page where we want to preserve the RSC * special case because it is the only page where we want to preserve the RSC
* server extension. * server extension.
*/ */
export function getPageFromPath(pagePath: string, pageExtensions: string[]) { export function getPageFromPath(
pagePath: string,
pageExtensions: string[],
isRoot?: boolean
) {
const extensions = pagePath.includes('/_app.server.') const extensions = pagePath.includes('/_app.server.')
? withoutRSCExtensions(pageExtensions) ? withoutRSCExtensions(pageExtensions)
: pageExtensions : pageExtensions
const page = normalizePathSep( let page = normalizePathSep(
pagePath.replace(new RegExp(`\\.+(${extensions.join('|')})$`), '') pagePath.replace(new RegExp(`\\.+(${extensions.join('|')})$`), '')
).replace(/\/index$/, '') )
if (!isRoot) {
page = page.replace(/\/index$/, '')
}
return page === '' ? '/' : page return page === '' ? '/' : page
} }
...@@ -43,15 +63,18 @@ export function getPageFromPath(pagePath: string, pageExtensions: string[]) { ...@@ -43,15 +63,18 @@ export function getPageFromPath(pagePath: string, pageExtensions: string[]) {
export function createPagesMapping({ export function createPagesMapping({
hasServerComponents, hasServerComponents,
isDev, isDev,
isRoot,
pageExtensions, pageExtensions,
pagePaths, pagePaths,
}: { }: {
hasServerComponents: boolean hasServerComponents: boolean
isDev: boolean isDev: boolean
isRoot?: boolean
pageExtensions: string[] pageExtensions: string[]
pagePaths: string[] pagePaths: string[]
}): { [page: string]: string } { }): { [page: string]: string } {
const previousPages: { [key: string]: string } = {} const previousPages: { [key: string]: string } = {}
const pathAlias = isRoot ? ROOT_DIR_ALIAS : PAGES_DIR_ALIAS
const pages = pagePaths.reduce<{ [key: string]: string }>( const pages = pagePaths.reduce<{ [key: string]: string }>(
(result, pagePath) => { (result, pagePath) => {
// Do not process .d.ts files inside the `pages` folder // Do not process .d.ts files inside the `pages` folder
...@@ -59,7 +82,7 @@ export function createPagesMapping({ ...@@ -59,7 +82,7 @@ export function createPagesMapping({
return result return result
} }
const pageKey = getPageFromPath(pagePath, pageExtensions) const pageKey = getPageFromPath(pagePath, pageExtensions, isRoot)
// Assume that if there's a Client Component, that there is // Assume that if there's a Client Component, that there is
// a matching Server Component that will map to the page. // a matching Server Component that will map to the page.
...@@ -80,7 +103,11 @@ export function createPagesMapping({ ...@@ -80,7 +103,11 @@ export function createPagesMapping({
previousPages[pageKey] = pagePath previousPages[pageKey] = pagePath
} }
result[pageKey] = normalizePathSep(join(PAGES_DIR_ALIAS, pagePath)) if (pageKey === 'root') {
result['root'] = normalizePathSep(join(ROOT_ALIAS, pagePath))
} else {
result[pageKey] = normalizePathSep(join(pathAlias, pagePath))
}
return result return result
}, },
{} {}
...@@ -89,6 +116,16 @@ export function createPagesMapping({ ...@@ -89,6 +116,16 @@ export function createPagesMapping({
// In development we always alias these to allow Webpack to fallback to // In development we always alias these to allow Webpack to fallback to
// the correct source file so that HMR can work properly when a file is // the correct source file so that HMR can work properly when a file is
// added or removed. // added or removed.
if (isRoot) {
if (isDev) {
pages['root'] = `${ROOT_ALIAS}/root`
} else {
pages['root'] = pages['root'] || 'next/dist/pages/root'
}
return pages
}
if (isDev) { if (isDev) {
delete pages['/_app'] delete pages['/_app']
delete pages['/_app.server'] delete pages['/_app.server']
...@@ -222,6 +259,8 @@ interface CreateEntrypointsParams { ...@@ -222,6 +259,8 @@ interface CreateEntrypointsParams {
pagesDir: string pagesDir: string
previewMode: __ApiPreviewProps previewMode: __ApiPreviewProps
target: 'server' | 'serverless' | 'experimental-serverless-trace' target: 'server' | 'serverless' | 'experimental-serverless-trace'
rootDir?: string
rootPaths?: Record<string, string>
} }
export function getEdgeServerEntry(opts: { export function getEdgeServerEntry(opts: {
...@@ -326,29 +365,45 @@ export function getClientEntry(opts: { ...@@ -326,29 +365,45 @@ export function getClientEntry(opts: {
} }
export async function createEntrypoints(params: CreateEntrypointsParams) { export async function createEntrypoints(params: CreateEntrypointsParams) {
const { config, pages, pagesDir, isDev, target } = params const { config, pages, pagesDir, isDev, target, rootDir, rootPaths } = params
const edgeServer: webpack5.EntryObject = {} const edgeServer: webpack5.EntryObject = {}
const server: webpack5.EntryObject = {} const server: webpack5.EntryObject = {}
const client: webpack5.EntryObject = {} const client: webpack5.EntryObject = {}
await Promise.all( const getEntryHandler =
Object.keys(pages).map(async (page) => { (mappings: Record<string, string>, isRoot: boolean) =>
async (page: string) => {
const bundleFile = normalizePagePath(page) const bundleFile = normalizePagePath(page)
const clientBundlePath = posix.join('pages', bundleFile) const clientBundlePath = posix.join('pages', bundleFile)
const serverBundlePath = posix.join('pages', bundleFile) const serverBundlePath = posix.join(
isRoot ? (bundleFile === '/root' ? './' : 'root') : 'pages',
bundleFile
)
// Handle paths that have aliases
const pageFilePath = (() => {
const absolutePagePath = mappings[page]
if (absolutePagePath.startsWith(PAGES_DIR_ALIAS)) {
return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir)
}
if (absolutePagePath.startsWith(ROOT_DIR_ALIAS) && rootDir) {
return absolutePagePath.replace(ROOT_DIR_ALIAS, rootDir)
}
if (absolutePagePath.startsWith(ROOT_ALIAS) && rootDir) {
return absolutePagePath.replace(ROOT_ALIAS, join(rootDir, '..'))
}
return require.resolve(absolutePagePath)
})()
runDependingOnPageType({ runDependingOnPageType({
page, page,
pageRuntime: await getPageRuntime( pageRuntime: await getPageRuntime(pageFilePath, config, isDev),
!pages[page].startsWith(PAGES_DIR_ALIAS)
? require.resolve(pages[page])
: join(pagesDir, pages[page].replace(PAGES_DIR_ALIAS, '')),
config,
isDev
),
onClient: () => { onClient: () => {
client[clientBundlePath] = getClientEntry({ client[clientBundlePath] = getClientEntry({
absolutePagePath: pages[page], absolutePagePath: mappings[page],
page, page,
}) })
}, },
...@@ -357,26 +412,31 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -357,26 +412,31 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
if (page !== '/_app' && page !== '/_document') { if (page !== '/_app' && page !== '/_document') {
server[serverBundlePath] = getServerlessEntry({ server[serverBundlePath] = getServerlessEntry({
...params, ...params,
absolutePagePath: pages[page], absolutePagePath: mappings[page],
page, page,
}) })
} }
} else { } else {
server[serverBundlePath] = [pages[page]] server[serverBundlePath] = [mappings[page]]
} }
}, },
onEdgeServer: () => { onEdgeServer: () => {
edgeServer[serverBundlePath] = getEdgeServerEntry({ edgeServer[serverBundlePath] = getEdgeServerEntry({
...params, ...params,
absolutePagePath: pages[page], absolutePagePath: mappings[page],
bundlePath: clientBundlePath, bundlePath: clientBundlePath,
isDev: false, isDev: false,
page, page,
}) })
}, },
}) })
}) }
)
if (rootDir && rootPaths) {
const entryHandler = getEntryHandler(rootPaths, true)
await Promise.all(Object.keys(rootPaths).map(entryHandler))
}
await Promise.all(Object.keys(pages).map(getEntryHandler(pages, false)))
return { return {
client, client,
...@@ -450,9 +510,10 @@ export function finalizeEntrypoint({ ...@@ -450,9 +510,10 @@ export function finalizeEntrypoint({
if ( if (
// Client special cases // Client special cases
name !== 'polyfills' && name !== 'polyfills' &&
name !== 'main' && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN &&
name !== 'amp' && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT &&
name !== 'react-refresh' name !== CLIENT_STATIC_FILES_RUNTIME_AMP &&
name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH
) { ) {
return { return {
dependOn: dependOn:
......
...@@ -114,6 +114,7 @@ import { MiddlewareManifest } from './webpack/plugins/middleware-plugin' ...@@ -114,6 +114,7 @@ import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import { recursiveCopy } from '../lib/recursive-copy' import { recursiveCopy } from '../lib/recursive-copy'
import { recursiveReadDir } from '../lib/recursive-readdir' import { recursiveReadDir } from '../lib/recursive-readdir'
import { lockfilePatchPromise, teardownTraceSubscriber } from './swc' import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
import { findPageFile } from '../server/lib/find-page-file'
export type SsgRoute = { export type SsgRoute = {
initialRevalidateSeconds: number | false initialRevalidateSeconds: number | false
...@@ -309,6 +310,26 @@ export default async function build( ...@@ -309,6 +310,26 @@ export default async function build(
new RegExp(`\\.(?:${config.pageExtensions.join('|')})$`) new RegExp(`\\.(?:${config.pageExtensions.join('|')})$`)
) )
) )
let rootPaths: string[] | undefined
if (rootDir) {
rootPaths = await nextBuildSpan
.traceChild('collect-root-paths')
.traceAsyncFn(() =>
recursiveReadDir(
rootDir,
new RegExp(`\\.(?:${config.pageExtensions.join('|')})$`)
)
)
const rootFile = await findPageFile(
path.join(rootDir, '..'),
'root',
config.pageExtensions
)
if (rootFile) rootPaths.push(rootFile)
}
// needed for static exporting since we want to replace with HTML // needed for static exporting since we want to replace with HTML
// files // files
...@@ -332,6 +353,22 @@ export default async function build( ...@@ -332,6 +353,22 @@ export default async function build(
}) })
) )
let mappedRootPaths: ReturnType<typeof createPagesMapping> | undefined
if (rootPaths && rootDir) {
mappedRootPaths = nextBuildSpan
.traceChild('create-root-mapping')
.traceFn(() =>
createPagesMapping({
pagePaths: rootPaths!,
hasServerComponents,
isDev: false,
isRoot: true,
pageExtensions: config.pageExtensions,
})
)
}
const entrypoints = await nextBuildSpan const entrypoints = await nextBuildSpan
.traceChild('create-entrypoints') .traceChild('create-entrypoints')
.traceAsyncFn(() => .traceAsyncFn(() =>
...@@ -344,6 +381,8 @@ export default async function build( ...@@ -344,6 +381,8 @@ export default async function build(
pagesDir, pagesDir,
previewMode: previewProps, previewMode: previewProps,
target, target,
rootDir,
rootPaths: mappedRootPaths,
}) })
) )
...@@ -649,6 +688,7 @@ export default async function build( ...@@ -649,6 +688,7 @@ export default async function build(
rewrites, rewrites,
runWebpackSpan, runWebpackSpan,
target, target,
rootDir,
} }
const configs = await runWebpackSpan const configs = await runWebpackSpan
......
...@@ -10,12 +10,15 @@ import { ...@@ -10,12 +10,15 @@ import {
NEXT_PROJECT_ROOT, NEXT_PROJECT_ROOT,
NEXT_PROJECT_ROOT_DIST_CLIENT, NEXT_PROJECT_ROOT_DIST_CLIENT,
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
ROOT_ALIAS,
ROOT_DIR_ALIAS,
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js' import { CustomRoutes } from '../lib/load-custom-routes.js'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK, CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
...@@ -312,6 +315,7 @@ export default async function getBaseWebpackConfig( ...@@ -312,6 +315,7 @@ export default async function getBaseWebpackConfig(
rewrites, rewrites,
runWebpackSpan, runWebpackSpan,
target = 'server', target = 'server',
rootDir,
}: { }: {
buildId: string buildId: string
config: NextConfigComplete config: NextConfigComplete
...@@ -325,6 +329,7 @@ export default async function getBaseWebpackConfig( ...@@ -325,6 +329,7 @@ export default async function getBaseWebpackConfig(
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
runWebpackSpan: Span runWebpackSpan: Span
target?: string target?: string
rootDir?: string
} }
): Promise<webpack.Configuration> { ): Promise<webpack.Configuration> {
const isClient = compilerType === 'client' const isClient = compilerType === 'client'
...@@ -537,6 +542,18 @@ export default async function getBaseWebpackConfig( ...@@ -537,6 +542,18 @@ export default async function getBaseWebpackConfig(
) )
) )
.replace(/\\/g, '/'), .replace(/\\/g, '/'),
...(config.experimental.rootDir
? {
[CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT]:
`./` +
path
.relative(
dir,
path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'root-next.js')
)
.replace(/\\/g, '/'),
}
: {}),
} as ClientEntries) } as ClientEntries)
: undefined : undefined
...@@ -559,6 +576,7 @@ export default async function getBaseWebpackConfig( ...@@ -559,6 +576,7 @@ export default async function getBaseWebpackConfig(
const customAppAliases: { [key: string]: string[] } = {} const customAppAliases: { [key: string]: string[] } = {}
const customErrorAlias: { [key: string]: string[] } = {} const customErrorAlias: { [key: string]: string[] } = {}
const customDocumentAliases: { [key: string]: string[] } = {} const customDocumentAliases: { [key: string]: string[] } = {}
const customRootAliases: { [key: string]: string[] } = {}
if (dev) { if (dev) {
customAppAliases[`${PAGES_DIR_ALIAS}/_app`] = [ customAppAliases[`${PAGES_DIR_ALIAS}/_app`] = [
...@@ -589,6 +607,16 @@ export default async function getBaseWebpackConfig( ...@@ -589,6 +607,16 @@ export default async function getBaseWebpackConfig(
}, [] as string[]), }, [] as string[]),
`next/dist/pages/_document.js`, `next/dist/pages/_document.js`,
] ]
if (config.experimental.rootDir && rootDir) {
customRootAliases[`${ROOT_ALIAS}/root`] = [
...config.pageExtensions.reduce((prev, ext) => {
prev.push(path.join(rootDir, `root.${ext}`))
return prev
}, [] as string[]),
'next/dist/pages/root.js',
]
}
} }
const resolveConfig = { const resolveConfig = {
...@@ -620,8 +648,15 @@ export default async function getBaseWebpackConfig( ...@@ -620,8 +648,15 @@ export default async function getBaseWebpackConfig(
...customAppAliases, ...customAppAliases,
...customErrorAlias, ...customErrorAlias,
...customDocumentAliases, ...customDocumentAliases,
...customRootAliases,
[PAGES_DIR_ALIAS]: pagesDir, [PAGES_DIR_ALIAS]: pagesDir,
...(rootDir
? {
[ROOT_DIR_ALIAS]: rootDir,
[ROOT_ALIAS]: path.join(rootDir, '..'),
}
: {}),
[DOT_NEXT_ALIAS]: distDir, [DOT_NEXT_ALIAS]: distDir,
...(isClient || isEdgeServer ? getOptimizedAliases() : {}), ...(isClient || isEdgeServer ? getOptimizedAliases() : {}),
...getReactProfilingInProduction(), ...getReactProfilingInProduction(),
...@@ -1523,6 +1558,7 @@ export default async function getBaseWebpackConfig( ...@@ -1523,6 +1558,7 @@ export default async function getBaseWebpackConfig(
serverless: isLikeServerless, serverless: isLikeServerless,
dev, dev,
isEdgeRuntime: isEdgeServer, isEdgeRuntime: isEdgeServer,
rootEnabled: !!config.experimental.rootDir,
}), }),
// MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_* // MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_*
// replacement is done before its process.env.* handling // replacement is done before its process.env.* handling
...@@ -1533,6 +1569,7 @@ export default async function getBaseWebpackConfig( ...@@ -1533,6 +1569,7 @@ export default async function getBaseWebpackConfig(
rewrites, rewrites,
isDevFallback, isDevFallback,
exportRuntime: hasConcurrentFeatures, exportRuntime: hasConcurrentFeatures,
rootEnabled: !!config.experimental.rootDir,
}), }),
new ProfilingPlugin({ runWebpackSpan }), new ProfilingPlugin({ runWebpackSpan }),
config.optimizeFonts && config.optimizeFonts &&
......
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
MIDDLEWARE_BUILD_MANIFEST, MIDDLEWARE_BUILD_MANIFEST,
CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_PATH,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
...@@ -95,12 +96,14 @@ export default class BuildManifestPlugin { ...@@ -95,12 +96,14 @@ export default class BuildManifestPlugin {
private rewrites: CustomRoutes['rewrites'] private rewrites: CustomRoutes['rewrites']
private isDevFallback: boolean private isDevFallback: boolean
private exportRuntime: boolean private exportRuntime: boolean
private rootEnabled: boolean
constructor(options: { constructor(options: {
buildId: string buildId: string
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
isDevFallback?: boolean isDevFallback?: boolean
exportRuntime?: boolean exportRuntime?: boolean
rootEnabled: boolean
}) { }) {
this.buildId = options.buildId this.buildId = options.buildId
this.isDevFallback = !!options.isDevFallback this.isDevFallback = !!options.isDevFallback
...@@ -109,6 +112,7 @@ export default class BuildManifestPlugin { ...@@ -109,6 +112,7 @@ export default class BuildManifestPlugin {
afterFiles: [], afterFiles: [],
fallback: [], fallback: [],
} }
this.rootEnabled = options.rootEnabled
this.rewrites.beforeFiles = options.rewrites.beforeFiles.map(processRoute) this.rewrites.beforeFiles = options.rewrites.beforeFiles.map(processRoute)
this.rewrites.afterFiles = options.rewrites.afterFiles.map(processRoute) this.rewrites.afterFiles = options.rewrites.afterFiles.map(processRoute)
this.rewrites.fallback = options.rewrites.fallback.map(processRoute) this.rewrites.fallback = options.rewrites.fallback.map(processRoute)
...@@ -127,6 +131,7 @@ export default class BuildManifestPlugin { ...@@ -127,6 +131,7 @@ export default class BuildManifestPlugin {
devFiles: [], devFiles: [],
ampDevFiles: [], ampDevFiles: [],
lowPriorityFiles: [], lowPriorityFiles: [],
rootMainFiles: [],
pages: { '/_app': [] }, pages: { '/_app': [] },
ampFirstPages: [], ampFirstPages: [],
} }
...@@ -147,6 +152,16 @@ export default class BuildManifestPlugin { ...@@ -147,6 +152,16 @@ export default class BuildManifestPlugin {
getEntrypointFiles(entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN)) getEntrypointFiles(entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN))
) )
if (this.rootEnabled) {
assetMap.rootMainFiles = [
...new Set(
getEntrypointFiles(
entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT)
)
),
]
}
const compilationAssets: { const compilationAssets: {
name: string name: string
source: typeof sources.RawSource source: typeof sources.RawSource
...@@ -178,6 +193,7 @@ export default class BuildManifestPlugin { ...@@ -178,6 +193,7 @@ export default class BuildManifestPlugin {
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
...(this.rootEnabled ? [CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT] : []),
]) ])
for (const entrypoint of compilation.entrypoints.values()) { for (const entrypoint of compilation.entrypoints.values()) {
......
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { PAGES_MANIFEST } from '../../../shared/lib/constants' import {
PAGES_MANIFEST,
ROOT_PATHS_MANIFEST,
} from '../../../shared/lib/constants'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint' import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
export type PagesManifest = { [page: string]: string } export type PagesManifest = { [page: string]: string }
let edgeServerPages = {} let edgeServerPages = {}
let nodeServerPages = {} let nodeServerPages = {}
let edgeServerRootPaths = {}
let nodeServerRootPaths = {}
// This plugin creates a pages-manifest.json from page entrypoints. // This plugin creates a pages-manifest.json from page entrypoints.
// This is used for mapping paths like `/` to `.next/server/static/<buildid>/pages/index.js` when doing SSR // This is used for mapping paths like `/` to `.next/server/static/<buildid>/pages/index.js` when doing SSR
...@@ -14,27 +20,32 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -14,27 +20,32 @@ export default class PagesManifestPlugin implements webpack.Plugin {
serverless: boolean serverless: boolean
dev: boolean dev: boolean
isEdgeRuntime: boolean isEdgeRuntime: boolean
rootEnabled: boolean
constructor({ constructor({
serverless, serverless,
dev, dev,
isEdgeRuntime, isEdgeRuntime,
rootEnabled,
}: { }: {
serverless: boolean serverless: boolean
dev: boolean dev: boolean
isEdgeRuntime: boolean isEdgeRuntime: boolean
rootEnabled: boolean
}) { }) {
this.serverless = serverless this.serverless = serverless
this.dev = dev this.dev = dev
this.isEdgeRuntime = isEdgeRuntime this.isEdgeRuntime = isEdgeRuntime
this.rootEnabled = rootEnabled
} }
createAssets(compilation: any, assets: any) { createAssets(compilation: any, assets: any) {
const entrypoints = compilation.entrypoints const entrypoints = compilation.entrypoints
const pages: PagesManifest = {} const pages: PagesManifest = {}
const rootPaths: PagesManifest = {}
for (const entrypoint of entrypoints.values()) { for (const entrypoint of entrypoints.values()) {
const pagePath = getRouteFromEntrypoint(entrypoint.name) const pagePath = getRouteFromEntrypoint(entrypoint.name, this.rootEnabled)
if (!pagePath) { if (!pagePath) {
continue continue
...@@ -54,22 +65,30 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -54,22 +65,30 @@ export default class PagesManifestPlugin implements webpack.Plugin {
continue continue
} }
// Write filename, replace any backslashes in path (on windows) with forwardslashes for cross-platform consistency. // Write filename, replace any backslashes in path (on windows) with forwardslashes for cross-platform consistency.
pages[pagePath] = files[files.length - 1] let file = files[files.length - 1]
if (!this.dev) { if (!this.dev) {
if (!this.isEdgeRuntime) { if (!this.isEdgeRuntime) {
pages[pagePath] = pages[pagePath].slice(3) file = file.slice(3)
} }
} }
pages[pagePath] = pages[pagePath].replace(/\\/g, '/') file = normalizePathSep(file)
if (entrypoint.name.startsWith('root/')) {
rootPaths[pagePath] = file
} else {
pages[pagePath] = file
}
} }
// This plugin is used by both the Node server and Edge server compilers, // This plugin is used by both the Node server and Edge server compilers,
// we need to merge both pages to generate the full manifest. // we need to merge both pages to generate the full manifest.
if (this.isEdgeRuntime) { if (this.isEdgeRuntime) {
edgeServerPages = pages edgeServerPages = pages
edgeServerRootPaths = rootPaths
} else { } else {
nodeServerPages = pages nodeServerPages = pages
nodeServerRootPaths = rootPaths
} }
assets[ assets[
...@@ -84,6 +103,21 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -84,6 +103,21 @@ export default class PagesManifestPlugin implements webpack.Plugin {
2 2
) )
) )
if (this.rootEnabled) {
assets[
`${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + ROOT_PATHS_MANIFEST
] = new sources.RawSource(
JSON.stringify(
{
...edgeServerRootPaths,
...nodeServerRootPaths,
},
null,
2
)
)
}
} }
apply(compiler: webpack.Compiler): void { apply(compiler: webpack.Compiler): void {
......
...@@ -581,6 +581,7 @@ export default async function exportApp( ...@@ -581,6 +581,7 @@ export default async function exportApp(
outDir, outDir,
pagesDataDir, pagesDataDir,
renderOpts, renderOpts,
rootDir: nextConfig.experimental.rootDir,
serverRuntimeConfig, serverRuntimeConfig,
subFolders, subFolders,
buildExport: options.buildExport, buildExport: options.buildExport,
......
...@@ -60,6 +60,7 @@ interface ExportPageInput { ...@@ -60,6 +60,7 @@ interface ExportPageInput {
parentSpanId: any parentSpanId: any
httpAgentOptions: NextConfigComplete['httpAgentOptions'] httpAgentOptions: NextConfigComplete['httpAgentOptions']
serverComponents?: boolean serverComponents?: boolean
rootDir?: boolean
} }
interface ExportPageResults { interface ExportPageResults {
...@@ -84,6 +85,7 @@ interface RenderOpts { ...@@ -84,6 +85,7 @@ interface RenderOpts {
locale?: string locale?: string
defaultLocale?: string defaultLocale?: string
trailingSlash?: boolean trailingSlash?: boolean
rootDir?: boolean
} }
type ComponentModule = ComponentType<{}> & { type ComponentModule = ComponentType<{}> & {
...@@ -97,6 +99,7 @@ export default async function exportPage({ ...@@ -97,6 +99,7 @@ export default async function exportPage({
pathMap, pathMap,
distDir, distDir,
outDir, outDir,
rootDir,
pagesDataDir, pagesDataDir,
renderOpts, renderOpts,
buildExport, buildExport,
...@@ -262,7 +265,13 @@ export default async function exportPage({ ...@@ -262,7 +265,13 @@ export default async function exportPage({
getServerSideProps, getServerSideProps,
getStaticProps, getStaticProps,
pageConfig, pageConfig,
} = await loadComponents(distDir, page, serverless, serverComponents) } = await loadComponents(
distDir,
page,
serverless,
serverComponents,
rootDir
)
const ampState = { const ampState = {
ampFirst: pageConfig?.amp === true, ampFirst: pageConfig?.amp === true,
hasQuery: Boolean(query.amp), hasQuery: Boolean(query.amp),
......
...@@ -25,6 +25,8 @@ export const MIDDLEWARE_ROUTE = /_middleware$/ ...@@ -25,6 +25,8 @@ export const MIDDLEWARE_ROUTE = /_middleware$/
// we have to use a private alias // we have to use a private alias
export const PAGES_DIR_ALIAS = 'private-next-pages' export const PAGES_DIR_ALIAS = 'private-next-pages'
export const DOT_NEXT_ALIAS = 'private-dot-next' export const DOT_NEXT_ALIAS = 'private-dot-next'
export const ROOT_DIR_ALIAS = 'private-next-root-dir'
export const ROOT_ALIAS = 'private-next-root'
export const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict` export const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`
......
import React from 'react'
export type RootProps = {
headChildren: any
bodyChildren: any
}
export default function Root({ headChildren, bodyChildren }: RootProps) {
return (
<html>
<head>
{headChildren}
<title>Test</title>
</head>
<body>{bodyChildren}</body>
</html>
)
}
...@@ -70,6 +70,7 @@ import { createHeaderRoute, createRedirectRoute } from './server-route-utils' ...@@ -70,6 +70,7 @@ import { createHeaderRoute, createRedirectRoute } from './server-route-utils'
import { PrerenderManifest } from '../build' import { PrerenderManifest } from '../build'
import { ImageConfigComplete } from '../shared/lib/image-config' import { ImageConfigComplete } from '../shared/lib/image-config'
import { replaceBasePath } from './router-utils' import { replaceBasePath } from './router-utils'
import { normalizeRootPath } from '../shared/lib/router/utils/root-paths'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -141,6 +142,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -141,6 +142,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected publicDir: string protected publicDir: string
protected hasStaticDir: boolean protected hasStaticDir: boolean
protected pagesManifest?: PagesManifest protected pagesManifest?: PagesManifest
protected rootPathsManifest?: PagesManifest
protected buildId: string protected buildId: string
protected minimalMode: boolean protected minimalMode: boolean
protected renderOpts: { protected renderOpts: {
...@@ -180,6 +182,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -180,6 +182,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
private responseCache: ResponseCache private responseCache: ResponseCache
protected router: Router protected router: Router
protected dynamicRoutes?: DynamicRoutes protected dynamicRoutes?: DynamicRoutes
protected rootPathRoutes?: Record<string, string>
protected customRoutes: CustomRoutes protected customRoutes: CustomRoutes
protected middlewareManifest?: MiddlewareManifest protected middlewareManifest?: MiddlewareManifest
protected middleware?: RoutingItem[] protected middleware?: RoutingItem[]
...@@ -190,6 +193,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -190,6 +193,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected abstract getPublicDir(): string protected abstract getPublicDir(): string
protected abstract getHasStaticDir(): boolean protected abstract getHasStaticDir(): boolean
protected abstract getPagesManifest(): PagesManifest | undefined protected abstract getPagesManifest(): PagesManifest | undefined
protected abstract getRootPathsManifest(): PagesManifest | undefined
protected abstract getBuildId(): string protected abstract getBuildId(): string
protected abstract generatePublicRoutes(): Route[] protected abstract generatePublicRoutes(): Route[]
protected abstract generateImageRoutes(): Route[] protected abstract generateImageRoutes(): Route[]
...@@ -352,6 +356,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -352,6 +356,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}) })
this.pagesManifest = this.getPagesManifest() this.pagesManifest = this.getPagesManifest()
this.rootPathsManifest = this.getRootPathsManifest()
this.middlewareManifest = this.getMiddlewareManifest() this.middlewareManifest = this.getMiddlewareManifest()
this.customRoutes = this.getCustomRoutes() this.customRoutes = this.getCustomRoutes()
...@@ -869,6 +874,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -869,6 +874,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const { useFileSystemPublicRoutes } = this.nextConfig const { useFileSystemPublicRoutes } = this.nextConfig
if (useFileSystemPublicRoutes) { if (useFileSystemPublicRoutes) {
this.rootPathRoutes = this.getRootPathRoutes()
this.dynamicRoutes = this.getDynamicRoutes() this.dynamicRoutes = this.getDynamicRoutes()
if (!this.minimalMode) { if (!this.minimalMode) {
this.middleware = this.getMiddleware() this.middleware = this.getMiddleware()
...@@ -890,6 +896,30 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -890,6 +896,30 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
} }
protected isRoutableRootPath(pathname: string): boolean {
if (this.rootPathRoutes) {
const paths = Object.keys(this.rootPathRoutes)
/**
* a root path is only routable if
* 1. has root/hello.js and no root/hello/ folder
* 2. has root/hello.js and a root/hello/index.js
*/
const hasFolderIndex = this.rootPathRoutes[`${pathname}/index`]
const hasFolder = paths.some((path) => {
return path.startsWith(`${pathname}/`)
})
if (hasFolder && hasFolderIndex) {
return true
}
if (!hasFolder && this.rootPathRoutes[pathname]) {
return true
}
}
return false
}
protected async hasPage(pathname: string): Promise<boolean> { protected async hasPage(pathname: string): Promise<boolean> {
let found = false let found = false
try { try {
...@@ -962,7 +992,10 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -962,7 +992,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const addedPages = new Set<string>() const addedPages = new Set<string>()
return getSortedRoutes( return getSortedRoutes(
Object.keys(this.pagesManifest!).map( [
...Object.keys(this.rootPathRoutes || {}),
...Object.keys(this.pagesManifest!),
].map(
(page) => (page) =>
normalizeLocalePath(page, this.nextConfig.i18n?.locales).pathname normalizeLocalePath(page, this.nextConfig.i18n?.locales).pathname
) )
...@@ -978,6 +1011,35 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -978,6 +1011,35 @@ export default abstract class Server<ServerOptions extends Options = Options> {
.filter((item): item is RoutingItem => Boolean(item)) .filter((item): item is RoutingItem => Boolean(item))
} }
protected getRootPathRoutes(): Record<string, string> {
const rootPathRoutes: Record<string, string> = {}
Object.keys(this.rootPathsManifest || {}).forEach((entry) => {
rootPathRoutes[normalizeRootPath(entry)] = entry
})
return rootPathRoutes
}
protected getRootPathLayouts(pathname: string): string[] {
const layoutPaths: string[] = []
if (this.rootPathRoutes) {
const paths = Object.values(this.rootPathRoutes)
const parts = pathname.split('/').filter(Boolean)
for (let i = 1; i < parts.length; i++) {
const parentPath = `/${parts.slice(0, i).join('/')}`
if (paths.includes(parentPath)) {
layoutPaths.push(parentPath)
}
}
// TODO: when should we bail on adding the root.js wrapper
layoutPaths.unshift('/_root')
}
return layoutPaths
}
protected async run( protected async run(
req: BaseNextRequest, req: BaseNextRequest,
res: BaseNextResponse, res: BaseNextResponse,
...@@ -1688,14 +1750,63 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1688,14 +1750,63 @@ export default abstract class Server<ServerOptions extends Options = Options> {
let page = pathname let page = pathname
const bubbleNoFallback = !!query._nextBubbleNoFallback const bubbleNoFallback = !!query._nextBubbleNoFallback
delete query._nextBubbleNoFallback delete query._nextBubbleNoFallback
// map the route to the actual bundle name e.g.
// `/dashboard/rootonly/hello` -> `/dashboard+rootonly/hello`
const getOriginalRootPath = (rootPath: string) => {
if (this.nextConfig.experimental.rootDir) {
const originalRootPath =
this.rootPathRoutes?.[`${pathname}/index`] ||
this.rootPathRoutes?.[pathname]
if (!originalRootPath) {
return null
}
const isRoutable = this.isRoutableRootPath(rootPath)
// 404 when layout is hit and this isn't a routable path
// e.g. root/hello.js with root/hello/another.js but
// no root/hello/index.js
if (!isRoutable) {
return ''
}
return originalRootPath
}
return null
}
const gatherRootLayouts = async (
rootPath: string,
result: FindComponentsResult
): Promise<void> => {
const layoutPaths = this.getRootPathLayouts(rootPath)
result.components.rootLayouts = await Promise.all(
layoutPaths.map(async (path) => {
const layoutRes = await this.findPageComponents(path)
return {
isRoot: path === '/_root',
Component: layoutRes?.components.Component!,
getStaticProps: layoutRes?.components.getStaticProps,
getServerSideProps: layoutRes?.components.getServerSideProps,
}
})
)
}
try { try {
// Ensure a request to the URL /accounts/[id] will be treated as a dynamic // Ensure a request to the URL /accounts/[id] will be treated as a dynamic
// route correctly and not loaded immediately without parsing params. // route correctly and not loaded immediately without parsing params.
if (!isDynamicRoute(pathname)) { if (!isDynamicRoute(pathname)) {
const result = await this.findPageComponents(pathname, query) const rootPath = getOriginalRootPath(pathname)
if (typeof rootPath === 'string') {
page = rootPath
}
const result = await this.findPageComponents(page, query)
if (result) { if (result) {
try { try {
if (result.components.isRootPath) {
await gatherRootLayouts(page, result)
}
return await this.renderToResponseWithComponents(ctx, result) return await this.renderToResponseWithComponents(ctx, result)
} catch (err) { } catch (err) {
const isNoFallbackError = err instanceof NoFallbackError const isNoFallbackError = err instanceof NoFallbackError
...@@ -1713,6 +1824,12 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1713,6 +1824,12 @@ export default abstract class Server<ServerOptions extends Options = Options> {
if (!params) { if (!params) {
continue continue
} }
page = dynamicRoute.page
const rootPath = getOriginalRootPath(page)
if (typeof rootPath === 'string') {
page = rootPath
}
const dynamicRouteResult = await this.findPageComponents( const dynamicRouteResult = await this.findPageComponents(
dynamicRoute.page, dynamicRoute.page,
...@@ -1721,11 +1838,13 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1721,11 +1838,13 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) )
if (dynamicRouteResult) { if (dynamicRouteResult) {
try { try {
page = dynamicRoute.page if (dynamicRouteResult.components.isRootPath) {
await gatherRootLayouts(page, dynamicRouteResult)
}
return await this.renderToResponseWithComponents( return await this.renderToResponseWithComponents(
{ {
...ctx, ...ctx,
pathname: dynamicRoute.page, pathname: page,
renderOpts: { renderOpts: {
...ctx.renderOpts, ...ctx.renderOpts,
params, params,
......
...@@ -168,6 +168,7 @@ export default class HotReloader { ...@@ -168,6 +168,7 @@ export default class HotReloader {
private fallbackWatcher: any private fallbackWatcher: any
private hotReloaderSpan: Span private hotReloaderSpan: Span
private pagesMapping: { [key: string]: string } = {} private pagesMapping: { [key: string]: string } = {}
private rootDir?: string
constructor( constructor(
dir: string, dir: string,
...@@ -178,6 +179,7 @@ export default class HotReloader { ...@@ -178,6 +179,7 @@ export default class HotReloader {
buildId, buildId,
previewProps, previewProps,
rewrites, rewrites,
rootDir,
}: { }: {
config: NextConfigComplete config: NextConfigComplete
pagesDir: string pagesDir: string
...@@ -185,12 +187,14 @@ export default class HotReloader { ...@@ -185,12 +187,14 @@ export default class HotReloader {
buildId: string buildId: string
previewProps: __ApiPreviewProps previewProps: __ApiPreviewProps
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
rootDir?: string
} }
) { ) {
this.buildId = buildId this.buildId = buildId
this.dir = dir this.dir = dir
this.middlewares = [] this.middlewares = []
this.pagesDir = pagesDir this.pagesDir = pagesDir
this.rootDir = rootDir
this.distDir = distDir this.distDir = distDir
this.clientStats = null this.clientStats = null
this.serverStats = null this.serverStats = null
...@@ -423,6 +427,7 @@ export default class HotReloader { ...@@ -423,6 +427,7 @@ export default class HotReloader {
pagesDir: this.pagesDir, pagesDir: this.pagesDir,
rewrites: this.rewrites, rewrites: this.rewrites,
runWebpackSpan: this.hotReloaderSpan, runWebpackSpan: this.hotReloaderSpan,
rootDir: this.rootDir,
} }
return webpackConfigSpan return webpackConfigSpan
...@@ -834,6 +839,7 @@ export default class HotReloader { ...@@ -834,6 +839,7 @@ export default class HotReloader {
multiCompiler, multiCompiler,
watcher: this.watcher, watcher: this.watcher,
pagesDir: this.pagesDir, pagesDir: this.pagesDir,
rootDir: this.rootDir,
nextConfig: this.config, nextConfig: this.config,
...(this.config.onDemandEntries as { ...(this.config.onDemandEntries as {
maxInactiveAge: number maxInactiveAge: number
......
...@@ -65,6 +65,8 @@ import { getMiddlewareRegex } from '../../shared/lib/router/utils/get-middleware ...@@ -65,6 +65,8 @@ import { getMiddlewareRegex } from '../../shared/lib/router/utils/get-middleware
import { isCustomErrorPage, isReservedPage } from '../../build/utils' import { isCustomErrorPage, isReservedPage } from '../../build/utils'
import { NodeNextResponse, NodeNextRequest } from '../base-http/node' import { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import { getPageRuntime, invalidatePageRuntimeCache } from '../../build/entries' import { getPageRuntime, invalidatePageRuntimeCache } from '../../build/entries'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import { normalizeRootPath } from '../../shared/lib/router/utils/root-paths'
// Load ReactDevOverlay only when needed // Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: React.FunctionComponent let ReactDevOverlayImpl: React.FunctionComponent
...@@ -96,7 +98,6 @@ export default class DevServer extends Server { ...@@ -96,7 +98,6 @@ export default class DevServer extends Server {
protected sortedRoutes?: string[] protected sortedRoutes?: string[]
private addedUpgradeListener = false private addedUpgradeListener = false
private pagesDir: string private pagesDir: string
// @ts-ignore TODO: add implementation
private rootDir?: string private rootDir?: string
protected staticPathsWorker?: { [key: string]: any } & { protected staticPathsWorker?: { [key: string]: any } & {
...@@ -264,24 +265,61 @@ export default class DevServer extends Server { ...@@ -264,24 +265,61 @@ export default class DevServer extends Server {
}) })
let wp = (this.webpackWatcher = new Watchpack()) let wp = (this.webpackWatcher = new Watchpack())
wp.watch([], [this.pagesDir], 0) const toWatch = [this.pagesDir!]
if (this.rootDir) {
toWatch.push(this.rootDir)
}
wp.watch([], toWatch, 0)
wp.on('aggregated', async () => { wp.on('aggregated', async () => {
const routedMiddleware = [] const routedMiddleware = []
const routedPages = [] const routedPages: string[] = []
const knownFiles = wp.getTimeInfoEntries() const knownFiles = wp.getTimeInfoEntries()
const rootPaths: Record<string, string> = {}
const ssrMiddleware = new Set<string>() const ssrMiddleware = new Set<string>()
for (const [fileName, { accuracy, safeTime }] of knownFiles) { for (const [fileName, { accuracy, safeTime }] of knownFiles) {
if (accuracy === undefined || !regexPageExtension.test(fileName)) { if (accuracy === undefined || !regexPageExtension.test(fileName)) {
continue continue
} }
let pageName: string = ''
let isRootPath = false
const pageName = absolutePathToPage( if (
this.pagesDir, this.rootDir &&
fileName, normalizePathSep(fileName).startsWith(
this.nextConfig.pageExtensions normalizePathSep(this.rootDir)
) )
) {
isRootPath = true
pageName = absolutePathToPage(
this.rootDir,
fileName,
this.nextConfig.pageExtensions,
false
)
} else {
pageName = absolutePathToPage(
this.pagesDir,
fileName,
this.nextConfig.pageExtensions
)
}
if (isRootPath) {
// TODO: should only routes ending in /index.js be route-able?
const originalPageName = pageName
pageName = normalizeRootPath(pageName)
rootPaths[pageName] = originalPageName
if (routedPages.includes(pageName)) {
continue
}
} else {
// /index is preserved for root folder
pageName = pageName.replace(/\/index$/, '') || '/'
}
if (regexMiddleware.test(fileName)) { if (regexMiddleware.test(fileName)) {
routedMiddleware.push( routedMiddleware.push(
...@@ -310,6 +348,7 @@ export default class DevServer extends Server { ...@@ -310,6 +348,7 @@ export default class DevServer extends Server {
routedPages.push(pageName) routedPages.push(pageName)
} }
this.rootPathRoutes = rootPaths
this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({ this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({
match: getRouteMatcher( match: getRouteMatcher(
getMiddlewareRegex(page, !ssrMiddleware.has(page)) getMiddlewareRegex(page, !ssrMiddleware.has(page))
...@@ -398,6 +437,7 @@ export default class DevServer extends Server { ...@@ -398,6 +437,7 @@ export default class DevServer extends Server {
previewProps: this.getPreviewProps(), previewProps: this.getPreviewProps(),
buildId: this.buildId, buildId: this.buildId,
rewrites, rewrites,
rootDir: this.rootDir,
}) })
await super.prepare() await super.prepare()
await this.addExportPathMapRoutes() await this.addExportPathMapRoutes()
...@@ -445,7 +485,6 @@ export default class DevServer extends Server { ...@@ -445,7 +485,6 @@ export default class DevServer extends Server {
protected async hasPage(pathname: string): Promise<boolean> { protected async hasPage(pathname: string): Promise<boolean> {
let normalizedPath: string let normalizedPath: string
try { try {
normalizedPath = normalizePagePath(pathname) normalizedPath = normalizePagePath(pathname)
} catch (err) { } catch (err) {
...@@ -456,6 +495,16 @@ export default class DevServer extends Server { ...@@ -456,6 +495,16 @@ export default class DevServer extends Server {
return false return false
} }
// check rootDir first if enabled
if (this.rootDir) {
const pageFile = await findPageFile(
this.rootDir,
normalizedPath,
this.nextConfig.pageExtensions
)
if (pageFile) return true
}
const pageFile = await findPageFile( const pageFile = await findPageFile(
this.pagesDir, this.pagesDir,
normalizedPath, normalizedPath,
...@@ -737,6 +786,10 @@ export default class DevServer extends Server { ...@@ -737,6 +786,10 @@ export default class DevServer extends Server {
return undefined return undefined
} }
protected getRootPathsManifest(): undefined {
return undefined
}
protected getMiddleware(): never[] { protected getMiddleware(): never[] {
return [] return []
} }
......
...@@ -54,6 +54,7 @@ export function onDemandEntryHandler({ ...@@ -54,6 +54,7 @@ export function onDemandEntryHandler({
nextConfig, nextConfig,
pagesBufferLength, pagesBufferLength,
pagesDir, pagesDir,
rootDir,
watcher, watcher,
}: { }: {
maxInactiveAge: number maxInactiveAge: number
...@@ -61,6 +62,7 @@ export function onDemandEntryHandler({ ...@@ -61,6 +62,7 @@ export function onDemandEntryHandler({
nextConfig: NextConfigComplete nextConfig: NextConfigComplete
pagesBufferLength: number pagesBufferLength: number
pagesDir: string pagesDir: string
rootDir?: string
watcher: any watcher: any
}) { }) {
const invalidator = new Invalidator(watcher) const invalidator = new Invalidator(watcher)
...@@ -78,13 +80,16 @@ export function onDemandEntryHandler({ ...@@ -78,13 +80,16 @@ export function onDemandEntryHandler({
function getPagePathsFromEntrypoints( function getPagePathsFromEntrypoints(
type: 'client' | 'server' | 'edge-server', type: 'client' | 'server' | 'edge-server',
entrypoints: Map<string, { name?: string }> entrypoints: Map<string, { name?: string }>,
root?: boolean
) { ) {
const pagePaths: string[] = [] const pagePaths: string[] = []
for (const entrypoint of entrypoints.values()) { for (const entrypoint of entrypoints.values()) {
const page = getRouteFromEntrypoint(entrypoint.name!) const page = getRouteFromEntrypoint(entrypoint.name!, root)
if (page) { if (page) {
pagePaths.push(`${type}${page}`) pagePaths.push(`${type}${page}`)
} else if (root && entrypoint.name === 'root') {
pagePaths.push(`${type}/${entrypoint.name}`)
} }
} }
...@@ -96,19 +101,23 @@ export function onDemandEntryHandler({ ...@@ -96,19 +101,23 @@ export function onDemandEntryHandler({
return invalidator.doneBuilding() return invalidator.doneBuilding()
} }
const [clientStats, serverStats, edgeServerStats] = multiStats.stats const [clientStats, serverStats, edgeServerStats] = multiStats.stats
const root = !!rootDir
const pagePaths = [ const pagePaths = [
...getPagePathsFromEntrypoints( ...getPagePathsFromEntrypoints(
'client', 'client',
clientStats.compilation.entrypoints clientStats.compilation.entrypoints,
root
), ),
...getPagePathsFromEntrypoints( ...getPagePathsFromEntrypoints(
'server', 'server',
serverStats.compilation.entrypoints serverStats.compilation.entrypoints,
root
), ),
...(edgeServerStats ...(edgeServerStats
? getPagePathsFromEntrypoints( ? getPagePathsFromEntrypoints(
'edge-server', 'edge-server',
edgeServerStats.compilation.entrypoints edgeServerStats.compilation.entrypoints,
root
) )
: []), : []),
] ]
...@@ -172,7 +181,8 @@ export function onDemandEntryHandler({ ...@@ -172,7 +181,8 @@ export function onDemandEntryHandler({
const pagePathData = await findPagePathData( const pagePathData = await findPagePathData(
pagesDir, pagesDir,
page, page,
nextConfig.pageExtensions nextConfig.pageExtensions,
rootDir
) )
let entryAdded = false let entryAdded = false
...@@ -329,18 +339,50 @@ class Invalidator { ...@@ -329,18 +339,50 @@ class Invalidator {
async function findPagePathData( async function findPagePathData(
pagesDir: string, pagesDir: string,
page: string, page: string,
extensions: string[] extensions: string[],
rootDir?: string
) { ) {
const normalizedPagePath = tryToNormalizePagePath(page) const normalizedPagePath = tryToNormalizePagePath(page)
const pagePath = await findPageFile(pagesDir, normalizedPagePath, extensions) let pagePath: string | null = null
let isRoot = false
const isRootFile = rootDir && normalizedPagePath === '/_root'
// check rootDir first
if (rootDir) {
pagePath = await findPageFile(
join(rootDir, isRootFile ? '..' : ''),
isRootFile ? 'root' : normalizedPagePath,
extensions
)
if (pagePath) {
isRoot = true
}
}
if (!pagePath) {
pagePath = await findPageFile(pagesDir, normalizedPagePath, extensions)
}
if (pagePath !== null) { if (pagePath !== null) {
const pageUrl = ensureLeadingSlash( const pageUrl = ensureLeadingSlash(
removePagePathTail(normalizePathSep(pagePath), extensions) removePagePathTail(normalizePathSep(pagePath), extensions, !isRoot)
) )
const bundleFile = normalizePagePath(pageUrl)
let bundlePath
let absolutePagePath
if (isRootFile) {
bundlePath = 'root'
absolutePagePath = join(rootDir!, '..', pagePath)
} else {
bundlePath = posix.join(isRoot ? 'root' : 'pages', bundleFile)
absolutePagePath = join(isRoot ? rootDir! : pagesDir, pagePath)
}
return { return {
absolutePagePath: join(pagesDir, pagePath), absolutePagePath,
bundlePath: posix.join('pages', normalizePagePath(pageUrl)), bundlePath,
page: posix.normalize(pageUrl), page: posix.normalize(pageUrl),
} }
} }
......
...@@ -6,6 +6,7 @@ export type BuildManifest = { ...@@ -6,6 +6,7 @@ export type BuildManifest = {
ampDevFiles: readonly string[] ampDevFiles: readonly string[]
polyfillFiles: readonly string[] polyfillFiles: readonly string[]
lowPriorityFiles: readonly string[] lowPriorityFiles: readonly string[]
rootMainFiles: readonly string[]
pages: { pages: {
'/_app': readonly string[] '/_app': readonly string[]
[page: string]: readonly string[] [page: string]: readonly string[]
......
...@@ -2,6 +2,8 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass ...@@ -2,6 +2,8 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass
// matches pages/:page*.js // matches pages/:page*.js
const SERVER_ROUTE_NAME_REGEX = /^pages[/\\](.*)$/ const SERVER_ROUTE_NAME_REGEX = /^pages[/\\](.*)$/
// matches root/:path*.js
const ROOT_ROUTE_NAME_REGEX = /^root[/\\](.*)$/
// matches static/pages/:page*.js // matches static/pages/:page*.js
const BROWSER_ROUTE_NAME_REGEX = /^static[/\\]pages[/\\](.*)$/ const BROWSER_ROUTE_NAME_REGEX = /^static[/\\]pages[/\\](.*)$/
...@@ -16,7 +18,8 @@ function matchBundle(regex: RegExp, input: string): string | null { ...@@ -16,7 +18,8 @@ function matchBundle(regex: RegExp, input: string): string | null {
} }
export default function getRouteFromEntrypoint( export default function getRouteFromEntrypoint(
entryFile: string entryFile: string,
root?: boolean
): string | null { ): string | null {
let pagePath = matchBundle(SERVER_ROUTE_NAME_REGEX, entryFile) let pagePath = matchBundle(SERVER_ROUTE_NAME_REGEX, entryFile)
...@@ -24,6 +27,11 @@ export default function getRouteFromEntrypoint( ...@@ -24,6 +27,11 @@ export default function getRouteFromEntrypoint(
return pagePath return pagePath
} }
if (root) {
pagePath = matchBundle(ROOT_ROUTE_NAME_REGEX, entryFile)
if (pagePath) return pagePath
}
// Potentially the passed item is a browser bundle so we try to match that also // Potentially the passed item is a browser bundle so we try to match that also
return matchBundle(BROWSER_ROUTE_NAME_REGEX, entryFile) return matchBundle(BROWSER_ROUTE_NAME_REGEX, entryFile)
} }
...@@ -20,7 +20,12 @@ export async function findPageFile( ...@@ -20,7 +20,12 @@ export async function findPageFile(
normalizedPagePath: string, normalizedPagePath: string,
pageExtensions: string[] pageExtensions: string[]
): Promise<string | null> { ): Promise<string | null> {
const pagePaths = getPagePaths(normalizedPagePath, pageExtensions) const isRootPaths = pagesDir.replace(/\\/g, '/').endsWith('/root')
const pagePaths = getPagePaths(
normalizedPagePath,
pageExtensions,
isRootPaths
)
const [existingPath, ...others] = ( const [existingPath, ...others] = (
await Promise.all( await Promise.all(
pagePaths.map(async (path) => pagePaths.map(async (path) =>
......
...@@ -9,7 +9,7 @@ import { ...@@ -9,7 +9,7 @@ import {
MIDDLEWARE_FLIGHT_MANIFEST, MIDDLEWARE_FLIGHT_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { join } from 'path' import { join } from 'path'
import { requirePage } from './require' import { requirePage, getPagePath } from './require'
import { BuildManifest } from './get-page-files' import { BuildManifest } from './get-page-files'
import { interopDefault } from '../lib/interop-default' import { interopDefault } from '../lib/interop-default'
import { import {
...@@ -40,6 +40,13 @@ export type LoadComponentsReturnType = { ...@@ -40,6 +40,13 @@ export type LoadComponentsReturnType = {
ComponentMod: any ComponentMod: any
AppMod: any AppMod: any
AppServerMod: any AppServerMod: any
isRootPath?: boolean
rootLayouts?: Array<{
isRoot?: boolean
Component: NextComponentType
getStaticProps?: GetStaticProps
getServerSideProps?: GetServerSideProps
}>
} }
export async function loadDefaultErrorComponents(distDir: string) { export async function loadDefaultErrorComponents(distDir: string) {
...@@ -67,7 +74,8 @@ export async function loadComponents( ...@@ -67,7 +74,8 @@ export async function loadComponents(
distDir: string, distDir: string,
pathname: string, pathname: string,
serverless: boolean, serverless: boolean,
serverComponents?: boolean serverComponents?: boolean,
rootEnabled?: boolean
): Promise<LoadComponentsReturnType> { ): Promise<LoadComponentsReturnType> {
if (serverless) { if (serverless) {
const ComponentMod = await requirePage(pathname, distDir, serverless) const ComponentMod = await requirePage(pathname, distDir, serverless)
...@@ -103,10 +111,12 @@ export async function loadComponents( ...@@ -103,10 +111,12 @@ export async function loadComponents(
} }
const [DocumentMod, AppMod, ComponentMod, AppServerMod] = await Promise.all([ const [DocumentMod, AppMod, ComponentMod, AppServerMod] = await Promise.all([
requirePage('/_document', distDir, serverless), requirePage('/_document', distDir, serverless, rootEnabled),
requirePage('/_app', distDir, serverless), requirePage('/_app', distDir, serverless, rootEnabled),
requirePage(pathname, distDir, serverless), requirePage(pathname, distDir, serverless, rootEnabled),
serverComponents ? requirePage('/_app.server', distDir, serverless) : null, serverComponents
? requirePage('/_app.server', distDir, serverless, rootEnabled)
: null,
]) ])
const [buildManifest, reactLoadableManifest, serverComponentManifest] = const [buildManifest, reactLoadableManifest, serverComponentManifest] =
...@@ -124,6 +134,20 @@ export async function loadComponents( ...@@ -124,6 +134,20 @@ export async function loadComponents(
const { getServerSideProps, getStaticProps, getStaticPaths } = ComponentMod const { getServerSideProps, getStaticProps, getStaticPaths } = ComponentMod
let isRootPath = false
if (rootEnabled) {
const pagePath = getPagePath(
pathname,
distDir,
serverless,
false,
undefined,
rootEnabled
)
isRootPath = !!pagePath?.match(/server[/\\]root[/\\]/)
}
return { return {
App, App,
Document, Document,
...@@ -138,5 +162,6 @@ export async function loadComponents( ...@@ -138,5 +162,6 @@ export async function loadComponents(
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
serverComponentManifest, serverComponentManifest,
isRootPath,
} }
} }
...@@ -31,6 +31,7 @@ import { ...@@ -31,6 +31,7 @@ import {
ROUTES_MANIFEST, ROUTES_MANIFEST,
MIDDLEWARE_FLIGHT_MANIFEST, MIDDLEWARE_FLIGHT_MANIFEST,
CLIENT_PUBLIC_FILES_PATH, CLIENT_PUBLIC_FILES_PATH,
ROOT_PATHS_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync' import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { format as formatUrl, UrlWithParsedQuery } from 'url' import { format as formatUrl, UrlWithParsedQuery } from 'url'
...@@ -45,6 +46,7 @@ import { getExtension, serveStatic } from './serve-static' ...@@ -45,6 +46,7 @@ import { getExtension, serveStatic } from './serve-static'
import { ParsedUrlQuery } from 'querystring' import { ParsedUrlQuery } from 'querystring'
import { apiResolver } from './api-utils/node' import { apiResolver } from './api-utils/node'
import { RenderOpts, renderToHTML } from './render' import { RenderOpts, renderToHTML } from './render'
import { renderToHTML as rootRenderToHTML } from './root-render'
import { ParsedUrl, parseUrl } from '../shared/lib/router/utils/parse-url' import { ParsedUrl, parseUrl } from '../shared/lib/router/utils/parse-url'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
...@@ -157,6 +159,16 @@ export default class NextNodeServer extends BaseServer { ...@@ -157,6 +159,16 @@ export default class NextNodeServer extends BaseServer {
return require(join(this.serverDistDir, PAGES_MANIFEST)) return require(join(this.serverDistDir, PAGES_MANIFEST))
} }
protected getRootPathsManifest(): PagesManifest | undefined {
if (this.nextConfig.experimental.rootDir) {
const rootPathsManifestPath = join(
this.serverDistDir,
ROOT_PATHS_MANIFEST
)
return require(rootPathsManifestPath)
}
}
protected getBuildId(): string { protected getBuildId(): string {
const buildIdFile = join(this.distDir, BUILD_ID_FILE) const buildIdFile = join(this.distDir, BUILD_ID_FILE)
try { try {
...@@ -572,6 +584,16 @@ export default class NextNodeServer extends BaseServer { ...@@ -572,6 +584,16 @@ export default class NextNodeServer extends BaseServer {
// https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952 // https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952
renderOpts.serverComponentManifest = this.serverComponentManifest renderOpts.serverComponentManifest = this.serverComponentManifest
if (renderOpts.isRootPath) {
return rootRenderToHTML(
req.originalRequest,
res.originalResponse,
pathname,
query,
renderOpts
)
}
return renderToHTML( return renderToHTML(
req.originalRequest, req.originalRequest,
res.originalResponse, res.originalResponse,
...@@ -619,7 +641,8 @@ export default class NextNodeServer extends BaseServer { ...@@ -619,7 +641,8 @@ export default class NextNodeServer extends BaseServer {
this.distDir, this.distDir,
this._isLikeServerless, this._isLikeServerless,
this.renderOpts.dev, this.renderOpts.dev,
locales locales,
this.nextConfig.experimental.rootDir
) )
} }
...@@ -649,7 +672,8 @@ export default class NextNodeServer extends BaseServer { ...@@ -649,7 +672,8 @@ export default class NextNodeServer extends BaseServer {
this.distDir, this.distDir,
pagePath!, pagePath!,
!this.renderOpts.dev && this._isLikeServerless, !this.renderOpts.dev && this._isLikeServerless,
this.renderOpts.serverComponents this.renderOpts.serverComponents,
this.nextConfig.experimental.rootDir
) )
if ( if (
......
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
PAGES_MANIFEST, PAGES_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
ROOT_PATHS_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
...@@ -25,12 +26,21 @@ export function getPagePath( ...@@ -25,12 +26,21 @@ export function getPagePath(
distDir: string, distDir: string,
serverless: boolean, serverless: boolean,
dev?: boolean, dev?: boolean,
locales?: string[] locales?: string[],
rootEnabled?: boolean
): string { ): string {
const serverBuildPath = join( const serverBuildPath = join(
distDir, distDir,
serverless && !dev ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY serverless && !dev ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
) )
let rootPathsManifest: undefined | PagesManifest
if (rootEnabled) {
if (page === '/_root') {
return join(serverBuildPath, 'root.js')
}
rootPathsManifest = require(join(serverBuildPath, ROOT_PATHS_MANIFEST))
}
const pagesManifest = require(join( const pagesManifest = require(join(
serverBuildPath, serverBuildPath,
PAGES_MANIFEST PAGES_MANIFEST
...@@ -42,31 +52,51 @@ export function getPagePath( ...@@ -42,31 +52,51 @@ export function getPagePath(
console.error(err) console.error(err)
throw pageNotFoundError(page) throw pageNotFoundError(page)
} }
let pagePath = pagesManifest[page]
if (!pagesManifest[page] && locales) { const checkManifest = (manifest: PagesManifest) => {
const manifestNoLocales: typeof pagesManifest = {} let curPath = manifest[page]
if (!manifest[curPath] && locales) {
const manifestNoLocales: typeof pagesManifest = {}
for (const key of Object.keys(pagesManifest)) { for (const key of Object.keys(manifest)) {
manifestNoLocales[normalizeLocalePath(key, locales).pathname] = manifestNoLocales[normalizeLocalePath(key, locales).pathname] =
pagesManifest[key] pagesManifest[key]
}
curPath = manifestNoLocales[page]
} }
pagePath = manifestNoLocales[page] return curPath
}
let pagePath: string | undefined
if (rootPathsManifest) {
pagePath = checkManifest(rootPathsManifest)
} }
if (!pagePath) { if (!pagePath) {
throw pageNotFoundError(page) pagePath = checkManifest(pagesManifest)
} }
if (!pagePath) {
throw pageNotFoundError(page)
}
return join(serverBuildPath, pagePath) return join(serverBuildPath, pagePath)
} }
export function requirePage( export function requirePage(
page: string, page: string,
distDir: string, distDir: string,
serverless: boolean serverless: boolean,
rootEnabled?: boolean
): any { ): any {
const pagePath = getPagePath(page, distDir, serverless) const pagePath = getPagePath(
page,
distDir,
serverless,
false,
undefined,
rootEnabled
)
if (pagePath.endsWith('.html')) { if (pagePath.endsWith('.html')) {
return promises.readFile(pagePath, 'utf8') return promises.readFile(pagePath, 'utf8')
} }
......
This diff is collapsed.
...@@ -103,6 +103,11 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -103,6 +103,11 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
[this.serverOptions.webServerConfig.page]: '', [this.serverOptions.webServerConfig.page]: '',
} }
} }
protected getRootPathsManifest() {
return {
[this.serverOptions.webServerConfig.page]: '',
}
}
protected getFilesystemPaths() { protected getFilesystemPaths() {
return new Set<string>() return new Set<string>()
} }
......
...@@ -4,6 +4,7 @@ export const PHASE_PRODUCTION_SERVER = 'phase-production-server' ...@@ -4,6 +4,7 @@ export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server' export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'
export const PHASE_TEST = 'phase-test' export const PHASE_TEST = 'phase-test'
export const PAGES_MANIFEST = 'pages-manifest.json' export const PAGES_MANIFEST = 'pages-manifest.json'
export const ROOT_PATHS_MANIFEST = 'root-paths-manifest.json'
export const BUILD_MANIFEST = 'build-manifest.json' export const BUILD_MANIFEST = 'build-manifest.json'
export const EXPORT_MARKER = 'export-marker.json' export const EXPORT_MARKER = 'export-marker.json'
export const EXPORT_DETAIL = 'export-detail.json' export const EXPORT_DETAIL = 'export-detail.json'
...@@ -37,6 +38,7 @@ export const MIDDLEWARE_REACT_LOADABLE_MANIFEST = ...@@ -37,6 +38,7 @@ export const MIDDLEWARE_REACT_LOADABLE_MANIFEST =
// static/runtime/main.js // static/runtime/main.js
export const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main` export const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main`
export const CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT = `${CLIENT_STATIC_FILES_RUNTIME_MAIN}-root`
// static/runtime/react-refresh.js // static/runtime/react-refresh.js
export const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `react-refresh` export const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `react-refresh`
// static/runtime/amp.js // static/runtime/amp.js
......
...@@ -88,8 +88,8 @@ function getRedirect({ ...@@ -88,8 +88,8 @@ function getRedirect({
nextConfig: { basePath?: string; i18n: I18NConfig; trailingSlash?: boolean } nextConfig: { basePath?: string; i18n: I18NConfig; trailingSlash?: boolean }
url: { hostname?: string | null; pathname: string } url: { hostname?: string | null; pathname: string }
}) { }) {
const isRootPath = denormalizePagePath(url.pathname) === '/' const isHomePage = denormalizePagePath(url.pathname) === '/'
if (nextConfig.i18n.localeDetection !== false && isRootPath) { if (nextConfig.i18n.localeDetection !== false && isHomePage) {
const preferredDomain = detectDomainLocale( const preferredDomain = detectDomainLocale(
nextConfig.i18n.domains, nextConfig.i18n.domains,
undefined, undefined,
......
...@@ -16,10 +16,12 @@ import { removePagePathTail } from './remove-page-path-tail' ...@@ -16,10 +16,12 @@ import { removePagePathTail } from './remove-page-path-tail'
export function absolutePathToPage( export function absolutePathToPage(
pagesDir: string, pagesDir: string,
pagePath: string, pagePath: string,
extensions: string[] extensions: string[],
stripIndex = true
) { ) {
return removePagePathTail( return removePagePathTail(
normalizePathSep(ensureLeadingSlash(relative(pagesDir, pagePath))), normalizePathSep(ensureLeadingSlash(relative(pagesDir, pagePath))),
extensions extensions,
stripIndex
) )
} }
...@@ -10,8 +10,23 @@ import { join } from '../isomorphic/path' ...@@ -10,8 +10,23 @@ import { join } from '../isomorphic/path'
* @param normalizedPagePath Normalized page path (it will denormalize). * @param normalizedPagePath Normalized page path (it will denormalize).
* @param extensions Allowed extensions. * @param extensions Allowed extensions.
*/ */
export function getPagePaths(normalizedPagePath: string, extensions: string[]) { export function getPagePaths(
normalizedPagePath: string,
extensions: string[],
isRoot?: boolean
) {
const page = denormalizePagePath(normalizedPagePath) const page = denormalizePagePath(normalizedPagePath)
if (isRoot) {
return flatten(
extensions.map((extension) => {
return normalizedPagePath.endsWith('/index')
? [`${page}.${extension}`, join(page, `index.${extension}`)]
: [`${page}.${extension}`]
})
)
}
return flatten( return flatten(
extensions.map((extension) => { extensions.map((extension) => {
return !normalizedPagePath.endsWith('/index') return !normalizedPagePath.endsWith('/index')
......
...@@ -10,10 +10,19 @@ import { normalizePathSep } from './normalize-path-sep' ...@@ -10,10 +10,19 @@ import { normalizePathSep } from './normalize-path-sep'
* @param pagePath A page to a page file (absolute or relative) * @param pagePath A page to a page file (absolute or relative)
* @param extensions Extensions allowed for the page. * @param extensions Extensions allowed for the page.
*/ */
export function removePagePathTail(pagePath: string, extensions: string[]) { export function removePagePathTail(
return ( pagePath: string,
normalizePathSep(pagePath) extensions: string[],
.replace(new RegExp(`\\.+(?:${extensions.join('|')})$`), '') stripIndex?: boolean
.replace(/\/index$/, '') || '/' ) {
pagePath = normalizePathSep(pagePath).replace(
new RegExp(`\\.+(?:${extensions.join('|')})$`),
''
) )
if (stripIndex) {
pagePath = pagePath.replace(/\/index$/, '') || '/'
}
return pagePath
} }
// strip `@propName` from pathname and normalize `+` to `/`
export function normalizeRootPath(pathname: string) {
let normalized = ''
pathname.split('/').forEach((segment) => {
segment.split('+').forEach((subSegment) => {
const value = subSegment.split('@').shift()
if (value) {
normalized += `/${value}`
}
})
})
return normalized
}
...@@ -1887,9 +1887,21 @@ export async function pages_document(task, opts) { ...@@ -1887,9 +1887,21 @@ export async function pages_document(task, opts) {
.target('dist/pages') .target('dist/pages')
} }
export async function pages_root(task, opts) {
await task
.source('pages/root.tsx')
.swc('server', { dev: opts.dev, keepImportAssertions: true })
}
export async function pages(task, opts) { export async function pages(task, opts) {
await task.parallel( await task.parallel(
['pages_app', 'pages_app_server', 'pages_error', 'pages_document'], [
'pages_app',
'pages_app_server',
'pages_error',
'pages_document',
'pages_root',
],
opts opts
) )
} }
......
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