Unverified Commit 5ddee449 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Add new target for middleware (#30299)

Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
Co-authored-by: 's avatarTim Neutkens <timneutkens@me.com>
parent da2bb523
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
"dev": "lerna run dev --stream --parallel", "dev": "lerna run dev --stream --parallel",
"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": "yarn jest",
"test-unit": "yarn jest test/unit/", "test-unit": "yarn jest test/unit/",
"testonly": "yarn jest --runInBand", "testonly": "yarn jest --runInBand",
"testheadless": "cross-env HEADLESS=true yarn testonly", "testheadless": "cross-env HEADLESS=true yarn testonly",
...@@ -137,9 +138,9 @@ ...@@ -137,9 +138,9 @@
"pretty-ms": "7.0.0", "pretty-ms": "7.0.0",
"random-seed": "0.3.0", "random-seed": "0.3.0",
"react": "17.0.2", "react": "17.0.2",
"react-18": "npm:react@next", "react-18": "npm:react@18.0.0-alpha-3c4c1c470-20211021",
"react-dom": "17.0.2", "react-dom": "17.0.2",
"react-dom-18": "npm:react-dom@next", "react-dom-18": "npm:react-dom@18.0.0-alpha-3c4c1c470-20211021",
"react-ssr-prepass": "1.0.8", "react-ssr-prepass": "1.0.8",
"release": "6.3.0", "release": "6.3.0",
"request-promise-core": "1.1.2", "request-promise-core": "1.1.2",
......
...@@ -12,7 +12,10 @@ import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-lo ...@@ -12,7 +12,10 @@ import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-lo
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader' import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import { LoadedEnvFiles } from '@next/env' import { LoadedEnvFiles } from '@next/env'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
import { isFlightPage } from './utils'
import { ssrEntries } from './webpack/plugins/middleware-plugin'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack' import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { MIDDLEWARE_SSR_RUNTIME_WEBPACK } from '../shared/lib/constants'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
type PagesMapping = { type PagesMapping = {
...@@ -22,14 +25,23 @@ type PagesMapping = { ...@@ -22,14 +25,23 @@ type PagesMapping = {
export function createPagesMapping( export function createPagesMapping(
pagePaths: string[], pagePaths: string[],
extensions: string[], extensions: string[],
isDev: boolean isDev: boolean,
hasServerComponents: boolean
): PagesMapping { ): PagesMapping {
const previousPages: PagesMapping = {} const previousPages: PagesMapping = {}
const pages: PagesMapping = pagePaths.reduce( const pages: PagesMapping = pagePaths.reduce(
(result: PagesMapping, pagePath): PagesMapping => { (result: PagesMapping, pagePath): PagesMapping => {
let page = `${pagePath let page = pagePath.replace(
.replace(new RegExp(`\\.+(${extensions.join('|')})$`), '') new RegExp(`\\.+(${extensions.join('|')})$`),
.replace(/\\/g, '/')}`.replace(/\/index$/, '') ''
)
if (hasServerComponents && /\.client$/.test(page)) {
// Assume that if there's a Client Component, that there is
// a matching Server Component that will map to the page.
return result
}
page = page.replace(/\\/g, '/').replace(/\/index$/, '')
const pageKey = page === '' ? '/' : page const pageKey = page === '' ? '/' : page
...@@ -68,6 +80,7 @@ export function createPagesMapping( ...@@ -68,6 +80,7 @@ export function createPagesMapping(
type Entrypoints = { type Entrypoints = {
client: webpack5.EntryObject client: webpack5.EntryObject
server: webpack5.EntryObject server: webpack5.EntryObject
serverWeb: webpack5.EntryObject
} }
export function createEntrypoints( export function createEntrypoints(
...@@ -80,6 +93,7 @@ export function createEntrypoints( ...@@ -80,6 +93,7 @@ export function createEntrypoints(
): Entrypoints { ): Entrypoints {
const client: webpack5.EntryObject = {} const client: webpack5.EntryObject = {}
const server: webpack5.EntryObject = {} const server: webpack5.EntryObject = {}
const serverWeb: webpack5.EntryObject = {}
const hasRuntimeConfig = const hasRuntimeConfig =
Object.keys(config.publicRuntimeConfig).length > 0 || Object.keys(config.publicRuntimeConfig).length > 0 ||
...@@ -120,6 +134,8 @@ export function createEntrypoints( ...@@ -120,6 +134,8 @@ export function createEntrypoints(
const serverBundlePath = posix.join('pages', bundleFile) const serverBundlePath = posix.join('pages', bundleFile)
const isLikeServerless = isTargetLikeServerless(target) const isLikeServerless = isTargetLikeServerless(target)
const isFlight = isFlightPage(config, absolutePagePath)
const webServerRuntime = !!config.experimental.concurrentFeatures
if (page.match(MIDDLEWARE_ROUTE)) { if (page.match(MIDDLEWARE_ROUTE)) {
const loaderOpts: MiddlewareLoaderOptions = { const loaderOpts: MiddlewareLoaderOptions = {
...@@ -133,6 +149,27 @@ export function createEntrypoints( ...@@ -133,6 +149,27 @@ export function createEntrypoints(
return return
} }
if (
webServerRuntime &&
!(page === '/_app' || page === '/_error' || page === '/_document') &&
!isApiRoute
) {
ssrEntries.set(clientBundlePath, { requireFlightManifest: isFlight })
serverWeb[serverBundlePath] = finalizeEntrypoint({
name: '[name].js',
value: `next-middleware-ssr-loader?${stringify({
page,
absolutePagePath,
isServerComponent: isFlight,
buildId,
basePath: config.basePath,
assetPrefix: config.assetPrefix,
} as any)}!`,
isServer: false,
isServerWeb: true,
})
}
if (isApiRoute && isLikeServerless) { if (isApiRoute && isLikeServerless) {
const serverlessLoaderOptions: ServerlessLoaderQuery = { const serverlessLoaderOptions: ServerlessLoaderQuery = {
page, page,
...@@ -143,8 +180,20 @@ export function createEntrypoints( ...@@ -143,8 +180,20 @@ export function createEntrypoints(
serverlessLoaderOptions serverlessLoaderOptions
)}!` )}!`
} else if (isApiRoute || target === 'server') { } else if (isApiRoute || target === 'server') {
if (
!webServerRuntime ||
page === '/_document' ||
page === '/_app' ||
page === '/_error'
) {
server[serverBundlePath] = [absolutePagePath] server[serverBundlePath] = [absolutePagePath]
} else if (isLikeServerless && page !== '/_app' && page !== '/_document') { }
} else if (
isLikeServerless &&
page !== '/_app' &&
page !== '/_document' &&
!webServerRuntime
) {
const serverlessLoaderOptions: ServerlessLoaderQuery = { const serverlessLoaderOptions: ServerlessLoaderQuery = {
page, page,
absolutePagePath, absolutePagePath,
...@@ -182,6 +231,7 @@ export function createEntrypoints( ...@@ -182,6 +231,7 @@ export function createEntrypoints(
return { return {
client, client,
server, server,
serverWeb,
} }
} }
...@@ -189,10 +239,14 @@ export function finalizeEntrypoint({ ...@@ -189,10 +239,14 @@ export function finalizeEntrypoint({
name, name,
value, value,
isServer, isServer,
isMiddleware,
isServerWeb,
}: { }: {
isServer: boolean isServer: boolean
name: string name: string
value: ObjectValue<webpack5.EntryObject> value: ObjectValue<webpack5.EntryObject>
isMiddleware?: boolean
isServerWeb?: boolean
}): ObjectValue<webpack5.EntryObject> { }): ObjectValue<webpack5.EntryObject> {
const entry = const entry =
typeof value !== 'object' || Array.isArray(value) typeof value !== 'object' || Array.isArray(value)
...@@ -209,8 +263,19 @@ export function finalizeEntrypoint({ ...@@ -209,8 +263,19 @@ export function finalizeEntrypoint({
} }
} }
if (name.match(MIDDLEWARE_ROUTE)) { if (isServerWeb) {
return { const ssrMiddlewareEntry = {
library: {
name: ['_ENTRIES', `middleware_[name]`],
type: 'assign',
},
runtime: MIDDLEWARE_SSR_RUNTIME_WEBPACK,
...entry,
}
return ssrMiddlewareEntry
}
if (isMiddleware) {
const middlewareEntry = {
filename: 'server/[name].js', filename: 'server/[name].js',
layer: 'middleware', layer: 'middleware',
library: { library: {
...@@ -219,6 +284,7 @@ export function finalizeEntrypoint({ ...@@ -219,6 +284,7 @@ export function finalizeEntrypoint({
}, },
...entry, ...entry,
} }
return middlewareEntry
} }
if ( if (
......
...@@ -42,6 +42,7 @@ import { ...@@ -42,6 +42,7 @@ import {
PAGES_MANIFEST, PAGES_MANIFEST,
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
PRERENDER_MANIFEST, PRERENDER_MANIFEST,
MIDDLEWARE_FLIGHT_MANIFEST,
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
ROUTES_MANIFEST, ROUTES_MANIFEST,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
...@@ -141,10 +142,15 @@ export default async function build( ...@@ -141,10 +142,15 @@ export default async function build(
const config: NextConfigComplete = await nextBuildSpan const config: NextConfigComplete = await nextBuildSpan
.traceChild('load-next-config') .traceChild('load-next-config')
.traceAsyncFn(() => loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)) .traceAsyncFn(() => loadConfig(PHASE_PRODUCTION_BUILD, dir, conf))
const distDir = path.join(dir, config.distDir) const distDir = path.join(dir, config.distDir)
setGlobal('phase', PHASE_PRODUCTION_BUILD) setGlobal('phase', PHASE_PRODUCTION_BUILD)
setGlobal('distDir', distDir) setGlobal('distDir', distDir)
const webServerRuntime = !!config.experimental.concurrentFeatures
const hasServerComponents =
webServerRuntime && !!config.experimental.serverComponents
const { target } = config const { target } = config
const buildId: string = await nextBuildSpan const buildId: string = await nextBuildSpan
.traceChild('generate-buildid') .traceChild('generate-buildid')
...@@ -256,7 +262,6 @@ export default async function build( ...@@ -256,7 +262,6 @@ export default async function build(
const pagePaths: string[] = await nextBuildSpan const pagePaths: string[] = await nextBuildSpan
.traceChild('collect-pages') .traceChild('collect-pages')
.traceAsyncFn(() => collectPages(pagesDir, config.pageExtensions)) .traceAsyncFn(() => collectPages(pagesDir, config.pageExtensions))
// needed for static exporting since we want to replace with HTML // needed for static exporting since we want to replace with HTML
// files // files
const allStaticPages = new Set<string>() const allStaticPages = new Set<string>()
...@@ -271,8 +276,14 @@ export default async function build( ...@@ -271,8 +276,14 @@ export default async function build(
const mappedPages = nextBuildSpan const mappedPages = nextBuildSpan
.traceChild('create-pages-mapping') .traceChild('create-pages-mapping')
.traceFn(() => .traceFn(() =>
createPagesMapping(pagePaths, config.pageExtensions, false) createPagesMapping(
pagePaths,
config.pageExtensions,
false,
hasServerComponents
) )
)
const entrypoints = nextBuildSpan const entrypoints = nextBuildSpan
.traceChild('create-entrypoints') .traceChild('create-entrypoints')
.traceFn(() => .traceFn(() =>
...@@ -538,6 +549,9 @@ export default async function build( ...@@ -538,6 +549,9 @@ export default async function build(
path.relative(distDir, manifestPath), path.relative(distDir, manifestPath),
BUILD_MANIFEST, BUILD_MANIFEST,
PRERENDER_MANIFEST, PRERENDER_MANIFEST,
hasServerComponents
? path.join(SERVER_DIRECTORY, MIDDLEWARE_FLIGHT_MANIFEST + '.js')
: null,
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
config.optimizeFonts config.optimizeFonts
? path.join( ? path.join(
...@@ -579,6 +593,20 @@ export default async function build( ...@@ -579,6 +593,20 @@ export default async function build(
rewrites, rewrites,
runWebpackSpan, runWebpackSpan,
}), }),
webServerRuntime
? getBaseWebpackConfig(dir, {
buildId,
reactProductionProfiling,
isServer: true,
webServerRuntime: true,
config,
target,
pagesDir,
entrypoints: entrypoints.serverWeb,
rewrites,
runWebpackSpan,
})
: null,
]) ])
) )
...@@ -609,9 +637,21 @@ export default async function build( ...@@ -609,9 +637,21 @@ export default async function build(
} }
} else { } else {
const serverResult = await runCompiler(configs[1], { runWebpackSpan }) const serverResult = await runCompiler(configs[1], { runWebpackSpan })
const serverWebResult = configs[2]
? await runCompiler(configs[2], { runWebpackSpan })
: null
result = { result = {
warnings: [...clientResult.warnings, ...serverResult.warnings], warnings: [
errors: [...clientResult.errors, ...serverResult.errors], ...clientResult.warnings,
...serverResult.warnings,
...(serverWebResult?.warnings || []),
],
errors: [
...clientResult.errors,
...serverResult.errors,
...(serverWebResult?.errors || []),
],
} }
} }
}) })
...@@ -839,6 +879,7 @@ export default async function build( ...@@ -839,6 +879,7 @@ export default async function build(
distDir, distDir,
config.experimental.gzipSize config.experimental.gzipSize
) )
await Promise.all( await Promise.all(
pageKeys.map(async (page) => { pageKeys.map(async (page) => {
const checkPageSpan = staticCheckSpan.traceChild('check-page', { const checkPageSpan = staticCheckSpan.traceChild('check-page', {
...@@ -858,8 +899,13 @@ export default async function build( ...@@ -858,8 +899,13 @@ export default async function build(
let isStatic = false let isStatic = false
let isHybridAmp = false let isHybridAmp = false
let ssgPageRoutes: string[] | null = null let ssgPageRoutes: string[] | null = null
let isMiddlewareRoute = !!page.match(MIDDLEWARE_ROUTE)
if (!page.match(MIDDLEWARE_ROUTE) && !page.match(RESERVED_PAGE)) { if (
!isMiddlewareRoute &&
!page.match(RESERVED_PAGE) &&
!webServerRuntime
) {
try { try {
let isPageStaticSpan = let isPageStaticSpan =
checkPageSpan.traceChild('is-page-static') checkPageSpan.traceChild('is-page-static')
...@@ -923,6 +969,7 @@ export default async function build( ...@@ -923,6 +969,7 @@ export default async function build(
serverPropsPages.add(page) serverPropsPages.add(page)
} else if ( } else if (
workerResult.isStatic && workerResult.isStatic &&
!workerResult.hasFlightData &&
(await customAppGetInitialPropsPromise) === false (await customAppGetInitialPropsPromise) === false
) { ) {
staticPages.add(page) staticPages.add(page)
...@@ -966,6 +1013,10 @@ export default async function build( ...@@ -966,6 +1013,10 @@ export default async function build(
totalSize: allSize, totalSize: allSize,
static: isStatic, static: isStatic,
isSsg, isSsg,
isWebSsr:
webServerRuntime &&
!isMiddlewareRoute &&
!page.match(RESERVED_PAGE),
isHybridAmp, isHybridAmp,
ssgPageRoutes, ssgPageRoutes,
initialRevalidateSeconds: false, initialRevalidateSeconds: false,
...@@ -1220,11 +1271,11 @@ export default async function build( ...@@ -1220,11 +1271,11 @@ export default async function build(
const routeRegex = getRouteRegex(dataRoute.replace(/\.json$/, '')) const routeRegex = getRouteRegex(dataRoute.replace(/\.json$/, ''))
dataRouteRegex = normalizeRouteRegex( dataRouteRegex = normalizeRouteRegex(
routeRegex.re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.json$') routeRegex.re.source.replace(/\(\?:\\\/\)\?\$$/, `\\.json$`)
) )
namedDataRouteRegex = routeRegex.namedRegex!.replace( namedDataRouteRegex = routeRegex.namedRegex!.replace(
/\(\?:\/\)\?\$$/, /\(\?:\/\)\?\$$/,
'\\.json$' `\\.json$`
) )
routeKeys = routeRegex.routeKeys routeKeys = routeRegex.routeKeys
} else { } else {
......
...@@ -12,6 +12,7 @@ export function startedDevelopmentServer(appUrl: string, bindAddr: string) { ...@@ -12,6 +12,7 @@ export function startedDevelopmentServer(appUrl: string, bindAddr: string) {
let previousClient: webpack5.Compiler | null = null let previousClient: webpack5.Compiler | null = null
let previousServer: webpack5.Compiler | null = null let previousServer: webpack5.Compiler | null = null
let previousServerWeb: webpack5.Compiler | null = null
type CompilerDiagnostics = { type CompilerDiagnostics = {
modules: number modules: number
...@@ -38,6 +39,7 @@ export type AmpPageStatus = { ...@@ -38,6 +39,7 @@ export type AmpPageStatus = {
type BuildStatusStore = { type BuildStatusStore = {
client: WebpackStatus client: WebpackStatus
server: WebpackStatus server: WebpackStatus
serverWeb?: WebpackStatus
trigger: string | undefined trigger: string | undefined
amp: AmpPageStatus amp: AmpPageStatus
} }
...@@ -100,16 +102,17 @@ const buildStore = createStore<BuildStatusStore>() ...@@ -100,16 +102,17 @@ const buildStore = createStore<BuildStatusStore>()
let buildWasDone = false let buildWasDone = false
let clientWasLoading = true let clientWasLoading = true
let serverWasLoading = true let serverWasLoading = true
let serverWebWasLoading = false
buildStore.subscribe((state) => { buildStore.subscribe((state) => {
const { amp, client, server, trigger } = state const { amp, client, server, serverWeb, trigger } = state
const { bootstrap: bootstrapping, appUrl } = consoleStore.getState() const { bootstrap: bootstrapping, appUrl } = consoleStore.getState()
if (bootstrapping && (client.loading || server.loading)) { if (bootstrapping && (client.loading || server.loading)) {
return return
} }
if (client.loading || server.loading) { if (client.loading || server.loading || serverWeb?.loading) {
consoleStore.setState( consoleStore.setState(
{ {
bootstrap: false, bootstrap: false,
...@@ -121,9 +124,12 @@ buildStore.subscribe((state) => { ...@@ -121,9 +124,12 @@ buildStore.subscribe((state) => {
) )
clientWasLoading = (!buildWasDone && clientWasLoading) || client.loading clientWasLoading = (!buildWasDone && clientWasLoading) || client.loading
serverWasLoading = (!buildWasDone && serverWasLoading) || server.loading serverWasLoading = (!buildWasDone && serverWasLoading) || server.loading
serverWebWasLoading =
(!buildWasDone && serverWasLoading) || !!serverWeb?.loading
buildWasDone = false buildWasDone = false
return return
} }
if (serverWeb?.loading) return
buildWasDone = true buildWasDone = true
...@@ -133,14 +139,17 @@ buildStore.subscribe((state) => { ...@@ -133,14 +139,17 @@ buildStore.subscribe((state) => {
loading: false, loading: false,
typeChecking: false, typeChecking: false,
partial: partial:
clientWasLoading && !serverWasLoading clientWasLoading && !serverWasLoading && !serverWebWasLoading
? 'client' ? 'client'
: serverWasLoading && !clientWasLoading : serverWasLoading && !clientWasLoading && !serverWebWasLoading
? 'server' ? 'server'
: serverWebWasLoading && !clientWasLoading && !serverWasLoading
? 'serverWeb'
: undefined, : undefined,
modules: modules:
(clientWasLoading ? client.modules : 0) + (clientWasLoading ? client.modules : 0) +
(serverWasLoading ? server.modules : 0), (serverWasLoading ? server.modules : 0) +
(serverWebWasLoading ? serverWeb?.modules || 0 : 0),
} }
if (client.errors) { if (client.errors) {
// Show only client errors // Show only client errors
...@@ -162,11 +171,22 @@ buildStore.subscribe((state) => { ...@@ -162,11 +171,22 @@ buildStore.subscribe((state) => {
} as OutputState, } as OutputState,
true true
) )
} else if (serverWeb && serverWeb.errors) {
// Show only serverWeb errors
consoleStore.setState(
{
...partialState,
errors: serverWeb.errors,
warnings: null,
} as OutputState,
true
)
} else { } else {
// Show warnings from all of them // Show warnings from all of them
const warnings = [ const warnings = [
...(client.warnings || []), ...(client.warnings || []),
...(server.warnings || []), ...(server.warnings || []),
...((serverWeb && serverWeb.warnings) || []),
...((Object.keys(amp).length > 0 && formatAmpMessages(amp)) || []), ...((Object.keys(amp).length > 0 && formatAmpMessages(amp)) || []),
] ]
...@@ -209,15 +229,21 @@ export function ampValidation( ...@@ -209,15 +229,21 @@ export function ampValidation(
export function watchCompilers( export function watchCompilers(
client: webpack5.Compiler, client: webpack5.Compiler,
server: webpack5.Compiler server: webpack5.Compiler,
serverWeb: webpack5.Compiler
) { ) {
if (previousClient === client && previousServer === server) { if (
previousClient === client &&
previousServer === server &&
previousServerWeb === serverWeb
) {
return return
} }
buildStore.setState({ buildStore.setState({
client: { loading: true }, client: { loading: true },
server: { loading: true }, server: { loading: true },
serverWeb: serverWeb ? { loading: true } : undefined,
trigger: 'initial', trigger: 'initial',
}) })
...@@ -276,9 +302,18 @@ export function watchCompilers( ...@@ -276,9 +302,18 @@ export function watchCompilers(
}) })
} }
}) })
if (serverWeb) {
tapCompiler('serverWeb', serverWeb, (status) => {
buildStore.setState({
serverWeb: status,
trigger: undefined,
})
})
}
previousClient = client previousClient = client
previousServer = server previousServer = server
previousServerWeb = serverWeb
} }
export function reportTrigger(trigger: string) { export function reportTrigger(trigger: string) {
......
...@@ -14,7 +14,7 @@ export type OutputState = ...@@ -14,7 +14,7 @@ export type OutputState =
| { | {
loading: false loading: false
typeChecking: boolean typeChecking: boolean
partial: 'client' | 'server' | undefined partial: 'client' | 'server' | 'serverWeb' | undefined
modules: number modules: number
errors: string[] | null errors: string[] | null
warnings: string[] | null warnings: string[] | null
......
...@@ -68,6 +68,7 @@ export interface PageInfo { ...@@ -68,6 +68,7 @@ export interface PageInfo {
totalSize: number totalSize: number
static: boolean static: boolean
isSsg: boolean isSsg: boolean
isWebSsr: boolean
ssgPageRoutes: string[] | null ssgPageRoutes: string[] | null
initialRevalidateSeconds: number | false initialRevalidateSeconds: number | false
pageDuration: number | undefined pageDuration: number | undefined
...@@ -176,7 +177,6 @@ export async function printTreeView( ...@@ -176,7 +177,6 @@ export async function printTreeView(
const pageInfo = pageInfos.get(item) const pageInfo = pageInfos.get(item)
const ampFirst = buildManifest.ampFirstPages.includes(item) const ampFirst = buildManifest.ampFirstPages.includes(item)
const totalDuration = const totalDuration =
(pageInfo?.pageDuration || 0) + (pageInfo?.pageDuration || 0) +
(pageInfo?.ssgPageDurations?.reduce((a, b) => a + (b || 0), 0) || 0) (pageInfo?.ssgPageDurations?.reduce((a, b) => a + (b || 0), 0) || 0)
...@@ -186,11 +186,14 @@ export async function printTreeView( ...@@ -186,11 +186,14 @@ export async function printTreeView(
? ' ' ? ' '
: item.endsWith('/_middleware') : item.endsWith('/_middleware')
? 'ƒ' ? 'ƒ'
: pageInfo?.isWebSsr
? 'ℇ'
: pageInfo?.static : pageInfo?.static
? '○' ? '○'
: pageInfo?.isSsg : pageInfo?.isSsg
? '●' ? '●'
: 'λ' : 'λ'
usedSymbols.add(symbol) usedSymbols.add(symbol)
if (pageInfo?.initialRevalidateSeconds) usedSymbols.add('ISR') if (pageInfo?.initialRevalidateSeconds) usedSymbols.add('ISR')
...@@ -354,6 +357,11 @@ export async function printTreeView( ...@@ -354,6 +357,11 @@ export async function printTreeView(
'(Middleware)', '(Middleware)',
`intercepts requests (uses ${chalk.cyan('_middleware')})`, `intercepts requests (uses ${chalk.cyan('_middleware')})`,
], ],
usedSymbols.has('ℇ') && [
'ℇ',
'(Streaming)',
`server-side renders with streaming (uses React 18 SSR streaming or Server Components)`,
],
usedSymbols.has('λ') && [ usedSymbols.has('λ') && [
'λ', 'λ',
serverless ? '(Lambda)' : '(Server)', serverless ? '(Lambda)' : '(Server)',
...@@ -841,6 +849,7 @@ export async function isPageStatic( ...@@ -841,6 +849,7 @@ export async function isPageStatic(
isStatic?: boolean isStatic?: boolean
isAmpOnly?: boolean isAmpOnly?: boolean
isHybridAmp?: boolean isHybridAmp?: boolean
hasFlightData?: boolean
hasServerProps?: boolean hasServerProps?: boolean
hasStaticProps?: boolean hasStaticProps?: boolean
prerenderRoutes?: string[] prerenderRoutes?: string[]
...@@ -855,6 +864,7 @@ export async function isPageStatic( ...@@ -855,6 +864,7 @@ export async function isPageStatic(
try { try {
require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig) require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig)
setHttpAgentOptions(httpAgentOptions) setHttpAgentOptions(httpAgentOptions)
const mod = await loadComponents(distDir, page, serverless) const mod = await loadComponents(distDir, page, serverless)
const Comp = mod.Component const Comp = mod.Component
...@@ -862,6 +872,7 @@ export async function isPageStatic( ...@@ -862,6 +872,7 @@ export async function isPageStatic(
throw new Error('INVALID_DEFAULT_EXPORT') throw new Error('INVALID_DEFAULT_EXPORT')
} }
const hasFlightData = !!(Comp as any).__next_rsc__
const hasGetInitialProps = !!(Comp as any).getInitialProps const hasGetInitialProps = !!(Comp as any).getInitialProps
const hasStaticProps = !!mod.getStaticProps const hasStaticProps = !!mod.getStaticProps
const hasStaticPaths = !!mod.getStaticPaths const hasStaticPaths = !!mod.getStaticPaths
...@@ -949,7 +960,11 @@ export async function isPageStatic( ...@@ -949,7 +960,11 @@ export async function isPageStatic(
const isNextImageImported = (global as any).__NEXT_IMAGE_IMPORTED const isNextImageImported = (global as any).__NEXT_IMAGE_IMPORTED
const config: PageConfig = mod.pageConfig const config: PageConfig = mod.pageConfig
return { return {
isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps, isStatic:
!hasStaticProps &&
!hasGetInitialProps &&
!hasServerProps &&
!hasFlightData,
isHybridAmp: config.amp === 'hybrid', isHybridAmp: config.amp === 'hybrid',
isAmpOnly: config.amp === true, isAmpOnly: config.amp === true,
prerenderRoutes, prerenderRoutes,
...@@ -957,6 +972,7 @@ export async function isPageStatic( ...@@ -957,6 +972,7 @@ export async function isPageStatic(
encodedPrerenderRoutes, encodedPrerenderRoutes,
hasStaticProps, hasStaticProps,
hasServerProps, hasServerProps,
hasFlightData,
isNextImageImported, isNextImageImported,
traceIncludes: config.unstable_includeFiles || [], traceIncludes: config.unstable_includeFiles || [],
traceExcludes: config.unstable_excludeFiles || [], traceExcludes: config.unstable_excludeFiles || [],
...@@ -1090,3 +1106,30 @@ export function getCssFilePaths(buildManifest: BuildManifest): string[] { ...@@ -1090,3 +1106,30 @@ export function getCssFilePaths(buildManifest: BuildManifest): string[] {
return [...cssFiles] return [...cssFiles]
} }
export function getRawPageExtensions(pageExtensions: string[]): string[] {
return pageExtensions.filter(
(ext) => !ext.startsWith('client.') && !ext.startsWith('server.')
)
}
export function isFlightPage(
nextConfig: NextConfigComplete,
pagePath: string
): boolean {
if (
!(
nextConfig.experimental.serverComponents &&
nextConfig.experimental.concurrentFeatures
)
)
return false
const rawPageExtensions = getRawPageExtensions(
nextConfig.pageExtensions || []
)
const isRscPage = rawPageExtensions.some((ext) => {
return new RegExp(`\\.server\\.${ext}$`).test(pagePath)
})
return isRscPage
}
This diff is collapsed.
...@@ -7,21 +7,28 @@ export const base = curry(function base( ...@@ -7,21 +7,28 @@ export const base = curry(function base(
config: webpack.Configuration config: webpack.Configuration
) { ) {
config.mode = ctx.isDevelopment ? 'development' : 'production' config.mode = ctx.isDevelopment ? 'development' : 'production'
config.name = ctx.isServer ? 'server' : 'client' config.name = ctx.isServer
? ctx.webServerRuntime
? 'server-web'
: 'server'
: 'client'
// @ts-ignore TODO webpack 5 typings // @ts-ignore TODO webpack 5 typings
config.target = ctx.isServer ? 'node12.22' : ['web', 'es5'] config.target = !ctx.targetWeb ? 'node12.22' : ['web', 'es5']
// https://webpack.js.org/configuration/devtool/#development // https://webpack.js.org/configuration/devtool/#development
if (ctx.isDevelopment) { if (ctx.isDevelopment) {
if (process.env.__NEXT_TEST_MODE && !process.env.__NEXT_TEST_WITH_DEVTOOL) { if (process.env.__NEXT_TEST_MODE && !process.env.__NEXT_TEST_WITH_DEVTOOL) {
config.devtool = false config.devtool = false
} else { } else {
if (!ctx.webServerRuntime) {
// `eval-source-map` provides full-fidelity source maps for the // `eval-source-map` provides full-fidelity source maps for the
// original source, including columns and original variable names. // original source, including columns and original variable names.
// This is desirable so the in-browser debugger can correctly pause // This is desirable so the in-browser debugger can correctly pause
// and show scoped variables with their original names. // and show scoped variables with their original names.
config.devtool = 'eval-source-map' config.devtool = 'eval-source-map'
} }
}
} else { } else {
// Enable browser sourcemaps: // Enable browser sourcemaps:
if (ctx.productionBrowserSourceMaps && ctx.isClient) { if (ctx.productionBrowserSourceMaps && ctx.isClient) {
......
...@@ -12,6 +12,8 @@ export async function build( ...@@ -12,6 +12,8 @@ export async function build(
customAppFile, customAppFile,
isDevelopment, isDevelopment,
isServer, isServer,
webServerRuntime,
targetWeb,
assetPrefix, assetPrefix,
sassOptions, sassOptions,
productionBrowserSourceMaps, productionBrowserSourceMaps,
...@@ -22,6 +24,8 @@ export async function build( ...@@ -22,6 +24,8 @@ export async function build(
customAppFile: RegExp customAppFile: RegExp
isDevelopment: boolean isDevelopment: boolean
isServer: boolean isServer: boolean
webServerRuntime: boolean
targetWeb: boolean
assetPrefix: string assetPrefix: string
sassOptions: any sassOptions: any
productionBrowserSourceMaps: boolean productionBrowserSourceMaps: boolean
...@@ -35,7 +39,9 @@ export async function build( ...@@ -35,7 +39,9 @@ export async function build(
isDevelopment, isDevelopment,
isProduction: !isDevelopment, isProduction: !isDevelopment,
isServer, isServer,
webServerRuntime,
isClient: !isServer, isClient: !isServer,
targetWeb,
assetPrefix: assetPrefix assetPrefix: assetPrefix
? assetPrefix.endsWith('/') ? assetPrefix.endsWith('/')
? assetPrefix.slice(0, -1) ? assetPrefix.slice(0, -1)
......
...@@ -10,6 +10,8 @@ export type ConfigurationContext = { ...@@ -10,6 +10,8 @@ export type ConfigurationContext = {
isServer: boolean isServer: boolean
isClient: boolean isClient: boolean
webServerRuntime: boolean
targetWeb: boolean
assetPrefix: string assetPrefix: string
......
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as acorn from 'acorn'
type ResolveContext = {
conditions: Array<string>
parentURL: string | void
}
type ResolveFunction = (
specifier: string,
context: ResolveContext,
resolve: ResolveFunction
) => { url: string } | Promise<{ url: string }>
type TransformSourceFunction = (url: string, callback: () => void) => void
type Source = string | ArrayBuffer | Uint8Array
let stashedResolve: null | ResolveFunction = null
function addExportNames(names: string[], node: any) {
switch (node.type) {
case 'Identifier':
names.push(node.name)
return
case 'ObjectPattern':
for (let i = 0; i < node.properties.length; i++)
addExportNames(names, node.properties[i])
return
case 'ArrayPattern':
for (let i = 0; i < node.elements.length; i++) {
const element = node.elements[i]
if (element) addExportNames(names, element)
}
return
case 'Property':
addExportNames(names, node.value)
return
case 'AssignmentPattern':
addExportNames(names, node.left)
return
case 'RestElement':
addExportNames(names, node.argument)
return
case 'ParenthesizedExpression':
addExportNames(names, node.expression)
return
default:
return
}
}
function resolveClientImport(
specifier: string,
parentURL: string
): { url: string } | Promise<{ url: string }> {
// Resolve an import specifier as if it was loaded by the client. This doesn't use
// the overrides that this loader does but instead reverts to the default.
// This resolution algorithm will not necessarily have the same configuration
// as the actual client loader. It should mostly work and if it doesn't you can
// always convert to explicit exported names instead.
const conditions = ['node', 'import']
if (stashedResolve === null) {
throw new Error(
'Expected resolve to have been called before transformSource'
)
}
return stashedResolve(specifier, { conditions, parentURL }, stashedResolve)
}
async function parseExportNamesInto(
transformedSource: string,
names: Array<string>,
parentURL: string,
loadModule: TransformSourceFunction
): Promise<void> {
const { body } = acorn.parse(transformedSource, {
ecmaVersion: 2019,
sourceType: 'module',
}) as any
for (let i = 0; i < body.length; i++) {
const node = body[i]
switch (node.type) {
case 'ExportAllDeclaration':
if (node.exported) {
addExportNames(names, node.exported)
continue
} else {
const { url } = await resolveClientImport(
node.source.value,
parentURL
)
const source = ''
parseExportNamesInto(source, names, url, loadModule)
continue
}
case 'ExportDefaultDeclaration':
names.push('default')
continue
case 'ExportNamedDeclaration':
if (node.declaration) {
if (node.declaration.type === 'VariableDeclaration') {
const declarations = node.declaration.declarations
for (let j = 0; j < declarations.length; j++) {
addExportNames(names, declarations[j].id)
}
} else {
addExportNames(names, node.declaration.id)
}
}
if (node.specificers) {
const specificers = node.specificers
for (let j = 0; j < specificers.length; j++) {
addExportNames(names, specificers[j].exported)
}
}
continue
default:
return
}
}
}
export default async function transformSource(
this: any,
source: Source
): Promise<Source> {
const { resourcePath, resourceQuery } = this
if (resourceQuery !== '?flight') return source
let url = resourcePath
const transformedSource = source
if (typeof transformedSource !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
const names: string[] = []
await parseExportNamesInto(
transformedSource as string,
names,
url + resourceQuery,
this.loadModule
)
// next.js/packages/next/link.js
if (/[\\/]next[\\/](link|image)\.js$/.test(url)) {
names.push('default')
}
let newSrc =
"const MODULE_REFERENCE = Symbol.for('react.module.reference');\n"
for (let i = 0; i < names.length; i++) {
const name = names[i]
if (name === 'default') {
newSrc += 'export default '
} else {
newSrc += 'export const ' + name + ' = '
}
newSrc += '{ $$typeof: MODULE_REFERENCE, filepath: '
newSrc += JSON.stringify(url)
newSrc += ', name: '
newSrc += JSON.stringify(name)
newSrc += '};\n'
}
return newSrc
}
import loaderUtils from 'next/dist/compiled/loader-utils'
import * as acorn from 'acorn'
import { getRawPageExtensions } from '../../utils'
function isClientComponent(importSource: string, pageExtensions: string[]) {
return new RegExp(`\\.client(\\.(${pageExtensions.join('|')}))?`).test(
importSource
)
}
function isNextComponent(importSource: string) {
return (
importSource.includes('next/link') || importSource.includes('next/image')
)
}
export function isImageImport(importSource: string) {
// TODO: share extension with next/image
// TODO: add other static assets, jpeg -> jpg
return ['jpg', 'jpeg', 'png', 'webp', 'avif'].some((imageExt) =>
importSource.endsWith('.' + imageExt)
)
}
async function parseImportsInfo(
source: string,
imports: Array<string>,
isClientCompilation: boolean,
pageExtensions: string[]
): Promise<string> {
const { body } = acorn.parse(source, {
ecmaVersion: 2019,
sourceType: 'module',
}) as any
let transformedSource = ''
let lastIndex = 0
for (let i = 0; i < body.length; i++) {
const node = body[i]
switch (node.type) {
case 'ImportDeclaration':
// When importing from a server component, ignore
const importSource = node.source.value
if (
!(
isClientComponent(importSource, pageExtensions) ||
isNextComponent(importSource) ||
isImageImport(importSource)
)
) {
continue
}
if (!isClientCompilation) {
transformedSource += source.substr(
lastIndex,
node.source.start - lastIndex
)
transformedSource += JSON.stringify(`${node.source.value}?flight`)
}
lastIndex = node.source.end
imports.push(`require(${JSON.stringify(importSource)})`)
continue
default:
break
}
}
if (!isClientCompilation) {
transformedSource += source.substr(lastIndex)
}
return transformedSource
}
export default async function transformSource(
this: any,
source: string
): Promise<string> {
const { client: isClientCompilation, pageExtensions: pageExtensionsJson } =
loaderUtils.getOptions(this)
const { resourcePath } = this
const pageExtensions = JSON.parse(pageExtensionsJson)
if (typeof source !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
if (resourcePath.includes('/node_modules/')) {
return source
}
const imports: string[] = []
const transformed = await parseImportsInfo(
source,
imports,
isClientCompilation,
getRawPageExtensions(pageExtensions)
)
const noop = `\nexport const __rsc_noop__=()=>{${imports.join(';')}}`
const defaultExportNoop = isClientCompilation
? `\nexport default function Comp(){}\nComp.__next_rsc__=1`
: ''
return transformed + noop + defaultExportNoop
}
import loaderUtils from 'next/dist/compiled/loader-utils'
import { getStringifiedAbsolutePath } from './utils'
export default function middlewareRSCLoader(this: any) {
const {
absolutePagePath,
basePath,
isServerComponent,
assetPrefix,
buildId,
} = loaderUtils.getOptions(this)
const stringifiedAbsolutePagePath = loaderUtils.stringifyRequest(
this,
absolutePagePath
)
const stringifiedAbsoluteDocumentPath = getStringifiedAbsolutePath(
this,
'./pages/_document'
)
const stringifiedAbsoluteAppPath = getStringifiedAbsolutePath(
this,
'./pages/_app'
)
const transformed = `
import { adapter } from 'next/dist/server/web/adapter'
import { RouterContext } from 'next/dist/shared/lib/router-context'
import { renderToHTML } from 'next/dist/server/web/render'
import React, { createElement } from 'react'
import ReactDOMServer from 'react-dom/server.browser'
${
isServerComponent
? `
import { renderToReadableStream } from 'react-server-dom-webpack/writer.browser.server'
import { createFromReadableStream } from 'react-server-dom-webpack'`
: ''
}
var {
default: Page,
config,
getStaticProps,
getServerSideProps,
getStaticPaths
} = require(${stringifiedAbsolutePagePath})
var Document = require(${stringifiedAbsoluteDocumentPath}).default
var App = require(${stringifiedAbsoluteAppPath}).default
const buildManifest = self.__BUILD_MANIFEST
const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST
const rscManifest = self._middleware_rsc_manifest
if (typeof Page !== 'function') {
throw new Error('Your page must export a \`default\` component');
}
function wrapReadable (readable) {
var encoder = new TextEncoder()
var transformStream = new TransformStream()
var writer = transformStream.writable.getWriter()
var reader = readable.getReader()
var process = () => {
reader.read().then(({ done, value }) => {
if (!done) {
writer.write(typeof value === 'string' ? encoder.encode(value) : value)
process()
} else {
writer.close()
}
})
}
process()
return transformStream.readable
}
${
isServerComponent
? `
const renderFlight = props => renderToReadableStream(createElement(Page, props), rscManifest)
let responseCache
const FlightWrapper = props => {
var response = responseCache
if (!response) {
responseCache = response = createFromReadableStream(renderFlight(props))
}
return response.readRoot()
}
const Component = props => {
return createElement(
React.Suspense,
{ fallback: null },
createElement(FlightWrapper, props)
)
}`
: `
const Component = Page`
}
function render(request) {
const url = request.nextUrl
const query = Object.fromEntries(url.searchParams)
// Preflight request
if (request.method === 'HEAD') {
return new Response('OK.', {
headers: { 'x-middleware-ssr': '1' }
})
}
${
isServerComponent
? `
// Flight data request
const isFlightDataRequest = query.__flight__ !== undefined
if (isFlightDataRequest) {
delete query.__flight__
return new Response(
wrapReadable(
renderFlight({
router: {
route: url.pathname,
asPath: url.pathname,
pathname: url.pathname,
query,
}
})
)
)
}`
: ''
}
const renderOpts = {
Component,
pageConfig: config || {},
// Locales are not supported yet.
// locales: i18n?.locales,
// locale: detectedLocale,
// defaultLocale,
// domainLocales: i18n?.domains,
App,
Document,
buildManifest,
getStaticProps,
getServerSideProps,
getStaticPaths,
reactLoadableManifest,
buildId: ${JSON.stringify(buildId)},
assetPrefix: ${JSON.stringify(assetPrefix || '')},
env: process.env,
basePath: ${JSON.stringify(basePath || '')},
supportsDynamicHTML: true,
concurrentFeatures: true,
renderServerComponent: ${isServerComponent ? 'true' : 'false'},
}
const transformStream = new TransformStream()
const writer = transformStream.writable.getWriter()
const encoder = new TextEncoder()
renderToHTML(
{ url: url.pathname },
{},
url.pathname,
query,
renderOpts
).then(result => {
result.pipe({
write: str => writer.write(encoder.encode(str)),
end: () => writer.close()
})
})
return new Response(transformStream.readable, {
headers: { 'x-middleware-ssr': '1' }
})
}
export default function rscMiddleware(opts) {
return adapter({
...opts,
handler: render
})
}
`
return transformed
}
import loaderUtils from 'next/dist/compiled/loader-utils'
export function getStringifiedAbsolutePath(target: any, path: string) {
return loaderUtils.stringifyRequest(
target,
target.utils.absolutify(target.rootContext, path)
)
}
...@@ -2,6 +2,7 @@ import devalue from 'next/dist/compiled/devalue' ...@@ -2,6 +2,7 @@ import devalue from 'next/dist/compiled/devalue'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { import {
BUILD_MANIFEST, BUILD_MANIFEST,
MIDDLEWARE_BUILD_MANIFEST,
CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_PATH,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
...@@ -93,11 +94,13 @@ export default class BuildManifestPlugin { ...@@ -93,11 +94,13 @@ export default class BuildManifestPlugin {
private buildId: string private buildId: string
private rewrites: CustomRoutes['rewrites'] private rewrites: CustomRoutes['rewrites']
private isDevFallback: boolean private isDevFallback: boolean
private exportRuntime: boolean
constructor(options: { constructor(options: {
buildId: string buildId: string
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
isDevFallback?: boolean isDevFallback?: boolean
exportRuntime?: boolean
}) { }) {
this.buildId = options.buildId this.buildId = options.buildId
this.isDevFallback = !!options.isDevFallback this.isDevFallback = !!options.isDevFallback
...@@ -109,6 +112,7 @@ export default class BuildManifestPlugin { ...@@ -109,6 +112,7 @@ export default class BuildManifestPlugin {
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)
this.exportRuntime = !!options.exportRuntime
} }
createAssets(compiler: any, compilation: any, assets: any) { createAssets(compiler: any, compilation: any, assets: any) {
...@@ -228,6 +232,13 @@ export default class BuildManifestPlugin { ...@@ -228,6 +232,13 @@ export default class BuildManifestPlugin {
JSON.stringify(assetMap, null, 2) JSON.stringify(assetMap, null, 2)
) )
if (this.exportRuntime) {
assets[`server/${MIDDLEWARE_BUILD_MANIFEST}.js`] =
new sources.RawSource(
`self.__BUILD_MANIFEST=${JSON.stringify(assetMap)}`
)
}
if (!this.isDevFallback) { if (!this.isDevFallback) {
const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js` const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
......
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { MIDDLEWARE_FLIGHT_MANIFEST } from '../../../shared/lib/constants'
// This is the module that will be used to anchor all client references to.
// I.e. it will have all the client files as async deps from this point on.
// We use the Flight client implementation because you can't get to these
// without the client runtime so it's the first time in the loading sequence
// you might want them.
// const clientFileName = require.resolve('../');
type Options = {
dev: boolean
clientComponentsRegex: RegExp
}
const PLUGIN_NAME = 'FlightManifestPlugin'
export class FlightManifestPlugin {
dev: boolean = false
clientComponentsRegex: RegExp
constructor(options: Options) {
if (typeof options.dev === 'boolean') {
this.dev = options.dev
}
this.clientComponentsRegex = options.clientComponentsRegex
}
apply(compiler: any) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation: any, { normalModuleFactory }: any) => {
compilation.dependencyFactories.set(
(webpack as any).dependencies.ModuleDependency,
normalModuleFactory
)
compilation.dependencyTemplates.set(
(webpack as any).dependencies.ModuleDependency,
new (webpack as any).dependencies.NullDependency.Template()
)
}
)
// Only for webpack 5
compiler.hooks.make.tap(PLUGIN_NAME, (compilation: any) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => this.createAsset(assets, compilation, compiler)
)
})
}
createAsset(assets: any, compilation: any, compiler: any) {
const json: any = {}
const { clientComponentsRegex } = this
compilation.chunkGroups.forEach((chunkGroup: any) => {
function recordModule(id: string, _chunk: any, mod: any) {
const resource = mod.resource?.replace(/\?flight$/, '')
// TODO: Hook into deps instead of the target module.
// That way we know by the type of dep whether to include.
// It also resolves conflicts when the same module is in multiple chunks.
const isNextClientComponent = /next[\\/](link|image)/.test(resource)
if (!clientComponentsRegex.test(resource) && !isNextClientComponent) {
return
}
const moduleExports: any = json[resource] || {}
const exportsInfo = compilation.moduleGraph.getExportsInfo(mod)
const providedExports = exportsInfo.getProvidedExports()
const moduleExportedKeys = ['', '*'].concat(
// TODO: improve exports detection
providedExports === true || providedExports == null
? 'default'
: providedExports
)
moduleExportedKeys.forEach((name) => {
if (!moduleExports[name]) {
moduleExports[name] = {
id,
name,
chunks: [],
}
}
})
json[resource] = moduleExports
}
chunkGroup.chunks.forEach((chunk: any) => {
const chunkModules =
compilation.chunkGraph.getChunkModulesIterable(chunk)
for (const mod of chunkModules) {
let modId: string
const context = compiler.context
const nameForCondition = mod.nameForCondition()
if (nameForCondition && nameForCondition.startsWith(context)) {
modId = '.' + nameForCondition.slice(context.length)
} else {
modId = compilation.chunkGraph.getModuleId(mod)
}
// remove resource query on production
if (typeof modId === 'string') {
modId = modId.split('?')[0]
}
recordModule(modId, chunk, mod)
// If this is a concatenation, register each child to the parent ID.
if (mod.modules) {
mod.modules.forEach((concatenatedMod: any) => {
recordModule(modId, chunk, concatenatedMod)
})
}
}
})
})
const output =
`self._middleware_rsc_manifest=(typeof _ENTRIES === "undefined"?{}:_ENTRIES)._middleware_rsc_manifest=` +
JSON.stringify(json)
assets[`server/${MIDDLEWARE_FLIGHT_MANIFEST}.js`] = new sources.RawSource(
output
)
}
}
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { getMiddlewareRegex } from '../../../shared/lib/router/utils' import { getMiddlewareRegex } from '../../../shared/lib/router/utils'
import { getSortedRoutes } from '../../../shared/lib/router/utils' import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { MIDDLEWARE_MANIFEST } from '../../../shared/lib/constants' import {
MIDDLEWARE_MANIFEST,
MIDDLEWARE_FLIGHT_MANIFEST,
MIDDLEWARE_SSR_RUNTIME_WEBPACK,
MIDDLEWARE_BUILD_MANIFEST,
MIDDLEWARE_REACT_LOADABLE_MANIFEST,
} from '../../../shared/lib/constants'
import { MIDDLEWARE_ROUTE } from '../../../lib/constants' import { MIDDLEWARE_ROUTE } from '../../../lib/constants'
import { nonNullable } from '../../../lib/non-nullable'
const PLUGIN_NAME = 'MiddlewarePlugin' const PLUGIN_NAME = 'MiddlewarePlugin'
const MIDDLEWARE_FULL_ROUTE_REGEX = /^pages[/\\]?(.*)\/_middleware$/ const MIDDLEWARE_FULL_ROUTE_REGEX = /^pages[/\\]?(.*)\/_middleware$/
export const ssrEntries = new Map<string, { requireFlightManifest: boolean }>()
export interface MiddlewareManifest { export interface MiddlewareManifest {
version: 1 version: 1
sortedMiddleware: string[] sortedMiddleware: [string, boolean][]
middleware: { middleware: {
[page: string]: { [page: string]: {
env: string[] env: string[]
...@@ -23,9 +32,17 @@ export interface MiddlewareManifest { ...@@ -23,9 +32,17 @@ export interface MiddlewareManifest {
export default class MiddlewarePlugin { export default class MiddlewarePlugin {
dev: boolean dev: boolean
hasServerComponents?: boolean
constructor({ dev }: { dev: boolean }) { constructor({
dev,
hasServerComponents,
}: {
dev: boolean
hasServerComponents?: boolean
}) {
this.dev = dev this.dev = dev
this.hasServerComponents = hasServerComponents
} }
createAssets( createAssets(
...@@ -42,12 +59,28 @@ export default class MiddlewarePlugin { ...@@ -42,12 +59,28 @@ export default class MiddlewarePlugin {
for (const entrypoint of entrypoints.values()) { for (const entrypoint of entrypoints.values()) {
const result = MIDDLEWARE_FULL_ROUTE_REGEX.exec(entrypoint.name) const result = MIDDLEWARE_FULL_ROUTE_REGEX.exec(entrypoint.name)
const location = result ? `/${result[1]}` : null const ssrEntryInfo = ssrEntries.get(entrypoint.name)
const location = result
? `/${result[1]}`
: ssrEntryInfo
? entrypoint.name.slice('pages'.length).replace(/\/index$/, '') || '/'
: null
if (!location) { if (!location) {
continue continue
} }
const files = ssrEntryInfo
const files = entrypoint ? [
`server/${MIDDLEWARE_SSR_RUNTIME_WEBPACK}.js`,
ssrEntryInfo.requireFlightManifest
? `server/${MIDDLEWARE_FLIGHT_MANIFEST}.js`
: null,
`server/${MIDDLEWARE_BUILD_MANIFEST}.js`,
`server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`,
`server/${entrypoint.name}.js`,
].filter(nonNullable)
: entrypoint
.getFiles() .getFiles()
.filter((file: string) => !file.endsWith('.hot-update.js')) .filter((file: string) => !file.endsWith('.hot-update.js'))
.map((file: string) => .map((file: string) =>
...@@ -59,17 +92,22 @@ export default class MiddlewarePlugin { ...@@ -59,17 +92,22 @@ export default class MiddlewarePlugin {
) )
middlewareManifest.middleware[location] = { middlewareManifest.middleware[location] = {
env: envPerRoute.get(entrypoint.name)!, env: envPerRoute.get(entrypoint.name) || [],
files, files,
name: entrypoint.name, name: entrypoint.name,
page: location, page: location,
regexp: getMiddlewareRegex(location).namedRegex!, regexp: getMiddlewareRegex(location, !ssrEntryInfo).namedRegex!,
} }
} }
middlewareManifest.sortedMiddleware = getSortedRoutes( middlewareManifest.sortedMiddleware = getSortedRoutes(
Object.keys(middlewareManifest.middleware) Object.keys(middlewareManifest.middleware)
).map((key) => {
const ssrEntryInfo = ssrEntries.get(
middlewareManifest.middleware[key].name
) )
return [key, !!ssrEntryInfo]
})
assets[`server/${MIDDLEWARE_MANIFEST}`] = new sources.RawSource( assets[`server/${MIDDLEWARE_MANIFEST}`] = new sources.RawSource(
JSON.stringify(middlewareManifest, null, 2) JSON.stringify(middlewareManifest, null, 2)
......
...@@ -145,10 +145,16 @@ function buildManifest( ...@@ -145,10 +145,16 @@ function buildManifest(
export class ReactLoadablePlugin { export class ReactLoadablePlugin {
private filename: string private filename: string
private pagesDir: string private pagesDir: string
private runtimeAsset?: string
constructor(opts: { filename: string; pagesDir: string }) { constructor(opts: {
filename: string
pagesDir: string
runtimeAsset?: string
}) {
this.filename = opts.filename this.filename = opts.filename
this.pagesDir = opts.pagesDir this.pagesDir = opts.pagesDir
this.runtimeAsset = opts.runtimeAsset
} }
createAssets(compiler: any, compilation: any, assets: any) { createAssets(compiler: any, compilation: any, assets: any) {
...@@ -157,6 +163,11 @@ export class ReactLoadablePlugin { ...@@ -157,6 +163,11 @@ export class ReactLoadablePlugin {
assets[this.filename] = new sources.RawSource( assets[this.filename] = new sources.RawSource(
JSON.stringify(manifest, null, 2) JSON.stringify(manifest, null, 2)
) )
if (this.runtimeAsset) {
assets[this.runtimeAsset] = new sources.RawSource(
`self.__REACT_LOADABLE_MANIFEST=${JSON.stringify(manifest)}`
)
}
return assets return assets
} }
......
...@@ -301,7 +301,11 @@ export class TerserPlugin { ...@@ -301,7 +301,11 @@ export class TerserPlugin {
compiler.hooks.compilation.tap(pluginName, (compilation) => { compiler.hooks.compilation.tap(pluginName, (compilation) => {
// Don't run minifier against mini-css-extract-plugin // Don't run minifier against mini-css-extract-plugin
if (compilation.name !== 'client' && compilation.name !== 'server') { if (
compilation.name !== 'client' &&
compilation.name !== 'server' &&
compilation.name !== 'server-web'
) {
return return
} }
......
...@@ -84,7 +84,10 @@ export async function getNotFoundError( ...@@ -84,7 +84,10 @@ export async function getNotFoundError(
) )
.filter( .filter(
(name) => (name) =>
name && !/next-(middleware|client-pages)-loader\.js/.test(name) name &&
!/next-(middleware|client-pages|flight-(client|server))-loader\.js/.test(
name
)
) )
if (moduleTrace.length === 0) return '' if (moduleTrace.length === 0) return ''
......
...@@ -39,7 +39,9 @@ function formatMessage(message, verbose) { ...@@ -39,7 +39,9 @@ function formatMessage(message, verbose) {
message.moduleTrace && message.moduleTrace &&
message.moduleTrace.filter( message.moduleTrace.filter(
(trace) => (trace) =>
!/next-(middleware|client-pages)-loader\.js/.test(trace.originName) !/next-(middleware|client-pages|flight-(client|server))-loader\.js/.test(
trace.originName
)
) )
message = message =
(message.moduleName ? stripAnsi(message.moduleName) + '\n' : '') + (message.moduleName ? stripAnsi(message.moduleName) + '\n' : '') +
......
...@@ -31,7 +31,7 @@ import initHeadManager from './head-manager' ...@@ -31,7 +31,7 @@ import initHeadManager from './head-manager'
import PageLoader, { StyleSheetTuple } from './page-loader' import PageLoader, { StyleSheetTuple } from './page-loader'
import measureWebVitals from './performance-relayer' import measureWebVitals from './performance-relayer'
import { RouteAnnouncer } from './route-announcer' import { RouteAnnouncer } from './route-announcer'
import { createRouter, makePublicRouterInstance } from './router' import { createRouter, makePublicRouterInstance, useRouter } from './router'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { trackWebVitalMetric } from './vitals' import { trackWebVitalMetric } from './vitals'
...@@ -81,6 +81,7 @@ const { ...@@ -81,6 +81,7 @@ const {
locales, locales,
domainLocales, domainLocales,
isPreview, isPreview,
rsc,
} = data } = data
let { defaultLocale } = data let { defaultLocale } = data
...@@ -639,17 +640,78 @@ const wrapApp = ...@@ -639,17 +640,78 @@ const wrapApp =
) )
} }
let RSCComponent: (props: any) => JSX.Element
if (process.env.__NEXT_RSC) {
function createResponseCache() {
return new Map<string, any>()
}
const rscCache = createResponseCache()
const RSCWrapper = ({
cacheKey,
serialized,
_fresh,
}: {
cacheKey: string
serialized?: string
_fresh?: boolean
}) => {
const { createFromFetch } = require('react-server-dom-webpack')
let response = rscCache.get(cacheKey)
// If there is no cache, or there is serialized data already
if (!response) {
response = createFromFetch(
serialized
? (() => {
const t = new TransformStream()
t.writable.getWriter().write(new TextEncoder().encode(serialized))
return Promise.resolve({ body: t.readable })
})()
: (() => {
const search = location.search
const flightReqUrl =
location.pathname +
search +
(search ? '&__flight__' : '?__flight__')
return fetch(flightReqUrl)
})()
)
rscCache.set(cacheKey, response)
}
const root = response.readRoot()
return root
}
RSCComponent = (props: any) => {
const { asPath: cacheKey } = useRouter() as any
return (
<React.Suspense fallback={null}>
<RSCWrapper
cacheKey={cacheKey}
serialized={(props as any).__flight_serialized__}
_fresh={(props as any).__flight_fresh__}
/>
</React.Suspense>
)
}
}
let lastAppProps: AppProps let lastAppProps: AppProps
function doRender(input: RenderRouteInfo): Promise<any> { function doRender(input: RenderRouteInfo): Promise<any> {
let { App, Component, props, err }: RenderRouteInfo = input let { App, Component, props, err, __N_RSC }: RenderRouteInfo = input
let styleSheets: StyleSheetTuple[] | undefined = let styleSheets: StyleSheetTuple[] | undefined =
'initial' in input ? undefined : input.styleSheets 'initial' in input ? undefined : input.styleSheets
Component = Component || lastAppProps.Component Component = Component || lastAppProps.Component
props = props || lastAppProps.props props = props || lastAppProps.props
const isRSC = process.env.__NEXT_RSC && 'initial' in input ? !!rsc : !!__N_RSC
const appProps: AppProps = { const appProps: AppProps = {
...props, ...props,
Component, Component: isRSC ? RSCComponent : Component,
err, err,
router, router,
} }
......
...@@ -38,7 +38,7 @@ export default class PageLoader { ...@@ -38,7 +38,7 @@ export default class PageLoader {
private promisedSsgManifest?: Promise<ClientSsgManifest> private promisedSsgManifest?: Promise<ClientSsgManifest>
private promisedDevPagesManifest?: Promise<any> private promisedDevPagesManifest?: Promise<any>
private promisedMiddlewareManifest?: Promise<string[]> private promisedMiddlewareManifest?: Promise<[string, boolean][]>
public routeLoader: RouteLoader public routeLoader: RouteLoader
constructor(buildId: string, assetPrefix: string) { constructor(buildId: string, assetPrefix: string) {
...@@ -84,7 +84,7 @@ export default class PageLoader { ...@@ -84,7 +84,7 @@ export default class PageLoader {
} }
} }
getMiddlewareList(): Promise<string[]> { getMiddlewareList(): Promise<[string, boolean][]> {
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
return getMiddlewareManifest() return getMiddlewareManifest()
} else { } else {
...@@ -114,17 +114,26 @@ export default class PageLoader { ...@@ -114,17 +114,26 @@ export default class PageLoader {
* @param {string} asPath the URL as shown in browser (virtual path); used for dynamic routes * @param {string} asPath the URL as shown in browser (virtual path); used for dynamic routes
* @returns {string} * @returns {string}
*/ */
getDataHref( getDataHref({
href: string, href,
asPath: string, asPath,
ssg: boolean, ssg,
rsc,
locale,
}: {
href: string
asPath: string
ssg: boolean
rsc?: boolean
locale?: string | false locale?: string | false
): string { }): string {
const { pathname: hrefPathname, query, search } = parseRelativeUrl(href) const { pathname: hrefPathname, query, search } = parseRelativeUrl(href)
const { pathname: asPathname } = parseRelativeUrl(asPath) const { pathname: asPathname } = parseRelativeUrl(asPath)
const route = normalizeRoute(hrefPathname) const route = normalizeRoute(hrefPathname)
const getHrefForSlug = (path: string) => { const getHrefForSlug = (path: string) => {
if (rsc) return path + '?__flight__'
const dataRoute = getAssetPathFromRoute( const dataRoute = getAssetPathFromRoute(
removePathTrailingSlash(addLocale(path, locale)), removePathTrailingSlash(addLocale(path, locale)),
'.json' '.json'
......
export function interopDefault(mod: any) {
return mod.default || mod
}
...@@ -72,6 +72,7 @@ ...@@ -72,6 +72,7 @@
"@next/react-dev-overlay": "12.0.1-canary.0", "@next/react-dev-overlay": "12.0.1-canary.0",
"@next/react-refresh-utils": "12.0.1-canary.0", "@next/react-refresh-utils": "12.0.1-canary.0",
"@node-rs/helper": "1.2.1", "@node-rs/helper": "1.2.1",
"acorn": "8.5.0",
"assert": "2.0.0", "assert": "2.0.0",
"browserify-zlib": "0.2.0", "browserify-zlib": "0.2.0",
"browserslist": "4.16.6", "browserslist": "4.16.6",
...@@ -102,6 +103,7 @@ ...@@ -102,6 +103,7 @@
"raw-body": "2.4.1", "raw-body": "2.4.1",
"react-is": "17.0.2", "react-is": "17.0.2",
"react-refresh": "0.8.3", "react-refresh": "0.8.3",
"react-server-dom-webpack": "0.0.0-experimental-3c4c1c470-20211021",
"regenerator-runtime": "0.13.4", "regenerator-runtime": "0.13.4",
"stream-browserify": "3.0.0", "stream-browserify": "3.0.0",
"stream-http": "3.1.1", "stream-http": "3.1.1",
...@@ -112,13 +114,14 @@ ...@@ -112,13 +114,14 @@
"use-subscription": "1.5.1", "use-subscription": "1.5.1",
"util": "0.12.4", "util": "0.12.4",
"vm-browserify": "1.1.2", "vm-browserify": "1.1.2",
"watchpack": "2.1.1" "watchpack": "2.1.1",
"web-streams-polyfill": "3.0.3"
}, },
"peerDependencies": { "peerDependencies": {
"fibers": ">= 3.1.0", "fibers": ">= 3.1.0",
"node-sass": "^4.0.0 || ^5.0.0 || ^6.0.0", "node-sass": "^4.0.0 || ^5.0.0 || ^6.0.0",
"react": "^17.0.2", "react": "^17.0.2 || ^18.0.0",
"react-dom": "^17.0.2", "react-dom": "^17.0.2 || ^18.0.0",
"sass": "^1.3.0" "sass": "^1.3.0"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
......
...@@ -6,10 +6,10 @@ import { PageConfig, PreviewData } from 'next/types' ...@@ -6,10 +6,10 @@ import { PageConfig, PreviewData } from 'next/types'
import { Stream } from 'stream' import { Stream } from 'stream'
import { isResSent, NextApiRequest, NextApiResponse } from '../shared/lib/utils' import { isResSent, NextApiRequest, NextApiResponse } from '../shared/lib/utils'
import { decryptWithSecret, encryptWithSecret } from './crypto-utils' import { decryptWithSecret, encryptWithSecret } from './crypto-utils'
import { interopDefault } from './load-components'
import { sendEtagResponse } from './send-payload' import { sendEtagResponse } from './send-payload'
import generateETag from 'etag' import generateETag from 'etag'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { interopDefault } from '../lib/interop-default'
export type NextApiRequestCookies = { [key: string]: string } export type NextApiRequestCookies = { [key: string]: string }
export type NextApiRequestQuery = { [key: string]: string | string[] } export type NextApiRequestQuery = { [key: string]: string | string[] }
......
...@@ -26,8 +26,9 @@ import { denormalizePagePath, normalizePathSep } from '../normalize-page-path' ...@@ -26,8 +26,9 @@ import { denormalizePagePath, normalizePathSep } from '../normalize-page-path'
import getRouteFromEntrypoint from '../get-route-from-entrypoint' import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { isWriteable } from '../../build/is-writeable' import { isWriteable } from '../../build/is-writeable'
import { ClientPagesLoaderOptions } from '../../build/webpack/loaders/next-client-pages-loader' import { ClientPagesLoaderOptions } from '../../build/webpack/loaders/next-client-pages-loader'
import { ssrEntries } from '../../build/webpack/plugins/middleware-plugin'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { difference } from '../../build/utils' import { difference, isFlightPage } from '../../build/utils'
import { NextConfigComplete } from '../config-shared' import { NextConfigComplete } from '../config-shared'
import { CustomRoutes } from '../../lib/load-custom-routes' import { CustomRoutes } from '../../lib/load-custom-routes'
import { DecodeError } from '../../shared/lib/utils' import { DecodeError } from '../../shared/lib/utils'
...@@ -141,6 +142,8 @@ export default class HotReloader { ...@@ -141,6 +142,8 @@ export default class HotReloader {
private pagesDir: string private pagesDir: string
private webpackHotMiddleware?: WebpackHotMiddleware private webpackHotMiddleware?: WebpackHotMiddleware
private config: NextConfigComplete private config: NextConfigComplete
private webServerRuntime: boolean
private hasServerComponents: boolean
public clientStats: webpack5.Stats | null public clientStats: webpack5.Stats | null
public serverStats: webpack5.Stats | null public serverStats: webpack5.Stats | null
private clientError: Error | null = null private clientError: Error | null = null
...@@ -179,6 +182,11 @@ export default class HotReloader { ...@@ -179,6 +182,11 @@ export default class HotReloader {
this.serverPrevDocumentHash = null this.serverPrevDocumentHash = null
this.config = config this.config = config
this.webServerRuntime = !!config.experimental.concurrentFeatures
this.hasServerComponents = !!(
config.experimental.concurrentFeatures &&
config.experimental.serverComponents
)
this.previewProps = previewProps this.previewProps = previewProps
this.rewrites = rewrites this.rewrites = rewrites
this.hotReloaderSpan = trace('hot-reloader') this.hotReloaderSpan = trace('hot-reloader')
...@@ -301,7 +309,8 @@ export default class HotReloader { ...@@ -301,7 +309,8 @@ export default class HotReloader {
createPagesMapping( createPagesMapping(
pagePaths.filter((i) => i !== null) as string[], pagePaths.filter((i) => i !== null) as string[],
this.config.pageExtensions, this.config.pageExtensions,
true true,
this.hasServerComponents
) )
) )
const entrypoints = webpackConfigSpan const entrypoints = webpackConfigSpan
...@@ -320,7 +329,8 @@ export default class HotReloader { ...@@ -320,7 +329,8 @@ export default class HotReloader {
return webpackConfigSpan return webpackConfigSpan
.traceChild('generate-webpack-config') .traceChild('generate-webpack-config')
.traceAsyncFn(() => .traceAsyncFn(() =>
Promise.all([ Promise.all(
[
getBaseWebpackConfig(this.dir, { getBaseWebpackConfig(this.dir, {
dev: true, dev: true,
isServer: false, isServer: false,
...@@ -341,7 +351,21 @@ export default class HotReloader { ...@@ -341,7 +351,21 @@ export default class HotReloader {
entrypoints: entrypoints.server, entrypoints: entrypoints.server,
runWebpackSpan: this.hotReloaderSpan, runWebpackSpan: this.hotReloaderSpan,
}), }),
]) this.webServerRuntime
? getBaseWebpackConfig(this.dir, {
dev: true,
isServer: true,
webServerRuntime: true,
config: this.config,
buildId: this.buildId,
pagesDir: this.pagesDir,
rewrites: this.rewrites,
entrypoints: entrypoints.serverWeb,
runWebpackSpan: this.hotReloaderSpan,
})
: null,
].filter(Boolean) as webpack.Configuration[]
)
) )
}) })
} }
...@@ -403,10 +427,11 @@ export default class HotReloader { ...@@ -403,10 +427,11 @@ export default class HotReloader {
for (const config of configs) { for (const config of configs) {
const defaultEntry = config.entry const defaultEntry = config.entry
config.entry = async (...args) => { config.entry = async (...args) => {
// @ts-ignore entry is always a functon // @ts-ignore entry is always a function
const entrypoints = await defaultEntry(...args) const entrypoints = await defaultEntry(...args)
const isClientCompilation = config.name === 'client' const isClientCompilation = config.name === 'client'
const isServerCompilation = config.name === 'server'
const isServerWebCompilation = config.name === 'server-web'
await Promise.all( await Promise.all(
Object.keys(entries).map(async (pageKey) => { Object.keys(entries).map(async (pageKey) => {
...@@ -420,6 +445,8 @@ export default class HotReloader { ...@@ -420,6 +445,8 @@ export default class HotReloader {
return return
} }
const isApiRoute = page.match(API_ROUTE)
if (!isClientCompilation && isMiddleware) { if (!isClientCompilation && isMiddleware) {
return return
} }
...@@ -432,6 +459,14 @@ export default class HotReloader { ...@@ -432,6 +459,14 @@ export default class HotReloader {
return return
} }
const isServerComponent =
this.hasServerComponents &&
isFlightPage(this.config, absolutePagePath)
if (isServerCompilation && this.webServerRuntime && !isApiRoute) {
return
}
entries[pageKey].status = BUILDING entries[pageKey].status = BUILDING
const pageLoaderOpts: ClientPagesLoaderOptions = { const pageLoaderOpts: ClientPagesLoaderOptions = {
page, page,
...@@ -443,6 +478,7 @@ export default class HotReloader { ...@@ -443,6 +478,7 @@ export default class HotReloader {
name: bundlePath, name: bundlePath,
value: `next-middleware-loader?${stringify(pageLoaderOpts)}!`, value: `next-middleware-loader?${stringify(pageLoaderOpts)}!`,
isServer: false, isServer: false,
isMiddleware: true,
}) })
} else if (isClientCompilation) { } else if (isClientCompilation) {
entrypoints[bundlePath] = finalizeEntrypoint({ entrypoints[bundlePath] = finalizeEntrypoint({
...@@ -450,6 +486,41 @@ export default class HotReloader { ...@@ -450,6 +486,41 @@ export default class HotReloader {
value: `next-client-pages-loader?${stringify(pageLoaderOpts)}!`, value: `next-client-pages-loader?${stringify(pageLoaderOpts)}!`,
isServer: false, isServer: false,
}) })
if (isServerComponent) {
ssrEntries.set(bundlePath, { requireFlightManifest: true })
} else if (
this.webServerRuntime &&
!(
page === '/_app' ||
page === '/_error' ||
page === '/_document'
)
) {
ssrEntries.set(bundlePath, { requireFlightManifest: false })
}
} else if (isServerWebCompilation) {
if (
!(
page === '/_app' ||
page === '/_error' ||
page === '/_document'
)
) {
entrypoints[bundlePath] = finalizeEntrypoint({
name: '[name].js',
value: `next-middleware-ssr-loader?${stringify({
page,
absolutePagePath,
isServerComponent,
buildId: this.buildId,
basePath: this.config.basePath,
assetPrefix: this.config.assetPrefix,
} as any)}!`,
isServer: false,
isServerWeb: true,
})
}
} else { } else {
let request = relative(config.context!, absolutePagePath) let request = relative(config.context!, absolutePagePath)
if (!isAbsolute(request) && !request.startsWith('../')) { if (!isAbsolute(request) && !request.startsWith('../')) {
...@@ -475,7 +546,11 @@ export default class HotReloader { ...@@ -475,7 +546,11 @@ export default class HotReloader {
const multiCompiler = webpack(configs) as unknown as webpack5.MultiCompiler const multiCompiler = webpack(configs) as unknown as webpack5.MultiCompiler
watchCompilers(multiCompiler.compilers[0], multiCompiler.compilers[1]) watchCompilers(
multiCompiler.compilers[0],
multiCompiler.compilers[1],
multiCompiler.compilers[2] || null
)
// Watch for changes to client/server page files so we can tell when just // Watch for changes to client/server page files so we can tell when just
// the server file changes and trigger a reload for GS(S)P pages // the server file changes and trigger a reload for GS(S)P pages
...@@ -647,7 +722,7 @@ export default class HotReloader { ...@@ -647,7 +722,7 @@ export default class HotReloader {
this.onDemandEntries = onDemandEntryHandler(this.watcher, multiCompiler, { this.onDemandEntries = onDemandEntryHandler(this.watcher, multiCompiler, {
pagesDir: this.pagesDir, pagesDir: this.pagesDir,
pageExtensions: this.config.pageExtensions, nextConfig: this.config,
...(this.config.onDemandEntries as { ...(this.config.onDemandEntries as {
maxInactiveAge: number maxInactiveAge: number
pagesBufferLength: number pagesBufferLength: number
......
...@@ -242,6 +242,12 @@ export default class DevServer extends Server { ...@@ -242,6 +242,12 @@ export default class DevServer extends Server {
const routedMiddleware = [] const routedMiddleware = []
const routedPages = [] const routedPages = []
const knownFiles = wp.getTimeInfoEntries() const knownFiles = wp.getTimeInfoEntries()
const ssrMiddleware = new Set<string>()
const isWebServerRuntime =
this.nextConfig.experimental.concurrentFeatures
const hasServerComponents =
isWebServerRuntime && this.nextConfig.experimental.serverComponents
for (const [fileName, { accuracy }] of knownFiles) { for (const [fileName, { accuracy }] of knownFiles) {
if (accuracy === undefined || !regexPageExtension.test(fileName)) { if (accuracy === undefined || !regexPageExtension.test(fileName)) {
continue continue
...@@ -261,12 +267,30 @@ export default class DevServer extends Server { ...@@ -261,12 +267,30 @@ export default class DevServer extends Server {
pageName = pageName.replace(regexPageExtension, '') pageName = pageName.replace(regexPageExtension, '')
pageName = pageName.replace(/\/index$/, '') || '/' pageName = pageName.replace(/\/index$/, '') || '/'
if (hasServerComponents && pageName.endsWith('.server')) {
routedMiddleware.push(pageName)
ssrMiddleware.add(pageName)
} else if (
isWebServerRuntime &&
!(
pageName === '/_app' ||
pageName === '/_error' ||
pageName === '/_document'
)
) {
routedMiddleware.push(pageName)
ssrMiddleware.add(pageName)
}
routedPages.push(pageName) routedPages.push(pageName)
} }
this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({ this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({
match: getRouteMatcher(getMiddlewareRegex(page)), match: getRouteMatcher(
getMiddlewareRegex(page, !ssrMiddleware.has(page))
),
page, page,
ssr: ssrMiddleware.has(page),
})) }))
try { try {
...@@ -641,12 +665,17 @@ export default class DevServer extends Server { ...@@ -641,12 +665,17 @@ export default class DevServer extends Server {
return [] return []
} }
protected async hasMiddleware(pathname: string): Promise<boolean> { protected async hasMiddleware(
return this.hasPage(getMiddlewareFilepath(pathname)) pathname: string,
isSSR?: boolean
): Promise<boolean> {
return this.hasPage(isSSR ? pathname : getMiddlewareFilepath(pathname))
} }
protected async ensureMiddleware(pathname: string) { protected async ensureMiddleware(pathname: string, isSSR?: boolean) {
return this.hotReloader!.ensurePage(getMiddlewareFilepath(pathname)) return this.hotReloader!.ensurePage(
isSSR ? pathname : getMiddlewareFilepath(pathname)
)
} }
generateRoutes() { generateRoutes() {
...@@ -698,7 +727,10 @@ export default class DevServer extends Server { ...@@ -698,7 +727,10 @@ export default class DevServer extends Server {
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end( res.end(
JSON.stringify( JSON.stringify(
this.middleware?.map((middleware) => middleware.page) || [] this.middleware?.map((middleware) => [
middleware.page,
!!middleware.ssr,
]) || []
) )
) )
return { return {
......
...@@ -8,6 +8,7 @@ import getRouteFromEntrypoint from '../get-route-from-entrypoint' ...@@ -8,6 +8,7 @@ import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { API_ROUTE, MIDDLEWARE_ROUTE } from '../../lib/constants' import { API_ROUTE, MIDDLEWARE_ROUTE } from '../../lib/constants'
import { reportTrigger } from '../../build/output' import { reportTrigger } from '../../build/output'
import type ws from 'ws' import type ws from 'ws'
import { NextConfigComplete } from '../config-shared'
export const ADDED = Symbol('added') export const ADDED = Symbol('added')
export const BUILDING = Symbol('building') export const BUILDING = Symbol('building')
...@@ -28,12 +29,12 @@ export default function onDemandEntryHandler( ...@@ -28,12 +29,12 @@ export default function onDemandEntryHandler(
multiCompiler: webpack.MultiCompiler, multiCompiler: webpack.MultiCompiler,
{ {
pagesDir, pagesDir,
pageExtensions, nextConfig,
maxInactiveAge, maxInactiveAge,
pagesBufferLength, pagesBufferLength,
}: { }: {
pagesDir: string pagesDir: string
pageExtensions: string[] nextConfig: NextConfigComplete
maxInactiveAge: number maxInactiveAge: number
pagesBufferLength: number pagesBufferLength: number
} }
...@@ -72,7 +73,7 @@ export default function onDemandEntryHandler( ...@@ -72,7 +73,7 @@ export default function onDemandEntryHandler(
if (invalidator.rebuildAgain) { if (invalidator.rebuildAgain) {
return invalidator.doneBuilding() return invalidator.doneBuilding()
} }
const [clientStats, serverStats] = multiStats.stats const [clientStats, serverStats, serverWebStats] = multiStats.stats
const pagePaths = [ const pagePaths = [
...getPagePathsFromEntrypoints( ...getPagePathsFromEntrypoints(
'client', 'client',
...@@ -82,6 +83,12 @@ export default function onDemandEntryHandler( ...@@ -82,6 +83,12 @@ export default function onDemandEntryHandler(
'server', 'server',
serverStats.compilation.entrypoints serverStats.compilation.entrypoints
), ),
...(serverWebStats
? getPagePathsFromEntrypoints(
'server-web',
serverWebStats.compilation.entrypoints
)
: []),
] ]
for (const page of pagePaths) { for (const page of pagePaths) {
...@@ -158,7 +165,7 @@ export default function onDemandEntryHandler( ...@@ -158,7 +165,7 @@ export default function onDemandEntryHandler(
let pagePath = await findPageFile( let pagePath = await findPageFile(
pagesDir, pagesDir,
normalizedPagePath, normalizedPagePath,
pageExtensions nextConfig.pageExtensions
) )
// Default the /_error route to the Next.js provided default page // Default the /_error route to the Next.js provided default page
...@@ -179,7 +186,10 @@ export default function onDemandEntryHandler( ...@@ -179,7 +186,10 @@ export default function onDemandEntryHandler(
let pageUrl = pagePath.replace(/\\/g, '/') let pageUrl = pagePath.replace(/\\/g, '/')
pageUrl = `${pageUrl[0] !== '/' ? '/' : ''}${pageUrl pageUrl = `${pageUrl[0] !== '/' ? '/' : ''}${pageUrl
.replace(new RegExp(`\\.+(?:${pageExtensions.join('|')})$`), '') .replace(
new RegExp(`\\.+(?:${nextConfig.pageExtensions.join('|')})$`),
''
)
.replace(/\/index$/, '')}` .replace(/\/index$/, '')}`
pageUrl = pageUrl === '' ? '/' : pageUrl pageUrl = pageUrl === '' ? '/' : pageUrl
...@@ -193,9 +203,10 @@ export default function onDemandEntryHandler( ...@@ -193,9 +203,10 @@ export default function onDemandEntryHandler(
const isMiddleware = normalizedPage.match(MIDDLEWARE_ROUTE) const isMiddleware = normalizedPage.match(MIDDLEWARE_ROUTE)
const isApiRoute = normalizedPage.match(API_ROUTE) && !isMiddleware const isApiRoute = normalizedPage.match(API_ROUTE) && !isMiddleware
const isServerWeb = !!nextConfig.experimental.concurrentFeatures
let entriesChanged = false let entriesChanged = false
const addPageEntry = (type: 'client' | 'server') => { const addPageEntry = (type: 'client' | 'server' | 'server-web') => {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
// Makes sure the page that is being kept in on-demand-entries matches the webpack output // Makes sure the page that is being kept in on-demand-entries matches the webpack output
const pageKey = `${type}${page}` const pageKey = `${type}${page}`
...@@ -235,7 +246,10 @@ export default function onDemandEntryHandler( ...@@ -235,7 +246,10 @@ export default function onDemandEntryHandler(
? addPageEntry('server') ? addPageEntry('server')
: clientOnly || isMiddleware : clientOnly || isMiddleware
? addPageEntry('client') ? addPageEntry('client')
: Promise.all([addPageEntry('client'), addPageEntry('server')]) : Promise.all([
addPageEntry('client'),
addPageEntry(isServerWeb ? 'server-web' : 'server'),
])
if (entriesChanged) { if (entriesChanged) {
reportTrigger( reportTrigger(
......
...@@ -6,6 +6,7 @@ import { join } from 'path' ...@@ -6,6 +6,7 @@ import { join } from 'path'
import { requirePage } from './require' import { requirePage } from './require'
import { BuildManifest } from './get-page-files' import { BuildManifest } from './get-page-files'
import { AppType, DocumentType } from '../shared/lib/utils' import { AppType, DocumentType } from '../shared/lib/utils'
import { interopDefault } from '../lib/interop-default'
import { import {
PageConfig, PageConfig,
GetStaticPaths, GetStaticPaths,
...@@ -13,10 +14,6 @@ import { ...@@ -13,10 +14,6 @@ import {
GetStaticProps, GetStaticProps,
} from 'next/types' } from 'next/types'
export function interopDefault(mod: any) {
return mod.default || mod
}
export type ManifestItem = { export type ManifestItem = {
id: number | string id: number | string
files: string[] files: string[]
......
...@@ -84,7 +84,6 @@ import './node-polyfill-fetch' ...@@ -84,7 +84,6 @@ import './node-polyfill-fetch'
import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import { removePathTrailingSlash } from '../client/normalize-trailing-slash' import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path' import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'
import { FontManifest } from './font-utils'
import { denormalizePagePath } from './denormalize-page-path' import { denormalizePagePath } from './denormalize-page-path'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
...@@ -104,6 +103,7 @@ import { parseUrl as simpleParseUrl } from '../shared/lib/router/utils/parse-url ...@@ -104,6 +103,7 @@ import { parseUrl as simpleParseUrl } from '../shared/lib/router/utils/parse-url
import { MIDDLEWARE_ROUTE } from '../lib/constants' import { MIDDLEWARE_ROUTE } from '../lib/constants'
import { NextResponse } from './web/spec-extension/response' import { NextResponse } from './web/spec-extension/response'
import { run } from './web/sandbox' import { run } from './web/sandbox'
import type { FontManifest } from './font-utils'
import type { FetchEventResult } from './web/types' import type { FetchEventResult } from './web/types'
import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin' import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
import type { ParsedNextUrl } from '../shared/lib/router/utils/parse-next-url' import type { ParsedNextUrl } from '../shared/lib/router/utils/parse-next-url'
...@@ -125,6 +125,7 @@ export type FindComponentsResult = { ...@@ -125,6 +125,7 @@ export type FindComponentsResult = {
interface RoutingItem { interface RoutingItem {
page: string page: string
match: ReturnType<typeof getRouteMatcher> match: ReturnType<typeof getRouteMatcher>
ssr?: boolean
} }
export type ServerConstructor = { export type ServerConstructor = {
...@@ -569,15 +570,19 @@ export default class Server { ...@@ -569,15 +570,19 @@ export default class Server {
} }
protected getMiddleware() { protected getMiddleware() {
return Object.keys(this.middlewareManifest?.middleware || {}).map( const middleware = this.middlewareManifest?.middleware || {}
(page) => ({ return Object.keys(middleware).map((page) => ({
match: getRouteMatcher(getMiddlewareRegex(page)), match: getRouteMatcher(
getMiddlewareRegex(page, MIDDLEWARE_ROUTE.test(middleware[page].name))
),
page, page,
}) }))
)
} }
protected async hasMiddleware(pathname: string): Promise<boolean> { protected async hasMiddleware(
pathname: string,
_isSSR?: boolean
): Promise<boolean> {
try { try {
return ( return (
getMiddlewareInfo({ getMiddlewareInfo({
...@@ -592,7 +597,7 @@ export default class Server { ...@@ -592,7 +597,7 @@ export default class Server {
return false return false
} }
protected async ensureMiddleware(_pathname: string) {} protected async ensureMiddleware(_pathname: string, _isSSR?: boolean) {}
private middlewareBetaWarning = execOnce(() => { private middlewareBetaWarning = execOnce(() => {
Log.warn( Log.warn(
...@@ -629,12 +634,12 @@ export default class Server { ...@@ -629,12 +634,12 @@ export default class Server {
for (const middleware of this.middleware || []) { for (const middleware of this.middleware || []) {
if (middleware.match(params.parsedUrl.pathname)) { if (middleware.match(params.parsedUrl.pathname)) {
if (!(await this.hasMiddleware(middleware.page))) { if (!(await this.hasMiddleware(middleware.page, middleware.ssr))) {
console.warn(`The Edge Function for ${middleware.page} was not found`) console.warn(`The Edge Function for ${middleware.page} was not found`)
continue continue
} }
await this.ensureMiddleware(middleware.page) await this.ensureMiddleware(middleware.page, middleware.ssr)
const middlewareInfo = getMiddlewareInfo({ const middlewareInfo = getMiddlewareInfo({
dev: this.renderOpts.dev, dev: this.renderOpts.dev,
...@@ -665,6 +670,7 @@ export default class Server { ...@@ -665,6 +670,7 @@ export default class Server {
url: (params.request as any).__NEXT_INIT_URL, url: (params.request as any).__NEXT_INIT_URL,
page: page, page: page,
}, },
ssr: !!this.nextConfig.experimental.concurrentFeatures,
}) })
for (let [key, value] of result.response.headers) { for (let [key, value] of result.response.headers) {
......
import { ServerResponse } from 'http' import type { ServerResponse } from 'http'
import { Writable } from 'stream' import type { Writable } from 'stream'
export type NodeWritablePiper = ( export type NodeWritablePiper = (
res: Writable, res: Writable,
......
import { IncomingMessage, ServerResponse } from 'http' import { IncomingMessage, ServerResponse } from 'http'
import { ParsedUrlQuery } from 'querystring' import { ParsedUrlQuery } from 'querystring'
import { Writable } from 'stream' import type { Writable as WritableType } from 'stream'
import React from 'react' import React from 'react'
import * as ReactDOMServer from 'react-dom/server' import * as ReactDOMServer from 'react-dom/server'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx' import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
import { warn } from '../build/output/log'
import { UnwrapPromise } from '../lib/coalesced-function' import { UnwrapPromise } from '../lib/coalesced-function'
import { import {
GSP_NO_RETURNED_VALUE, GSP_NO_RETURNED_VALUE,
...@@ -30,7 +29,6 @@ import { defaultHead } from '../shared/lib/head' ...@@ -30,7 +29,6 @@ import { defaultHead } from '../shared/lib/head'
import { HeadManagerContext } from '../shared/lib/head-manager-context' import { HeadManagerContext } from '../shared/lib/head-manager-context'
import Loadable from '../shared/lib/loadable' import Loadable from '../shared/lib/loadable'
import { LoadableContext } from '../shared/lib/loadable-context' import { LoadableContext } from '../shared/lib/loadable-context'
import postProcess from '../shared/lib/post-process'
import { RouterContext } from '../shared/lib/router-context' import { RouterContext } from '../shared/lib/router-context'
import { NextRouter } from '../shared/lib/router/router' import { NextRouter } from '../shared/lib/router/router'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
...@@ -49,16 +47,11 @@ import { ...@@ -49,16 +47,11 @@ import {
RenderPage, RenderPage,
RenderPageResult, RenderPageResult,
} from '../shared/lib/utils' } from '../shared/lib/utils'
import { import type { NextApiRequestCookies, __ApiPreviewProps } from './api-utils'
tryGetPreviewData,
NextApiRequestCookies,
__ApiPreviewProps,
} from './api-utils'
import { denormalizePagePath } from './denormalize-page-path' import { denormalizePagePath } from './denormalize-page-path'
import { FontManifest, getFontDefinitionFromManifest } from './font-utils' import type { FontManifest } from './font-utils'
import { LoadComponentsReturnType, ManifestItem } from './load-components' import type { LoadComponentsReturnType, ManifestItem } from './load-components'
import { normalizePagePath } from './normalize-page-path' import { normalizePagePath } from './normalize-page-path'
import optimizeAmp from './optimize-amp'
import { import {
allowedStatusCodes, allowedStatusCodes,
getRedirectStatus, getRedirectStatus,
...@@ -68,6 +61,27 @@ import { DomainLocale } from './config' ...@@ -68,6 +61,27 @@ import { DomainLocale } from './config'
import RenderResult, { NodeWritablePiper } from './render-result' import RenderResult, { NodeWritablePiper } from './render-result'
import isError from '../lib/is-error' import isError from '../lib/is-error'
let Writable: typeof import('stream').Writable
let Buffer: typeof import('buffer').Buffer
let optimizeAmp: typeof import('./optimize-amp').default
let getFontDefinitionFromManifest: typeof import('./font-utils').getFontDefinitionFromManifest
let tryGetPreviewData: typeof import('./api-utils').tryGetPreviewData
let warn: typeof import('../build/output/log').warn
let postProcess: typeof import('../shared/lib/post-process').default
if (!process.browser) {
Writable = require('stream').Writable
Buffer = require('buffer').Buffer
optimizeAmp = require('./optimize-amp').default
getFontDefinitionFromManifest =
require('./font-utils').getFontDefinitionFromManifest
tryGetPreviewData = require('./api-utils').tryGetPreviewData
warn = require('../build/output/log').warn
postProcess = require('../shared/lib/post-process').default
} else {
warn = console.warn.bind(console)
}
function noRouter() { function noRouter() {
const message = const message =
'No router instance found. you should only use "next/router" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance' 'No router instance found. you should only use "next/router" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance'
...@@ -189,6 +203,7 @@ export type RenderOptsPartial = { ...@@ -189,6 +203,7 @@ export type RenderOptsPartial = {
devOnlyCacheBusterQueryString?: string devOnlyCacheBusterQueryString?: string
resolvedUrl?: string resolvedUrl?: string
resolvedAsPath?: string resolvedAsPath?: string
renderServerComponent?: null | (() => Promise<string>)
distDir?: string distDir?: string
locale?: string locale?: string
locales?: string[] locales?: string[]
...@@ -291,6 +306,7 @@ export async function renderToHTML( ...@@ -291,6 +306,7 @@ export async function renderToHTML(
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
getServerSideProps, getServerSideProps,
renderServerComponent,
isDataReq, isDataReq,
params, params,
previewProps, previewProps,
...@@ -343,6 +359,8 @@ export async function renderToHTML( ...@@ -343,6 +359,8 @@ export async function renderToHTML(
const hasPageGetInitialProps = !!(Component as any).getInitialProps const hasPageGetInitialProps = !!(Component as any).getInitialProps
const isRSC = !!renderServerComponent
const pageIsDynamic = isDynamicRoute(pathname) const pageIsDynamic = isDynamicRoute(pathname)
const isAutoExport = const isAutoExport =
...@@ -453,7 +471,7 @@ export async function renderToHTML( ...@@ -453,7 +471,7 @@ export async function renderToHTML(
let isPreview let isPreview
let previewData: PreviewData let previewData: PreviewData
if ((isSSG || getServerSideProps) && !isFallback) { if ((isSSG || getServerSideProps) && !isFallback && !process.browser) {
// Reads of this are cached on the `req` object, so this should resolve // Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous // instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless. // invoke, where we'd have to consider server & serverless.
...@@ -521,7 +539,8 @@ export async function renderToHTML( ...@@ -521,7 +539,8 @@ export async function renderToHTML(
hybrid: pageConfig.amp === 'hybrid', hybrid: pageConfig.amp === 'hybrid',
} }
const inAmpMode = isInAmpMode(ampState) // Disable AMP under the web environment
const inAmpMode = !process.browser && isInAmpMode(ampState)
const reactLoadableModules: string[] = [] const reactLoadableModules: string[] = []
...@@ -995,8 +1014,11 @@ export async function renderToHTML( ...@@ -995,8 +1014,11 @@ export async function renderToHTML(
<App {...props} Component={Component} router={router} /> <App {...props} Component={Component} router={router} />
</AppContainer> </AppContainer>
) )
const bodyResult = concurrentFeatures const bodyResult = concurrentFeatures
? await renderToStream(content, generateStaticHTML) ? process.browser
? await renderToReadableStream(content)
: await renderToNodeStream(content, generateStaticHTML)
: piperFromArray([ReactDOMServer.renderToString(content)]) : piperFromArray([ReactDOMServer.renderToString(content)])
return { return {
...@@ -1060,6 +1082,7 @@ export async function renderToHTML( ...@@ -1060,6 +1082,7 @@ export async function renderToHTML(
err: renderOpts.err ? serializeError(dev, renderOpts.err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML err: renderOpts.err ? serializeError(dev, renderOpts.err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
gsp: !!getStaticProps ? true : undefined, // whether the page is getStaticProps gsp: !!getStaticProps ? true : undefined, // whether the page is getStaticProps
gssp: !!getServerSideProps ? true : undefined, // whether the page is getServerSideProps gssp: !!getServerSideProps ? true : undefined, // whether the page is getServerSideProps
rsc: isRSC ? true : undefined, // whether the page is a server components page
customServer, // whether the user is using a custom server customServer, // whether the user is using a custom server
gip: hasPageGetInitialProps ? true : undefined, // whether the page has getInitialProps gip: hasPageGetInitialProps ? true : undefined, // whether the page has getInitialProps
appGip: !defaultAppGetInitialProps ? true : undefined, // whether the _app has getInitialProps appGip: !defaultAppGetInitialProps ? true : undefined, // whether the _app has getInitialProps
...@@ -1156,8 +1179,9 @@ export async function renderToHTML( ...@@ -1156,8 +1179,9 @@ export async function renderToHTML(
return html return html
} }
: null, : null,
process.env.__NEXT_OPTIMIZE_FONTS || !process.browser &&
process.env.__NEXT_OPTIMIZE_IMAGES (process.env.__NEXT_OPTIMIZE_FONTS ||
process.env.__NEXT_OPTIMIZE_IMAGES)
? async (html: string) => { ? async (html: string) => {
return await postProcess( return await postProcess(
html, html,
...@@ -1171,6 +1195,10 @@ export async function renderToHTML( ...@@ -1171,6 +1195,10 @@ export async function renderToHTML(
: null, : null,
renderOpts.optimizeCss renderOpts.optimizeCss
? async (html: string) => { ? async (html: string) => {
if (process.browser) {
// Have to disable critters under the web environment.
return html
} else {
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
const Critters = require('critters') const Critters = require('critters')
const cssOptimizer = new Critters({ const cssOptimizer = new Critters({
...@@ -1184,6 +1212,7 @@ export async function renderToHTML( ...@@ -1184,6 +1212,7 @@ export async function renderToHTML(
}) })
return await cssOptimizer.process(html) return await cssOptimizer.process(html)
} }
}
: null, : null,
inAmpMode || hybridAmp inAmpMode || hybridAmp
? async (html: string) => { ? async (html: string) => {
...@@ -1231,26 +1260,33 @@ function serializeError( ...@@ -1231,26 +1260,33 @@ function serializeError(
} }
} }
function renderToStream( function renderToNodeStream(
element: React.ReactElement, element: React.ReactElement,
generateStaticHTML: boolean generateStaticHTML: boolean
): Promise<NodeWritablePiper> { ): Promise<NodeWritablePiper> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let underlyingStream: { let underlyingStream: {
resolve: (error?: Error) => void resolve: (error?: Error) => void
writable: Writable writable: WritableType
queuedCallbacks: Array<() => void> queuedCallbacks: Array<() => void>
} | null = null } | null = null
const stream = new Writable({ const stream = new Writable({
// Use the buffer from the underlying stream // Use the buffer from the underlying stream
highWaterMark: 0, highWaterMark: 0,
write(chunk, encoding, callback) { writev(chunks, callback) {
let str = ''
for (let { chunk } of chunks) {
str += chunk.toString()
}
if (!underlyingStream) { if (!underlyingStream) {
throw new Error( throw new Error(
'invariant: write called without an underlying stream. This is a bug in Next.js' 'invariant: write called without an underlying stream. This is a bug in Next.js'
) )
} }
if (!underlyingStream.writable.write(chunk, encoding)) {
if (!underlyingStream.writable.write(str)) {
underlyingStream.queuedCallbacks.push(() => callback()) underlyingStream.queuedCallbacks.push(() => callback())
} else { } else {
callback() callback()
...@@ -1338,6 +1374,27 @@ function renderToStream( ...@@ -1338,6 +1374,27 @@ function renderToStream(
}) })
} }
function renderToReadableStream(
element: React.ReactElement
): NodeWritablePiper {
return (res, next) => {
const readable = (ReactDOMServer as any).renderToReadableStream(element)
const reader = readable.getReader()
const decoder = new TextDecoder()
const process = () => {
reader.read().then(({ done, value }: any) => {
if (!done) {
res.write(typeof value === 'string' ? value : decoder.decode(value))
process()
} else {
next()
}
})
}
process()
}
}
function chainPipers(pipers: NodeWritablePiper[]): NodeWritablePiper { function chainPipers(pipers: NodeWritablePiper[]): NodeWritablePiper {
return pipers.reduceRight( return pipers.reduceRight(
(lhs, rhs) => (res, next) => { (lhs, rhs) => (res, next) => {
......
...@@ -55,6 +55,7 @@ export function getPagePath( ...@@ -55,6 +55,7 @@ export function getPagePath(
if (!pagePath) { if (!pagePath) {
throw pageNotFoundError(page) throw pageNotFoundError(page)
} }
return join(serverBuildPath, pagePath) return join(serverBuildPath, pagePath)
} }
......
export { renderToHTML } from '../render'
...@@ -65,16 +65,23 @@ export class ReadableStream<T> { ...@@ -65,16 +65,23 @@ export class ReadableStream<T> {
let pullPromise: any let pullPromise: any
let transformController: TransformStreamDefaultController let transformController: TransformStreamDefaultController
const { readable, writable } = new TransformStream({ const { readable, writable } = new TransformStream(
{
start: (controller: TransformStreamDefaultController) => { start: (controller: TransformStreamDefaultController) => {
transformController = controller transformController = controller
}, },
}) },
undefined,
{
highWaterMark: 1,
}
)
const writer = writable.getWriter() const writer = writable.getWriter()
const encoder = new TextEncoder()
const controller: ReadableStreamController<T> = { const controller: ReadableStreamController<T> = {
get desiredSize() { get desiredSize() {
return writer.desiredSize return transformController.desiredSize
}, },
close: () => { close: () => {
if (!closed) { if (!closed) {
...@@ -83,7 +90,7 @@ export class ReadableStream<T> { ...@@ -83,7 +90,7 @@ export class ReadableStream<T> {
} }
}, },
enqueue: (chunk: T) => { enqueue: (chunk: T) => {
writer.write(chunk) writer.write(typeof chunk === 'string' ? encoder.encode(chunk) : chunk)
pull() pull()
}, },
error: (reason: any) => { error: (reason: any) => {
......
import type { RequestData, FetchEventResult, NodeHeaders } from '../types' import type { RequestData, FetchEventResult, NodeHeaders } from '../types'
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node' import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { dirname } from 'path' import { dirname } from 'path'
import { ReadableStream } from 'next/dist/compiled/web-streams-polyfill'
import { readFileSync } from 'fs' import { readFileSync } from 'fs'
import { TransformStream } from 'next/dist/compiled/web-streams-polyfill' import { TransformStream } from 'next/dist/compiled/web-streams-polyfill'
import * as polyfills from './polyfills' import * as polyfills from './polyfills'
...@@ -36,6 +35,7 @@ export async function run(params: { ...@@ -36,6 +35,7 @@ export async function run(params: {
name: string name: string
paths: string[] paths: string[]
request: RequestData request: RequestData
ssr: boolean
}): Promise<FetchEventResult> { }): Promise<FetchEventResult> {
if (cache === undefined) { if (cache === undefined) {
const context: { [key: string]: any } = { const context: { [key: string]: any } = {
...@@ -74,7 +74,7 @@ export async function run(params: { ...@@ -74,7 +74,7 @@ export async function run(params: {
File, File,
FormData, FormData,
process: { env: { ...process.env } }, process: { env: { ...process.env } },
ReadableStream, ReadableStream: polyfills.ReadableStream,
setInterval, setInterval,
setTimeout, setTimeout,
TextDecoder: polyfills.TextDecoder, TextDecoder: polyfills.TextDecoder,
...@@ -127,6 +127,19 @@ export async function run(params: { ...@@ -127,6 +127,19 @@ export async function run(params: {
} }
const entryPoint = cache.context._ENTRIES[`middleware_${params.name}`] const entryPoint = cache.context._ENTRIES[`middleware_${params.name}`]
if (params.ssr) {
const rscManifest = cache.context._ENTRIES._middleware_rsc_manifest
cache = undefined
if (rscManifest && entryPoint) {
return entryPoint.default({
request: params.request,
rscManifest,
})
}
}
return entryPoint.default({ request: params.request }) return entryPoint.default({ request: params.request })
} }
......
...@@ -25,6 +25,15 @@ export const CLIENT_STATIC_FILES_PATH = 'static' ...@@ -25,6 +25,15 @@ export const CLIENT_STATIC_FILES_PATH = 'static'
export const CLIENT_STATIC_FILES_RUNTIME = 'runtime' export const CLIENT_STATIC_FILES_RUNTIME = 'runtime'
export const BODY_RENDER_TARGET = '__NEXT_BODY_RENDER_TARGET__' export const BODY_RENDER_TARGET = '__NEXT_BODY_RENDER_TARGET__'
export const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__' export const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'
// server/middleware-flight-manifest.js
export const MIDDLEWARE_FLIGHT_MANIFEST = 'middleware-flight-manifest'
// server/middleware-build-manifest.js
export const MIDDLEWARE_BUILD_MANIFEST = 'middleware-build-manifest'
// server/middleware-react-loadable-manifest.js
export const MIDDLEWARE_REACT_LOADABLE_MANIFEST =
'middleware-react-loadable-manifest'
// static/runtime/main.js // static/runtime/main.js
export const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main` export const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main`
// static/runtime/react-refresh.js // static/runtime/react-refresh.js
...@@ -35,10 +44,13 @@ export const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp` ...@@ -35,10 +44,13 @@ export const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp`
export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack` export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`
// static/runtime/polyfills.js // static/runtime/polyfills.js
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(`polyfills`) export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(`polyfills`)
// server/middleware-flight-runtime.js
export const MIDDLEWARE_SSR_RUNTIME_WEBPACK = 'middleware-ssr-runtime'
export const TEMPORARY_REDIRECT_STATUS = 307 export const TEMPORARY_REDIRECT_STATUS = 307
export const PERMANENT_REDIRECT_STATUS = 308 export const PERMANENT_REDIRECT_STATUS = 308
export const STATIC_PROPS_ID = '__N_SSG' export const STATIC_PROPS_ID = '__N_SSG'
export const SERVER_PROPS_ID = '__N_SSP' export const SERVER_PROPS_ID = '__N_SSP'
export const FLIGHT_PROPS_ID = '__N_RSC'
export const GOOGLE_FONT_PROVIDER = 'https://fonts.googleapis.com/css' export const GOOGLE_FONT_PROVIDER = 'https://fonts.googleapis.com/css'
export const OPTIMIZED_FONT_PROVIDERS = [ export const OPTIMIZED_FONT_PROVIDERS = [
{ url: GOOGLE_FONT_PROVIDER, preconnect: 'https://fonts.gstatic.com' }, { url: GOOGLE_FONT_PROVIDER, preconnect: 'https://fonts.gstatic.com' },
......
import React from 'react' import React from 'react'
import { NextRouter } from './router/router' import type { NextRouter } from './router/router'
export const RouterContext = React.createContext<NextRouter>(null as any) export const RouterContext = React.createContext<NextRouter>(null as any)
......
...@@ -64,6 +64,7 @@ interface PreflightData { ...@@ -64,6 +64,7 @@ interface PreflightData {
redirect?: string | null redirect?: string | null
refresh?: boolean refresh?: boolean
rewrite?: string | null rewrite?: string | null
ssr?: boolean
} }
type PreflightEffect = type PreflightEffect =
...@@ -474,6 +475,7 @@ export type CompletePrivateRouteInfo = { ...@@ -474,6 +475,7 @@ export type CompletePrivateRouteInfo = {
styleSheets: StyleSheetTuple[] styleSheets: StyleSheetTuple[]
__N_SSG?: boolean __N_SSG?: boolean
__N_SSP?: boolean __N_SSP?: boolean
__N_RSC?: boolean
props?: Record<string, any> props?: Record<string, any>
err?: Error err?: Error
error?: any error?: any
...@@ -510,7 +512,11 @@ const manualScrollRestoration = ...@@ -510,7 +512,11 @@ const manualScrollRestoration =
const SSG_DATA_NOT_FOUND = Symbol('SSG_DATA_NOT_FOUND') const SSG_DATA_NOT_FOUND = Symbol('SSG_DATA_NOT_FOUND')
function fetchRetry(url: string, attempts: number): Promise<any> { function fetchRetry(
url: string,
attempts: number,
opts: { text?: boolean }
): Promise<any> {
return fetch(url, { return fetch(url, {
// Cookies are required to be present for Next.js' SSG "Preview Mode". // Cookies are required to be present for Next.js' SSG "Preview Mode".
// Cookies may also be required for `getServerSideProps`. // Cookies may also be required for `getServerSideProps`.
...@@ -527,7 +533,7 @@ function fetchRetry(url: string, attempts: number): Promise<any> { ...@@ -527,7 +533,7 @@ function fetchRetry(url: string, attempts: number): Promise<any> {
}).then((res) => { }).then((res) => {
if (!res.ok) { if (!res.ok) {
if (attempts > 1 && res.status >= 500) { if (attempts > 1 && res.status >= 500) {
return fetchRetry(url, attempts - 1) return fetchRetry(url, attempts - 1, opts)
} }
if (res.status === 404) { if (res.status === 404) {
return res.json().then((data) => { return res.json().then((data) => {
...@@ -539,13 +545,14 @@ function fetchRetry(url: string, attempts: number): Promise<any> { ...@@ -539,13 +545,14 @@ function fetchRetry(url: string, attempts: number): Promise<any> {
} }
throw new Error(`Failed to load static props`) throw new Error(`Failed to load static props`)
} }
return res.json() return opts.text ? res.text() : res.json()
}) })
} }
function fetchNextData( function fetchNextData(
dataHref: string, dataHref: string,
isServerRender: boolean, isServerRender: boolean,
text: boolean | undefined,
inflightCache: NextDataCache, inflightCache: NextDataCache,
persistCache: boolean persistCache: boolean
) { ) {
...@@ -554,7 +561,11 @@ function fetchNextData( ...@@ -554,7 +561,11 @@ function fetchNextData(
if (inflightCache[cacheKey] !== undefined) { if (inflightCache[cacheKey] !== undefined) {
return inflightCache[cacheKey] return inflightCache[cacheKey]
} }
return (inflightCache[cacheKey] = fetchRetry(dataHref, isServerRender ? 3 : 1) return (inflightCache[cacheKey] = fetchRetry(
dataHref,
isServerRender ? 3 : 1,
{ text }
)
.catch((err: Error) => { .catch((err: Error) => {
// We should only trigger a server-side transition if this was caused // We should only trigger a server-side transition if this was caused
// on a client-side transition. Otherwise, we'd get into an infinite // on a client-side transition. Otherwise, we'd get into an infinite
...@@ -671,6 +682,7 @@ export default class Router implements BaseRouter { ...@@ -671,6 +682,7 @@ export default class Router implements BaseRouter {
err, err,
__N_SSG: initialProps && initialProps.__N_SSG, __N_SSG: initialProps && initialProps.__N_SSG,
__N_SSP: initialProps && initialProps.__N_SSP, __N_SSP: initialProps && initialProps.__N_SSP,
__N_RSC: !!(Component as any)?.__next_rsc__,
} }
} }
...@@ -1466,9 +1478,10 @@ export default class Router implements BaseRouter { ...@@ -1466,9 +1478,10 @@ export default class Router implements BaseRouter {
styleSheets: res.styleSheets, styleSheets: res.styleSheets,
__N_SSG: res.mod.__N_SSG, __N_SSG: res.mod.__N_SSG,
__N_SSP: res.mod.__N_SSP, __N_SSP: res.mod.__N_SSP,
__N_RSC: !!(res.page as any).__next_rsc__,
}))) })))
const { Component, __N_SSG, __N_SSP } = routeInfo const { Component, __N_SSG, __N_SSP, __N_RSC } = routeInfo
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const { isValidElementType } = require('react-is') const { isValidElementType } = require('react-is')
...@@ -1481,13 +1494,14 @@ export default class Router implements BaseRouter { ...@@ -1481,13 +1494,14 @@ export default class Router implements BaseRouter {
let dataHref: string | undefined let dataHref: string | undefined
if (__N_SSG || __N_SSP) { if (__N_SSG || __N_SSP || __N_RSC) {
dataHref = this.pageLoader.getDataHref( dataHref = this.pageLoader.getDataHref({
formatWithValidation({ pathname, query }), href: formatWithValidation({ pathname, query }),
resolvedAs, asPath: resolvedAs,
__N_SSG, ssg: __N_SSG,
this.locale rsc: __N_RSC,
) locale: this.locale,
})
} }
const props = await this._getData<CompletePrivateRouteInfo>(() => const props = await this._getData<CompletePrivateRouteInfo>(() =>
...@@ -1495,6 +1509,7 @@ export default class Router implements BaseRouter { ...@@ -1495,6 +1509,7 @@ export default class Router implements BaseRouter {
? fetchNextData( ? fetchNextData(
dataHref!, dataHref!,
this.isSsr, this.isSsr,
false,
__N_SSG ? this.sdc : this.sdr, __N_SSG ? this.sdc : this.sdr,
!!__N_SSG !!__N_SSG
) )
...@@ -1512,6 +1527,16 @@ export default class Router implements BaseRouter { ...@@ -1512,6 +1527,16 @@ export default class Router implements BaseRouter {
) )
) )
if (__N_RSC) {
const { fresh, data } = (await this._getData(() =>
this._getFlightData(dataHref!)
)) as { fresh: boolean; data: string }
;(props as any).pageProps = Object.assign((props as any).pageProps, {
__flight_serialized__: data,
__flight_fresh__: fresh,
})
}
routeInfo.props = props routeInfo.props = props
this.components[route] = routeInfo this.components[route] = routeInfo
return routeInfo return routeInfo
...@@ -1693,15 +1718,17 @@ export default class Router implements BaseRouter { ...@@ -1693,15 +1718,17 @@ export default class Router implements BaseRouter {
this.pageLoader._isSsg(route).then((isSsg: boolean) => { this.pageLoader._isSsg(route).then((isSsg: boolean) => {
return isSsg return isSsg
? fetchNextData( ? fetchNextData(
this.pageLoader.getDataHref( this.pageLoader.getDataHref({
url, href: url,
resolvedAs, asPath: resolvedAs,
true, ssg: true,
locale:
typeof options.locale !== 'undefined' typeof options.locale !== 'undefined'
? options.locale ? options.locale
: this.locale : this.locale,
), }),
false, false,
false, // text
this.sdc, this.sdc,
true true
) )
...@@ -1765,6 +1792,21 @@ export default class Router implements BaseRouter { ...@@ -1765,6 +1792,21 @@ export default class Router implements BaseRouter {
}) })
} }
_getFlightData(dataHref: string): Promise<object> {
const { href: cacheKey } = new URL(dataHref, window.location.href)
if (!this.isPreview && this.sdc[cacheKey]) {
return Promise.resolve({ fresh: false, data: this.sdc[cacheKey] })
}
return fetchNextData(dataHref, true, true, this.sdc, false).then(
(serialized) => {
this.sdc[cacheKey] = serialized
return { fresh: true, data: serialized }
}
)
}
async _preflightRequest(options: { async _preflightRequest(options: {
as: string as: string
cache?: boolean cache?: boolean
...@@ -1777,9 +1819,9 @@ export default class Router implements BaseRouter { ...@@ -1777,9 +1819,9 @@ export default class Router implements BaseRouter {
this.locale this.locale
) )
const fns: string[] = await this.pageLoader.getMiddlewareList() const fns: [string, boolean][] = await this.pageLoader.getMiddlewareList()
const requiresPreflight = fns.some((middleware) => { const requiresPreflight = fns.some(([middleware, isSSR]) => {
return getRouteMatcher(getMiddlewareRegex(middleware))(cleanedAs) return getRouteMatcher(getMiddlewareRegex(middleware, !isSSR))(cleanedAs)
}) })
if (!requiresPreflight) { if (!requiresPreflight) {
...@@ -1859,7 +1901,8 @@ export default class Router implements BaseRouter { ...@@ -1859,7 +1901,8 @@ export default class Router implements BaseRouter {
} }
} }
if (preflight.refresh) { // For SSR requests, they will be handled like normal pages.
if (preflight.refresh && !preflight.ssr) {
return { return {
type: 'refresh', type: 'refresh',
} }
...@@ -1900,6 +1943,7 @@ export default class Router implements BaseRouter { ...@@ -1900,6 +1943,7 @@ export default class Router implements BaseRouter {
redirect: res.headers.get('Location'), redirect: res.headers.get('Location'),
refresh: res.headers.has('x-middleware-refresh'), refresh: res.headers.has('x-middleware-refresh'),
rewrite: res.headers.get('x-middleware-rewrite'), rewrite: res.headers.get('x-middleware-rewrite'),
ssr: !!res.headers.get('x-middleware-ssr'),
} }
}) })
.then((data) => { .then((data) => {
......
import { getParametrizedRoute, RouteRegex } from './route-regex' import { getParametrizedRoute, RouteRegex } from './route-regex'
export function getMiddlewareRegex(normalizedRoute: string): RouteRegex { export function getMiddlewareRegex(
normalizedRoute: string,
catchAll: boolean = true
): RouteRegex {
const result = getParametrizedRoute(normalizedRoute) const result = getParametrizedRoute(normalizedRoute)
let catchAllRegex = catchAll ? '(?!_next).*' : ''
let catchAllGroupedRegex = catchAll ? '(?:(/.*)?)' : ''
if ('routeKeys' in result) { if ('routeKeys' in result) {
if (result.parameterizedRoute === '/') { if (result.parameterizedRoute === '/') {
return { return {
groups: {}, groups: {},
namedRegex: `^/(?!_next).*$`, namedRegex: `^/${catchAllRegex}$`,
re: new RegExp('^/(?!_next).*$'), re: new RegExp(`^/${catchAllRegex}$`),
routeKeys: {}, routeKeys: {},
} }
} }
return { return {
groups: result.groups, groups: result.groups,
namedRegex: `^${result.namedParameterizedRoute}(?:(/.*)?)$`, namedRegex: `^${result.namedParameterizedRoute}${catchAllGroupedRegex}$`,
re: new RegExp(`^${result.parameterizedRoute}(?:(/.*)?)$`), re: new RegExp(`^${result.parameterizedRoute}${catchAllGroupedRegex}$`),
routeKeys: result.routeKeys, routeKeys: result.routeKeys,
} }
} }
...@@ -23,12 +30,12 @@ export function getMiddlewareRegex(normalizedRoute: string): RouteRegex { ...@@ -23,12 +30,12 @@ export function getMiddlewareRegex(normalizedRoute: string): RouteRegex {
if (result.parameterizedRoute === '/') { if (result.parameterizedRoute === '/') {
return { return {
groups: {}, groups: {},
re: new RegExp('^/.*$'), re: new RegExp(`^/${catchAllRegex}$`),
} }
} }
return { return {
groups: {}, groups: {},
re: new RegExp(`^${result.parameterizedRoute}(?:(/.*)?)$`), re: new RegExp(`^${result.parameterizedRoute}${catchAllGroupedRegex}$`),
} }
} }
...@@ -107,6 +107,7 @@ export type NEXT_DATA = { ...@@ -107,6 +107,7 @@ export type NEXT_DATA = {
domainLocales?: DomainLocale[] domainLocales?: DomainLocale[]
scriptLoader?: any[] scriptLoader?: any[]
isPreview?: boolean isPreview?: boolean
rsc?: boolean
} }
/** /**
...@@ -174,6 +175,7 @@ export type AppPropsType< ...@@ -174,6 +175,7 @@ export type AppPropsType<
router: R router: R
__N_SSG?: boolean __N_SSG?: boolean
__N_SSP?: boolean __N_SSP?: boolean
__N_RSC?: boolean
} }
export type DocumentContext = NextPageContext & { export type DocumentContext = NextPageContext & {
......
...@@ -2,6 +2,9 @@ ...@@ -2,6 +2,9 @@
declare module 'next/dist/compiled/babel/plugin-transform-modules-commonjs' declare module 'next/dist/compiled/babel/plugin-transform-modules-commonjs'
declare module 'next/dist/compiled/babel/plugin-syntax-jsx' declare module 'next/dist/compiled/babel/plugin-syntax-jsx'
declare module 'browserslist' declare module 'browserslist'
declare module 'react-server-dom-webpack/writer.browser.server'
declare module 'react-server-dom-webpack'
declare module 'cssnano-simple' { declare module 'cssnano-simple' {
const cssnanoSimple: any const cssnanoSimple: any
export = cssnanoSimple export = cssnanoSimple
......
...@@ -48,6 +48,7 @@ function isSafeExport(key: string): boolean { ...@@ -48,6 +48,7 @@ function isSafeExport(key: string): boolean {
key === '__esModule' || key === '__esModule' ||
key === '__N_SSG' || key === '__N_SSG' ||
key === '__N_SSP' || key === '__N_SSP' ||
key === '__N_RSC' ||
// TODO: remove this key from page config instead of allow listing it // TODO: remove this key from page config instead of allow listing it
key === 'config' key === 'config'
) )
......
module.exports = {
pageExtensions: ['js', 'ts', 'jsx'], // .tsx won't be treat as page,
experimental: {
reactRoot: true,
concurrentFeatures: true,
serverComponents: true,
},
webpack(config) {
const { alias } = config.resolve
alias['react/jsx-dev-runtime'] = 'react-18/jsx-dev-runtime.js'
alias['react/jsx-runtime'] = 'react-18/jsx-runtime.js'
// Use react 18
alias['react'] = 'react-18'
alias['react-dom'] = 'react-dom-18'
alias['react-dom/server'] = 'react-dom-18/server'
return config
},
}
{
"private": true,
"scripts": {
"lnext": "node -r ../../react-18/test/require-hook.js ../../../../packages/next/dist/bin/next",
"dev": "yarn lnext dev",
"build": "yarn lnext build",
"start": "yarn lnext start"
}
}
function App({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default App
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
export default function Index() {
return 'thisistheindexpage'
}
export default function InvalidExt() {
return 'invalid-ext'
}
import NextImage from 'next/image'
import src from '../../public/test.jpg'
export default function Image() {
return <NextImage src={src} />
}
import NextLink from 'next/link'
export default function Link() {
return (
<NextLink href={`/`}>
<a>go home</a>
</NextLink>
)
}
export default function Pid() {
return '[pid]' // TODO: display based on query
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
/* eslint-env jest */
import { join } from 'path'
import fs from 'fs-extra'
import {
findPort,
killApp,
launchApp,
nextBuild as _nextBuild,
nextStart as _nextStart,
renderViaHTTP,
} from 'next-test-utils'
const nodeArgs = ['-r', join(__dirname, '../../react-18/test/require-hook.js')]
const appDir = join(__dirname, '../app')
const distDir = join(__dirname, '../app/.next')
async function nextBuild(dir) {
return await _nextBuild(dir, [], {
stdout: true,
stderr: true,
nodeArgs,
})
}
async function nextStart(dir, port) {
return await _nextStart(dir, port, {
stdout: true,
stderr: true,
nodeArgs,
})
}
async function nextDev(dir, port) {
return await launchApp(dir, port, {
stdout: true,
stderr: true,
nodeArgs,
})
}
describe('RSC basic', () => {
const context = { appDir }
it('should warn user for experimental risk with server components', async () => {
const middlewareWarning = `Using the experimental web runtime.`
const rscWarning = `You have experimental React Server Components enabled.`
const { stdout } = await nextBuild(context.appDir)
expect(stdout).toContain(rscWarning)
expect(stdout).toContain(middlewareWarning)
})
})
describe('RSC prod', () => {
const context = { appDir }
beforeAll(async () => {
context.appPort = await findPort()
await nextBuild(context.appDir)
context.server = await nextStart(context.appDir, context.appPort)
})
afterAll(async () => {
await killApp(context.server)
})
it('should generate rsc middleware manifests', async () => {
const distServerDir = join(distDir, 'server')
const hasFile = (filename) => fs.existsSync(join(distServerDir, filename))
const files = [
'middleware-build-manifest.js',
'middleware-flight-manifest.js',
'middleware-ssr-runtime.js',
'middleware-manifest.json',
]
files.forEach((file) => {
expect(hasFile(file)).toBe(true)
})
})
runTests(context)
})
describe('RSC dev', () => {
const context = { appDir }
beforeAll(async () => {
context.appPort = await findPort()
context.server = await nextDev(context.appDir, context.appPort)
})
afterAll(async () => {
await killApp(context.server)
})
runTests(context)
})
async function runTests(context) {
it('should render the correct html', async () => {
const homeHTML = await renderViaHTTP(context.appPort, '/')
const linkHTML = await renderViaHTTP(context.appPort, '/next-api/link')
expect(homeHTML).toContain('thisistheindexpage')
expect(linkHTML).toContain('go home')
})
}
...@@ -5491,6 +5491,16 @@ acorn-walk@^8.0.0: ...@@ -5491,6 +5491,16 @@ acorn-walk@^8.0.0:
resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.0.0.tgz#56ae4c0f434a45fff4a125e7ea95fa9c98f67a16" resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.0.0.tgz#56ae4c0f434a45fff4a125e7ea95fa9c98f67a16"
integrity sha512-oZRad/3SMOI/pxbbmqyurIx7jHw1wZDcR9G44L8pUVFEomX/0dH89SrM1KaDXuv1NpzAXz6Op/Xu/Qd5XXzdEA== integrity sha512-oZRad/3SMOI/pxbbmqyurIx7jHw1wZDcR9G44L8pUVFEomX/0dH89SrM1KaDXuv1NpzAXz6Op/Xu/Qd5XXzdEA==
acorn@8.5.0, acorn@^8.3.0, acorn@^8.4.1:
version "8.5.0"
resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.5.0.tgz#4512ccb99b3698c752591e9bb4472e38ad43cee2"
integrity sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q==
acorn@^6.2.1:
version "6.4.2"
resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.2.tgz#35866fd710528e92de10cf06016498e47e39e1e6"
integrity sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==
acorn@^6.4.1: acorn@^6.4.1:
version "6.4.1" version "6.4.1"
resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.1.tgz#531e58ba3f51b9dacb9a6646ca4debf5b14ca474" resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.1.tgz#531e58ba3f51b9dacb9a6646ca4debf5b14ca474"
...@@ -5519,11 +5529,6 @@ acorn@^8.2.4: ...@@ -5519,11 +5529,6 @@ acorn@^8.2.4:
resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.4.1.tgz#56c36251fc7cabc7096adc18f05afe814321a28c" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.4.1.tgz#56c36251fc7cabc7096adc18f05afe814321a28c"
integrity sha512-asabaBSkEKosYKMITunzX177CXxQ4Q8BSSzMTKD+FefUhipQC70gfW5SiUDhYQ3vk8G+81HqQk7Fv9OXwwn9KA== integrity sha512-asabaBSkEKosYKMITunzX177CXxQ4Q8BSSzMTKD+FefUhipQC70gfW5SiUDhYQ3vk8G+81HqQk7Fv9OXwwn9KA==
acorn@^8.3.0, acorn@^8.4.1:
version "8.5.0"
resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.5.0.tgz#4512ccb99b3698c752591e9bb4472e38ad43cee2"
integrity sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q==
add-stream@^1.0.0: add-stream@^1.0.0:
version "1.0.0" version "1.0.0"
resolved "https://registry.yarnpkg.com/add-stream/-/add-stream-1.0.0.tgz#6a7990437ca736d5e1288db92bd3266d5f5cb2aa" resolved "https://registry.yarnpkg.com/add-stream/-/add-stream-1.0.0.tgz#6a7990437ca736d5e1288db92bd3266d5f5cb2aa"
...@@ -13858,6 +13863,7 @@ negotiator@0.6.2: ...@@ -13858,6 +13863,7 @@ negotiator@0.6.2:
neo-async@2.6.1: neo-async@2.6.1:
version "2.6.1" version "2.6.1"
resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.1.tgz#ac27ada66167fa8849a6addd837f6b189ad2081c" resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.1.tgz#ac27ada66167fa8849a6addd837f6b189ad2081c"
integrity sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw==
neo-async@^2.5.0, neo-async@^2.6.0, neo-async@^2.6.1, neo-async@^2.6.2: neo-async@^2.5.0, neo-async@^2.6.0, neo-async@^2.6.1, neo-async@^2.6.2:
version "2.6.2" version "2.6.2"
...@@ -16344,22 +16350,22 @@ rc@^1.0.1, rc@^1.1.6, rc@^1.2.7, rc@^1.2.8: ...@@ -16344,22 +16350,22 @@ rc@^1.0.1, rc@^1.1.6, rc@^1.2.7, rc@^1.2.8:
minimist "^1.2.0" minimist "^1.2.0"
strip-json-comments "~2.0.1" strip-json-comments "~2.0.1"
"react-18@npm:react@next": "react-18@npm:react@18.0.0-alpha-3c4c1c470-20211021":
version "18.0.0-alpha-996da67b2-20211018" version "18.0.0-alpha-3c4c1c470-20211021"
resolved "https://registry.yarnpkg.com/react/-/react-18.0.0-alpha-996da67b2-20211018.tgz#9b92e0f6e0dc69a7e7d85a591593bbd53e4d660f" resolved "https://registry.yarnpkg.com/react/-/react-18.0.0-alpha-3c4c1c470-20211021.tgz#82d8d375d25e6022cee34031947537e44fcdee07"
integrity sha512-N8FJrmv97+0bDyqCATzqBXwtdIleQccf950MeJEnQbufh/lA7bRphMXOC5H/99cQJ1gl4zFoXFCuaU+UGbS6HA== integrity sha512-uuwpd6i7/SJZ5YeADm9ZYXWE0YNucKhcXXHRpNwSkFrKD3OUIH6rNme82q+jsWXzjZ0fIMhRgsKTaLXpcVYjZw==
dependencies: dependencies:
loose-envify "^1.1.0" loose-envify "^1.1.0"
object-assign "^4.1.1" object-assign "^4.1.1"
"react-dom-18@npm:react-dom@next": "react-dom-18@npm:react-dom@18.0.0-alpha-3c4c1c470-20211021":
version "18.0.0-alpha-996da67b2-20211018" version "18.0.0-alpha-3c4c1c470-20211021"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-18.0.0-alpha-996da67b2-20211018.tgz#536b75359832644bae5343d638951e878b3bf438" resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-18.0.0-alpha-3c4c1c470-20211021.tgz#74d34897397f9a5fda9c2fd9e349d908d374e8b9"
integrity sha512-cFhSJEZKsZONn5zhmD8n9FiAuAkzf0OrLxAdqCAHF6Dllp/p6lecOwptR46V7Q+ECu1zFV1CjAgU962Au/0CGA== integrity sha512-n3Y8YMlwZ48joxM9z2MnDVZeWdsyn+TgY7H8HjuB/Z3BDv3TH088azv2oVpQpfNz2iV0apw6rxzbEpoUuHzQyw==
dependencies: dependencies:
loose-envify "^1.1.0" loose-envify "^1.1.0"
object-assign "^4.1.1" object-assign "^4.1.1"
scheduler "0.21.0-alpha-996da67b2-20211018" scheduler "0.21.0-alpha-3c4c1c470-20211021"
react-dom@17.0.2: react-dom@17.0.2:
version "17.0.2" version "17.0.2"
...@@ -16389,6 +16395,16 @@ react-refresh@0.8.3: ...@@ -16389,6 +16395,16 @@ react-refresh@0.8.3:
resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.8.3.tgz#721d4657672d400c5e3c75d063c4a85fb2d5d68f" resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.8.3.tgz#721d4657672d400c5e3c75d063c4a85fb2d5d68f"
integrity sha512-X8jZHc7nCMjaCqoU+V2I0cOhNW+QMBwSUkeXnTi8IPe6zaRWfn60ZzvFDZqWPfmSJfjub7dDW1SP0jaHWLu/hg== integrity sha512-X8jZHc7nCMjaCqoU+V2I0cOhNW+QMBwSUkeXnTi8IPe6zaRWfn60ZzvFDZqWPfmSJfjub7dDW1SP0jaHWLu/hg==
react-server-dom-webpack@0.0.0-experimental-3c4c1c470-20211021:
version "0.0.0-experimental-3c4c1c470-20211021"
resolved "https://registry.yarnpkg.com/react-server-dom-webpack/-/react-server-dom-webpack-0.0.0-experimental-3c4c1c470-20211021.tgz#cdcaa2f19c8d820c1f4d31252319fb05e2de0e88"
integrity sha512-YyRlED5kR0C2aQ3IJ/8BR2TELt51RcDZhnUDKz+m/HU+Gb/qak0CZkG0A8Zxffom9VI6HFkUj1dRFZqm0Lh9Pg==
dependencies:
acorn "^6.2.1"
loose-envify "^1.1.0"
neo-async "^2.6.1"
object-assign "^4.1.1"
react-ssr-prepass@1.0.8: react-ssr-prepass@1.0.8:
version "1.0.8" version "1.0.8"
resolved "https://registry.yarnpkg.com/react-ssr-prepass/-/react-ssr-prepass-1.0.8.tgz#036abffe541975b20213cf7b261c05ac2843480d" resolved "https://registry.yarnpkg.com/react-ssr-prepass/-/react-ssr-prepass-1.0.8.tgz#036abffe541975b20213cf7b261c05ac2843480d"
...@@ -17331,10 +17347,10 @@ saxes@^5.0.1: ...@@ -17331,10 +17347,10 @@ saxes@^5.0.1:
dependencies: dependencies:
xmlchars "^2.2.0" xmlchars "^2.2.0"
scheduler@0.21.0-alpha-996da67b2-20211018: scheduler@0.21.0-alpha-3c4c1c470-20211021:
version "0.21.0-alpha-996da67b2-20211018" version "0.21.0-alpha-3c4c1c470-20211021"
resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.21.0-alpha-996da67b2-20211018.tgz#de96129e104370b0a6c937c3d723d118f83afd41" resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.21.0-alpha-3c4c1c470-20211021.tgz#5c786383bbf1fe09a108c4f7d78e7d16eb75d338"
integrity sha512-7N20qihDl+CD+XFj8wwcqjArQ2UIW1xvwCBixHCKUAtJZ//4YYITfIjNpeci2OeYFw9RMiVabgF+LtzDT+64fw== integrity sha512-G8N3UiaKIy5hGBY8Imy/fNHdslvMNK/7PbzrSS0BG2o2zFX6V/i9QBiEZ+PshVbMNH3OwihHO5LSrmAZHkwZoQ==
dependencies: dependencies:
loose-envify "^1.1.0" loose-envify "^1.1.0"
object-assign "^4.1.1" object-assign "^4.1.1"
......
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