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

Rename app paths folder (#37146)

parent 1cd34dd6
...@@ -15,6 +15,9 @@ ...@@ -15,6 +15,9 @@
"dev2": "while true; do yarn --check-files && yarn dev; done", "dev2": "while true; do yarn --check-files && yarn dev; done",
"test-types": "yarn tsc", "test-types": "yarn tsc",
"test-unit": "yarn jest test/unit/", "test-unit": "yarn jest test/unit/",
"test-dev": "cross-env NEXT_TEST_MODE=dev yarn testheadless",
"test-start": "cross-env NEXT_TEST_MODE=start yarn testheadless",
"test-deploy": "cross-env NEXT_TEST_MODE=deploy yarn testheadless",
"testonly": "yarn jest --runInBand", "testonly": "yarn jest --runInBand",
"testheadless": "cross-env HEADLESS=true yarn testonly", "testheadless": "cross-env HEADLESS=true yarn testonly",
"genstats": "cross-env LOCAL_STATS=true node .github/actions/next-stats-action/src/index.js", "genstats": "cross-env LOCAL_STATS=true node .github/actions/next-stats-action/src/index.js",
......
...@@ -16,7 +16,7 @@ import { ...@@ -16,7 +16,7 @@ import {
MIDDLEWARE_FILENAME, MIDDLEWARE_FILENAME,
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
ROOT_DIR_ALIAS, ROOT_DIR_ALIAS,
VIEWS_DIR_ALIAS, APP_DIR_ALIAS,
} from '../lib/constants' } from '../lib/constants'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
...@@ -60,7 +60,7 @@ export function createPagesMapping({ ...@@ -60,7 +60,7 @@ export function createPagesMapping({
isDev: boolean isDev: boolean
pageExtensions: string[] pageExtensions: string[]
pagePaths: string[] pagePaths: string[]
pagesType: 'pages' | 'root' | 'views' pagesType: 'pages' | 'root' | 'app'
}): { [page: string]: string } { }): { [page: string]: string } {
const previousPages: { [key: string]: string } = {} const previousPages: { [key: string]: string } = {}
const pages = pagePaths.reduce<{ [key: string]: string }>( const pages = pagePaths.reduce<{ [key: string]: string }>(
...@@ -95,8 +95,8 @@ export function createPagesMapping({ ...@@ -95,8 +95,8 @@ export function createPagesMapping({
join( join(
pagesType === 'pages' pagesType === 'pages'
? PAGES_DIR_ALIAS ? PAGES_DIR_ALIAS
: pagesType === 'views' : pagesType === 'app'
? VIEWS_DIR_ALIAS ? APP_DIR_ALIAS
: ROOT_DIR_ALIAS, : ROOT_DIR_ALIAS,
pagePath pagePath
) )
...@@ -140,8 +140,8 @@ interface CreateEntrypointsParams { ...@@ -140,8 +140,8 @@ interface CreateEntrypointsParams {
rootDir: string rootDir: string
rootPaths?: Record<string, string> rootPaths?: Record<string, string>
target: 'server' | 'serverless' | 'experimental-serverless-trace' target: 'server' | 'serverless' | 'experimental-serverless-trace'
viewsDir?: string appDir?: string
viewPaths?: Record<string, string> appPaths?: Record<string, string>
pageExtensions: string[] pageExtensions: string[]
} }
...@@ -186,14 +186,14 @@ export function getEdgeServerEntry(opts: { ...@@ -186,14 +186,14 @@ export function getEdgeServerEntry(opts: {
} }
} }
export function getViewsEntry(opts: { export function getAppEntry(opts: {
name: string name: string
pagePath: string pagePath: string
viewsDir: string appDir: string
pageExtensions: string[] pageExtensions: string[]
}) { }) {
return { return {
import: `next-view-loader?${stringify(opts)}!`, import: `next-app-loader?${stringify(opts)}!`,
layer: 'sc_server', layer: 'sc_server',
} }
} }
...@@ -269,8 +269,8 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -269,8 +269,8 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
rootDir, rootDir,
rootPaths, rootPaths,
target, target,
viewsDir, appDir,
viewPaths, appPaths,
pageExtensions, pageExtensions,
} = params } = params
const edgeServer: webpack5.EntryObject = {} const edgeServer: webpack5.EntryObject = {}
...@@ -278,15 +278,15 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -278,15 +278,15 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
const client: webpack5.EntryObject = {} const client: webpack5.EntryObject = {}
const getEntryHandler = const getEntryHandler =
(mappings: Record<string, string>, pagesType: 'views' | 'pages' | 'root') => (mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') =>
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 = const serverBundlePath =
pagesType === 'pages' pagesType === 'pages'
? posix.join('pages', bundleFile) ? posix.join('pages', bundleFile)
: pagesType === 'views' : pagesType === 'app'
? posix.join('views', bundleFile) ? posix.join('app', bundleFile)
: bundleFile.slice(1) : bundleFile.slice(1)
const absolutePagePath = mappings[page] const absolutePagePath = mappings[page]
...@@ -296,8 +296,8 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -296,8 +296,8 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir) return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir)
} }
if (absolutePagePath.startsWith(VIEWS_DIR_ALIAS) && viewsDir) { if (absolutePagePath.startsWith(APP_DIR_ALIAS) && appDir) {
return absolutePagePath.replace(VIEWS_DIR_ALIAS, viewsDir) return absolutePagePath.replace(APP_DIR_ALIAS, appDir)
} }
if (absolutePagePath.startsWith(ROOT_DIR_ALIAS)) { if (absolutePagePath.startsWith(ROOT_DIR_ALIAS)) {
...@@ -344,11 +344,11 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -344,11 +344,11 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
} }
}, },
onServer: () => { onServer: () => {
if (pagesType === 'views' && viewsDir) { if (pagesType === 'app' && appDir) {
server[serverBundlePath] = getViewsEntry({ server[serverBundlePath] = getAppEntry({
name: serverBundlePath, name: serverBundlePath,
pagePath: mappings[page], pagePath: mappings[page],
viewsDir, appDir,
pageExtensions, pageExtensions,
}) })
} else if (isTargetLikeServerless(target)) { } else if (isTargetLikeServerless(target)) {
...@@ -381,9 +381,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -381,9 +381,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}) })
} }
if (viewsDir && viewPaths) { if (appDir && appPaths) {
const entryHandler = getEntryHandler(viewPaths, 'views') const entryHandler = getEntryHandler(appPaths, 'app')
await Promise.all(Object.keys(viewPaths).map(entryHandler)) await Promise.all(Object.keys(appPaths).map(entryHandler))
} }
if (rootPaths) { if (rootPaths) {
await Promise.all( await Promise.all(
......
...@@ -205,9 +205,9 @@ export default async function build( ...@@ -205,9 +205,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, views: viewsDir } = findPagesDir( const { pages: pagesDir, appDir } = findPagesDir(
dir, dir,
config.experimental.viewsDir config.experimental.appDir
) )
const hasPublicDir = await fileExists(publicDir) const hasPublicDir = await fileExists(publicDir)
...@@ -270,7 +270,7 @@ export default async function build( ...@@ -270,7 +270,7 @@ export default async function build(
nextBuildSpan.traceChild('verify-typescript-setup').traceAsyncFn(() => nextBuildSpan.traceChild('verify-typescript-setup').traceAsyncFn(() =>
verifyTypeScriptSetup( verifyTypeScriptSetup(
dir, dir,
[pagesDir, viewsDir].filter(Boolean) as string[], [pagesDir, appDir].filter(Boolean) as string[],
!ignoreTypeScriptErrors, !ignoreTypeScriptErrors,
config.typescript.tsconfigPath, config.typescript.tsconfigPath,
config.images.disableStaticImages, config.images.disableStaticImages,
...@@ -333,14 +333,14 @@ export default async function build( ...@@ -333,14 +333,14 @@ export default async function build(
) )
) )
let viewPaths: string[] | undefined let appPaths: string[] | undefined
if (viewsDir) { if (appDir) {
viewPaths = await nextBuildSpan appPaths = await nextBuildSpan
.traceChild('collect-view-paths') .traceChild('collect-app-paths')
.traceAsyncFn(() => .traceAsyncFn(() =>
recursiveReadDir( recursiveReadDir(
viewsDir, appDir,
new RegExp(`page\\.(?:${config.pageExtensions.join('|')})$`) new RegExp(`page\\.(?:${config.pageExtensions.join('|')})$`)
) )
) )
...@@ -377,17 +377,17 @@ export default async function build( ...@@ -377,17 +377,17 @@ export default async function build(
}) })
) )
let mappedViewPaths: { [page: string]: string } | undefined let mappedappPaths: { [page: string]: string } | undefined
if (viewPaths && viewsDir) { if (appPaths && appDir) {
mappedViewPaths = nextBuildSpan mappedappPaths = nextBuildSpan
.traceChild('create-views-mapping') .traceChild('create-app-mapping')
.traceFn(() => .traceFn(() =>
createPagesMapping({ createPagesMapping({
pagePaths: viewPaths!, pagePaths: appPaths!,
hasServerComponents, hasServerComponents,
isDev: false, isDev: false,
pagesType: 'views', pagesType: 'app',
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
}) })
) )
...@@ -418,8 +418,8 @@ export default async function build( ...@@ -418,8 +418,8 @@ export default async function build(
target, target,
rootDir: dir, rootDir: dir,
rootPaths: mappedRootPaths, rootPaths: mappedRootPaths,
viewsDir, appDir,
viewPaths: mappedViewPaths, appPaths: mappedappPaths,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
}) })
) )
...@@ -719,7 +719,7 @@ export default async function build( ...@@ -719,7 +719,7 @@ export default async function build(
rewrites, rewrites,
runWebpackSpan, runWebpackSpan,
target, target,
viewsDir, appDir,
} }
const configs = await runWebpackSpan const configs = await runWebpackSpan
......
...@@ -11,7 +11,7 @@ import { ...@@ -11,7 +11,7 @@ import {
NEXT_PROJECT_ROOT_DIST_CLIENT, NEXT_PROJECT_ROOT_DIST_CLIENT,
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
ROOT_DIR_ALIAS, ROOT_DIR_ALIAS,
VIEWS_DIR_ALIAS, APP_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'
...@@ -333,7 +333,7 @@ export default async function getBaseWebpackConfig( ...@@ -333,7 +333,7 @@ export default async function getBaseWebpackConfig(
rewrites, rewrites,
runWebpackSpan, runWebpackSpan,
target = 'server', target = 'server',
viewsDir, appDir,
}: { }: {
buildId: string buildId: string
config: NextConfigComplete config: NextConfigComplete
...@@ -347,7 +347,7 @@ export default async function getBaseWebpackConfig( ...@@ -347,7 +347,7 @@ export default async function getBaseWebpackConfig(
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
runWebpackSpan: Span runWebpackSpan: Span
target?: string target?: string
viewsDir?: string appDir?: string
} }
): Promise<webpack.Configuration> { ): Promise<webpack.Configuration> {
const isClient = compilerType === 'client' const isClient = compilerType === 'client'
...@@ -569,14 +569,14 @@ export default async function getBaseWebpackConfig( ...@@ -569,14 +569,14 @@ export default async function getBaseWebpackConfig(
) )
) )
.replace(/\\/g, '/'), .replace(/\\/g, '/'),
...(config.experimental.viewsDir ...(config.experimental.appDir
? { ? {
[CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT]: [CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT]:
`./` + `./` +
path path
.relative( .relative(
dir, dir,
path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'views-next.js') path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'app-next.js')
) )
.replace(/\\/g, '/'), .replace(/\\/g, '/'),
} }
...@@ -661,9 +661,9 @@ export default async function getBaseWebpackConfig( ...@@ -661,9 +661,9 @@ export default async function getBaseWebpackConfig(
...customRootAliases, ...customRootAliases,
[PAGES_DIR_ALIAS]: pagesDir, [PAGES_DIR_ALIAS]: pagesDir,
...(viewsDir ...(appDir
? { ? {
[VIEWS_DIR_ALIAS]: viewsDir, [APP_DIR_ALIAS]: appDir,
} }
: {}), : {}),
[ROOT_DIR_ALIAS]: dir, [ROOT_DIR_ALIAS]: dir,
...@@ -1183,7 +1183,7 @@ export default async function getBaseWebpackConfig( ...@@ -1183,7 +1183,7 @@ export default async function getBaseWebpackConfig(
? `[name].js` ? `[name].js`
: `../[name].js` : `../[name].js`
: `static/chunks/${isDevFallback ? 'fallback/' : ''}[name]${ : `static/chunks/${isDevFallback ? 'fallback/' : ''}[name]${
dev ? '' : viewsDir ? '-[chunkhash]' : '-[contenthash]' dev ? '' : appDir ? '-[chunkhash]' : '-[contenthash]'
}.js`, }.js`,
library: isClient || isEdgeServer ? '_N_E' : undefined, library: isClient || isEdgeServer ? '_N_E' : undefined,
libraryTarget: isClient || isEdgeServer ? 'assign' : 'commonjs2', libraryTarget: isClient || isEdgeServer ? 'assign' : 'commonjs2',
...@@ -1221,7 +1221,7 @@ export default async function getBaseWebpackConfig( ...@@ -1221,7 +1221,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', 'next-app-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)
...@@ -1602,7 +1602,7 @@ export default async function getBaseWebpackConfig( ...@@ -1602,7 +1602,7 @@ export default async function getBaseWebpackConfig(
serverless: isLikeServerless, serverless: isLikeServerless,
dev, dev,
isEdgeRuntime: isEdgeServer, isEdgeRuntime: isEdgeServer,
rootEnabled: !!config.experimental.viewsDir, appDirEnabled: !!config.experimental.appDir,
}), }),
// 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
...@@ -1613,7 +1613,7 @@ export default async function getBaseWebpackConfig( ...@@ -1613,7 +1613,7 @@ export default async function getBaseWebpackConfig(
rewrites, rewrites,
isDevFallback, isDevFallback,
exportRuntime: hasConcurrentFeatures, exportRuntime: hasConcurrentFeatures,
rootEnabled: !!config.experimental.viewsDir, appDirEnabled: !!config.experimental.appDir,
}), }),
new ProfilingPlugin({ runWebpackSpan }), new ProfilingPlugin({ runWebpackSpan }),
config.optimizeFonts && config.optimizeFonts &&
...@@ -1645,7 +1645,7 @@ export default async function getBaseWebpackConfig( ...@@ -1645,7 +1645,7 @@ export default async function getBaseWebpackConfig(
(isClient (isClient
? new FlightManifestPlugin({ ? new FlightManifestPlugin({
dev, dev,
viewsDir: !!config.experimental.viewsDir, appDir: !!config.experimental.appDir,
pageExtensions: rawPageExtensions, pageExtensions: rawPageExtensions,
}) })
: new ClientEntryPlugin({ : new ClientEntryPlugin({
......
...@@ -4,9 +4,9 @@ import { NODE_RESOLVE_OPTIONS } from '../../webpack-config' ...@@ -4,9 +4,9 @@ import { NODE_RESOLVE_OPTIONS } from '../../webpack-config'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
function pathToUrlPath(pathname: string) { function pathToUrlPath(pathname: string) {
let urlPath = pathname.replace(/^private-next-views-dir/, '') let urlPath = pathname.replace(/^private-next-app-dir/, '')
// For `views/layout.js` // For `app/layout.js`
if (urlPath === '') { if (urlPath === '') {
urlPath = '/' urlPath = '/'
} }
...@@ -36,17 +36,17 @@ async function resolveLayoutPathsByPage({ ...@@ -36,17 +36,17 @@ async function resolveLayoutPathsByPage({
let resolvedLayoutPath = await resolve(layoutPath) let resolvedLayoutPath = await resolve(layoutPath)
let urlPath = pathToUrlPath(pathWithoutSlashLayout) let urlPath = pathToUrlPath(pathWithoutSlashLayout)
// if we are in a new root views/(root) and a custom root layout was // if we are in a new root app/(root) and a custom root layout was
// not provided or a root layout views/layout is not present, we use // not provided or a root layout app/layout is not present, we use
// a default root layout to provide the html/body tags // a default root layout to provide the html/body tags
const isCustomRootLayout = isNewRootLayout && i === 2 const isCustomRootLayout = isNewRootLayout && i === 2
if ((isCustomRootLayout || i === 1) && !resolvedLayoutPath) { if ((isCustomRootLayout || i === 1) && !resolvedLayoutPath) {
resolvedLayoutPath = await resolve('next/dist/lib/views-layout') resolvedLayoutPath = await resolve('next/dist/lib/app-layout')
} }
layoutPaths.set(urlPath, resolvedLayoutPath) layoutPaths.set(urlPath, resolvedLayoutPath)
// if we're in a new root layout don't add the top-level view/layout // if we're in a new root layout don't add the top-level app/layout
if (isCustomRootLayout) { if (isCustomRootLayout) {
break break
} }
...@@ -54,19 +54,18 @@ async function resolveLayoutPathsByPage({ ...@@ -54,19 +54,18 @@ async function resolveLayoutPathsByPage({
return layoutPaths return layoutPaths
} }
const nextViewLoader: webpack.LoaderDefinitionFunction<{ const nextAppLoader: webpack.LoaderDefinitionFunction<{
name: string name: string
pagePath: string pagePath: string
viewsDir: string appDir: string
pageExtensions: string[] pageExtensions: string[]
}> = async function nextViewLoader() { }> = async function nextAppLoader() {
const { name, viewsDir, pagePath, pageExtensions } = this.getOptions() || {} const { name, appDir, pagePath, pageExtensions } = this.getOptions() || {}
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
buildInfo.route = { buildInfo.route = {
page: name.replace(/^views/, ''), page: name.replace(/^app/, ''),
absolutePagePath: absolutePagePath: appDir + pagePath.replace(/^private-next-app-dir/, ''),
viewsDir + pagePath.replace(/^private-next-views-dir/, ''),
} }
const extensions = pageExtensions.map((extension) => `.${extension}`) const extensions = pageExtensions.map((extension) => `.${extension}`)
...@@ -99,9 +98,7 @@ const nextViewLoader: webpack.LoaderDefinitionFunction<{ ...@@ -99,9 +98,7 @@ const nextViewLoader: webpack.LoaderDefinitionFunction<{
componentsCode.push(codeLine) componentsCode.push(codeLine)
} else { } else {
for (const ext of extensions) { for (const ext of extensions) {
this.addMissingDependency( this.addMissingDependency(path.join(appDir, layoutPath, `layout${ext}`))
path.join(viewsDir, layoutPath, `layout${ext}`)
)
} }
} }
} }
...@@ -120,9 +117,9 @@ const nextViewLoader: webpack.LoaderDefinitionFunction<{ ...@@ -120,9 +117,9 @@ const nextViewLoader: webpack.LoaderDefinitionFunction<{
${componentsCode.join(',\n')} ${componentsCode.join(',\n')}
}; };
export const __next_view_webpack_require__ = __webpack_require__ export const __next_app_webpack_require__ = __webpack_require__
` `
return result return result
} }
export default nextViewLoader export default nextAppLoader
...@@ -96,14 +96,14 @@ export default class BuildManifestPlugin { ...@@ -96,14 +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 private appDirEnabled: 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 appDirEnabled: boolean
}) { }) {
this.buildId = options.buildId this.buildId = options.buildId
this.isDevFallback = !!options.isDevFallback this.isDevFallback = !!options.isDevFallback
...@@ -112,7 +112,7 @@ export default class BuildManifestPlugin { ...@@ -112,7 +112,7 @@ export default class BuildManifestPlugin {
afterFiles: [], afterFiles: [],
fallback: [], fallback: [],
} }
this.rootEnabled = options.rootEnabled this.appDirEnabled = options.appDirEnabled
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)
...@@ -152,7 +152,7 @@ export default class BuildManifestPlugin { ...@@ -152,7 +152,7 @@ export default class BuildManifestPlugin {
getEntrypointFiles(entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN)) getEntrypointFiles(entrypoints.get(CLIENT_STATIC_FILES_RUNTIME_MAIN))
) )
if (this.rootEnabled) { if (this.appDirEnabled) {
assetMap.rootMainFiles = [ assetMap.rootMainFiles = [
...new Set( ...new Set(
getEntrypointFiles( getEntrypointFiles(
...@@ -193,7 +193,7 @@ export default class BuildManifestPlugin { ...@@ -193,7 +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] : []), ...(this.appDirEnabled ? [CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT] : []),
]) ])
for (const entrypoint of compilation.entrypoints.values()) { for (const entrypoint of compilation.entrypoints.values()) {
......
...@@ -18,7 +18,7 @@ import { clientComponentRegex } from '../loaders/utils' ...@@ -18,7 +18,7 @@ import { clientComponentRegex } from '../loaders/utils'
type Options = { type Options = {
dev: boolean dev: boolean
viewsDir: boolean appDir: boolean
pageExtensions: string[] pageExtensions: string[]
} }
...@@ -27,13 +27,13 @@ const PLUGIN_NAME = 'FlightManifestPlugin' ...@@ -27,13 +27,13 @@ const PLUGIN_NAME = 'FlightManifestPlugin'
export class FlightManifestPlugin { export class FlightManifestPlugin {
dev: boolean = false dev: boolean = false
pageExtensions: string[] pageExtensions: string[]
viewsDir: boolean = false appDir: boolean = false
constructor(options: Options) { constructor(options: Options) {
if (typeof options.dev === 'boolean') { if (typeof options.dev === 'boolean') {
this.dev = options.dev this.dev = options.dev
} }
this.viewsDir = options.viewsDir this.appDir = options.appDir
this.pageExtensions = options.pageExtensions this.pageExtensions = options.pageExtensions
} }
...@@ -66,7 +66,7 @@ export class FlightManifestPlugin { ...@@ -66,7 +66,7 @@ export class FlightManifestPlugin {
createAsset(assets: any, compilation: any) { createAsset(assets: any, compilation: any) {
const manifest: any = {} const manifest: any = {}
const viewsDir = this.viewsDir const appDir = this.appDir
const dev = this.dev const dev = this.dev
compilation.chunkGroups.forEach((chunkGroup: any) => { compilation.chunkGroups.forEach((chunkGroup: any) => {
...@@ -103,7 +103,7 @@ export class FlightManifestPlugin { ...@@ -103,7 +103,7 @@ export class FlightManifestPlugin {
moduleExports[name] = { moduleExports[name] = {
id: id.replace(/^\(sc_server\)\//, ''), id: id.replace(/^\(sc_server\)\//, ''),
name, name,
chunks: viewsDir chunks: appDir
? chunk.ids.map((chunkId: string) => { ? chunk.ids.map((chunkId: string) => {
return ( return (
chunkId + ':' + chunk.name + (dev ? '' : '-' + chunk.hash) chunkId + ':' + chunk.name + (dev ? '' : '-' + chunk.hash)
......
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { import {
PAGES_MANIFEST, PAGES_MANIFEST,
VIEW_PATHS_MANIFEST, APP_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'
...@@ -20,23 +20,23 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -20,23 +20,23 @@ export default class PagesManifestPlugin implements webpack.Plugin {
serverless: boolean serverless: boolean
dev: boolean dev: boolean
isEdgeRuntime: boolean isEdgeRuntime: boolean
rootEnabled: boolean appDirEnabled: boolean
constructor({ constructor({
serverless, serverless,
dev, dev,
isEdgeRuntime, isEdgeRuntime,
rootEnabled, appDirEnabled,
}: { }: {
serverless: boolean serverless: boolean
dev: boolean dev: boolean
isEdgeRuntime: boolean isEdgeRuntime: boolean
rootEnabled: boolean appDirEnabled: boolean
}) { }) {
this.serverless = serverless this.serverless = serverless
this.dev = dev this.dev = dev
this.isEdgeRuntime = isEdgeRuntime this.isEdgeRuntime = isEdgeRuntime
this.rootEnabled = rootEnabled this.appDirEnabled = appDirEnabled
} }
createAssets(compilation: any, assets: any) { createAssets(compilation: any, assets: any) {
...@@ -45,7 +45,10 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -45,7 +45,10 @@ export default class PagesManifestPlugin implements webpack.Plugin {
const rootPaths: PagesManifest = {} const rootPaths: PagesManifest = {}
for (const entrypoint of entrypoints.values()) { for (const entrypoint of entrypoints.values()) {
const pagePath = getRouteFromEntrypoint(entrypoint.name, this.rootEnabled) const pagePath = getRouteFromEntrypoint(
entrypoint.name,
this.appDirEnabled
)
if (!pagePath) { if (!pagePath) {
continue continue
...@@ -74,7 +77,7 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -74,7 +77,7 @@ export default class PagesManifestPlugin implements webpack.Plugin {
} }
file = normalizePathSep(file) file = normalizePathSep(file)
if (entrypoint.name.startsWith('views/')) { if (entrypoint.name.startsWith('app/')) {
rootPaths[pagePath] = file rootPaths[pagePath] = file
} else { } else {
pages[pagePath] = file pages[pagePath] = file
...@@ -104,9 +107,9 @@ export default class PagesManifestPlugin implements webpack.Plugin { ...@@ -104,9 +107,9 @@ export default class PagesManifestPlugin implements webpack.Plugin {
) )
) )
if (this.rootEnabled) { if (this.appDirEnabled) {
assets[ assets[
`${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + VIEW_PATHS_MANIFEST `${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + APP_PATHS_MANIFEST
] = new sources.RawSource( ] = new sources.RawSource(
JSON.stringify( JSON.stringify(
{ {
......
...@@ -194,17 +194,17 @@ const RSCComponent = (props: any) => { ...@@ -194,17 +194,17 @@ const RSCComponent = (props: any) => {
) )
} }
const ViewRouterContext = React.createContext({}) const AppRouterContext = React.createContext({})
// TODO: move to client component when handling is implemented // TODO: move to client component when handling is implemented
function ViewRouter({ initialUrl, children }: any) { function AppRouter({ initialUrl, children }: any) {
const initialState = { const initialState = {
url: initialUrl, url: initialUrl,
} }
const previousUrlRef = React.useRef(initialState) const previousUrlRef = React.useRef(initialState)
const [current, setCurrent] = React.useState(initialState) const [current, setCurrent] = React.useState(initialState)
const viewRouter = React.useMemo(() => { const appRouter = React.useMemo(() => {
return { return {
push: (url: string) => { push: (url: string) => {
previousUrlRef.current = current previousUrlRef.current = current
...@@ -217,10 +217,10 @@ function ViewRouter({ initialUrl, children }: any) { ...@@ -217,10 +217,10 @@ function ViewRouter({ initialUrl, children }: any) {
}, [current]) }, [current])
// @ts-ignore TODO: for testing // @ts-ignore TODO: for testing
window.viewRouter = viewRouter window.appRouter = appRouter
console.log({ console.log({
viewRouter, appRouter,
previous: previousUrlRef.current, previous: previousUrlRef.current,
current, current,
}) })
...@@ -233,9 +233,9 @@ function ViewRouter({ initialUrl, children }: any) { ...@@ -233,9 +233,9 @@ function ViewRouter({ initialUrl, children }: any) {
} }
return ( return (
<ViewRouterContext.Provider value={viewRouter}> <AppRouterContext.Provider value={appRouter}>
{root ? root : children} {root ? root : children}
</ViewRouterContext.Provider> </AppRouterContext.Provider>
) )
} }
...@@ -243,9 +243,9 @@ export function hydrate() { ...@@ -243,9 +243,9 @@ export function hydrate() {
renderReactElement(appElement!, () => ( renderReactElement(appElement!, () => (
<React.StrictMode> <React.StrictMode>
<Root> <Root>
<ViewRouter initialUrl={location.pathname}> <AppRouter initialUrl={location.pathname}>
<RSCComponent /> <RSCComponent />
</ViewRouter> </AppRouter>
</Root> </Root>
</React.StrictMode> </React.StrictMode>
)) ))
......
import { hydrate, version } from './views-index' import { hydrate, version } from './app-index'
window.next = { window.next = {
version, version,
......
...@@ -583,7 +583,7 @@ export default async function exportApp( ...@@ -583,7 +583,7 @@ export default async function exportApp(
outDir, outDir,
pagesDataDir, pagesDataDir,
renderOpts, renderOpts,
viewsDir: nextConfig.experimental.viewsDir, appDir: nextConfig.experimental.appDir,
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
viewsDir?: boolean appDir?: 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
viewsDir?: boolean appDir?: 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,
viewsDir, appDir,
pagesDataDir, pagesDataDir,
renderOpts, renderOpts,
buildExport, buildExport,
...@@ -275,7 +275,7 @@ export default async function exportPage({ ...@@ -275,7 +275,7 @@ export default async function exportPage({
page, page,
serverless, serverless,
serverComponents, serverComponents,
viewsDir appDir
) )
const ampState = { const ampState = {
ampFirst: pageConfig?.amp === true, ampFirst: pageConfig?.amp === true,
......
...@@ -4,7 +4,7 @@ export type LayoutProps = { ...@@ -4,7 +4,7 @@ export type LayoutProps = {
children: any children: any
} }
export default function ViewsLayout({ children }: LayoutProps) { export default function AppLayout({ children }: LayoutProps) {
return ( return (
<html> <html>
<head> <head>
......
...@@ -28,7 +28,7 @@ export const MIDDLEWARE_FILE = `/${MIDDLEWARE_FILENAME}` ...@@ -28,7 +28,7 @@ export const MIDDLEWARE_FILE = `/${MIDDLEWARE_FILENAME}`
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_DIR_ALIAS = 'private-next-root-dir'
export const VIEWS_DIR_ALIAS = 'private-next-views-dir' export const APP_DIR_ALIAS = 'private-next-app-dir'
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' | 'views'): string | null { function findDir(dir: string, name: 'pages' | 'app'): 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' | 'views'): string | null { ...@@ -23,13 +23,13 @@ function findDir(dir: string, name: 'pages' | 'views'): string | null {
export function findPagesDir( export function findPagesDir(
dir: string, dir: string,
views?: boolean appDirEnabled?: boolean
): { pages: string; views?: string } { ): { pages: string; appDir?: string } {
const pagesDir = findDir(dir, 'pages') const pagesDir = findDir(dir, 'pages')
let viewsDir: undefined | string let appDir: undefined | string
if (views) { if (appDirEnabled) {
viewsDir = findDir(dir, 'views') || undefined appDir = findDir(dir, 'app') || 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,
views: viewsDir, appDir,
} }
} }
...@@ -161,10 +161,10 @@ function createServerComponentRenderer( ...@@ -161,10 +161,10 @@ function createServerComponentRenderer(
) { ) {
// We need to expose the `__webpack_require__` API globally for // We need to expose the `__webpack_require__` API globally for
// react-server-dom-webpack. This is a hack until we find a better way. // react-server-dom-webpack. This is a hack until we find a better way.
if (ComponentMod.__next_view_webpack_require__ || ComponentMod.__next_rsc__) { if (ComponentMod.__next_app_webpack_require__ || ComponentMod.__next_rsc__) {
// @ts-ignore // @ts-ignore
globalThis.__webpack_require__ = ComponentMod.__next_view_webpack_require__ globalThis.__webpack_require__ = ComponentMod.__next_app_webpack_require__
? ComponentMod.__next_view_webpack_require__ ? ComponentMod.__next_app_webpack_require__
: ComponentMod.__next_rsc__.__webpack_require__ : ComponentMod.__next_rsc__.__webpack_require__
// @ts-ignore // @ts-ignore
......
...@@ -65,7 +65,7 @@ import { createHeaderRoute, createRedirectRoute } from './server-route-utils' ...@@ -65,7 +65,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 { normalizeViewPath } from '../shared/lib/router/utils/view-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
...@@ -139,7 +139,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -139,7 +139,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 viewPathsManifest?: PagesManifest protected appPathsManifest?: PagesManifest
protected buildId: string protected buildId: string
protected minimalMode: boolean protected minimalMode: boolean
protected renderOpts: { protected renderOpts: {
...@@ -179,7 +179,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -179,7 +179,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 viewPathRoutes?: Record<string, string> protected appPathRoutes?: Record<string, string>
protected customRoutes: CustomRoutes protected customRoutes: CustomRoutes
protected serverComponentManifest?: any protected serverComponentManifest?: any
public readonly hostname?: string public readonly hostname?: string
...@@ -188,7 +188,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -188,7 +188,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 getViewPathsManifest(): PagesManifest | undefined protected abstract getAppPathsManifest(): 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[]
...@@ -338,7 +338,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -338,7 +338,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}) })
this.pagesManifest = this.getPagesManifest() this.pagesManifest = this.getPagesManifest()
this.viewPathsManifest = this.getViewPathsManifest() this.appPathsManifest = this.getAppPathsManifest()
this.customRoutes = this.getCustomRoutes() this.customRoutes = this.getCustomRoutes()
this.router = new Router(this.generateRoutes()) this.router = new Router(this.generateRoutes())
...@@ -851,7 +851,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -851,7 +851,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const { useFileSystemPublicRoutes } = this.nextConfig const { useFileSystemPublicRoutes } = this.nextConfig
if (useFileSystemPublicRoutes) { if (useFileSystemPublicRoutes) {
this.viewPathRoutes = this.getViewPathRoutes() this.appPathRoutes = this.getappPathRoutes()
this.dynamicRoutes = this.getDynamicRoutes() this.dynamicRoutes = this.getDynamicRoutes()
} }
...@@ -943,7 +943,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -943,7 +943,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return getSortedRoutes( return getSortedRoutes(
[ [
...Object.keys(this.viewPathRoutes || {}), ...Object.keys(this.appPathRoutes || {}),
...Object.keys(this.pagesManifest!), ...Object.keys(this.pagesManifest!),
].map( ].map(
(page) => (page) =>
...@@ -961,20 +961,20 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -961,20 +961,20 @@ export default abstract class Server<ServerOptions extends Options = Options> {
.filter((item): item is RoutingItem => Boolean(item)) .filter((item): item is RoutingItem => Boolean(item))
} }
protected getViewPathRoutes(): Record<string, string> { protected getappPathRoutes(): Record<string, string> {
const viewPathRoutes: Record<string, string> = {} const appPathRoutes: Record<string, string> = {}
Object.keys(this.viewPathsManifest || {}).forEach((entry) => { Object.keys(this.appPathsManifest || {}).forEach((entry) => {
viewPathRoutes[normalizeViewPath(entry)] = entry appPathRoutes[normalizeAppPath(entry)] = entry
}) })
return viewPathRoutes return appPathRoutes
} }
protected getViewPathLayouts(pathname: string): string[] { protected getappPathLayouts(pathname: string): string[] {
const layoutPaths: string[] = [] const layoutPaths: string[] = []
if (this.viewPathRoutes) { if (this.appPathRoutes) {
const paths = Object.values(this.viewPathRoutes) const paths = Object.values(this.appPathRoutes)
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++) {
...@@ -985,7 +985,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -985,7 +985,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
} }
if (this.viewPathRoutes['/layout']) { if (this.appPathRoutes['/layout']) {
layoutPaths.unshift('/layout') layoutPaths.unshift('/layout')
} }
} }
...@@ -1705,17 +1705,17 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1705,17 +1705,17 @@ 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 getOriginalViewPath = (viewPath: string) => { const getOriginalappPath = (appPath: string) => {
if (this.nextConfig.experimental.viewsDir) { if (this.nextConfig.experimental.appDir) {
const originalViewPath = const originalappPath =
this.viewPathRoutes?.[`${viewPath}/index`] || this.appPathRoutes?.[`${appPath}/index`] ||
this.viewPathRoutes?.[`${viewPath}`] this.appPathRoutes?.[`${appPath}`]
if (!originalViewPath) { if (!originalappPath) {
return null return null
} }
return originalViewPath return originalappPath
} }
return null return null
} }
...@@ -1724,10 +1724,10 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1724,10 +1724,10 @@ 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 viewPath = getOriginalViewPath(pathname) const appPath = getOriginalappPath(pathname)
if (typeof viewPath === 'string') { if (typeof appPath === 'string') {
page = viewPath page = appPath
} }
const result = await this.findPageComponents(page, query) const result = await this.findPageComponents(page, query)
if (result) { if (result) {
...@@ -1750,10 +1750,10 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1750,10 +1750,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
continue continue
} }
page = dynamicRoute.page page = dynamicRoute.page
const viewPath = getOriginalViewPath(page) const appPath = getOriginalappPath(page)
if (typeof viewPath === 'string') { if (typeof appPath === 'string') {
page = viewPath page = appPath
} }
const dynamicRouteResult = await this.findPageComponents( const dynamicRouteResult = await this.findPageComponents(
......
...@@ -99,7 +99,7 @@ export interface ExperimentalConfig { ...@@ -99,7 +99,7 @@ export interface ExperimentalConfig {
scrollRestoration?: boolean scrollRestoration?: boolean
externalDir?: boolean externalDir?: boolean
conformance?: boolean conformance?: boolean
viewsDir?: boolean appDir?: boolean
amp?: { amp?: {
optimizer?: any optimizer?: any
validator?: string validator?: string
...@@ -501,7 +501,7 @@ export const defaultConfig: NextConfig = { ...@@ -501,7 +501,7 @@ export const defaultConfig: NextConfig = {
swcFileReading: true, swcFileReading: true,
craCompat: false, craCompat: false,
esmExternals: true, esmExternals: true,
viewsDir: false, appDir: false,
// default to 50MB limit // default to 50MB limit
isrMemoryCacheSize: 50 * 1024 * 1024, isrMemoryCacheSize: 50 * 1024 * 1024,
serverComponents: false, serverComponents: false,
......
...@@ -11,7 +11,7 @@ import { ...@@ -11,7 +11,7 @@ import {
finalizeEntrypoint, finalizeEntrypoint,
getClientEntry, getClientEntry,
getEdgeServerEntry, getEdgeServerEntry,
getViewsEntry, getAppEntry,
runDependingOnPageType, runDependingOnPageType,
} from '../../build/entries' } from '../../build/entries'
import { watchCompilers } from '../../build/output' import { watchCompilers } from '../../build/output'
...@@ -19,7 +19,7 @@ import getBaseWebpackConfig from '../../build/webpack-config' ...@@ -19,7 +19,7 @@ import getBaseWebpackConfig from '../../build/webpack-config'
import { import {
API_ROUTE, API_ROUTE,
MIDDLEWARE_FILENAME, MIDDLEWARE_FILENAME,
VIEWS_DIR_ALIAS, APP_DIR_ALIAS,
} from '../../lib/constants' } from '../../lib/constants'
import { recursiveDelete } from '../../lib/recursive-delete' import { recursiveDelete } from '../../lib/recursive-delete'
import { BLOCKED_PAGES } from '../../shared/lib/constants' import { BLOCKED_PAGES } from '../../shared/lib/constants'
...@@ -175,7 +175,7 @@ export default class HotReloader { ...@@ -175,7 +175,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 viewsDir?: string private appDir?: string
constructor( constructor(
dir: string, dir: string,
...@@ -186,7 +186,7 @@ export default class HotReloader { ...@@ -186,7 +186,7 @@ export default class HotReloader {
buildId, buildId,
previewProps, previewProps,
rewrites, rewrites,
viewsDir, appDir,
}: { }: {
config: NextConfigComplete config: NextConfigComplete
pagesDir: string pagesDir: string
...@@ -194,14 +194,14 @@ export default class HotReloader { ...@@ -194,14 +194,14 @@ export default class HotReloader {
buildId: string buildId: string
previewProps: __ApiPreviewProps previewProps: __ApiPreviewProps
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
viewsDir?: string appDir?: string
} }
) { ) {
this.buildId = buildId this.buildId = buildId
this.dir = dir this.dir = dir
this.middlewares = [] this.middlewares = []
this.pagesDir = pagesDir this.pagesDir = pagesDir
this.viewsDir = viewsDir this.appDir = appDir
this.distDir = distDir this.distDir = distDir
this.clientStats = null this.clientStats = null
this.serverStats = null this.serverStats = null
...@@ -437,7 +437,7 @@ export default class HotReloader { ...@@ -437,7 +437,7 @@ export default class HotReloader {
pagesDir: this.pagesDir, pagesDir: this.pagesDir,
rewrites: this.rewrites, rewrites: this.rewrites,
runWebpackSpan: this.hotReloaderSpan, runWebpackSpan: this.hotReloaderSpan,
viewsDir: this.viewsDir, appDir: this.appDir,
} }
return webpackConfigSpan return webpackConfigSpan
...@@ -633,14 +633,14 @@ export default class HotReloader { ...@@ -633,14 +633,14 @@ export default class HotReloader {
name: bundlePath, name: bundlePath,
isServerComponent, isServerComponent,
value: value:
this.viewsDir && bundlePath.startsWith('views/') this.appDir && bundlePath.startsWith('app/')
? getViewsEntry({ ? getAppEntry({
name: bundlePath, name: bundlePath,
pagePath: join( pagePath: join(
VIEWS_DIR_ALIAS, APP_DIR_ALIAS,
relative(this.viewsDir!, absolutePagePath) relative(this.appDir!, absolutePagePath)
), ),
viewsDir: this.viewsDir!, appDir: this.appDir!,
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
}) })
: request, : request,
...@@ -889,7 +889,7 @@ export default class HotReloader { ...@@ -889,7 +889,7 @@ export default class HotReloader {
multiCompiler, multiCompiler,
watcher: this.watcher, watcher: this.watcher,
pagesDir: this.pagesDir, pagesDir: this.pagesDir,
viewsDir: this.viewsDir, appDir: this.appDir,
rootDir: this.dir, rootDir: this.dir,
nextConfig: this.config, nextConfig: this.config,
...(this.config.onDemandEntries as { ...(this.config.onDemandEntries as {
......
...@@ -67,7 +67,7 @@ import { runDependingOnPageType } from '../../build/entries' ...@@ -67,7 +67,7 @@ import { runDependingOnPageType } from '../../build/entries'
import { NodeNextResponse, NodeNextRequest } from '../base-http/node' import { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import { getPageStaticInfo } from '../../build/analysis/get-page-static-info' import { getPageStaticInfo } from '../../build/analysis/get-page-static-info'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import { normalizeViewPath } from '../../shared/lib/router/utils/view-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { MIDDLEWARE_FILE } from '../../lib/constants' import { MIDDLEWARE_FILE } from '../../lib/constants'
// Load ReactDevOverlay only when needed // Load ReactDevOverlay only when needed
...@@ -100,7 +100,7 @@ export default class DevServer extends Server { ...@@ -100,7 +100,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 viewsDir?: string private appDir?: string
/** /**
* Since the dev server is stateful and middleware routes can be added and * Since the dev server is stateful and middleware routes can be added and
...@@ -188,12 +188,12 @@ export default class DevServer extends Server { ...@@ -188,12 +188,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, views: viewsDir } = findPagesDir( const { pages: pagesDir, appDir } = findPagesDir(
this.dir, this.dir,
this.nextConfig.experimental.viewsDir this.nextConfig.experimental.appDir
) )
this.pagesDir = pagesDir this.pagesDir = pagesDir
this.viewsDir = viewsDir this.appDir = appDir
} }
protected getBuildId(): string { protected getBuildId(): string {
...@@ -271,8 +271,8 @@ export default class DevServer extends Server { ...@@ -271,8 +271,8 @@ export default class DevServer extends Server {
let wp = (this.webpackWatcher = new Watchpack()) let wp = (this.webpackWatcher = new Watchpack())
const pages = [this.pagesDir] const pages = [this.pagesDir]
const views = this.viewsDir ? [this.viewsDir] : [] const app = this.appDir ? [this.appDir] : []
const directories = [...pages, ...views] const directories = [...pages, ...app]
const files = this.nextConfig.pageExtensions.map((extension) => const files = this.nextConfig.pageExtensions.map((extension) =>
pathJoin(this.dir, `${MIDDLEWARE_FILENAME}.${extension}`) pathJoin(this.dir, `${MIDDLEWARE_FILENAME}.${extension}`)
) )
...@@ -283,7 +283,7 @@ export default class DevServer extends Server { ...@@ -283,7 +283,7 @@ export default class DevServer extends Server {
const routedMiddleware: string[] = [] const routedMiddleware: string[] = []
const routedPages: string[] = [] const routedPages: string[] = []
const knownFiles = wp.getTimeInfoEntries() const knownFiles = wp.getTimeInfoEntries()
const viewPaths: Record<string, string> = {} const appPaths: Record<string, string> = {}
const ssrMiddleware = new Set<string>() const ssrMiddleware = new Set<string>()
for (const [fileName, meta] of knownFiles) { for (const [fileName, meta] of knownFiles) {
...@@ -294,10 +294,10 @@ export default class DevServer extends Server { ...@@ -294,10 +294,10 @@ export default class DevServer extends Server {
continue continue
} }
const isViewPath = Boolean( const isAppPath = Boolean(
this.viewsDir && this.appDir &&
normalizePathSep(fileName).startsWith( normalizePathSep(fileName).startsWith(
normalizePathSep(this.viewsDir) normalizePathSep(this.appDir)
) )
) )
...@@ -312,16 +312,16 @@ export default class DevServer extends Server { ...@@ -312,16 +312,16 @@ export default class DevServer extends Server {
} }
let pageName = absolutePathToPage(fileName, { let pageName = absolutePathToPage(fileName, {
pagesDir: isViewPath ? this.viewsDir! : this.pagesDir, pagesDir: isAppPath ? this.appDir! : this.pagesDir,
extensions: this.nextConfig.pageExtensions, extensions: this.nextConfig.pageExtensions,
keepIndex: isViewPath, keepIndex: isAppPath,
}) })
if (isViewPath) { if (isAppPath) {
// 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 = normalizeViewPath(pageName) pageName = normalizeAppPath(pageName)
viewPaths[pageName] = originalPageName appPaths[pageName] = originalPageName
if (routedPages.includes(pageName)) { if (routedPages.includes(pageName)) {
continue continue
...@@ -360,7 +360,7 @@ export default class DevServer extends Server { ...@@ -360,7 +360,7 @@ export default class DevServer extends Server {
routedPages.push(pageName) routedPages.push(pageName)
} }
this.viewPathRoutes = viewPaths this.appPathRoutes = appPaths
this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({ this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({
match: getRouteMatcher( match: getRouteMatcher(
getMiddlewareRegex(page, { catchAll: !ssrMiddleware.has(page) }) getMiddlewareRegex(page, { catchAll: !ssrMiddleware.has(page) })
...@@ -422,7 +422,7 @@ export default class DevServer extends Server { ...@@ -422,7 +422,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.viewsDir].filter(Boolean) as string[], [this.pagesDir!, this.appDir].filter(Boolean) as string[],
false, false,
this.nextConfig.typescript.tsconfigPath, this.nextConfig.typescript.tsconfigPath,
this.nextConfig.images.disableStaticImages this.nextConfig.images.disableStaticImages
...@@ -450,7 +450,7 @@ export default class DevServer extends Server { ...@@ -450,7 +450,7 @@ export default class DevServer extends Server {
previewProps: this.getPreviewProps(), previewProps: this.getPreviewProps(),
buildId: this.buildId, buildId: this.buildId,
rewrites, rewrites,
viewsDir: this.viewsDir, appDir: this.appDir,
}) })
await super.prepare() await super.prepare()
await this.addExportPathMapRoutes() await this.addExportPathMapRoutes()
...@@ -516,10 +516,10 @@ export default class DevServer extends Server { ...@@ -516,10 +516,10 @@ export default class DevServer extends Server {
).then(Boolean) ).then(Boolean)
} }
// check viewsDir first if enabled // check appDir first if enabled
if (this.viewsDir) { if (this.appDir) {
const pageFile = await findPageFile( const pageFile = await findPageFile(
this.viewsDir, this.appDir,
normalizedPath, normalizedPath,
this.nextConfig.pageExtensions this.nextConfig.pageExtensions
) )
...@@ -810,7 +810,7 @@ export default class DevServer extends Server { ...@@ -810,7 +810,7 @@ export default class DevServer extends Server {
return undefined return undefined
} }
protected getViewPathsManifest(): undefined { protected getAppPathsManifest(): undefined {
return undefined return undefined
} }
......
...@@ -65,7 +65,7 @@ export function onDemandEntryHandler({ ...@@ -65,7 +65,7 @@ export function onDemandEntryHandler({
pagesBufferLength, pagesBufferLength,
pagesDir, pagesDir,
rootDir, rootDir,
viewsDir, appDir,
watcher, watcher,
}: { }: {
maxInactiveAge: number maxInactiveAge: number
...@@ -74,7 +74,7 @@ export function onDemandEntryHandler({ ...@@ -74,7 +74,7 @@ export function onDemandEntryHandler({
pagesBufferLength: number pagesBufferLength: number
pagesDir: string pagesDir: string
rootDir: string rootDir: string
viewsDir?: string appDir?: string
watcher: any watcher: any
}) { }) {
invalidator = new Invalidator(watcher) invalidator = new Invalidator(watcher)
...@@ -113,7 +113,7 @@ export function onDemandEntryHandler({ ...@@ -113,7 +113,7 @@ export function onDemandEntryHandler({
return invalidator.doneBuilding() return invalidator.doneBuilding()
} }
const [clientStats, serverStats, edgeServerStats] = multiStats.stats const [clientStats, serverStats, edgeServerStats] = multiStats.stats
const root = !!viewsDir const root = !!appDir
const pagePaths = [ const pagePaths = [
...getPagePathsFromEntrypoints( ...getPagePathsFromEntrypoints(
'client', 'client',
...@@ -195,7 +195,7 @@ export function onDemandEntryHandler({ ...@@ -195,7 +195,7 @@ export function onDemandEntryHandler({
pagesDir, pagesDir,
page, page,
nextConfig.pageExtensions, nextConfig.pageExtensions,
viewsDir appDir
) )
let entryAdded = false let entryAdded = false
...@@ -366,7 +366,7 @@ async function findPagePathData( ...@@ -366,7 +366,7 @@ async function findPagePathData(
pagesDir: string, pagesDir: string,
page: string, page: string,
extensions: string[], extensions: string[],
viewsDir?: string appDir?: string
) { ) {
const normalizedPagePath = tryToNormalizePagePath(page) const normalizedPagePath = tryToNormalizePagePath(page)
let pagePath: string | null = null let pagePath: string | null = null
...@@ -391,9 +391,9 @@ async function findPagePathData( ...@@ -391,9 +391,9 @@ async function findPagePathData(
} }
} }
// Check viewsDir first falling back to pagesDir // Check appDir first falling back to pagesDir
if (viewsDir) { if (appDir) {
pagePath = await findPageFile(viewsDir, normalizedPagePath, extensions) pagePath = await findPageFile(appDir, normalizedPagePath, extensions)
if (pagePath) { if (pagePath) {
const pageUrl = ensureLeadingSlash( const pageUrl = ensureLeadingSlash(
removePagePathTail(normalizePathSep(pagePath), { removePagePathTail(normalizePathSep(pagePath), {
...@@ -403,8 +403,8 @@ async function findPagePathData( ...@@ -403,8 +403,8 @@ async function findPagePathData(
) )
return { return {
absolutePagePath: join(viewsDir, pagePath), absolutePagePath: join(appDir, pagePath),
bundlePath: posix.join('views', normalizePagePath(pageUrl)), bundlePath: posix.join('app', normalizePagePath(pageUrl)),
page: posix.normalize(pageUrl), page: posix.normalize(pageUrl),
} }
} }
......
...@@ -2,8 +2,8 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass ...@@ -2,8 +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 // matches app/:path*.js
const ROOT_ROUTE_NAME_REGEX = /^views[/\\](.*)$/ const APP_ROUTE_NAME_REGEX = /^app[/\\](.*)$/
// matches static/pages/:page*.js // matches static/pages/:page*.js
const BROWSER_ROUTE_NAME_REGEX = /^static[/\\]pages[/\\](.*)$/ const BROWSER_ROUTE_NAME_REGEX = /^static[/\\]pages[/\\](.*)$/
...@@ -19,7 +19,7 @@ function matchBundle(regex: RegExp, input: string): string | null { ...@@ -19,7 +19,7 @@ function matchBundle(regex: RegExp, input: string): string | null {
export default function getRouteFromEntrypoint( export default function getRouteFromEntrypoint(
entryFile: string, entryFile: string,
root?: boolean app?: boolean
): string | null { ): string | null {
let pagePath = matchBundle(SERVER_ROUTE_NAME_REGEX, entryFile) let pagePath = matchBundle(SERVER_ROUTE_NAME_REGEX, entryFile)
...@@ -27,8 +27,8 @@ export default function getRouteFromEntrypoint( ...@@ -27,8 +27,8 @@ export default function getRouteFromEntrypoint(
return pagePath return pagePath
} }
if (root) { if (app) {
pagePath = matchBundle(ROOT_ROUTE_NAME_REGEX, entryFile) pagePath = matchBundle(APP_ROUTE_NAME_REGEX, entryFile)
if (pagePath) return pagePath if (pagePath) return pagePath
} }
......
...@@ -40,7 +40,7 @@ export type LoadComponentsReturnType = { ...@@ -40,7 +40,7 @@ export type LoadComponentsReturnType = {
getStaticPaths?: GetStaticPaths getStaticPaths?: GetStaticPaths
getServerSideProps?: GetServerSideProps getServerSideProps?: GetServerSideProps
ComponentMod: any ComponentMod: any
isViewPath?: boolean isAppPath?: boolean
} }
export async function loadDefaultErrorComponents(distDir: string) { export async function loadDefaultErrorComponents(distDir: string) {
...@@ -66,7 +66,7 @@ export async function loadComponents( ...@@ -66,7 +66,7 @@ export async function loadComponents(
pathname: string, pathname: string,
serverless: boolean, serverless: boolean,
hasServerComponents?: boolean, hasServerComponents?: boolean,
rootEnabled?: boolean appDirEnabled?: boolean
): Promise<LoadComponentsReturnType> { ): Promise<LoadComponentsReturnType> {
if (serverless) { if (serverless) {
const ComponentMod = await requirePage(pathname, distDir, serverless) const ComponentMod = await requirePage(pathname, distDir, serverless)
...@@ -103,13 +103,13 @@ export async function loadComponents( ...@@ -103,13 +103,13 @@ export async function loadComponents(
const [DocumentMod, AppMod, ComponentMod] = await Promise.all([ const [DocumentMod, AppMod, ComponentMod] = await Promise.all([
Promise.resolve().then(() => Promise.resolve().then(() =>
requirePage('/_document', distDir, serverless, rootEnabled) requirePage('/_document', distDir, serverless, appDirEnabled)
), ),
Promise.resolve().then(() => Promise.resolve().then(() =>
requirePage('/_app', distDir, serverless, rootEnabled) requirePage('/_app', distDir, serverless, appDirEnabled)
), ),
Promise.resolve().then(() => Promise.resolve().then(() =>
requirePage(pathname, distDir, serverless, rootEnabled) requirePage(pathname, distDir, serverless, appDirEnabled)
), ),
]) ])
...@@ -129,7 +129,7 @@ export async function loadComponents( ...@@ -129,7 +129,7 @@ export async function loadComponents(
normalizePagePath(pathname) + NEXT_CLIENT_SSR_ENTRY_SUFFIX, normalizePagePath(pathname) + NEXT_CLIENT_SSR_ENTRY_SUFFIX,
distDir, distDir,
serverless, serverless,
rootEnabled appDirEnabled
) )
} catch (_) { } catch (_) {
// This page might not be a server component page, so there is no // This page might not be a server component page, so there is no
...@@ -143,18 +143,18 @@ export async function loadComponents( ...@@ -143,18 +143,18 @@ export async function loadComponents(
const { getServerSideProps, getStaticProps, getStaticPaths } = ComponentMod const { getServerSideProps, getStaticProps, getStaticPaths } = ComponentMod
let isViewPath = false let isAppPath = false
if (rootEnabled) { if (appDirEnabled) {
const pagePath = getPagePath( const pagePath = getPagePath(
pathname, pathname,
distDir, distDir,
serverless, serverless,
false, false,
undefined, undefined,
rootEnabled appDirEnabled
) )
isViewPath = !!pagePath?.match(/server[/\\]views[/\\]/) isAppPath = !!pagePath?.match(/server[/\\]app[/\\]/)
} }
return { return {
...@@ -169,6 +169,6 @@ export async function loadComponents( ...@@ -169,6 +169,6 @@ export async function loadComponents(
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
serverComponentManifest, serverComponentManifest,
isViewPath, isAppPath,
} }
} }
...@@ -30,7 +30,7 @@ import { ...@@ -30,7 +30,7 @@ import {
ROUTES_MANIFEST, ROUTES_MANIFEST,
MIDDLEWARE_FLIGHT_MANIFEST, MIDDLEWARE_FLIGHT_MANIFEST,
CLIENT_PUBLIC_FILES_PATH, CLIENT_PUBLIC_FILES_PATH,
VIEW_PATHS_MANIFEST, APP_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,7 +45,7 @@ import { getExtension, serveStatic } from './serve-static' ...@@ -45,7 +45,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 viewRenderToHTML } from './view-render' import { renderToHTML as appRenderToHTML } from './app-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'
...@@ -167,13 +167,10 @@ export default class NextNodeServer extends BaseServer { ...@@ -167,13 +167,10 @@ export default class NextNodeServer extends BaseServer {
return require(join(this.serverDistDir, PAGES_MANIFEST)) return require(join(this.serverDistDir, PAGES_MANIFEST))
} }
protected getViewPathsManifest(): PagesManifest | undefined { protected getAppPathsManifest(): PagesManifest | undefined {
if (this.nextConfig.experimental.viewsDir) { if (this.nextConfig.experimental.appDir) {
const viewPathsManifestPath = join( const appPathsManifestPath = join(this.serverDistDir, APP_PATHS_MANIFEST)
this.serverDistDir, return require(appPathsManifestPath)
VIEW_PATHS_MANIFEST
)
return require(viewPathsManifestPath)
} }
} }
...@@ -592,8 +589,8 @@ export default class NextNodeServer extends BaseServer { ...@@ -592,8 +589,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.isViewPath) { if (renderOpts.isAppPath) {
return viewRenderToHTML( return appRenderToHTML(
req.originalRequest, req.originalRequest,
res.originalResponse, res.originalResponse,
pathname, pathname,
...@@ -650,7 +647,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -650,7 +647,7 @@ export default class NextNodeServer extends BaseServer {
this._isLikeServerless, this._isLikeServerless,
this.renderOpts.dev, this.renderOpts.dev,
locales, locales,
this.nextConfig.experimental.viewsDir this.nextConfig.experimental.appDir
) )
} }
...@@ -681,7 +678,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -681,7 +678,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.viewsDir this.nextConfig.experimental.appDir
) )
if ( if (
......
...@@ -5,7 +5,7 @@ import { ...@@ -5,7 +5,7 @@ import {
PAGES_MANIFEST, PAGES_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
VIEW_PATHS_MANIFEST, APP_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'
...@@ -24,7 +24,7 @@ export function getPagePath( ...@@ -24,7 +24,7 @@ export function getPagePath(
serverless: boolean, serverless: boolean,
dev?: boolean, dev?: boolean,
locales?: string[], locales?: string[],
rootEnabled?: boolean appDirEnabled?: boolean
): string { ): string {
const serverBuildPath = join( const serverBuildPath = join(
distDir, distDir,
...@@ -32,11 +32,11 @@ export function getPagePath( ...@@ -32,11 +32,11 @@ export function getPagePath(
) )
let rootPathsManifest: undefined | PagesManifest let rootPathsManifest: undefined | PagesManifest
if (rootEnabled) { if (appDirEnabled) {
if (page === '/_root') { if (page === '/_root') {
return join(serverBuildPath, 'root.js') return join(serverBuildPath, 'root.js')
} }
rootPathsManifest = require(join(serverBuildPath, VIEW_PATHS_MANIFEST)) rootPathsManifest = require(join(serverBuildPath, APP_PATHS_MANIFEST))
} }
const pagesManifest = require(join( const pagesManifest = require(join(
serverBuildPath, serverBuildPath,
...@@ -84,7 +84,7 @@ export function requirePage( ...@@ -84,7 +84,7 @@ export function requirePage(
page: string, page: string,
distDir: string, distDir: string,
serverless: boolean, serverless: boolean,
rootEnabled?: boolean appDirEnabled?: boolean
): any { ): any {
const pagePath = getPagePath( const pagePath = getPagePath(
page, page,
...@@ -92,7 +92,7 @@ export function requirePage( ...@@ -92,7 +92,7 @@ export function requirePage(
serverless, serverless,
false, false,
undefined, undefined,
rootEnabled appDirEnabled
) )
if (pagePath.endsWith('.html')) { if (pagePath.endsWith('.html')) {
return promises.readFile(pagePath, 'utf8') return promises.readFile(pagePath, 'utf8')
......
...@@ -94,7 +94,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -94,7 +94,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
[this.serverOptions.webServerConfig.page]: '', [this.serverOptions.webServerConfig.page]: '',
} }
} }
protected getViewPathsManifest() { protected getAppPathsManifest() {
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 VIEW_PATHS_MANIFEST = 'view-paths-manifest.json' export const APP_PATHS_MANIFEST = 'app-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'
......
// remove (name) from pathname as it's not considered for routing // remove (name) from pathname as it's not considered for routing
export function normalizeViewPath(pathname: string) { export function normalizeAppPath(pathname: string) {
let normalized = '' let normalized = ''
const segments = pathname.split('/') const segments = pathname.split('/')
......
module.exports = { module.exports = {
experimental: { experimental: {
viewsDir: true, appDir: true,
runtime: 'nodejs', runtime: 'nodejs',
reactRoot: true, reactRoot: true,
serverComponents: true, serverComponents: true,
......
module.exports = { module.exports = {
experimental: { experimental: {
viewsDir: true, appDir: true,
runtime: 'nodejs', runtime: 'nodejs',
reactRoot: true, reactRoot: true,
serverComponents: true, serverComponents: true,
......
...@@ -22,7 +22,7 @@ describe('views dir', () => { ...@@ -22,7 +22,7 @@ describe('views 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')),
views: new FileRef(path.join(__dirname, 'app/views')), app: new FileRef(path.join(__dirname, 'app/app')),
'next.config.js': new FileRef( 'next.config.js': new FileRef(
path.join(__dirname, 'app/next.config.js') path.join(__dirname, 'app/next.config.js')
), ),
......
...@@ -21,7 +21,7 @@ describe('views dir rendering', () => { ...@@ -21,7 +21,7 @@ describe('views dir rendering', () => {
beforeAll(async () => { beforeAll(async () => {
next = await createNext({ next = await createNext({
files: { files: {
views: new FileRef(path.join(__dirname, 'app-rendering/views')), app: new FileRef(path.join(__dirname, 'app-rendering/app')),
pages: new FileRef(path.join(__dirname, 'app-rendering/pages')), pages: new FileRef(path.join(__dirname, 'app-rendering/pages')),
'next.config.js': new FileRef( 'next.config.js': new FileRef(
path.join(__dirname, 'app-rendering/next.config.js') path.join(__dirname, 'app-rendering/next.config.js')
......
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