Unverified Commit e8a8220d authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Tweak routing tests (#36667)

Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent da8d1984
...@@ -14,8 +14,7 @@ import { ...@@ -14,8 +14,7 @@ import {
API_ROUTE, API_ROUTE,
DOT_NEXT_ALIAS, DOT_NEXT_ALIAS,
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
ROOT_ALIAS, VIEWS_DIR_ALIAS,
ROOT_DIR_ALIAS,
} from '../lib/constants' } from '../lib/constants'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
...@@ -40,11 +39,7 @@ type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never ...@@ -40,11 +39,7 @@ 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( export function getPageFromPath(pagePath: string, pageExtensions: string[]) {
pagePath: string,
pageExtensions: string[],
isRoot?: boolean
) {
const extensions = pagePath.includes('/_app.server.') const extensions = pagePath.includes('/_app.server.')
? withoutRSCExtensions(pageExtensions) ? withoutRSCExtensions(pageExtensions)
: pageExtensions : pageExtensions
...@@ -53,9 +48,7 @@ export function getPageFromPath( ...@@ -53,9 +48,7 @@ export function getPageFromPath(
pagePath.replace(new RegExp(`\\.+(${extensions.join('|')})$`), '') pagePath.replace(new RegExp(`\\.+(${extensions.join('|')})$`), '')
) )
if (!isRoot) { page = page.replace(/\/index$/, '')
page = page.replace(/\/index$/, '')
}
return page === '' ? '/' : page return page === '' ? '/' : page
} }
...@@ -63,18 +56,18 @@ export function getPageFromPath( ...@@ -63,18 +56,18 @@ export function getPageFromPath(
export function createPagesMapping({ export function createPagesMapping({
hasServerComponents, hasServerComponents,
isDev, isDev,
isRoot, isViews,
pageExtensions, pageExtensions,
pagePaths, pagePaths,
}: { }: {
hasServerComponents: boolean hasServerComponents: boolean
isDev: boolean isDev: boolean
isRoot?: boolean isViews?: 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 pathAlias = isViews ? VIEWS_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
...@@ -82,7 +75,7 @@ export function createPagesMapping({ ...@@ -82,7 +75,7 @@ export function createPagesMapping({
return result return result
} }
const pageKey = getPageFromPath(pagePath, pageExtensions, isRoot) const pageKey = getPageFromPath(pagePath, pageExtensions)
// 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.
...@@ -103,11 +96,7 @@ export function createPagesMapping({ ...@@ -103,11 +96,7 @@ export function createPagesMapping({
previousPages[pageKey] = pagePath previousPages[pageKey] = pagePath
} }
if (pageKey === 'root') { result[pageKey] = normalizePathSep(join(pathAlias, pagePath))
result['root'] = normalizePathSep(join(ROOT_ALIAS, pagePath))
} else {
result[pageKey] = normalizePathSep(join(pathAlias, pagePath))
}
return result return result
}, },
{} {}
...@@ -117,12 +106,7 @@ export function createPagesMapping({ ...@@ -117,12 +106,7 @@ export function createPagesMapping({
// 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 (isViews) {
if (isDev) {
pages['root'] = `${ROOT_ALIAS}/root`
} else {
pages['root'] = pages['root'] || 'next/dist/pages/root'
}
return pages return pages
} }
...@@ -259,8 +243,8 @@ interface CreateEntrypointsParams { ...@@ -259,8 +243,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 viewsDir?: string
rootPaths?: Record<string, string> viewPaths?: Record<string, string>
} }
export function getEdgeServerEntry(opts: { export function getEdgeServerEntry(opts: {
...@@ -365,18 +349,18 @@ export function getClientEntry(opts: { ...@@ -365,18 +349,18 @@ export function getClientEntry(opts: {
} }
export async function createEntrypoints(params: CreateEntrypointsParams) { export async function createEntrypoints(params: CreateEntrypointsParams) {
const { config, pages, pagesDir, isDev, target, rootDir, rootPaths } = params const { config, pages, pagesDir, isDev, target, viewsDir, viewPaths } = 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 = {}
const getEntryHandler = const getEntryHandler =
(mappings: Record<string, string>, isRoot: boolean) => (mappings: Record<string, string>, isViews: boolean) =>
async (page: string) => { 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( const serverBundlePath = posix.join(
isRoot ? (bundleFile === '/root' ? './' : 'root') : 'pages', isViews ? 'views' : 'pages',
bundleFile bundleFile
) )
...@@ -387,12 +371,8 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -387,12 +371,8 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir) return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir)
} }
if (absolutePagePath.startsWith(ROOT_DIR_ALIAS) && rootDir) { if (absolutePagePath.startsWith(VIEWS_DIR_ALIAS) && viewsDir) {
return absolutePagePath.replace(ROOT_DIR_ALIAS, rootDir) return absolutePagePath.replace(VIEWS_DIR_ALIAS, viewsDir)
}
if (absolutePagePath.startsWith(ROOT_ALIAS) && rootDir) {
return absolutePagePath.replace(ROOT_ALIAS, join(rootDir, '..'))
} }
return require.resolve(absolutePagePath) return require.resolve(absolutePagePath)
...@@ -432,9 +412,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -432,9 +412,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}) })
} }
if (rootDir && rootPaths) { if (viewsDir && viewPaths) {
const entryHandler = getEntryHandler(rootPaths, true) const entryHandler = getEntryHandler(viewPaths, true)
await Promise.all(Object.keys(rootPaths).map(entryHandler)) await Promise.all(Object.keys(viewPaths).map(entryHandler))
} }
await Promise.all(Object.keys(pages).map(getEntryHandler(pages, false))) await Promise.all(Object.keys(pages).map(getEntryHandler(pages, false)))
......
...@@ -114,7 +114,6 @@ import { MiddlewareManifest } from './webpack/plugins/middleware-plugin' ...@@ -114,7 +114,6 @@ 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
...@@ -207,9 +206,9 @@ export default async function build( ...@@ -207,9 +206,9 @@ export default async function build(
setGlobal('telemetry', telemetry) setGlobal('telemetry', telemetry)
const publicDir = path.join(dir, 'public') const publicDir = path.join(dir, 'public')
const { pages: pagesDir, root: rootDir } = findPagesDir( const { pages: pagesDir, views: viewsDir } = findPagesDir(
dir, dir,
config.experimental.rootDir config.experimental.viewsDir
) )
const hasPublicDir = await fileExists(publicDir) const hasPublicDir = await fileExists(publicDir)
...@@ -245,7 +244,7 @@ export default async function build( ...@@ -245,7 +244,7 @@ export default async function build(
.traceAsyncFn(() => .traceAsyncFn(() =>
verifyTypeScriptSetup( verifyTypeScriptSetup(
dir, dir,
[pagesDir, rootDir].filter(Boolean) as string[], [pagesDir, viewsDir].filter(Boolean) as string[],
!ignoreTypeScriptErrors, !ignoreTypeScriptErrors,
config, config,
cacheDir cacheDir
...@@ -311,24 +310,17 @@ export default async function build( ...@@ -311,24 +310,17 @@ export default async function build(
) )
) )
let rootPaths: string[] | undefined let viewPaths: string[] | undefined
if (rootDir) { if (viewsDir) {
rootPaths = await nextBuildSpan viewPaths = await nextBuildSpan
.traceChild('collect-root-paths') .traceChild('collect-view-paths')
.traceAsyncFn(() => .traceAsyncFn(() =>
recursiveReadDir( recursiveReadDir(
rootDir, viewsDir,
new RegExp(`\\.(?:${config.pageExtensions.join('|')})$`) 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
...@@ -353,17 +345,17 @@ export default async function build( ...@@ -353,17 +345,17 @@ export default async function build(
}) })
) )
let mappedRootPaths: ReturnType<typeof createPagesMapping> | undefined let mappedViewPaths: ReturnType<typeof createPagesMapping> | undefined
if (rootPaths && rootDir) { if (viewPaths && viewsDir) {
mappedRootPaths = nextBuildSpan mappedViewPaths = nextBuildSpan
.traceChild('create-root-mapping') .traceChild('create-views-mapping')
.traceFn(() => .traceFn(() =>
createPagesMapping({ createPagesMapping({
pagePaths: rootPaths!, pagePaths: viewPaths!,
hasServerComponents, hasServerComponents,
isDev: false, isDev: false,
isRoot: true, isViews: true,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
}) })
) )
...@@ -381,8 +373,8 @@ export default async function build( ...@@ -381,8 +373,8 @@ export default async function build(
pagesDir, pagesDir,
previewMode: previewProps, previewMode: previewProps,
target, target,
rootDir, viewsDir,
rootPaths: mappedRootPaths, viewPaths: mappedViewPaths,
}) })
) )
...@@ -688,7 +680,7 @@ export default async function build( ...@@ -688,7 +680,7 @@ export default async function build(
rewrites, rewrites,
runWebpackSpan, runWebpackSpan,
target, target,
rootDir, viewsDir,
} }
const configs = await runWebpackSpan const configs = await runWebpackSpan
......
...@@ -10,8 +10,7 @@ import { ...@@ -10,8 +10,7 @@ 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, VIEWS_DIR_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'
...@@ -315,7 +314,7 @@ export default async function getBaseWebpackConfig( ...@@ -315,7 +314,7 @@ export default async function getBaseWebpackConfig(
rewrites, rewrites,
runWebpackSpan, runWebpackSpan,
target = 'server', target = 'server',
rootDir, viewsDir,
}: { }: {
buildId: string buildId: string
config: NextConfigComplete config: NextConfigComplete
...@@ -329,7 +328,7 @@ export default async function getBaseWebpackConfig( ...@@ -329,7 +328,7 @@ export default async function getBaseWebpackConfig(
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
runWebpackSpan: Span runWebpackSpan: Span
target?: string target?: string
rootDir?: string viewsDir?: string
} }
): Promise<webpack.Configuration> { ): Promise<webpack.Configuration> {
const isClient = compilerType === 'client' const isClient = compilerType === 'client'
...@@ -542,7 +541,7 @@ export default async function getBaseWebpackConfig( ...@@ -542,7 +541,7 @@ export default async function getBaseWebpackConfig(
) )
) )
.replace(/\\/g, '/'), .replace(/\\/g, '/'),
...(config.experimental.rootDir ...(config.experimental.viewsDir
? { ? {
[CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT]: [CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT]:
`./` + `./` +
...@@ -607,16 +606,6 @@ export default async function getBaseWebpackConfig( ...@@ -607,16 +606,6 @@ 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 = {
...@@ -651,10 +640,9 @@ export default async function getBaseWebpackConfig( ...@@ -651,10 +640,9 @@ export default async function getBaseWebpackConfig(
...customRootAliases, ...customRootAliases,
[PAGES_DIR_ALIAS]: pagesDir, [PAGES_DIR_ALIAS]: pagesDir,
...(rootDir ...(viewsDir
? { ? {
[ROOT_DIR_ALIAS]: rootDir, [VIEWS_DIR_ALIAS]: viewsDir,
[ROOT_ALIAS]: path.join(rootDir, '..'),
} }
: {}), : {}),
[DOT_NEXT_ALIAS]: distDir, [DOT_NEXT_ALIAS]: distDir,
...@@ -1190,6 +1178,7 @@ export default async function getBaseWebpackConfig( ...@@ -1190,6 +1178,7 @@ export default async function getBaseWebpackConfig(
'next-middleware-loader', 'next-middleware-loader',
'next-middleware-ssr-loader', 'next-middleware-ssr-loader',
'next-middleware-wasm-loader', 'next-middleware-wasm-loader',
'next-view-loader',
].reduce((alias, loader) => { ].reduce((alias, loader) => {
// using multiple aliases to replace `resolveLoader.modules` // using multiple aliases to replace `resolveLoader.modules`
alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader) alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader)
...@@ -1560,7 +1549,7 @@ export default async function getBaseWebpackConfig( ...@@ -1560,7 +1549,7 @@ export default async function getBaseWebpackConfig(
serverless: isLikeServerless, serverless: isLikeServerless,
dev, dev,
isEdgeRuntime: isEdgeServer, isEdgeRuntime: isEdgeServer,
rootEnabled: !!config.experimental.rootDir, rootEnabled: !!config.experimental.viewsDir,
}), }),
// 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
...@@ -1571,7 +1560,7 @@ export default async function getBaseWebpackConfig( ...@@ -1571,7 +1560,7 @@ export default async function getBaseWebpackConfig(
rewrites, rewrites,
isDevFallback, isDevFallback,
exportRuntime: hasConcurrentFeatures, exportRuntime: hasConcurrentFeatures,
rootEnabled: !!config.experimental.rootDir, rootEnabled: !!config.experimental.viewsDir,
}), }),
new ProfilingPlugin({ runWebpackSpan }), new ProfilingPlugin({ runWebpackSpan }),
config.optimizeFonts && config.optimizeFonts &&
......
import type webpack from 'webpack5'
const nextViewLoader: webpack.LoaderDefinitionFunction<{
components: string[]
}> = function nextViewLoader() {
const loaderOptions = this.getOptions() || {}
return `
export const components = {
${loaderOptions.components
.map((component) => `'${component}': () => import('${component}')`)
.join(',\n')}
}
`
}
export default nextViewLoader
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { import {
PAGES_MANIFEST, PAGES_MANIFEST,
ROOT_PATHS_MANIFEST, VIEW_PATHS_MANIFEST,
} from '../../../shared/lib/constants' } 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' import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
...@@ -74,7 +74,7 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -74,7 +74,7 @@ export default class PagesManifestPlugin implements webpack.Plugin {
} }
file = normalizePathSep(file) file = normalizePathSep(file)
if (entrypoint.name.startsWith('root/')) { if (entrypoint.name.startsWith('views/')) {
rootPaths[pagePath] = file rootPaths[pagePath] = file
} else { } else {
pages[pagePath] = file pages[pagePath] = file
...@@ -106,7 +106,7 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -106,7 +106,7 @@ export default class PagesManifestPlugin implements webpack.Plugin {
if (this.rootEnabled) { if (this.rootEnabled) {
assets[ assets[
`${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + ROOT_PATHS_MANIFEST `${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + VIEW_PATHS_MANIFEST
] = new sources.RawSource( ] = new sources.RawSource(
JSON.stringify( JSON.stringify(
{ {
......
...@@ -581,7 +581,7 @@ export default async function exportApp( ...@@ -581,7 +581,7 @@ export default async function exportApp(
outDir, outDir,
pagesDataDir, pagesDataDir,
renderOpts, renderOpts,
rootDir: nextConfig.experimental.rootDir, viewsDir: nextConfig.experimental.viewsDir,
serverRuntimeConfig, serverRuntimeConfig,
subFolders, subFolders,
buildExport: options.buildExport, buildExport: options.buildExport,
......
...@@ -60,7 +60,7 @@ interface ExportPageInput { ...@@ -60,7 +60,7 @@ interface ExportPageInput {
parentSpanId: any parentSpanId: any
httpAgentOptions: NextConfigComplete['httpAgentOptions'] httpAgentOptions: NextConfigComplete['httpAgentOptions']
serverComponents?: boolean serverComponents?: boolean
rootDir?: boolean viewsDir?: boolean
} }
interface ExportPageResults { interface ExportPageResults {
...@@ -85,7 +85,7 @@ interface RenderOpts { ...@@ -85,7 +85,7 @@ interface RenderOpts {
locale?: string locale?: string
defaultLocale?: string defaultLocale?: string
trailingSlash?: boolean trailingSlash?: boolean
rootDir?: boolean viewsDir?: boolean
} }
type ComponentModule = ComponentType<{}> & { type ComponentModule = ComponentType<{}> & {
...@@ -99,7 +99,7 @@ export default async function exportPage({ ...@@ -99,7 +99,7 @@ export default async function exportPage({
pathMap, pathMap,
distDir, distDir,
outDir, outDir,
rootDir, viewsDir,
pagesDataDir, pagesDataDir,
renderOpts, renderOpts,
buildExport, buildExport,
...@@ -270,7 +270,7 @@ export default async function exportPage({ ...@@ -270,7 +270,7 @@ export default async function exportPage({
page, page,
serverless, serverless,
serverComponents, serverComponents,
rootDir viewsDir
) )
const ampState = { const ampState = {
ampFirst: pageConfig?.amp === true, ampFirst: pageConfig?.amp === true,
......
...@@ -25,8 +25,7 @@ export const MIDDLEWARE_ROUTE = /_middleware$/ ...@@ -25,8 +25,7 @@ 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 VIEWS_DIR_ALIAS = 'private-next-views-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`
......
...@@ -10,7 +10,7 @@ export const existsSync = (f: string): boolean => { ...@@ -10,7 +10,7 @@ export const existsSync = (f: string): boolean => {
} }
} }
function findDir(dir: string, name: 'pages' | 'root'): string | null { function findDir(dir: string, name: 'pages' | 'views'): string | null {
// prioritize ./${name} over ./src/${name} // prioritize ./${name} over ./src/${name}
let curDir = path.join(dir, name) let curDir = path.join(dir, name)
if (existsSync(curDir)) return curDir if (existsSync(curDir)) return curDir
...@@ -23,13 +23,13 @@ function findDir(dir: string, name: 'pages' | 'root'): string | null { ...@@ -23,13 +23,13 @@ function findDir(dir: string, name: 'pages' | 'root'): string | null {
export function findPagesDir( export function findPagesDir(
dir: string, dir: string,
root?: boolean views?: boolean
): { pages: string; root?: string } { ): { pages: string; views?: string } {
const pagesDir = findDir(dir, 'pages') const pagesDir = findDir(dir, 'pages')
let rootDir: undefined | string let viewsDir: undefined | string
if (root) { if (views) {
rootDir = findDir(dir, 'root') || undefined viewsDir = findDir(dir, 'views') || undefined
} }
// TODO: allow "root" dir without pages dir // TODO: allow "root" dir without pages dir
...@@ -41,6 +41,6 @@ export function findPagesDir( ...@@ -41,6 +41,6 @@ export function findPagesDir(
return { return {
pages: pagesDir, pages: pagesDir,
root: rootDir, views: viewsDir,
} }
} }
import React from 'react' import React from 'react'
export type RootProps = { export type LayoutProps = {
headChildren: any headChildren: any
bodyChildren: any bodyChildren: any
} }
export default function Root({ headChildren, bodyChildren }: RootProps) { export default function ViewsLayout({
headChildren,
bodyChildren,
}: LayoutProps) {
return ( return (
<html> <html>
<head> <head>
......
...@@ -70,7 +70,7 @@ import { createHeaderRoute, createRedirectRoute } from './server-route-utils' ...@@ -70,7 +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' import { normalizeViewPath } from '../shared/lib/router/utils/view-paths'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -142,7 +142,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -142,7 +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 viewPathsManifest?: PagesManifest
protected buildId: string protected buildId: string
protected minimalMode: boolean protected minimalMode: boolean
protected renderOpts: { protected renderOpts: {
...@@ -182,7 +182,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -182,7 +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 viewPathRoutes?: Record<string, string>
protected customRoutes: CustomRoutes protected customRoutes: CustomRoutes
protected middlewareManifest?: MiddlewareManifest protected middlewareManifest?: MiddlewareManifest
protected middleware?: RoutingItem[] protected middleware?: RoutingItem[]
...@@ -193,7 +193,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -193,7 +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 getViewPathsManifest(): 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[]
...@@ -356,7 +356,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -356,7 +356,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}) })
this.pagesManifest = this.getPagesManifest() this.pagesManifest = this.getPagesManifest()
this.rootPathsManifest = this.getRootPathsManifest() this.viewPathsManifest = this.getViewPathsManifest()
this.middlewareManifest = this.getMiddlewareManifest() this.middlewareManifest = this.getMiddlewareManifest()
this.customRoutes = this.getCustomRoutes() this.customRoutes = this.getCustomRoutes()
...@@ -876,7 +876,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -876,7 +876,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.viewPathRoutes = this.getViewPathRoutes()
this.dynamicRoutes = this.getDynamicRoutes() this.dynamicRoutes = this.getDynamicRoutes()
if (!this.minimalMode) { if (!this.minimalMode) {
this.middleware = this.getMiddleware() this.middleware = this.getMiddleware()
...@@ -898,30 +898,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -898,30 +898,6 @@ 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 {
...@@ -995,7 +971,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -995,7 +971,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return getSortedRoutes( return getSortedRoutes(
[ [
...Object.keys(this.rootPathRoutes || {}), ...Object.keys(this.viewPathRoutes || {}),
...Object.keys(this.pagesManifest!), ...Object.keys(this.pagesManifest!),
].map( ].map(
(page) => (page) =>
...@@ -1013,31 +989,33 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1013,31 +989,33 @@ 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> { protected getViewPathRoutes(): Record<string, string> {
const rootPathRoutes: Record<string, string> = {} const viewPathRoutes: Record<string, string> = {}
Object.keys(this.rootPathsManifest || {}).forEach((entry) => { Object.keys(this.viewPathsManifest || {}).forEach((entry) => {
rootPathRoutes[normalizeRootPath(entry)] = entry viewPathRoutes[normalizeViewPath(entry)] = entry
}) })
return rootPathRoutes return viewPathRoutes
} }
protected getRootPathLayouts(pathname: string): string[] { protected getViewPathLayouts(pathname: string): string[] {
const layoutPaths: string[] = [] const layoutPaths: string[] = []
if (this.rootPathRoutes) { if (this.viewPathRoutes) {
const paths = Object.values(this.rootPathRoutes) const paths = Object.values(this.viewPathRoutes)
const parts = pathname.split('/').filter(Boolean) const parts = pathname.split('/').filter(Boolean)
for (let i = 1; i < parts.length; i++) { for (let i = 1; i < parts.length; i++) {
const parentPath = `/${parts.slice(0, i).join('/')}` const layoutPath = `/${parts.slice(0, i).join('/')}/layout`
if (paths.includes(parentPath)) { if (paths.includes(layoutPath)) {
layoutPaths.push(parentPath) layoutPaths.push(layoutPath)
} }
} }
// TODO: when should we bail on adding the root.js wrapper
layoutPaths.unshift('/_root') if (this.viewPathRoutes['/layout']) {
layoutPaths.unshift('/layout')
}
} }
return layoutPaths return layoutPaths
} }
...@@ -1755,38 +1733,31 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1755,38 +1733,31 @@ export default abstract class Server<ServerOptions extends Options = Options> {
delete query._nextBubbleNoFallback delete query._nextBubbleNoFallback
// map the route to the actual bundle name e.g. // map the route to the actual bundle name e.g.
// `/dashboard/rootonly/hello` -> `/dashboard+rootonly/hello` // `/dashboard/rootonly/hello` -> `/dashboard+rootonly/hello`
const getOriginalRootPath = (rootPath: string) => { const getOriginalViewPath = (viewPath: string) => {
if (this.nextConfig.experimental.rootDir) { if (this.nextConfig.experimental.viewsDir) {
const originalRootPath = const originalViewPath =
this.rootPathRoutes?.[`${pathname}/index`] || this.viewPathRoutes?.[`${viewPath}/index`] ||
this.rootPathRoutes?.[pathname] this.viewPathRoutes?.[`${viewPath}`]
if (!originalRootPath) { if (!originalViewPath) {
return null return null
} }
const isRoutable = this.isRoutableRootPath(rootPath)
// 404 when layout is hit and this isn't a routable path return originalViewPath
// e.g. root/hello.js with root/hello/another.js but
// no root/hello/index.js
if (!isRoutable) {
return ''
}
return originalRootPath
} }
return null return null
} }
const gatherRootLayouts = async ( const gatherViewLayouts = async (
rootPath: string, viewPath: string,
result: FindComponentsResult result: FindComponentsResult
): Promise<void> => { ): Promise<void> => {
const layoutPaths = this.getRootPathLayouts(rootPath) const layoutPaths = this.getViewPathLayouts(viewPath)
result.components.rootLayouts = await Promise.all( result.components.viewLayouts = await Promise.all(
layoutPaths.map(async (path) => { layoutPaths.map(async (path) => {
const layoutRes = await this.findPageComponents(path) const layoutRes = await this.findPageComponents(path)
return { return {
isRoot: path === '/_root', isRootLayout: path === '/layout',
Component: layoutRes?.components.Component!, Component: layoutRes?.components.Component!,
getStaticProps: layoutRes?.components.getStaticProps, getStaticProps: layoutRes?.components.getStaticProps,
getServerSideProps: layoutRes?.components.getServerSideProps, getServerSideProps: layoutRes?.components.getServerSideProps,
...@@ -1799,16 +1770,16 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1799,16 +1770,16 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// 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 rootPath = getOriginalRootPath(pathname) const viewPath = getOriginalViewPath(pathname)
if (typeof rootPath === 'string') { if (typeof viewPath === 'string') {
page = rootPath page = viewPath
} }
const result = await this.findPageComponents(page, query) const result = await this.findPageComponents(page, query)
if (result) { if (result) {
try { try {
if (result.components.isRootPath) { if (result.components.isViewPath) {
await gatherRootLayouts(page, result) await gatherViewLayouts(page, result)
} }
return await this.renderToResponseWithComponents(ctx, result) return await this.renderToResponseWithComponents(ctx, result)
} catch (err) { } catch (err) {
...@@ -1828,21 +1799,21 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1828,21 +1799,21 @@ export default abstract class Server<ServerOptions extends Options = Options> {
continue continue
} }
page = dynamicRoute.page page = dynamicRoute.page
const rootPath = getOriginalRootPath(page) const viewPath = getOriginalViewPath(page)
if (typeof rootPath === 'string') { if (typeof viewPath === 'string') {
page = rootPath page = viewPath
} }
const dynamicRouteResult = await this.findPageComponents( const dynamicRouteResult = await this.findPageComponents(
dynamicRoute.page, page,
query, query,
params params
) )
if (dynamicRouteResult) { if (dynamicRouteResult) {
try { try {
if (dynamicRouteResult.components.isRootPath) { if (dynamicRouteResult.components.isViewPath) {
await gatherRootLayouts(page, dynamicRouteResult) await gatherViewLayouts(page, dynamicRouteResult)
} }
return await this.renderToResponseWithComponents( return await this.renderToResponseWithComponents(
{ {
......
...@@ -96,7 +96,7 @@ export interface ExperimentalConfig { ...@@ -96,7 +96,7 @@ export interface ExperimentalConfig {
scrollRestoration?: boolean scrollRestoration?: boolean
externalDir?: boolean externalDir?: boolean
conformance?: boolean conformance?: boolean
rootDir?: boolean viewsDir?: boolean
amp?: { amp?: {
optimizer?: any optimizer?: any
validator?: string validator?: string
...@@ -494,7 +494,7 @@ export const defaultConfig: NextConfig = { ...@@ -494,7 +494,7 @@ export const defaultConfig: NextConfig = {
swcFileReading: true, swcFileReading: true,
craCompat: false, craCompat: false,
esmExternals: true, esmExternals: true,
rootDir: false, viewsDir: false,
// default to 50MB limit // default to 50MB limit
isrMemoryCacheSize: 50 * 1024 * 1024, isrMemoryCacheSize: 50 * 1024 * 1024,
serverComponents: false, serverComponents: false,
......
...@@ -168,7 +168,7 @@ export default class HotReloader { ...@@ -168,7 +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 private viewsDir?: string
constructor( constructor(
dir: string, dir: string,
...@@ -179,7 +179,7 @@ export default class HotReloader { ...@@ -179,7 +179,7 @@ export default class HotReloader {
buildId, buildId,
previewProps, previewProps,
rewrites, rewrites,
rootDir, viewsDir,
}: { }: {
config: NextConfigComplete config: NextConfigComplete
pagesDir: string pagesDir: string
...@@ -187,14 +187,14 @@ export default class HotReloader { ...@@ -187,14 +187,14 @@ export default class HotReloader {
buildId: string buildId: string
previewProps: __ApiPreviewProps previewProps: __ApiPreviewProps
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
rootDir?: string viewsDir?: 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.viewsDir = viewsDir
this.distDir = distDir this.distDir = distDir
this.clientStats = null this.clientStats = null
this.serverStats = null this.serverStats = null
...@@ -427,7 +427,7 @@ export default class HotReloader { ...@@ -427,7 +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, viewsDir: this.viewsDir,
} }
return webpackConfigSpan return webpackConfigSpan
...@@ -839,7 +839,7 @@ export default class HotReloader { ...@@ -839,7 +839,7 @@ export default class HotReloader {
multiCompiler, multiCompiler,
watcher: this.watcher, watcher: this.watcher,
pagesDir: this.pagesDir, pagesDir: this.pagesDir,
rootDir: this.rootDir, viewsDir: this.viewsDir,
nextConfig: this.config, nextConfig: this.config,
...(this.config.onDemandEntries as { ...(this.config.onDemandEntries as {
maxInactiveAge: number maxInactiveAge: number
......
...@@ -66,7 +66,7 @@ import { isCustomErrorPage, isReservedPage } from '../../build/utils' ...@@ -66,7 +66,7 @@ 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 { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import { normalizeRootPath } from '../../shared/lib/router/utils/root-paths' import { normalizeViewPath } from '../../shared/lib/router/utils/view-paths'
// Load ReactDevOverlay only when needed // Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: React.FunctionComponent let ReactDevOverlayImpl: React.FunctionComponent
...@@ -98,7 +98,7 @@ export default class DevServer extends Server { ...@@ -98,7 +98,7 @@ export default class DevServer extends Server {
protected sortedRoutes?: string[] protected sortedRoutes?: string[]
private addedUpgradeListener = false private addedUpgradeListener = false
private pagesDir: string private pagesDir: string
private rootDir?: string private viewsDir?: string
protected staticPathsWorker?: { [key: string]: any } & { protected staticPathsWorker?: { [key: string]: any } & {
loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths
...@@ -179,12 +179,12 @@ export default class DevServer extends Server { ...@@ -179,12 +179,12 @@ export default class DevServer extends Server {
this.isCustomServer = !options.isNextDevCommand this.isCustomServer = !options.isNextDevCommand
// TODO: hot-reload root/pages dirs? // TODO: hot-reload root/pages dirs?
const { pages: pagesDir, root: rootDir } = findPagesDir( const { pages: pagesDir, views: viewsDir } = findPagesDir(
this.dir, this.dir,
this.nextConfig.experimental.rootDir this.nextConfig.experimental.viewsDir
) )
this.pagesDir = pagesDir this.pagesDir = pagesDir
this.rootDir = rootDir this.viewsDir = viewsDir
} }
protected getBuildId(): string { protected getBuildId(): string {
...@@ -267,8 +267,8 @@ export default class DevServer extends Server { ...@@ -267,8 +267,8 @@ export default class DevServer extends Server {
let wp = (this.webpackWatcher = new Watchpack()) let wp = (this.webpackWatcher = new Watchpack())
const toWatch = [this.pagesDir!] const toWatch = [this.pagesDir!]
if (this.rootDir) { if (this.viewsDir) {
toWatch.push(this.rootDir) toWatch.push(this.viewsDir)
} }
wp.watch([], toWatch, 0) wp.watch([], toWatch, 0)
...@@ -276,7 +276,7 @@ export default class DevServer extends Server { ...@@ -276,7 +276,7 @@ export default class DevServer extends Server {
const routedMiddleware = [] const routedMiddleware = []
const routedPages: string[] = [] const routedPages: string[] = []
const knownFiles = wp.getTimeInfoEntries() const knownFiles = wp.getTimeInfoEntries()
const rootPaths: Record<string, string> = {} const viewPaths: 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) {
...@@ -284,17 +284,17 @@ export default class DevServer extends Server { ...@@ -284,17 +284,17 @@ export default class DevServer extends Server {
continue continue
} }
let pageName: string = '' let pageName: string = ''
let isRootPath = false let isViewPath = false
if ( if (
this.rootDir && this.viewsDir &&
normalizePathSep(fileName).startsWith( normalizePathSep(fileName).startsWith(
normalizePathSep(this.rootDir) normalizePathSep(this.viewsDir)
) )
) { ) {
isRootPath = true isViewPath = true
pageName = absolutePathToPage( pageName = absolutePathToPage(
this.rootDir, this.viewsDir,
fileName, fileName,
this.nextConfig.pageExtensions, this.nextConfig.pageExtensions,
false false
...@@ -307,11 +307,11 @@ export default class DevServer extends Server { ...@@ -307,11 +307,11 @@ export default class DevServer extends Server {
) )
} }
if (isRootPath) { if (isViewPath) {
// TODO: should only routes ending in /index.js be route-able? // TODO: should only routes ending in /index.js be route-able?
const originalPageName = pageName const originalPageName = pageName
pageName = normalizeRootPath(pageName) pageName = normalizeViewPath(pageName)
rootPaths[pageName] = originalPageName viewPaths[pageName] = originalPageName
if (routedPages.includes(pageName)) { if (routedPages.includes(pageName)) {
continue continue
...@@ -348,7 +348,7 @@ export default class DevServer extends Server { ...@@ -348,7 +348,7 @@ export default class DevServer extends Server {
routedPages.push(pageName) routedPages.push(pageName)
} }
this.rootPathRoutes = rootPaths this.viewPathRoutes = viewPaths
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))
...@@ -410,7 +410,7 @@ export default class DevServer extends Server { ...@@ -410,7 +410,7 @@ export default class DevServer extends Server {
setGlobal('phase', PHASE_DEVELOPMENT_SERVER) setGlobal('phase', PHASE_DEVELOPMENT_SERVER)
await verifyTypeScriptSetup( await verifyTypeScriptSetup(
this.dir, this.dir,
[this.pagesDir!, this.rootDir].filter(Boolean) as string[], [this.pagesDir!, this.viewsDir].filter(Boolean) as string[],
false, false,
this.nextConfig this.nextConfig
) )
...@@ -437,7 +437,7 @@ export default class DevServer extends Server { ...@@ -437,7 +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, viewsDir: this.viewsDir,
}) })
await super.prepare() await super.prepare()
await this.addExportPathMapRoutes() await this.addExportPathMapRoutes()
...@@ -495,10 +495,10 @@ export default class DevServer extends Server { ...@@ -495,10 +495,10 @@ export default class DevServer extends Server {
return false return false
} }
// check rootDir first if enabled // check viewsDir first if enabled
if (this.rootDir) { if (this.viewsDir) {
const pageFile = await findPageFile( const pageFile = await findPageFile(
this.rootDir, this.viewsDir,
normalizedPath, normalizedPath,
this.nextConfig.pageExtensions this.nextConfig.pageExtensions
) )
...@@ -786,7 +786,7 @@ export default class DevServer extends Server { ...@@ -786,7 +786,7 @@ export default class DevServer extends Server {
return undefined return undefined
} }
protected getRootPathsManifest(): undefined { protected getViewPathsManifest(): undefined {
return undefined return undefined
} }
......
...@@ -54,7 +54,7 @@ export function onDemandEntryHandler({ ...@@ -54,7 +54,7 @@ export function onDemandEntryHandler({
nextConfig, nextConfig,
pagesBufferLength, pagesBufferLength,
pagesDir, pagesDir,
rootDir, viewsDir,
watcher, watcher,
}: { }: {
maxInactiveAge: number maxInactiveAge: number
...@@ -62,7 +62,7 @@ export function onDemandEntryHandler({ ...@@ -62,7 +62,7 @@ export function onDemandEntryHandler({
nextConfig: NextConfigComplete nextConfig: NextConfigComplete
pagesBufferLength: number pagesBufferLength: number
pagesDir: string pagesDir: string
rootDir?: string viewsDir?: string
watcher: any watcher: any
}) { }) {
const invalidator = new Invalidator(watcher) const invalidator = new Invalidator(watcher)
...@@ -101,7 +101,7 @@ export function onDemandEntryHandler({ ...@@ -101,7 +101,7 @@ 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 root = !!viewsDir
const pagePaths = [ const pagePaths = [
...getPagePathsFromEntrypoints( ...getPagePathsFromEntrypoints(
'client', 'client',
...@@ -182,7 +182,7 @@ export function onDemandEntryHandler({ ...@@ -182,7 +182,7 @@ export function onDemandEntryHandler({
pagesDir, pagesDir,
page, page,
nextConfig.pageExtensions, nextConfig.pageExtensions,
rootDir viewsDir
) )
let entryAdded = false let entryAdded = false
...@@ -340,23 +340,18 @@ async function findPagePathData( ...@@ -340,23 +340,18 @@ async function findPagePathData(
pagesDir: string, pagesDir: string,
page: string, page: string,
extensions: string[], extensions: string[],
rootDir?: string viewsDir?: string
) { ) {
const normalizedPagePath = tryToNormalizePagePath(page) const normalizedPagePath = tryToNormalizePagePath(page)
let pagePath: string | null = null let pagePath: string | null = null
let isRoot = false let isView = false
const isRootFile = rootDir && normalizedPagePath === '/_root'
// check viewsDir first
// check rootDir first if (viewsDir) {
if (rootDir) { pagePath = await findPageFile(viewsDir, normalizedPagePath, extensions)
pagePath = await findPageFile(
join(rootDir, isRootFile ? '..' : ''),
isRootFile ? 'root' : normalizedPagePath,
extensions
)
if (pagePath) { if (pagePath) {
isRoot = true isView = true
} }
} }
...@@ -366,19 +361,11 @@ async function findPagePathData( ...@@ -366,19 +361,11 @@ async function findPagePathData(
if (pagePath !== null) { if (pagePath !== null) {
const pageUrl = ensureLeadingSlash( const pageUrl = ensureLeadingSlash(
removePagePathTail(normalizePathSep(pagePath), extensions, !isRoot) removePagePathTail(normalizePathSep(pagePath), extensions, !isView)
) )
const bundleFile = normalizePagePath(pageUrl) const bundleFile = normalizePagePath(pageUrl)
let bundlePath const bundlePath = posix.join(isView ? 'views' : 'pages', bundleFile)
let absolutePagePath const absolutePagePath = join(isView ? viewsDir! : pagesDir, pagePath)
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, absolutePagePath,
......
...@@ -3,7 +3,7 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass ...@@ -3,7 +3,7 @@ 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 // matches root/:path*.js
const ROOT_ROUTE_NAME_REGEX = /^root[/\\](.*)$/ const ROOT_ROUTE_NAME_REGEX = /^views[/\\](.*)$/
// matches static/pages/:page*.js // matches static/pages/:page*.js
const BROWSER_ROUTE_NAME_REGEX = /^static[/\\]pages[/\\](.*)$/ const BROWSER_ROUTE_NAME_REGEX = /^static[/\\]pages[/\\](.*)$/
......
...@@ -20,12 +20,7 @@ export async function findPageFile( ...@@ -20,12 +20,7 @@ export async function findPageFile(
normalizedPagePath: string, normalizedPagePath: string,
pageExtensions: string[] pageExtensions: string[]
): Promise<string | null> { ): Promise<string | null> {
const isRootPaths = pagesDir.replace(/\\/g, '/').endsWith('/root') const pagePaths = getPagePaths(normalizedPagePath, pageExtensions)
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) =>
......
...@@ -40,9 +40,9 @@ export type LoadComponentsReturnType = { ...@@ -40,9 +40,9 @@ export type LoadComponentsReturnType = {
ComponentMod: any ComponentMod: any
AppMod: any AppMod: any
AppServerMod: any AppServerMod: any
isRootPath?: boolean isViewPath?: boolean
rootLayouts?: Array<{ viewLayouts?: Array<{
isRoot?: boolean isRootLayout?: boolean
Component: NextComponentType Component: NextComponentType
getStaticProps?: GetStaticProps getStaticProps?: GetStaticProps
getServerSideProps?: GetServerSideProps getServerSideProps?: GetServerSideProps
...@@ -134,7 +134,7 @@ export async function loadComponents( ...@@ -134,7 +134,7 @@ export async function loadComponents(
const { getServerSideProps, getStaticProps, getStaticPaths } = ComponentMod const { getServerSideProps, getStaticProps, getStaticPaths } = ComponentMod
let isRootPath = false let isViewPath = false
if (rootEnabled) { if (rootEnabled) {
const pagePath = getPagePath( const pagePath = getPagePath(
...@@ -145,7 +145,7 @@ export async function loadComponents( ...@@ -145,7 +145,7 @@ export async function loadComponents(
undefined, undefined,
rootEnabled rootEnabled
) )
isRootPath = !!pagePath?.match(/server[/\\]root[/\\]/) isViewPath = !!pagePath?.match(/server[/\\]views[/\\]/)
} }
return { return {
...@@ -162,6 +162,6 @@ export async function loadComponents( ...@@ -162,6 +162,6 @@ export async function loadComponents(
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
serverComponentManifest, serverComponentManifest,
isRootPath, isViewPath,
} }
} }
...@@ -31,7 +31,7 @@ import { ...@@ -31,7 +31,7 @@ import {
ROUTES_MANIFEST, ROUTES_MANIFEST,
MIDDLEWARE_FLIGHT_MANIFEST, MIDDLEWARE_FLIGHT_MANIFEST,
CLIENT_PUBLIC_FILES_PATH, CLIENT_PUBLIC_FILES_PATH,
ROOT_PATHS_MANIFEST, VIEW_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'
...@@ -46,7 +46,7 @@ import { getExtension, serveStatic } from './serve-static' ...@@ -46,7 +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 { renderToHTML as viewRenderToHTML } from './view-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'
...@@ -159,13 +159,13 @@ export default class NextNodeServer extends BaseServer { ...@@ -159,13 +159,13 @@ export default class NextNodeServer extends BaseServer {
return require(join(this.serverDistDir, PAGES_MANIFEST)) return require(join(this.serverDistDir, PAGES_MANIFEST))
} }
protected getRootPathsManifest(): PagesManifest | undefined { protected getViewPathsManifest(): PagesManifest | undefined {
if (this.nextConfig.experimental.rootDir) { if (this.nextConfig.experimental.viewsDir) {
const rootPathsManifestPath = join( const viewPathsManifestPath = join(
this.serverDistDir, this.serverDistDir,
ROOT_PATHS_MANIFEST VIEW_PATHS_MANIFEST
) )
return require(rootPathsManifestPath) return require(viewPathsManifestPath)
} }
} }
...@@ -584,8 +584,8 @@ export default class NextNodeServer extends BaseServer { ...@@ -584,8 +584,8 @@ 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) { if (renderOpts.isViewPath) {
return rootRenderToHTML( return viewRenderToHTML(
req.originalRequest, req.originalRequest,
res.originalResponse, res.originalResponse,
pathname, pathname,
...@@ -642,7 +642,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -642,7 +642,7 @@ export default class NextNodeServer extends BaseServer {
this._isLikeServerless, this._isLikeServerless,
this.renderOpts.dev, this.renderOpts.dev,
locales, locales,
this.nextConfig.experimental.rootDir this.nextConfig.experimental.viewsDir
) )
} }
...@@ -673,7 +673,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -673,7 +673,7 @@ export default class NextNodeServer extends BaseServer {
pagePath!, pagePath!,
!this.renderOpts.dev && this._isLikeServerless, !this.renderOpts.dev && this._isLikeServerless,
this.renderOpts.serverComponents, this.renderOpts.serverComponents,
this.nextConfig.experimental.rootDir this.nextConfig.experimental.viewsDir
) )
if ( if (
......
...@@ -6,7 +6,7 @@ import { ...@@ -6,7 +6,7 @@ import {
PAGES_MANIFEST, PAGES_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
ROOT_PATHS_MANIFEST, VIEW_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'
...@@ -39,7 +39,7 @@ export function getPagePath( ...@@ -39,7 +39,7 @@ export function getPagePath(
if (page === '/_root') { if (page === '/_root') {
return join(serverBuildPath, 'root.js') return join(serverBuildPath, 'root.js')
} }
rootPathsManifest = require(join(serverBuildPath, ROOT_PATHS_MANIFEST)) rootPathsManifest = require(join(serverBuildPath, VIEW_PATHS_MANIFEST))
} }
const pagesManifest = require(join( const pagesManifest = require(join(
serverBuildPath, serverBuildPath,
......
...@@ -21,6 +21,7 @@ import { FlushEffectsContext } from '../shared/lib/flush-effects' ...@@ -21,6 +21,7 @@ import { FlushEffectsContext } from '../shared/lib/flush-effects'
import ReactDOMServer from 'react-dom/server.browser' import ReactDOMServer from 'react-dom/server.browser'
import { isDynamicRoute } from '../shared/lib/router/utils' import { isDynamicRoute } from '../shared/lib/router/utils'
import { tryGetPreviewData } from './api-utils/node' import { tryGetPreviewData } from './api-utils/node'
import DefaultRootLayout from '../lib/views-layout'
export type RenderOptsPartial = { export type RenderOptsPartial = {
err?: Error | null err?: Error | null
...@@ -215,7 +216,7 @@ export async function renderToHTML( ...@@ -215,7 +216,7 @@ export async function renderToHTML(
const hasConcurrentFeatures = !!runtime const hasConcurrentFeatures = !!runtime
const pageIsDynamic = isDynamicRoute(pathname) const pageIsDynamic = isDynamicRoute(pathname)
const layouts = renderOpts.rootLayouts || [] const layouts = renderOpts.viewLayouts || []
layouts.push({ layouts.push({
Component: renderOpts.Component, Component: renderOpts.Component,
...@@ -242,7 +243,7 @@ export async function renderToHTML( ...@@ -242,7 +243,7 @@ export async function renderToHTML(
const dataCacheKey = i.toString() const dataCacheKey = i.toString()
const layout = layouts[i] const layout = layouts[i]
if (layout.isRoot) { if (layout.isRootLayout) {
RootLayout = layout.Component RootLayout = layout.Component
continue continue
} }
...@@ -330,7 +331,8 @@ export async function renderToHTML( ...@@ -330,7 +331,8 @@ export async function renderToHTML(
if (!RootLayout) { if (!RootLayout) {
// TODO: fallback to our own root layout? // TODO: fallback to our own root layout?
throw new Error('invariant RootLayout not loaded') // throw new Error('invariant RootLayout not loaded')
RootLayout = DefaultRootLayout
} }
const headChildren = buildManifest.rootMainFiles.map((src) => ( const headChildren = buildManifest.rootMainFiles.map((src) => (
......
...@@ -103,7 +103,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -103,7 +103,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
[this.serverOptions.webServerConfig.page]: '', [this.serverOptions.webServerConfig.page]: '',
} }
} }
protected getRootPathsManifest() { protected getViewPathsManifest() {
return { return {
[this.serverOptions.webServerConfig.page]: '', [this.serverOptions.webServerConfig.page]: '',
} }
......
...@@ -4,7 +4,7 @@ export const PHASE_PRODUCTION_SERVER = 'phase-production-server' ...@@ -4,7 +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 VIEW_PATHS_MANIFEST = 'view-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'
......
...@@ -10,23 +10,9 @@ import { join } from '../isomorphic/path' ...@@ -10,23 +10,9 @@ 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( export function getPagePaths(normalizedPagePath: string, extensions: string[]) {
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')
......
// 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
}
// remove (name) from pathname as it's not considered for routing
export function normalizeViewPath(pathname: string) {
let normalized = ''
const segments = pathname.split('/')
segments.forEach((segment, index) => {
if (!segment) return
if (segment.startsWith('(') && segment.endsWith(')')) {
return
}
if (segment === 'page' && index === segments.length - 1) {
return
}
normalized += `/${segment}`
})
return normalized
}
...@@ -1887,21 +1887,9 @@ export async function pages_document(task, opts) { ...@@ -1887,21 +1887,9 @@ 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
) )
} }
......
export async function getServerSideProps({ params }) {
if (params.slug === 'nonexistent') {
return {
notFound: true,
}
}
return {
props: {
isUser: params.slug === 'tim',
isBoth: params.slug === 'both',
},
}
}
export default function UserOrTeam({ isUser, isBoth, user, team }) {
return (
<>
{isUser && !isBoth ? user : team}
{isBoth ? (
<>
{user}
{team}
</>
) : null}
</>
)
}
export default function TeamHomePage(props) {
return (
<>
<p>hello from team homepage</p>
</>
)
}
export default function TeamMembersPage(props) {
return (
<>
<p>hello from team/members</p>
</>
)
}
export default function UserHomePage(props) {
return (
<>
<p>hello from user homepage</p>
</>
)
}
export default function UserTeamsPage(props) {
return (
<>
<p>hello from user/teams</p>
</>
)
}
module.exports = { module.exports = {
experimental: { experimental: {
rootDir: true, viewsDir: true,
runtime: 'nodejs', runtime: 'nodejs',
reactRoot: true, reactRoot: true,
serverComponents: true, serverComponents: true,
......
...@@ -5,7 +5,11 @@ import path from 'path' ...@@ -5,7 +5,11 @@ import path from 'path'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
describe('root dir', () => { describe('views dir', () => {
if (process.env.NEXT_TEST_REACT_VERSION === '^17') {
it('should skip for react v17', () => {})
return
}
let next: NextInstance let next: NextInstance
beforeAll(async () => { beforeAll(async () => {
...@@ -13,18 +17,11 @@ describe('root dir', () => { ...@@ -13,18 +17,11 @@ describe('root dir', () => {
files: { files: {
public: new FileRef(path.join(__dirname, 'app/public')), public: new FileRef(path.join(__dirname, 'app/public')),
pages: new FileRef(path.join(__dirname, 'app/pages')), pages: new FileRef(path.join(__dirname, 'app/pages')),
root: new FileRef(path.join(__dirname, 'app/root')), views: new FileRef(path.join(__dirname, 'app/views')),
'root.server.js': new FileRef(
path.join(__dirname, 'app/root.server.js')
),
'next.config.js': new FileRef( 'next.config.js': new FileRef(
path.join(__dirname, 'app/next.config.js') path.join(__dirname, 'app/next.config.js')
), ),
}, },
dependencies: {
react: '18.0.0-rc.2',
'react-dom': '18.0.0-rc.2',
},
}) })
}) })
afterAll(() => next.destroy()) afterAll(() => next.destroy())
...@@ -60,7 +57,7 @@ describe('root dir', () => { ...@@ -60,7 +57,7 @@ describe('root dir', () => {
// TODO: why is this routable but /should-not-serve-server.server.js // TODO: why is this routable but /should-not-serve-server.server.js
it('should not include parent when not in parent directory with route in directory', async () => { it('should not include parent when not in parent directory with route in directory', async () => {
const html = await renderViaHTTP(next.url, '/dashboard/rootonly/hello') const html = await renderViaHTTP(next.url, '/dashboard/hello')
const $ = cheerio.load(html) const $ = cheerio.load(html)
// Should be nested in /root.js // Should be nested in /root.js
...@@ -131,51 +128,6 @@ describe('root dir', () => { ...@@ -131,51 +128,6 @@ describe('root dir', () => {
expect(html).toContain('hello from root/partial-match-[id]. ID is: 123') expect(html).toContain('hello from root/partial-match-[id]. ID is: 123')
}) })
// TODO: Implement
describe.skip('parallel routes', () => {
describe('conditional routes', () => {
it('should serve user page', async () => {
const html = await renderViaHTTP(next.url, '/conditional/tim')
expect(html).toContain('hello from user homepage')
})
it('should serve user teams page', async () => {
const html = await renderViaHTTP(next.url, '/conditional/tim/teams')
expect(html).toContain('hello from user/teams')
})
it('should not serve teams page to user', async () => {
const html = await renderViaHTTP(next.url, '/conditional/tim/members')
expect(html).not.toContain('hello from team/members')
})
it('should serve team page', async () => {
const html = await renderViaHTTP(next.url, '/conditional/vercel')
expect(html).toContain('hello from team homepage')
})
it('should serve team members page', async () => {
const html = await renderViaHTTP(
next.url,
'/conditional/vercel/members'
)
expect(html).toContain('hello from team/members')
})
it('should provide both matches if both paths match', async () => {
const html = await renderViaHTTP(next.url, '/conditional/both')
expect(html).toContain('hello from team homepage')
expect(html).toContain('hello from user homepage')
})
it('should 404 based on getServerSideProps', async () => {
const res = await fetchViaHTTP(next.url, '/conditional/nonexistent')
expect(res.status).toBe(404)
expect(await res.text()).toContain('This page could not be found')
})
})
})
describe('server components', () => { describe('server components', () => {
// TODO: why is this not servable but /dashboard+rootonly/hello.server.js // TODO: why is this not servable but /dashboard+rootonly/hello.server.js
// should be? Seems like they both either should be servable or not // should be? Seems like they both either should be servable or not
......
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