Unverified Commit 1255e199 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Reorganize client references manifest (#46777)

* Rename client reference plugins from `Flight*` to `ClientReference*`
* Rename `serverComponentManifest` to `clientReferenceManifest`
* Group the key/value in client reference manifest
* Update turbopack crates
parent 53f29cd6
......@@ -22,8 +22,8 @@ declare global {
import type { Ipc } from "@vercel/turbopack-next/ipc/index";
import type { IncomingMessage, ServerResponse } from "node:http";
import type {
FlightCSSManifest,
FlightManifest,
ClientCSSReferenceManifest,
ClientReferenceManifest,
} from "next/dist/build/webpack/plugins/flight-manifest-plugin";
import type { RenderData } from "types/turbopack";
import type { RenderOpts } from "next/dist/server/app-render/types";
......@@ -107,13 +107,6 @@ type LoaderTree = [
components: ComponentsType
];
type ServerComponentsManifest = {
[id: string]: ServerComponentsManifestModule;
};
type ServerComponentsManifestModule = {
[exportName: string]: { id: string; chunks: string[]; name: string };
};
async function runOperation(renderData: RenderData) {
const layoutInfoChunks: Record<string, string[]> = {};
const pageItem = LAYOUT_INFO[LAYOUT_INFO.length - 1];
......@@ -140,74 +133,83 @@ async function runOperation(renderData: RenderData) {
const proxyMethodsForModule = (
id: string
): ProxyHandler<FlightManifest["__ssr_module_mapping__"][""]> => ({
get(_target, name) {
return {
id,
chunks: JSON.parse(id)[1],
name,
};
},
});
const proxyMethodsNested = (): ProxyHandler<
FlightManifest["__ssr_module_mapping__"]
): ProxyHandler<ClientReferenceManifest["ssrModuleMapping"]> => {
return {
get(_target, prop: string) {
return {
id,
chunks: JSON.parse(id)[1],
name: prop,
};
},
};
}
const proxyMethodsNested = (type: "ssrModuleMapping" | "clientModules"): ProxyHandler<
ClientReferenceManifest["ssrModuleMapping"] | ClientReferenceManifest["clientModules"]
> => {
return {
get(target, name, receiver) {
if (name === "__ssr_module_mapping__") {
return manifest;
get(_target, key: string) {
if (type === "ssrModuleMapping") {
return new Proxy({}, proxyMethodsForModule(key as string));
}
if (name === "__entry_css_files__") {
return __entry_css_files__;
if (type === "clientModules") {
// The key is a `${file}#${name}`, but `file` can contain `#` itself.
// There are 2 possibilities:
// "file#" => id = "file", name = ""
// "file#foo" => id = "file", name = "foo"
const pos = key.lastIndexOf("#");
let id = key;
let name = "";
if (pos !== -1) {
id = key.slice(0, pos);
name = key.slice(pos + 1);
} else {
throw new Error("key need to be in format of ${file}#${name}");
}
return {
id,
name,
chunks: JSON.parse(id)[1],
};
}
return new Proxy({}, proxyMethodsForModule(name as string));
},
};
};
const proxyMethods = (): ProxyHandler<FlightManifest> => {
const proxyMethods = (): ProxyHandler<ClientReferenceManifest> => {
const clientModulesProxy = new Proxy({}, proxyMethodsNested("clientModules"));
const ssrModuleMappingProxy = new Proxy({}, proxyMethodsNested("ssrModuleMapping"));
return {
get(_target, key: string) {
if (key === "__ssr_module_mapping__") {
return new Proxy({} as any, proxyMethodsNested());
get(_target: any, prop: string) {
if (prop === "ssrModuleMapping") {
return ssrModuleMappingProxy;
}
if (key === "__entry_css_files__") {
return __entry_css_files__;
if (prop === "clientModules") {
return clientModulesProxy;
}
// The key is a `${file}#${name}`, but `file` can contain `#` itself.
// There are 2 possibilities:
// "file#" => id = "file", name = ""
// "file#foo" => id = "file", name = "foo"
const pos = key.lastIndexOf("#");
let id = key;
let name = "";
if (pos === -1) {
throw new Error("key need to be in format of ${file}#${name}");
} else {
id = key.slice(0, pos);
name = key.slice(pos + 1);
if (prop === "cssFiles") {
return cssFiles;
}
return {
id,
name,
chunks: JSON.parse(id)[1],
};
},
};
};
const manifest: FlightManifest = new Proxy({} as any, proxyMethods());
const serverCSSManifest: FlightCSSManifest = {};
const __entry_css_files__: FlightManifest["__entry_css_files__"] = {};
const manifest: ClientReferenceManifest = new Proxy({} as any, proxyMethods());
const serverCSSManifest: ClientCSSReferenceManifest = {
cssImports: {},
cssModules: {},
};
const cssFiles: ClientReferenceManifest["cssFiles"] = {};
for (const [key, chunks] of Object.entries(layoutInfoChunks)) {
const cssChunks = chunks.filter((path) => path.endsWith(".css"));
serverCSSManifest[`${key}.js`] = cssChunks.map((chunk) =>
serverCSSManifest.cssImports[`${key}.js`] = cssChunks.map((chunk) =>
JSON.stringify([chunk, [chunk]])
);
__entry_css_files__[key] = cssChunks;
cssFiles[key] = cssChunks;
}
serverCSSManifest.__entry_css_mods__ = {
page: serverCSSManifest["page.js"],
serverCSSManifest.cssModules = {
page: serverCSSManifest.cssImports["page.js"],
};
const req: IncomingMessage = {
url: renderData.url,
......@@ -244,7 +246,7 @@ async function runOperation(renderData: RenderData) {
tree,
pages: ["page.js"],
},
serverComponentManifest: manifest,
clientReferenceManifest: manifest,
serverCSSManifest,
runtime: "nodejs",
serverComponents: true,
......
export function isClientReference(reference: any): boolean {
return reference?.$$typeof === Symbol.for('react.client.reference')
}
......@@ -54,7 +54,7 @@ import {
loadRequireHook,
overrideBuiltInReactPackages,
} from './webpack/require-hook'
import { isClientReference } from './is-client-reference'
import { isClientReference } from '../lib/client-reference'
import { StaticGenerationAsyncStorageWrapper } from '../server/async-storage/static-generation-async-storage-wrapper'
import { IncrementalCache } from '../server/lib/incremental-cache'
import { patchFetch } from '../server/lib/patch-fetch'
......
......@@ -46,8 +46,8 @@ import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'
import { regexLikeCss } from './webpack/config/blocks/css'
import { CopyFilePlugin } from './webpack/plugins/copy-file-plugin'
import { FlightManifestPlugin } from './webpack/plugins/flight-manifest-plugin'
import { FlightClientEntryPlugin } from './webpack/plugins/flight-client-entry-plugin'
import { ClientReferenceManifestPlugin } from './webpack/plugins/flight-manifest-plugin'
import { ClientReferenceEntryPlugin } from './webpack/plugins/flight-client-entry-plugin'
import { NextTypesPlugin } from './webpack/plugins/next-types-plugin'
import type {
Feature,
......@@ -2224,11 +2224,11 @@ export default async function getBaseWebpackConfig(
hasAppDir && isClient && new AppBuildManifestPlugin({ dev }),
hasServerComponents &&
(isClient
? new FlightManifestPlugin({
? new ClientReferenceManifestPlugin({
dev,
appDir,
})
: new FlightClientEntryPlugin({
: new ClientReferenceEntryPlugin({
appDir,
dev,
isEdgeServer,
......
......@@ -149,7 +149,7 @@ export default async function edgeSSRLoader(this: any) {
appRenderToHTML,
pagesRenderToHTML,
reactLoadableManifest,
serverComponentManifest: ${isServerComponent} ? rscManifest : null,
clientReferenceManifest: ${isServerComponent} ? rscManifest : null,
serverCSSManifest: ${isServerComponent} ? rscCssManifest : null,
serverActionsManifest: ${isServerComponent} ? rscServerManifest : null,
subresourceIntegrityManifest,
......
......@@ -3,6 +3,7 @@ import type { NextConfigComplete } from '../../../../server/config-shared'
import type { DocumentType, AppType } from '../../../../shared/lib/utils'
import type { BuildManifest } from '../../../../server/get-page-files'
import type { ReactLoadableManifest } from '../../../../server/load-components'
import type { ClientReferenceManifest } from '../../plugins/flight-manifest-plugin'
import type { NextFontManifestPlugin } from '../../plugins/next-font-manifest-plugin'
import WebServer from '../../../../server/web-server'
......@@ -25,7 +26,7 @@ export function getRender({
reactLoadableManifest,
appRenderToHTML,
pagesRenderToHTML,
serverComponentManifest,
clientReferenceManifest,
subresourceIntegrityManifest,
serverCSSManifest,
serverActionsManifest,
......@@ -47,7 +48,7 @@ export function getRender({
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
subresourceIntegrityManifest?: Record<string, string>
serverComponentManifest: any
clientReferenceManifest?: ClientReferenceManifest
serverCSSManifest: any
serverActionsManifest: any
appServerMod: any
......@@ -79,7 +80,7 @@ export function getRender({
runtime: SERVER_RUNTIME.experimentalEdge,
supportsDynamicHTML: true,
disableOptimizedLoading: true,
serverComponentManifest,
clientReferenceManifest,
serverCSSManifest,
serverActionsManifest,
},
......
......@@ -3,7 +3,7 @@ import type {
ClientComponentImports,
NextFlightClientEntryLoaderOptions,
} from '../loaders/next-flight-client-entry-loader'
import type { FlightCSSManifest } from './flight-manifest-plugin'
import type { ClientCSSReferenceManifest } from './flight-manifest-plugin'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { stringify } from 'querystring'
......@@ -56,8 +56,8 @@ const pluginState = getProxiedPluginState({
actionModId: {} as Record<string, string | number>,
// Manifest of CSS entry files for server/edge server.
serverCSSManifest: {} as FlightCSSManifest,
edgeServerCSSManifest: {} as FlightCSSManifest,
serverCSSManifest: {} as ClientCSSReferenceManifest,
edgeServerCSSManifest: {} as ClientCSSReferenceManifest,
// Mapping of resource path to module id for server/edge server.
serverModuleIds: {} as Record<string, string | number>,
......@@ -71,7 +71,7 @@ const pluginState = getProxiedPluginState({
injectedClientEntries: {} as Record<string, string>,
})
export class FlightClientEntryPlugin {
export class ClientReferenceEntryPlugin {
dev: boolean
appDir: string
isEdgeServer: boolean
......@@ -378,12 +378,10 @@ export class FlightClientEntryPlugin {
}
const entryCSSInfo: Record<string, string[]> =
cssManifest.__entry_css_mods__ || {}
cssManifest.cssModules || {}
entryCSSInfo[entryName] = [...cssImportsForChunk[entryName]]
Object.assign(cssManifest, {
__entry_css_mods__: entryCSSInfo,
})
cssManifest.cssModules = entryCSSInfo
})
})
......@@ -408,7 +406,8 @@ export class FlightClientEntryPlugin {
clientEntryDependencyMap,
})
Object.assign(cssManifest, cssImports)
if (!cssManifest.cssImports) cssManifest.cssImports = {}
Object.assign(cssManifest.cssImports, cssImports)
}
})
})
......@@ -421,18 +420,17 @@ export class FlightClientEntryPlugin {
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
},
(assets: webpack.Compilation['assets']) => {
const manifest = JSON.stringify(
{
...pluginState.serverCSSManifest,
...pluginState.edgeServerCSSManifest,
__entry_css_mods__: {
...pluginState.serverCSSManifest.__entry_css_mods__,
...pluginState.edgeServerCSSManifest.__entry_css_mods__,
},
const data: ClientCSSReferenceManifest = {
cssImports: {
...pluginState.serverCSSManifest.cssImports,
...pluginState.edgeServerCSSManifest.cssImports,
},
null,
this.dev ? 2 : undefined
)
cssModules: {
...pluginState.serverCSSManifest.cssModules,
...pluginState.edgeServerCSSManifest.cssModules,
},
}
const manifest = JSON.stringify(data, null, this.dev ? 2 : undefined)
assets[FLIGHT_SERVER_CSS_MANIFEST + '.json'] = new sources.RawSource(
manifest
) as unknown as webpack.sources.RawSource
......
......@@ -18,6 +18,7 @@ import { getProxiedPluginState } from '../../build-context'
import { traverseModules } from '../utils'
import { nonNullable } from '../../../lib/non-nullable'
import { WEBPACK_LAYERS } from '../../../lib/constants'
import { getClientReferenceModuleKey } from '../../../lib/client-reference'
interface Options {
dev: boolean
......@@ -38,7 +39,7 @@ const pluginState = getProxiedPluginState({
ASYNC_CLIENT_MODULES: [] as string[],
})
interface ManifestNode {
export interface ManifestNode {
[moduleExport: string]: {
/**
* Webpack module id
......@@ -60,29 +61,31 @@ interface ManifestNode {
}
}
export type FlightManifest = {
__ssr_module_mapping__: {
[modulePath: string]: ManifestNode
export type ClientReferenceManifest = {
clientModules: ManifestNode
ssrModuleMapping: {
[moduleId: string]: ManifestNode
}
__edge_ssr_module_mapping__: {
[modulePath: string]: ManifestNode
edgeSSRModuleMapping: {
[moduleId: string]: ManifestNode
}
__entry_css_files__: {
cssFiles: {
[entryPathWithoutExtension: string]: string[]
}
} & ManifestNode
}
export type FlightCSSManifest = {
[modulePath: string]: string[]
} & {
__entry_css_mods__?: {
export type ClientCSSReferenceManifest = {
cssImports: {
[modulePath: string]: string[]
}
cssModules?: {
[entry: string]: string[]
}
}
const PLUGIN_NAME = 'FlightManifestPlugin'
const PLUGIN_NAME = 'ClientReferenceManifestPlugin'
export class FlightManifestPlugin {
export class ClientReferenceManifestPlugin {
dev: Options['dev'] = false
appDir: Options['appDir']
ASYNC_CLIENT_MODULES: Set<string>
......@@ -126,11 +129,11 @@ export class FlightManifestPlugin {
compilation: webpack.Compilation,
context: string
) {
// @ts-ignore
const manifest: FlightManifest = {
__ssr_module_mapping__: {},
__edge_ssr_module_mapping__: {},
__entry_css_files__: {},
const manifest: ClientReferenceManifest = {
ssrModuleMapping: {},
edgeSSRModuleMapping: {},
cssFiles: {},
clientModules: {},
}
const dev = this.dev
......@@ -183,8 +186,9 @@ export class FlightManifestPlugin {
return
}
const moduleIdMapping = manifest.__ssr_module_mapping__
const edgeModuleIdMapping = manifest.__edge_ssr_module_mapping__
const moduleReferences = manifest.clientModules
const moduleIdMapping = manifest.ssrModuleMapping
const edgeModuleIdMapping = manifest.edgeSSRModuleMapping
// 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`
......@@ -198,18 +202,19 @@ export class FlightManifestPlugin {
ssrNamedModuleId = `./${ssrNamedModuleId.replace(/\\/g, '/')}`
if (isCSSModule) {
if (!manifest[resource + '#']) {
manifest[resource + '#'] = {
const exportName = getClientReferenceModuleKey(resource, '')
if (!moduleReferences[exportName]) {
moduleReferences[exportName] = {
id: id || '',
name: '',
name: 'default',
chunks: chunkCSS,
}
} else {
// It is possible that there are multiple modules with the same resource,
// e.g. extracted by mini-css-extract-plugin. In that case we need to
// merge the chunks.
manifest[resource + '#'].chunks = [
...new Set([...manifest[resource + '#'].chunks, ...chunkCSS]),
moduleReferences[exportName].chunks = [
...new Set([...moduleReferences[exportName].chunks, ...chunkCSS]),
]
}
......@@ -279,48 +284,31 @@ export class FlightManifestPlugin {
: null
function addClientReference(name: string) {
if (name === '*') {
manifest[resource] = {
id,
chunks: requiredChunks,
name: '*',
async: isAsyncModule,
}
if (esmResource) {
manifest[esmResource] = manifest[resource]
}
} else if (name === '') {
manifest[resource + '#'] = {
id,
chunks: requiredChunks,
name: '',
async: isAsyncModule,
}
if (esmResource) {
manifest[esmResource + '#'] = manifest[resource + '#']
}
} else {
manifest[resource + '#' + name] = {
id,
chunks: requiredChunks,
name,
async: isAsyncModule,
}
if (esmResource) {
manifest[esmResource + '#' + name] =
manifest[resource + '#' + name]
}
const exportName = getClientReferenceModuleKey(resource, name)
manifest.clientModules[exportName] = {
id,
name,
chunks: requiredChunks,
async: isAsyncModule,
}
if (esmResource) {
const edgeExportName = getClientReferenceModuleKey(
esmResource,
name
)
manifest.clientModules[edgeExportName] =
manifest.clientModules[exportName]
}
}
function addSSRIdMapping(name: string) {
const key = resource + (name === '*' ? '' : '#' + name)
const exportName = getClientReferenceModuleKey(resource, name)
if (
typeof pluginState.serverModuleIds[ssrNamedModuleId] !== 'undefined'
) {
moduleIdMapping[id] = moduleIdMapping[id] || {}
moduleIdMapping[id][name] = {
...manifest[key],
...manifest.clientModules[exportName],
id: pluginState.serverModuleIds[ssrNamedModuleId],
}
}
......@@ -331,7 +319,7 @@ export class FlightManifestPlugin {
) {
edgeModuleIdMapping[id] = edgeModuleIdMapping[id] || {}
edgeModuleIdMapping[id][name] = {
...manifest[key],
...manifest.clientModules[exportName],
id: pluginState.edgeServerModuleIds[ssrNamedModuleId],
}
}
......@@ -355,7 +343,7 @@ export class FlightManifestPlugin {
// If the chunk is from `app/` chunkGroup, use it first.
// This make sure not to load the overlapped chunk from `pages/` chunkGroup
if (
!manifest[key] ||
!manifest.clientModules[key] ||
(chunkGroup.name && /^app[\\/]/.test(chunkGroup.name))
) {
addClientReference(name)
......@@ -364,8 +352,9 @@ export class FlightManifestPlugin {
addSSRIdMapping(name)
})
manifest.__ssr_module_mapping__ = moduleIdMapping
manifest.__edge_ssr_module_mapping__ = edgeModuleIdMapping
manifest.clientModules = moduleReferences
manifest.ssrModuleMapping = moduleIdMapping
manifest.edgeSSRModuleMapping = edgeModuleIdMapping
}
chunkGroup.chunks.forEach((chunk: webpack.Chunk) => {
......@@ -394,7 +383,7 @@ export class FlightManifestPlugin {
}
})
const entryCSSFiles: any = manifest.__entry_css_files__ || {}
const entryCSSFiles: { [key: string]: string[] } = manifest.cssFiles || {}
const addCSSFilesToEntry = (
files: string[],
......@@ -423,7 +412,7 @@ export class FlightManifestPlugin {
})
}
manifest.__entry_css_files__ = entryCSSFiles
manifest.cssFiles = entryCSSFiles
})
const file = 'server/' + CLIENT_REFERENCE_MANIFEST
......
......@@ -482,7 +482,7 @@ export default async function exportApp(
if (options.buildExport && hasAppDir) {
// @ts-expect-error untyped
renderOpts.serverComponentManifest = require(join(
renderOpts.clientReferenceManifest = require(join(
distDir,
SERVER_DIRECTORY,
CLIENT_REFERENCE_MANIFEST + '.json'
......
/**
* filepath export module key
* "file" '*' "file"
* "file" '' "file#"
* "file" '<named>' "file#<named>"
*
* @param filepath file path to the module
* @param exports '' | '*' | '<named>'
*/
export function getClientReferenceModuleKey(
filepath: string,
exportName: string
): string {
return exportName === '*' ? filepath : filepath + '#' + exportName
}
export function isClientReference(reference: any): boolean {
return reference?.$$typeof === Symbol.for('react.client.reference')
}
......@@ -8,7 +8,7 @@ import { createDefaultMetadata } from './default-metadata'
import { resolveOpenGraph, resolveTwitter } from './resolvers/resolve-opengraph'
import { resolveTitle } from './resolvers/resolve-title'
import { resolveAsArrayOrUndefined } from './generate/utils'
import { isClientReference } from '../../build/is-client-reference'
import { isClientReference } from '../client-reference'
import {
getLayoutOrPageModule,
LoaderTree,
......
import type { IncomingMessage, ServerResponse } from 'http'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import type {
FlightCSSManifest,
FlightManifest,
import {
ClientCSSReferenceManifest,
ClientReferenceManifest,
} from '../../build/webpack/plugins/flight-manifest-plugin'
import type {
ChildProp,
......@@ -58,7 +58,10 @@ import { MetadataTree } from '../../lib/metadata/metadata'
import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper'
import { StaticGenerationAsyncStorageWrapper } from '../async-storage/static-generation-async-storage-wrapper'
import { collectMetadata } from '../../lib/metadata/resolve-metadata'
import { isClientReference } from '../../build/is-client-reference'
import {
getClientReferenceModuleKey,
isClientReference,
} from '../../lib/client-reference'
import { getLayoutOrPageModule, LoaderTree } from '../lib/app-dir-module'
import { warnOnce } from '../../shared/lib/utils/warn-once'
import { isNotFoundError } from '../../client/components/not-found'
......@@ -217,7 +220,7 @@ interface FlightResponseRef {
function useFlightResponse(
writable: WritableStream<Uint8Array>,
req: ReadableStream<Uint8Array>,
serverComponentManifest: any,
clientReferenceManifest: ClientReferenceManifest,
rscChunks: Uint8Array[],
flightResponseRef: FlightResponseRef,
nonce?: string
......@@ -232,8 +235,8 @@ function useFlightResponse(
const [renderStream, forwardStream] = readableStreamTee(req)
const res = createFromReadableStream(renderStream, {
moduleMap: isEdgeRuntime
? serverComponentManifest.__edge_ssr_module_mapping__
: serverComponentManifest.__ssr_module_mapping__,
? clientReferenceManifest.edgeSSRModuleMapping
: clientReferenceManifest.ssrModuleMapping,
})
flightResponseRef.current = res
......@@ -293,12 +296,12 @@ function createServerComponentRenderer<Props>(
},
{
transformStream,
serverComponentManifest,
clientReferenceManifest,
serverContexts,
rscChunks,
}: {
transformStream: TransformStream<Uint8Array, Uint8Array>
serverComponentManifest: NonNullable<RenderOpts['serverComponentManifest']>
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
serverContexts: Array<
[ServerContextName: string, JSONValue: Object | number | string]
>
......@@ -322,7 +325,7 @@ function createServerComponentRenderer<Props>(
if (!RSCStream) {
RSCStream = ComponentMod.renderToReadableStream(
<ComponentToRender {...(props as any)} />,
serverComponentManifest,
clientReferenceManifest.clientModules,
{
context: serverContexts,
onError: serverComponentsErrorHandler,
......@@ -340,7 +343,7 @@ function createServerComponentRenderer<Props>(
const response = useFlightResponse(
writable,
reqStream,
serverComponentManifest,
clientReferenceManifest,
rscChunks,
flightResponseRef,
nonce
......@@ -402,18 +405,18 @@ function getSegmentParam(segment: string): {
* Get inline <link> tags based on server CSS manifest. Only used when rendering to HTML.
*/
function getCssInlinedLinkTags(
serverComponentManifest: FlightManifest,
serverCSSManifest: FlightCSSManifest,
clientReferenceManifest: ClientReferenceManifest,
serverCSSManifest: ClientCSSReferenceManifest,
filePath: string,
serverCSSForEntries: string[],
injectedCSS: Set<string>,
collectNewCSSImports?: boolean
): string[] {
const layoutOrPageCssModules = serverCSSManifest[filePath]
const layoutOrPageCssModules = serverCSSManifest.cssImports[filePath]
const filePathWithoutExt = filePath.replace(/\.[^.]+$/, '')
const cssFilesForEntry = new Set(
serverComponentManifest.__entry_css_files__?.[filePathWithoutExt] || []
clientReferenceManifest.cssFiles?.[filePathWithoutExt] || []
)
if (!layoutOrPageCssModules || !cssFilesForEntry.size) {
......@@ -431,7 +434,10 @@ function getCssInlinedLinkTags(
// If the CSS is already injected by a parent layer, we don't need
// to inject it again.
if (!injectedCSS.has(mod)) {
const modData = serverComponentManifest[mod + '#']
const modData =
clientReferenceManifest.clientModules[
getClientReferenceModuleKey(mod, '')
]
if (modData) {
for (const chunk of modData.chunks) {
// If the current entry in the final tree-shaked bundle has that CSS
......@@ -454,17 +460,17 @@ function getCssInlinedLinkTags(
}
function getServerCSSForEntries(
serverCSSManifest: FlightCSSManifest,
serverCSSManifest: ClientCSSReferenceManifest,
entries: string[]
) {
const css = []
for (const entry of entries) {
const entryName = entry.replace(/\.[^.]+$/, '')
if (
serverCSSManifest.__entry_css_mods__ &&
serverCSSManifest.__entry_css_mods__[entryName]
serverCSSManifest.cssModules &&
serverCSSManifest.cssModules[entryName]
) {
css.push(...serverCSSManifest.__entry_css_mods__[entryName])
css.push(...serverCSSManifest.cssModules[entryName])
}
}
return css
......@@ -474,7 +480,7 @@ function getServerCSSForEntries(
* Get inline <link rel="preload" as="font"> tags based on server CSS manifest and next/font manifest. Only used when rendering to HTML.
*/
function getPreloadedFontFilesInlineLinkTags(
serverCSSManifest: FlightCSSManifest,
serverCSSManifest: ClientCSSReferenceManifest,
nextFontManifest: NextFontManifest | undefined,
serverCSSForEntries: string[],
filePath: string | undefined,
......@@ -483,7 +489,7 @@ function getPreloadedFontFilesInlineLinkTags(
if (!nextFontManifest || !filePath) {
return null
}
const layoutOrPageCss = serverCSSManifest[filePath]
const layoutOrPageCss = serverCSSManifest.cssImports[filePath]
if (!layoutOrPageCss) {
return null
......@@ -631,15 +637,16 @@ export async function renderToHTMLOrFlight(
const {
buildManifest,
subresourceIntegrityManifest,
serverComponentManifest,
serverActionsManifest,
serverCSSManifest = {},
ComponentMod,
dev,
nextFontManifest,
supportsDynamicHTML,
} = renderOpts
const clientReferenceManifest = renderOpts.clientReferenceManifest!
const serverCSSManifest = renderOpts.serverCSSManifest!
const capturedErrors: Error[] = []
const allCapturedErrors: Error[] = []
const isNextExport = !!renderOpts.nextExport
......@@ -918,8 +925,8 @@ export async function renderToHTMLOrFlight(
injectedCSS: Set<string>
}): Promise<any> => {
const cssHrefs = getCssInlinedLinkTags(
serverComponentManifest,
serverCSSManifest,
clientReferenceManifest,
serverCSSManifest!,
filePath,
serverCSSForEntries,
injectedCSS
......@@ -983,7 +990,7 @@ export async function renderToHTMLOrFlight(
const injectedCSSWithCurrentLayout = new Set(injectedCSS)
const stylesheets: string[] = layoutOrPagePath
? getCssInlinedLinkTags(
serverComponentManifest,
clientReferenceManifest,
serverCSSManifest!,
layoutOrPagePath,
serverCSSForEntries,
......@@ -1461,7 +1468,7 @@ export async function renderToHTMLOrFlight(
)
if (layoutPath) {
getCssInlinedLinkTags(
serverComponentManifest,
clientReferenceManifest,
serverCSSManifest!,
layoutPath,
serverCSSForEntries,
......@@ -1544,7 +1551,7 @@ export async function renderToHTMLOrFlight(
// which contains the subset React.
const readable = ComponentMod.renderToReadableStream(
flightData,
serverComponentManifest,
clientReferenceManifest.clientModules,
{
context: serverContexts,
onError: flightDataRendererErrorHandler,
......@@ -1585,7 +1592,7 @@ export async function renderToHTMLOrFlight(
const serverComponentsRenderOpts = {
transformStream: serverComponentsInlinedTransformStream,
serverComponentManifest,
clientReferenceManifest,
serverContexts,
rscChunks: [],
}
......
import type { LoadComponentsReturnType } from '../load-components'
import type { ServerRuntime } from '../../../types'
import type {
FlightCSSManifest,
FlightManifest,
ClientCSSReferenceManifest,
ClientReferenceManifest,
} from '../../build/webpack/plugins/flight-manifest-plugin'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
......@@ -114,8 +114,8 @@ export type ChildProp = {
export type RenderOptsPartial = {
err?: Error | null
dev?: boolean
serverComponentManifest?: FlightManifest
serverCSSManifest?: FlightCSSManifest
clientReferenceManifest?: ClientReferenceManifest
serverCSSManifest?: ClientCSSReferenceManifest
supportsDynamicHTML: boolean
runtime?: ServerRuntime
serverComponents?: boolean
......
......@@ -28,6 +28,7 @@ import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plug
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type { PayloadOptions } from './send-payload'
import type { PrerenderManifest } from '../build'
import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import { format as formatUrl, parse as parseUrl } from 'url'
......@@ -227,7 +228,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
crossOrigin?: string
supportsDynamicHTML?: boolean
isBot?: boolean
serverComponentManifest?: any
clientReferenceManifest?: ClientReferenceManifest
serverCSSManifest?: any
serverActionsManifest?: any
nextFontManifest?: NextFontManifest
......@@ -241,7 +242,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected router: Router
protected appPathRoutes?: Record<string, string[]>
protected customRoutes: CustomRoutes
protected serverComponentManifest?: any
protected clientReferenceManifest?: ClientReferenceManifest
protected serverCSSManifest?: any
protected nextFontManifest?: NextFontManifest
public readonly hostname?: string
......@@ -386,7 +387,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
this.hasAppDir =
!!this.nextConfig.experimental.appDir && this.getHasAppDir(dev)
const serverComponents = this.hasAppDir
this.serverComponentManifest = serverComponents
this.clientReferenceManifest = serverComponents
? this.getServerComponentManifest()
: undefined
this.serverCSSManifest = serverComponents
......@@ -1250,7 +1251,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later
const isFlightRequest = Boolean(
this.serverComponentManifest && req.headers[RSC.toLowerCase()]
this.clientReferenceManifest && req.headers[RSC.toLowerCase()]
)
// For pages we need to ensure the correct Vary header is set too, to avoid
......
......@@ -1661,7 +1661,7 @@ export default class DevServer extends Server {
// When the new page is compiled, we need to reload the server component
// manifest.
if (!!this.appDir) {
this.serverComponentManifest = super.getServerComponentManifest()
this.clientReferenceManifest = super.getServerComponentManifest()
this.serverCSSManifest = super.getServerCSSManifest()
}
this.nextFontManifest = super.getNextFontManifest()
......
......@@ -3,6 +3,7 @@ import type {
DocumentType,
NextComponentType,
} from '../shared/lib/utils'
import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'
import type {
PageConfig,
GetStaticPaths,
......@@ -35,7 +36,7 @@ export type LoadComponentsReturnType = {
buildManifest: BuildManifest
subresourceIntegrityManifest?: Record<string, string>
reactLoadableManifest: ReactLoadableManifest
serverComponentManifest?: any
clientReferenceManifest?: ClientReferenceManifest
serverActionsManifest?: any
Document: DocumentType
App: AppType
......@@ -104,16 +105,16 @@ async function loadComponentsImpl({
const [
buildManifest,
reactLoadableManifest,
serverComponentManifest,
clientReferenceManifest,
serverActionsManifest,
] = await Promise.all([
loadManifest<BuildManifest>(join(distDir, BUILD_MANIFEST)),
loadManifest<ReactLoadableManifest>(join(distDir, REACT_LOADABLE_MANIFEST)),
hasServerComponents
? loadManifest(
? loadManifest<ClientReferenceManifest>(
join(distDir, 'server', CLIENT_REFERENCE_MANIFEST + '.json')
)
: null,
: undefined,
hasServerComponents
? loadManifest(
join(distDir, 'server', SERVER_REFERENCE_MANIFEST + '.json')
......@@ -138,7 +139,7 @@ async function loadComponentsImpl({
getServerSideProps,
getStaticProps,
getStaticPaths,
serverComponentManifest,
clientReferenceManifest,
serverActionsManifest,
isAppPath,
pathname,
......
......@@ -852,9 +852,9 @@ export default class NextNodeServer extends BaseServer {
renderOpts: RenderOpts
): Promise<RenderResult> {
// Due to the way we pass data by mutating `renderOpts`, we can't extend the
// object here but only updating its `serverComponentManifest` field.
// object here but only updating its `clientReferenceManifest` field.
// https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952
renderOpts.serverComponentManifest = this.serverComponentManifest
renderOpts.clientReferenceManifest = this.clientReferenceManifest
renderOpts.serverCSSManifest = this.serverCSSManifest
renderOpts.nextFontManifest = this.nextFontManifest
......
......@@ -26,6 +26,7 @@ import type {
} from 'next/types'
import type { UnwrapPromise } from '../lib/coalesced-function'
import type { ReactReadableStream } from './node-web-streams-helper'
import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import React from 'react'
......@@ -246,7 +247,7 @@ export type RenderOptsPartial = {
devOnlyCacheBusterQueryString?: string
resolvedUrl?: string
resolvedAsPath?: string
serverComponentManifest?: any
clientReferenceManifest?: ClientReferenceManifest
serverCSSManifest?: any
nextFontManifest?: NextFontManifest
distDir?: string
......
......@@ -170,7 +170,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
}
protected getServerComponentManifest() {
return this.serverOptions.webServerConfig.extendRenderOpts
.serverComponentManifest
.clientReferenceManifest
}
protected getServerCSSManifest() {
return this.serverOptions.webServerConfig.extendRenderOpts.serverCSSManifest
......
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