Unverified Commit b5aa571c authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Refactor client entry plugin to separate methods. (#39162)

WIP.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
Co-authored-by: 's avatarShu Ding <3676859+shuding@users.noreply.github.com>
parent 0c7217ba
......@@ -15,12 +15,16 @@ import {
ROOT_DIR_ALIAS,
APP_DIR_ALIAS,
SERVER_RUNTIME,
WEBPACK_LAYERS,
} from '../lib/constants'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CompilerNameValues,
COMPILER_NAMES,
EDGE_RUNTIME_WEBPACK,
} from '../shared/lib/constants'
import { __ApiPreviewProps } from '../server/api-utils'
......@@ -203,7 +207,7 @@ export function getEdgeServerEntry(opts: {
return {
import: `next-edge-ssr-loader?${stringify(loaderParams)}!`,
layer: opts.isServerComponent ? 'sc_server' : undefined,
layer: opts.isServerComponent ? WEBPACK_LAYERS.server : undefined,
}
}
......@@ -215,7 +219,7 @@ export function getAppEntry(opts: {
}) {
return {
import: `next-app-loader?${stringify(opts)}!`,
layer: 'sc_server',
layer: WEBPACK_LAYERS.server,
}
}
......@@ -359,7 +363,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}
}
runDependingOnPageType({
await runDependingOnPageType({
page,
pageRuntime: staticInfo.runtime,
onClient: () => {
......@@ -393,7 +397,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
server[serverBundlePath] = isServerComponent
? {
import: mappings[page],
layer: 'sc_server',
layer: WEBPACK_LAYERS.server,
}
: [mappings[page]]
}
......@@ -435,33 +439,46 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}
}
export function runDependingOnPageType<T>(params: {
export async function runDependingOnPageType<T>(params: {
onClient: () => T
onEdgeServer: () => T
onServer: () => T
page: string
pageRuntime: ServerRuntime
}) {
}): Promise<void> {
if (isMiddlewareFile(params.page)) {
return { edgeServer: params.onEdgeServer() }
} else if (params.page.match(API_ROUTE)) {
return params.pageRuntime === SERVER_RUNTIME.edge
? { edgeServer: params.onEdgeServer() }
: { server: params.onServer() }
} else if (params.page === '/_document') {
return { server: params.onServer() }
} else if (
await params.onEdgeServer()
return
}
if (params.page.match(API_ROUTE)) {
if (params.pageRuntime === SERVER_RUNTIME.edge) {
await params.onEdgeServer()
return
}
await params.onServer()
return
}
if (params.page === '/_document') {
await params.onServer()
return
}
if (
params.page === '/_app' ||
params.page === '/_error' ||
params.page === '/404' ||
params.page === '/500'
) {
return { client: params.onClient(), server: params.onServer() }
} else {
return params.pageRuntime === SERVER_RUNTIME.edge
? { client: params.onClient(), edgeServer: params.onEdgeServer() }
: { client: params.onClient(), server: params.onServer() }
await Promise.all([params.onClient(), params.onServer()])
return
}
if (params.pageRuntime === SERVER_RUNTIME.edge) {
await Promise.all([params.onClient(), params.onEdgeServer()])
return
}
await Promise.all([params.onClient(), params.onServer()])
return
}
export function finalizeEntrypoint({
......@@ -471,7 +488,7 @@ export function finalizeEntrypoint({
isServerComponent,
appDir,
}: {
compilerType?: 'client' | 'server' | 'edge-server'
compilerType?: CompilerNameValues
name: string
value: ObjectValue<webpack5.EntryObject>
isServerComponent?: boolean
......@@ -483,18 +500,25 @@ export function finalizeEntrypoint({
: value
const isApi = name.startsWith('pages/api/')
if (compilerType === 'server') {
if (compilerType === COMPILER_NAMES.server) {
return {
publicPath: isApi ? '' : undefined,
runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime',
layer: isApi ? 'api' : isServerComponent ? 'sc_server' : undefined,
layer: isApi
? WEBPACK_LAYERS.api
: isServerComponent
? WEBPACK_LAYERS.server
: undefined,
...entry,
}
}
if (compilerType === 'edge-server') {
if (compilerType === COMPILER_NAMES.edgeServer) {
return {
layer: isMiddlewareFilename(name) || isApi ? 'middleware' : undefined,
layer:
isMiddlewareFilename(name) || isApi
? WEBPACK_LAYERS.middleware
: undefined,
library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' },
runtime: EDGE_RUNTIME_WEBPACK,
asyncChunks: false,
......@@ -504,7 +528,7 @@ export function finalizeEntrypoint({
if (
// Client special cases
name !== 'polyfills' &&
name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP &&
name !== CLIENT_STATIC_FILES_RUNTIME_AMP &&
......
......@@ -55,6 +55,7 @@ import {
MIDDLEWARE_MANIFEST,
APP_PATHS_MANIFEST,
APP_PATH_ROUTES_MANIFEST,
COMPILER_NAMES,
APP_BUILD_MANIFEST,
} from '../shared/lib/constants'
import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils'
......@@ -749,17 +750,17 @@ export default async function build(
Promise.all([
getBaseWebpackConfig(dir, {
...commonWebpackOptions,
compilerType: 'client',
compilerType: COMPILER_NAMES.client,
entrypoints: entrypoints.client,
}),
getBaseWebpackConfig(dir, {
...commonWebpackOptions,
compilerType: 'server',
compilerType: COMPILER_NAMES.server,
entrypoints: entrypoints.server,
}),
getBaseWebpackConfig(dir, {
...commonWebpackOptions,
compilerType: 'edge-server',
compilerType: COMPILER_NAMES.edgeServer,
entrypoints: entrypoints.edgeServer,
}),
])
......
......@@ -5,6 +5,7 @@ import createStore from 'next/dist/compiled/unistore'
import formatWebpackMessages from '../../client/dev/error-overlay/format-webpack-messages'
import { OutputState, store as consoleStore } from './store'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { CompilerNameValues, COMPILER_NAMES } from '../../shared/lib/constants'
export function startedDevelopmentServer(appUrl: string, bindAddr: string) {
consoleStore.setState({ appUrl, bindAddr })
......@@ -238,7 +239,7 @@ export function watchCompilers(
})
function tapCompiler(
key: 'client' | 'server' | 'edgeServer',
key: CompilerNameValues,
compiler: webpack5.Compiler,
onEvent: (status: WebpackStatus) => void
) {
......@@ -268,7 +269,7 @@ export function watchCompilers(
})
}
tapCompiler('client', client, (status) => {
tapCompiler(COMPILER_NAMES.client, client, (status) => {
if (
!status.loading &&
!buildStore.getState().server.loading &&
......@@ -284,7 +285,7 @@ export function watchCompilers(
})
}
})
tapCompiler('server', server, (status) => {
tapCompiler(COMPILER_NAMES.server, server, (status) => {
if (
!status.loading &&
!buildStore.getState().client.loading &&
......@@ -300,7 +301,7 @@ export function watchCompilers(
})
}
})
tapCompiler('edgeServer', edgeServer, (status) => {
tapCompiler(COMPILER_NAMES.edgeServer, edgeServer, (status) => {
if (
!status.loading &&
!buildStore.getState().client.loading &&
......
......@@ -13,6 +13,7 @@ import {
ROOT_DIR_ALIAS,
APP_DIR_ALIAS,
SERVER_RUNTIME,
WEBPACK_LAYERS,
} from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js'
......@@ -28,6 +29,8 @@ import {
SERVERLESS_DIRECTORY,
SERVER_DIRECTORY,
MODERN_BROWSERSLIST_TARGET,
COMPILER_NAMES,
CompilerNameValues,
} from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils'
import { NextConfigComplete } from '../server/config-shared'
......@@ -334,13 +337,13 @@ export default async function getBaseWebpackConfig(
reactProductionProfiling = false,
rewrites,
runWebpackSpan,
target = 'server',
target = COMPILER_NAMES.server,
appDir,
middlewareRegex,
}: {
buildId: string
config: NextConfigComplete
compilerType: 'client' | 'server' | 'edge-server'
compilerType: CompilerNameValues
dev?: boolean
entrypoints: webpack5.EntryObject
hasReactRoot: boolean
......@@ -354,9 +357,9 @@ export default async function getBaseWebpackConfig(
middlewareRegex?: string
}
): Promise<webpack.Configuration> {
const isClient = compilerType === 'client'
const isEdgeServer = compilerType === 'edge-server'
const isNodeServer = compilerType === 'server'
const isClient = compilerType === COMPILER_NAMES.client
const isEdgeServer = compilerType === COMPILER_NAMES.edgeServer
const isNodeServer = compilerType === COMPILER_NAMES.server
const { useTypeScript, jsConfig, resolvedBaseUrl } = await loadJsConfig(
dir,
config
......@@ -650,9 +653,9 @@ export default async function getBaseWebpackConfig(
const reactDomDir = dirname(require.resolve('react-dom/package.json'))
const mainFieldsPerCompiler: Record<typeof compilerType, string[]> = {
server: ['main', 'module'],
client: ['browser', 'module', 'main'],
'edge-server': ['browser', 'module', 'main'],
[COMPILER_NAMES.server]: ['main', 'module'],
[COMPILER_NAMES.client]: ['browser', 'module', 'main'],
[COMPILER_NAMES.edgeServer]: ['browser', 'module', 'main'],
}
const resolveConfig = {
......@@ -1310,14 +1313,14 @@ export default async function getBaseWebpackConfig(
// RSC server compilation loaders
{
...serverComponentCodeCondition,
issuerLayer: 'sc_server',
issuerLayer: WEBPACK_LAYERS.server,
use: {
loader: 'next-flight-server-loader',
},
},
{
test: clientComponentRegex,
issuerLayer: 'sc_server',
issuerLayer: WEBPACK_LAYERS.server,
use: {
loader: 'next-flight-client-loader',
},
......@@ -1325,7 +1328,7 @@ export default async function getBaseWebpackConfig(
// _app should be treated as a client component as well as all its dependencies.
{
test: new RegExp(`_app\\.(${rawPageExtensions.join('|')})$`),
layer: 'sc_client',
layer: WEBPACK_LAYERS.client,
},
]
: []
......@@ -1336,13 +1339,13 @@ export default async function getBaseWebpackConfig(
// same layer.
{
test: rscSharedRegex,
layer: 'rsc_shared_deps',
layer: WEBPACK_LAYERS.rscShared,
},
]
: []),
{
test: /\.(js|cjs|mjs)$/,
issuerLayer: 'api',
issuerLayer: WEBPACK_LAYERS.api,
parser: {
// Switch back to normal URL handling
url: true,
......@@ -1352,7 +1355,7 @@ export default async function getBaseWebpackConfig(
oneOf: [
{
...codeCondition,
issuerLayer: 'api',
issuerLayer: WEBPACK_LAYERS.api,
parser: {
// Switch back to normal URL handling
url: true,
......@@ -1361,7 +1364,7 @@ export default async function getBaseWebpackConfig(
},
{
...codeCondition,
issuerLayer: 'middleware',
issuerLayer: WEBPACK_LAYERS.middleware,
use: getBabelOrSwcLoader(),
},
{
......@@ -1399,7 +1402,7 @@ export default async function getBaseWebpackConfig(
{
oneOf: [
{
issuerLayer: 'middleware',
issuerLayer: WEBPACK_LAYERS.middleware,
resolve: {
fallback: {
process: require.resolve('./polyfills/process'),
......@@ -1499,7 +1502,7 @@ export default async function getBaseWebpackConfig(
[`process.env.${key}`]: JSON.stringify(config.env[key]),
}
}, {}),
...(compilerType !== 'edge-server'
...(compilerType !== COMPILER_NAMES.edgeServer
? {}
: {
EdgeRuntime: JSON.stringify(
......@@ -1785,10 +1788,10 @@ export default async function getBaseWebpackConfig(
dependency: 'url',
loader: 'next-middleware-asset-loader',
type: 'javascript/auto',
layer: 'edge-asset',
layer: WEBPACK_LAYERS.edgeAsset,
})
webpack5Config.module?.rules?.unshift({
issuerLayer: 'edge-asset',
issuerLayer: WEBPACK_LAYERS.edgeAsset,
type: 'asset/source',
})
}
......
import curry from 'next/dist/compiled/lodash.curry'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { COMPILER_NAMES } from '../../../../shared/lib/constants'
import { ConfigurationContext } from '../utils'
export const base = curry(function base(
......@@ -9,9 +10,9 @@ export const base = curry(function base(
config.mode = ctx.isDevelopment ? 'development' : 'production'
config.name = ctx.isServer
? ctx.isEdgeRuntime
? 'edge-server'
: 'server'
: 'client'
? COMPILER_NAMES.edgeServer
: COMPILER_NAMES.server
: COMPILER_NAMES.client
// @ts-ignore TODO webpack 5 typings
config.target = !ctx.targetWeb
......
import { SERVER_RUNTIME } from '../../../lib/constants'
export type ClientComponentImports = string[]
export type CssImports = Record<string, string[]>
export type NextFlightClientEntryLoaderOptions = {
modules: ClientComponentImports
/** This is transmitted as a string to `getOptions` */
server: boolean | 'true' | 'false'
}
export default async function transformSource(this: any): Promise<string> {
let { modules, runtime, ssr, server } = this.getOptions()
let { modules, server }: NextFlightClientEntryLoaderOptions =
this.getOptions()
const isServer = server === 'true'
if (!Array.isArray(modules)) {
modules = modules ? [modules] : []
}
......@@ -9,25 +19,17 @@ export default async function transformSource(this: any): Promise<string> {
const requests = modules as string[]
const code =
requests
.filter((request) => (server ? !request.endsWith('.css') : true))
// Filter out css files on the server
.filter((request) => (isServer ? !request.endsWith('.css') : true))
.map((request) => `import(/* webpackMode: "eager" */ '${request}')`)
.join(';\n') +
`
export const __next_rsc_css__ = ${JSON.stringify(
requests.filter((request) => request.endsWith('.css'))
)};
export const __next_rsc__ = {
server: false,
__webpack_require__
};
export default function RSC() {};
` +
// Currently for the Edge runtime, we treat all RSC pages as SSR pages.
(runtime === SERVER_RUNTIME.edge
? 'export const __N_SSP = true;'
: ssr
? `export const __N_SSP = true;`
: `export const __N_SSG = true;`)
`
return code
}
......@@ -24,9 +24,13 @@ interface Options {
pageExtensions: string[]
}
type ModuleId = string | number
/**
* Webpack module id
*/
// TODO-APP ensure `null` is included as it is used.
type ModuleId = string | number /*| null*/
type ManifestChunks = Array<`${string}:${string}` | string>
export type ManifestChunks = Array<`${string}:${string}` | string>
interface ManifestNode {
[moduleExport: string]: {
......@@ -45,7 +49,7 @@ interface ManifestNode {
}
}
type FlightManifest = {
export type FlightManifest = {
__ssr_module_mapping__: {
[moduleId: string]: ManifestNode
}
......@@ -53,6 +57,10 @@ type FlightManifest = {
[modulePath: string]: ManifestNode
}
export type FlightCSSManifest = {
[modulePath: string]: string[]
}
const PLUGIN_NAME = 'FlightManifestPlugin'
export class FlightManifestPlugin {
......@@ -139,7 +147,6 @@ export class FlightManifestPlugin {
const moduleExports = manifest[resource] || {}
const moduleIdMapping = manifest.__ssr_module_mapping__
moduleIdMapping[id] = moduleIdMapping[id] || {}
// Note that this isn't that reliable as webpack is still possible to assign
// additional queries to make sure there's no conflict even using the `named`
......@@ -161,6 +168,7 @@ export class FlightManifestPlugin {
chunks,
},
}
moduleIdMapping[id] = moduleIdMapping[id] || {}
moduleIdMapping[id]['default'] = {
id: ssrNamedModuleId,
name: 'default',
......@@ -269,6 +277,8 @@ export class FlightManifestPlugin {
chunks: requiredChunks.concat([...cssChunks]),
}
}
moduleIdMapping[id] = moduleIdMapping[id] || {}
if (!moduleIdMapping[id][name]) {
moduleIdMapping[id][name] = {
...moduleExports[name],
......
......@@ -626,6 +626,7 @@ function getEntryFiles(entryFiles: string[], meta: EntryMetadata) {
.map(
(file) =>
'server/' +
// TODO-APP: seems this should be removed.
file.replace('.js', NEXT_CLIENT_SSR_ENTRY_SUFFIX + '.js')
)
)
......
......@@ -89,13 +89,11 @@ let initialParallelRoutes: CacheNode['parallelRoutes'] =
export default function AppRouter({
initialTree,
initialCanonicalUrl,
initialStylesheets,
children,
hotReloader,
}: {
initialTree: FlightRouterState
initialCanonicalUrl: string
initialStylesheets: string[]
children: React.ReactNode
hotReloader?: React.ReactNode
}) {
......@@ -293,6 +291,7 @@ export default function AppRouter({
window.removeEventListener('popstate', onPopState)
}
}, [onPopState])
return (
<PathnameContext.Provider value={pathname}>
<SearchParamsContext.Provider value={searchParams}>
......@@ -311,7 +310,6 @@ export default function AppRouter({
// Root node always has `url`
// Provided in AppTreeContext to ensure it can be overwritten in layout-router
url: canonicalUrl,
stylesheets: initialStylesheets,
}}
>
<ErrorOverlay>
......
......@@ -360,11 +360,6 @@ export default function OuterLayoutRouter({
return (
<>
{/* {stylesheets
? stylesheets.map((href) => (
<link rel="stylesheet" href={`/_next/${href}`} key={href} />
))
: null} */}
{preservedSegments.map((preservedSegment) => {
return (
// Loading boundary is render for each segment to ensure they have their own loading state.
......
......@@ -75,3 +75,12 @@ export const SERVER_RUNTIME: Record<string, ServerRuntime> = {
edge: 'experimental-edge',
nodejs: 'nodejs',
}
export const WEBPACK_LAYERS = {
server: 'sc_server',
client: 'sc_client',
api: 'api',
rscShared: 'rsc_shared_deps',
middleware: 'middleware',
edgeAsset: 'edge-asset',
}
......@@ -22,6 +22,10 @@ import { htmlEscapeJsonString } from './htmlescape'
import { shouldUseReactRoot, stripInternalQueries } from './utils'
import { NextApiRequestCookies } from './api-utils'
import { matchSegment } from '../client/components/match-segments'
import {
FlightCSSManifest,
FlightManifest,
} from '../build/webpack/plugins/flight-manifest-plugin'
import { FlushEffectsContext } from '../client/components/hooks-client'
// this needs to be required lazily so that `next-server` can set
......@@ -34,6 +38,7 @@ export type RenderOptsPartial = {
err?: Error | null
dev?: boolean
serverComponentManifest?: any
serverCSSManifest?: any
supportsDynamicHTML?: boolean
runtime?: ServerRuntime
serverComponents?: boolean
......@@ -369,26 +374,32 @@ function getSegmentParam(segment: string): {
}
/**
* Get inline <link> tags based on __next_rsc_css__ manifest. Only used when rendering to HTML.
* Get inline <link> tags based on server CSS manifest. Only used when rendering to HTML.
*/
function getCssInlinedLinkTags(
ComponentMod: any,
serverComponentManifest: any
serverComponentManifest: FlightManifest,
serverCSSManifest: FlightCSSManifest
) {
const importedServerCSSFiles: string[] =
ComponentMod.__client__?.__next_rsc_css__ || []
return Array.from(
new Set(
importedServerCSSFiles
.map((css) =>
css.endsWith('.css')
? serverComponentManifest[css].default.chunks
: []
)
.flat()
)
)
const chunks: { [file: string]: string[] } = {}
// APP-TODO: Remove this once we have CSS injections at each level.
const allChunks = new Set<string>()
for (const layoutOrPage in serverCSSManifest) {
const uniqueChunks = new Set<string>()
for (const css of serverCSSManifest[layoutOrPage]) {
for (const chunk of serverComponentManifest[css].default.chunks) {
if (!uniqueChunks.has(chunk)) {
uniqueChunks.add(chunk)
chunks[layoutOrPage] = chunks[layoutOrPage] || []
chunks[layoutOrPage].push(chunk)
}
allChunks.add(chunk)
}
}
}
return [chunks, [...allChunks]] as [{ [file: string]: string[] }, string[]]
}
export async function renderToHTMLOrFlight(
......@@ -412,6 +423,7 @@ export async function renderToHTMLOrFlight(
const {
buildManifest,
serverComponentManifest,
serverCSSManifest,
supportsDynamicHTML,
ComponentMod,
} = renderOpts
......@@ -583,12 +595,16 @@ export async function renderToHTMLOrFlight(
parentParams,
firstItem,
rootLayoutIncluded,
}: {
serverStylesheets,
}: // parentSegmentPath,
{
createSegmentPath: CreateSegmentPath
loaderTree: LoaderTree
parentParams: { [key: string]: any }
rootLayoutIncluded?: boolean
firstItem?: boolean
serverStylesheets: { [file: string]: string[] }
// parentSegmentPath: string
}): Promise<{ Component: React.ComponentType }> => {
const Loading = loading ? await interopDefault(loading()) : undefined
const isLayout = typeof layout !== 'undefined'
......@@ -608,6 +624,10 @@ export async function renderToHTMLOrFlight(
const rootLayoutIncludedAtThisLevelOrAbove =
rootLayoutIncluded || rootLayoutAtThisLevel
// const cssSegmentPath =
// !parentSegmentPath && !segment ? '' : parentSegmentPath + '/' + segment
// const stylesheets = serverStylesheets[cssSegmentPath]
/**
* Check if the current layout/page is a client component
*/
......@@ -668,6 +688,8 @@ export async function renderToHTMLOrFlight(
loaderTree: parallelRoutes[parallelRouteKey],
parentParams: currentParams,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
serverStylesheets,
// parentSegmentPath: cssSegmentPath,
})
const childSegment = parallelRoutes[parallelRouteKey][0]
......@@ -807,16 +829,23 @@ export async function renderToHTMLOrFlight(
}
return (
<Component
{...props}
{...parallelRouteComponents}
// TODO-APP: params and query have to be blocked parallel route names. Might have to add a reserved name list.
// Params are always the current params that apply to the layout
// If you have a `/dashboard/[team]/layout.js` it will provide `team` as a param but not anything further down.
params={currentParams}
// Query is only provided to page
{...(isPage ? { searchParams: query } : {})}
/>
<>
{/* {stylesheets
? stylesheets.map((href) => (
<link rel="stylesheet" href={`/_next/${href}`} key={href} />
))
: null} */}
<Component
{...props}
{...parallelRouteComponents}
// TODO-APP: params and query have to be blocked parallel route names. Might have to add a reserved name list.
// Params are always the current params that apply to the layout
// If you have a `/dashboard/[team]/layout.js` it will provide `team` as a param but not anything further down.
params={currentParams}
// Query is only provided to page
{...(isPage ? { searchParams: query } : {})}
/>
</>
)
},
}
......@@ -881,6 +910,8 @@ export async function renderToHTMLOrFlight(
loaderTree: loaderTreeToFilter,
parentParams: currentParams,
firstItem: true,
serverStylesheets: serverCSSManifest,
// parentSegmentPath: '',
}
)
).Component
......@@ -928,12 +959,20 @@ export async function renderToHTMLOrFlight(
// Below this line is handling for rendering to HTML.
// Get all the server imported styles.
const [mappedServerCSSManifest, initialStylesheets] = getCssInlinedLinkTags(
serverComponentManifest,
serverCSSManifest
)
// Create full component tree from root to leaf.
const { Component: ComponentTree } = await createComponentTree({
createSegmentPath: (child) => child,
loaderTree: loaderTree,
parentParams: {},
firstItem: true,
serverStylesheets: mappedServerCSSManifest,
// parentSegmentPath: '',
})
// AppRouter is provided by next-app-loader
......@@ -947,10 +986,6 @@ export async function renderToHTMLOrFlight(
// TODO-APP: validate req.url as it gets passed to render.
const initialCanonicalUrl = req.url!
const initialStylesheets: string[] = getCssInlinedLinkTags(
ComponentMod,
serverComponentManifest
)
/**
* A new React Component that renders the provided React Component
......@@ -969,7 +1004,6 @@ export async function renderToHTMLOrFlight(
}
initialCanonicalUrl={initialCanonicalUrl}
initialTree={initialTree}
initialStylesheets={initialStylesheets}
>
<ComponentTree />
</AppRouter>
......
......@@ -30,7 +30,6 @@ import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/redirect-status'
import {
NEXT_BUILTIN_DOCUMENT,
NEXT_CLIENT_SSR_ENTRY_SUFFIX,
SERVERLESS_DIRECTORY,
SERVER_DIRECTORY,
STATIC_STATUS_PAGES,
......@@ -211,6 +210,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected appPathRoutes?: Record<string, string>
protected customRoutes: CustomRoutes
protected serverComponentManifest?: any
protected serverCSSManifest?: any
public readonly hostname?: string
public readonly port?: number
......@@ -245,6 +245,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected abstract getRoutesManifest(): CustomRoutes
protected abstract getPrerenderManifest(): PrerenderManifest
protected abstract getServerComponentManifest(): any
protected abstract getServerCSSManifest(): any
protected abstract attachRequestMeta(
req: BaseNextRequest,
parsedUrl: NextUrlWithParsedQuery
......@@ -331,6 +332,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
this.serverComponentManifest = serverComponents
? this.getServerComponentManifest()
: undefined
this.serverCSSManifest = serverComponents
? this.getServerCSSManifest()
: undefined
this.renderOpts = {
poweredByHeader: this.nextConfig.poweredByHeader,
......@@ -1046,9 +1050,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const appPathRoutes: Record<string, string> = {}
Object.keys(this.appPathsManifest || {}).forEach((entry) => {
if (entry.endsWith(NEXT_CLIENT_SSR_ENTRY_SUFFIX)) {
return
}
appPathRoutes[normalizeAppPath(entry) || '/'] = entry
})
return appPathRoutes
......
This diff is collapsed.
......@@ -30,6 +30,7 @@ import {
CLIENT_STATIC_FILES_PATH,
DEV_CLIENT_PAGES_MANIFEST,
DEV_MIDDLEWARE_MANIFEST,
COMPILER_NAMES,
} from '../../shared/lib/constants'
import Server, { WrappedBuildError } from '../next-server'
import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher'
......@@ -376,7 +377,7 @@ export default class DevServer extends Server {
continue
}
runDependingOnPageType({
await runDependingOnPageType({
page: pageName,
pageRuntime: staticInfo.runtime,
onClient: () => {},
......@@ -836,7 +837,7 @@ export default class DevServer extends Server {
const src = getErrorSource(err as Error)
const compilation = (
src === 'edge-server'
src === COMPILER_NAMES.edgeServer
? this.hotReloader?.edgeServerStats?.compilation
: this.hotReloader?.serverStats?.compilation
)!
......@@ -865,7 +866,7 @@ export default class DevServer extends Server {
Log[type === 'warning' ? 'warn' : 'error'](
`${file} (${lineNumber}:${column}) @ ${methodName}`
)
if (src === 'edge-server') {
if (src === COMPILER_NAMES.edgeServer) {
err = err.message
}
if (type === 'warning') {
......@@ -939,6 +940,10 @@ export default class DevServer extends Server {
return undefined
}
protected getServerCSSManifest() {
return undefined
}
protected async hasMiddleware(): Promise<boolean> {
return this.hasPage(this.actualMiddlewareFile!)
}
......@@ -1123,7 +1128,7 @@ export default class DevServer extends Server {
}
}
protected async ensureApiPage(pathname: string) {
protected async ensureApiPage(pathname: string): Promise<void> {
return this.hotReloader!.ensurePage(pathname)
}
......@@ -1148,6 +1153,7 @@ export default class DevServer extends Server {
// manifest.
if (serverComponents) {
this.serverComponentManifest = super.getServerComponentManifest()
this.serverCSSManifest = super.getServerCSSManifest()
}
return super.findPageComponents(pathname, query, params, isAppDir)
......
......@@ -13,13 +13,11 @@ import {
BUILD_MANIFEST,
REACT_LOADABLE_MANIFEST,
FLIGHT_MANIFEST,
NEXT_CLIENT_SSR_ENTRY_SUFFIX,
} from '../shared/lib/constants'
import { join } from 'path'
import { requirePage, getPagePath } from './require'
import { BuildManifest } from './get-page-files'
import { interopDefault } from '../lib/interop-default'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
export type ManifestItem = {
id: number | string
......@@ -122,22 +120,6 @@ export async function loadComponents(
: null,
])
if (hasServerComponents) {
try {
// Make sure to also load the client entry in cache.
const __client__ = await requirePage(
normalizePagePath(pathname) + NEXT_CLIENT_SSR_ENTRY_SUFFIX,
distDir,
serverless,
appDirEnabled
)
ComponentMod.__client__ = __client__
} catch (_) {
// This page might not be a server component page, so there is no
// client entry to load.
}
}
const Component = interopDefault(ComponentMod)
const Document = interopDefault(DocumentMod)
const App = interopDefault(AppMod)
......
......@@ -38,6 +38,7 @@ import {
FLIGHT_MANIFEST,
CLIENT_PUBLIC_FILES_PATH,
APP_PATHS_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
} from '../shared/lib/constants'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { format as formatUrl, UrlWithParsedQuery } from 'url'
......@@ -642,6 +643,7 @@ export default class NextNodeServer extends BaseServer {
// object here but only updating its `serverComponentManifest` field.
// https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952
renderOpts.serverComponentManifest = this.serverComponentManifest
renderOpts.serverCSSManifest = this.serverCSSManifest
if (
this.nextConfig.experimental.appDir &&
......@@ -787,6 +789,15 @@ export default class NextNodeServer extends BaseServer {
return require(join(this.distDir, 'server', FLIGHT_MANIFEST + '.json'))
}
protected getServerCSSManifest() {
if (!this.nextConfig.experimental.serverComponents) return undefined
return require(join(
this.distDir,
'server',
FLIGHT_SERVER_CSS_MANIFEST + '.json'
))
}
protected getCacheFilesystem(): CacheFs {
return {
readFile: (f) => fs.promises.readFile(f, 'utf8'),
......
......@@ -136,6 +136,18 @@ export function createFlushEffectStream(
})
}
export function renderToInitialStream({
ReactDOMServer,
element,
streamOptions,
}: {
ReactDOMServer: any
element: React.ReactElement
streamOptions?: any
}): Promise<ReactReadableStream> {
return ReactDOMServer.renderToReadableStream(element, streamOptions)
}
export function createHeadInjectionTransformStream(
inject: () => string
): TransformStream<Uint8Array, Uint8Array> {
......@@ -156,18 +168,6 @@ export function createHeadInjectionTransformStream(
})
}
export function renderToInitialStream({
ReactDOMServer,
element,
streamOptions,
}: {
ReactDOMServer: any
element: React.ReactElement
streamOptions?: any
}): Promise<ReactReadableStream> {
return ReactDOMServer.renderToReadableStream(element, streamOptions)
}
export async function continueFromInitialStream(
renderStream: ReactReadableStream,
{
......
......@@ -40,6 +40,7 @@ import {
UNSTABLE_REVALIDATE_RENAME_ERROR,
} from '../lib/constants'
import {
COMPILER_NAMES,
NEXT_BUILTIN_DOCUMENT,
SERVER_PROPS_ID,
STATIC_PROPS_ID,
......@@ -229,6 +230,7 @@ export type RenderOptsPartial = {
resolvedUrl?: string
resolvedAsPath?: string
serverComponentManifest?: any
serverCSSManifest?: any
distDir?: string
locale?: string
locales?: string[]
......@@ -1491,7 +1493,8 @@ export async function renderToHTML(
}
function errorToJSON(err: Error) {
let source: 'server' | 'edge-server' = 'server'
let source: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer =
'server'
if (process.env.NEXT_RUNTIME !== 'edge') {
source =
......@@ -1511,7 +1514,10 @@ function errorToJSON(err: Error) {
function serializeError(
dev: boolean | undefined,
err: Error
): Error & { statusCode?: number; source?: 'edge-server' | 'server' } {
): Error & {
statusCode?: number
source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer
} {
if (dev) {
return errorToJSON(err)
}
......
......@@ -127,6 +127,10 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
// @TODO: Need to return `extendRenderOpts.serverComponentManifest` here.
return undefined
}
protected getServerCSSManifest() {
// TODO-APP: Support web server.
return undefined
}
protected async renderHTML(
req: WebNextRequest,
_res: WebNextResponse,
......
......@@ -3,7 +3,10 @@ import {
decorateServerError,
getServerError,
} from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import { EDGE_UNSUPPORTED_NODE_APIS } from '../../../shared/lib/constants'
import {
COMPILER_NAMES,
EDGE_UNSUPPORTED_NODE_APIS,
} from '../../../shared/lib/constants'
import { EdgeRuntime } from 'next/dist/compiled/edge-runtime'
import { readFileSync, promises as fs } from 'fs'
import { validateURL } from '../utils'
......@@ -126,7 +129,7 @@ async function createModuleContext(options: ModuleContextOptions) {
new Error(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime`
),
'edge-server'
COMPILER_NAMES.edgeServer
)
warning.name = 'DynamicCodeEvaluationWarning'
Error.captureStackTrace(warning, __next_eval__)
......@@ -143,7 +146,7 @@ async function createModuleContext(options: ModuleContextOptions) {
const warning = getServerError(
new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'edge-server'
COMPILER_NAMES.edgeServer
)
warning.name = 'DynamicWasmCodeGenerationWarning'
Error.captureStackTrace(warning, __next_webassembly_compile__)
......@@ -170,7 +173,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation
const warning = getServerError(
new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'edge-server'
COMPILER_NAMES.edgeServer
)
warning.name = 'DynamicWasmCodeGenerationWarning'
Error.captureStackTrace(warning, __next_webassembly_instantiate__)
......@@ -334,7 +337,7 @@ function throwUnsupportedAPIError(name: string) {
const error =
new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
decorateServerError(error, 'edge-server')
decorateServerError(error, COMPILER_NAMES.edgeServer)
throw error
}
......@@ -342,7 +345,7 @@ function getDecorateUnhandledError(runtime: EdgeRuntime) {
const EdgeRuntimeError = runtime.evaluate(`Error`)
return (error: any) => {
if (error instanceof EdgeRuntimeError) {
decorateServerError(error, 'edge-server')
decorateServerError(error, COMPILER_NAMES.edgeServer)
}
}
}
......@@ -75,10 +75,12 @@ function withTaggedErrors(fn: RunnerFn): RunnerFn {
.then((result) => ({
...result,
waitUntil: result?.waitUntil?.catch((error) => {
// TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size.
throw getServerError(error, 'edge-server')
}),
}))
.catch((error) => {
// TODO: used COMPILER_NAMES.edgeServer instead
throw getServerError(error, 'edge-server')
})
}
......@@ -62,7 +62,6 @@ export const LayoutRouterContext = React.createContext<{
childNodes: CacheNode['parallelRoutes']
tree: FlightRouterState
url: string
stylesheets?: string[]
}>(null as any)
export const GlobalLayoutRouterContext = React.createContext<{
tree: FlightRouterState
......
type ValueOf<T> = Required<T>[keyof T]
export const COMPILER_NAMES = {
client: 'client',
server: 'server',
edgeServer: 'edge-server',
} as const
export type CompilerNameValues = ValueOf<typeof COMPILER_NAMES>
export const COMPILER_INDEXES: {
[compilerKey in CompilerNameValues]: number
} = {
[COMPILER_NAMES.client]: 0,
[COMPILER_NAMES.server]: 1,
[COMPILER_NAMES.edgeServer]: 2,
} as const
export const PHASE_EXPORT = 'phase-export'
export const PHASE_PRODUCTION_BUILD = 'phase-production-build'
export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
......@@ -40,6 +58,8 @@ export const NEXT_CLIENT_SSR_ENTRY_SUFFIX = '.__sc_client__'
// server/flight-manifest.js
export const FLIGHT_MANIFEST = 'flight-manifest'
// server/flight-server-css-manifest.json
export const FLIGHT_SERVER_CSS_MANIFEST = 'flight-server-css-manifest'
// server/middleware-build-manifest.js
export const MIDDLEWARE_BUILD_MANIFEST = 'middleware-build-manifest'
// server/middleware-react-loadable-manifest.js
......@@ -56,7 +76,10 @@ export const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp`
// static/runtime/webpack.js
export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`
// static/runtime/polyfills.js
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(`polyfills`)
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = 'polyfills'
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS
)
export const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack'
export const TEMPORARY_REDIRECT_STATUS = 307
export const PERMANENT_REDIRECT_STATUS = 308
......
......@@ -6,6 +6,7 @@ import type { IncomingMessage, ServerResponse } from 'http'
import type { NextRouter } from './router/router'
import type { ParsedUrlQuery } from 'querystring'
import type { PreviewData } from 'next/types'
import { COMPILER_NAMES } from './constants'
export type NextComponentType<
C extends BaseContext = NextPageContext,
......@@ -92,7 +93,10 @@ export type NEXT_DATA = {
autoExport?: boolean
isFallback?: boolean
dynamicIds?: (string | number)[]
err?: Error & { statusCode?: number; source?: 'server' | 'edge-server' }
err?: Error & {
statusCode?: number
source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer
}
gsp?: boolean
gssp?: boolean
customServer?: boolean
......
import './style2.css'
export default function ServerLayout({ children }) {
return <>{children}</>
}
import './style.css'
export default function Page() {
return <h1>Page</h1>
}
import './style.module.css'
import './style.css'
import './css-page/style.css'
import styles from './style.module.css'
export default function ServerLayout({ children }) {
......
import '../styles/global.css'
import './style.css'
export async function getServerSideProps() {
return {
......
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