Unverified Commit de6a1e3d authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Rename FontLoaderManifest to NextFontManifest and add better comments (#46922)

Rename FontLoaderManifest to NextFontManifest to make it more obvious
that it has to do with `next/font`.

There's a change to how the plugin determines if a module is generated
by `next/font`. Instead of looking at the target CSS file
https://github.com/vercel/next.js/blob/v13.2.4-canary.6/packages/next/src/build/webpack/plugins/font-loader-manifest-plugin.ts#L37-L49.
It simply looks if the module has `next-font-loader` in its loaders:
https://github.com/vercel/next.js/compare/canary...hanneslund:next.js:next-font-build-cleanup?expand=1#diff-34d7972c68687e875c868847f782f369c3af162a9af10949f3577660775afcb2R65-R74

Also more comments added to the manifest plugin and the `next/font`
postcss plugin.

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent bae5d6fc
......@@ -63,7 +63,7 @@ import {
APP_BUILD_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
RSC_MODULE_TYPES,
FONT_LOADER_MANIFEST,
NEXT_FONT_MANIFEST,
SUBRESOURCE_INTEGRITY_MANIFEST,
MIDDLEWARE_BUILD_MANIFEST,
MIDDLEWARE_REACT_LOADABLE_MANIFEST,
......@@ -992,8 +992,8 @@ export default async function build(
: null,
BUILD_ID_FILE,
appDir ? path.join(SERVER_DIRECTORY, APP_PATHS_MANIFEST) : null,
path.join(SERVER_DIRECTORY, FONT_LOADER_MANIFEST + '.js'),
path.join(SERVER_DIRECTORY, FONT_LOADER_MANIFEST + '.json'),
path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.js'),
path.join(SERVER_DIRECTORY, NEXT_FONT_MANIFEST + '.json'),
...(hasInstrumentationHook
? [
path.join(
......
......@@ -59,7 +59,7 @@ import loadJsConfig from './load-jsconfig'
import { loadBindings } from './swc'
import { AppBuildManifestPlugin } from './webpack/plugins/app-build-manifest-plugin'
import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin'
import { FontLoaderManifestPlugin } from './webpack/plugins/font-loader-manifest-plugin'
import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin'
import { getSupportedBrowsers } from './utils'
import { METADATA_IMAGE_RESOURCE_QUERY } from './webpack/loaders/metadata/discover'
......@@ -2210,7 +2210,7 @@ export default async function getBaseWebpackConfig(
!!config.experimental.sri?.algorithm &&
new SubresourceIntegrityPlugin(config.experimental.sri.algorithm),
isClient &&
new FontLoaderManifestPlugin({
new NextFontManifestPlugin({
appDirEnabled: !!config.experimental.appDir,
}),
!dev &&
......
......@@ -134,7 +134,7 @@ export default async function edgeSSRLoader(this: any) {
const subresourceIntegrityManifest = ${
sriEnabled ? 'self.__SUBRESOURCE_INTEGRITY_MANIFEST' : 'undefined'
}
const fontLoaderManifest = self.__FONT_LOADER_MANIFEST
const nextFontManifest = self.__NEXT_FONT_MANIFEST
const render = getRender({
pageType,
......@@ -155,7 +155,7 @@ export default async function edgeSSRLoader(this: any) {
subresourceIntegrityManifest,
config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)},
fontLoaderManifest,
nextFontManifest,
incrementalCacheHandler,
})
......
......@@ -3,7 +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 { FontLoaderManifest } from '../../plugins/font-loader-manifest-plugin'
import type { NextFontManifestPlugin } from '../../plugins/next-font-manifest-plugin'
import WebServer from '../../../../server/web-server'
import {
......@@ -31,7 +31,7 @@ export function getRender({
serverActionsManifest,
config,
buildId,
fontLoaderManifest,
nextFontManifest,
incrementalCacheHandler,
}: {
pagesType: 'app' | 'pages' | 'root'
......@@ -53,7 +53,7 @@ export function getRender({
appServerMod: any
config: NextConfigComplete
buildId: string
fontLoaderManifest: FontLoaderManifest
nextFontManifest: NextFontManifestPlugin
incrementalCacheHandler?: any
}) {
const isAppPath = pagesType === 'app'
......@@ -62,7 +62,7 @@ export function getRender({
buildManifest,
reactLoadableManifest,
subresourceIntegrityManifest,
fontLoaderManifest,
nextFontManifest,
Document,
App: appMod?.default as AppType,
}
......
......@@ -13,7 +13,16 @@ export default async function nextFontLoader(this: any) {
return fontLoaderSpan.traceAsyncFn(async () => {
const callback = this.async()
// next-swc next_font_loaders turns each font loader call into JSON
/**
* The next-swc plugin next_font_loaders turns font function calls into CSS imports.
* At the end of the import, it adds the call arguments and some additional data as a resourceQuery.
* e.g:
* const inter = Inter({ subset: ['latin'] })
* ->
* import inter from 'next/font/google/target.css?{"import":"Inter","subsets":["latin"]}'
*
* Here we parse the resourceQuery to get the font function name, call arguments, and the path to the file that called the font function.
*/
const {
path: relativeFilePathFromRoot,
import: functionName,
......@@ -60,6 +69,16 @@ export default async function nextFontLoader(this: any) {
})
)
/**
* Emit font files to .next/static/media as [hash].[ext].
*
* If the font should be preloaded, add .p to the filename: [hash].p.[ext]
* NextFontManifestPlugin adds these files to the next/font manifest.
*
* If the font is using a size-adjust fallback font, add -s to the filename: [hash]-s.[ext]
* NextFontManifestPlugin uses this to see if fallback fonts are being used.
* This is used to collect stats on fallback fonts usage by the Google Aurora team.
*/
const emitFontFile = (
content: Buffer,
ext: string,
......@@ -69,20 +88,23 @@ export default async function nextFontLoader(this: any) {
const opts = { context: this.rootContext, content }
const interpolatedName = loaderUtils.interpolateName(
this,
// Font files ending with .p.(woff|woff2|eot|ttf|otf) are preloaded
`static/media/[hash]${isUsingSizeAdjust ? '-s' : ''}${
preload ? '.p' : ''
}.${ext}`,
opts
)
const outputPath = `${assetPrefix}/_next/${interpolatedName}`
// Only the client emits the font file
if (!isServer) {
this.emitFile(interpolatedName, content, null)
}
// But both the server and client must get the resulting path
return outputPath
}
try {
// Import the font loader function from either next/font/local or next/font/google
// The font loader function emits font files and returns @font-faces and fallback font metrics
const fontLoader: FontLoader = require(fontLoaderPath).default
let { css, fallbackFonts, adjustFontFallback, weight, style, variable } =
await fontLoader({
......@@ -107,12 +129,15 @@ export default async function nextFontLoader(this: any) {
// Exports will be exported as is from css-loader instead of a CSS module export
const exports: { name: any; value: any }[] = []
// Generate a hash from the CSS content. Used to generate classnames and font families
const fontFamilyHash = loaderUtils.getHashDigest(
Buffer.from(css),
'md5',
'hex',
6
)
// Add CSS classes, exports and make the font-family localy scoped by turning it unguessable
const result = await postcss(
postcssNextFontPlugin({
......@@ -128,12 +153,13 @@ export default async function nextFontLoader(this: any) {
from: undefined,
})
// Reuse ast in css-loader
const ast = {
type: 'postcss',
version: result.processor.version,
root: result.root,
}
// Return the resulting CSS and send the postcss ast, font exports and the hash to the css-loader in the meta argument.
callback(null, result.css, null, {
exports,
ast,
......
import type { AdjustFontFallback } from '../../../../../font'
import postcss, { Declaration } from 'postcss'
/**
* The next/font postcss plugin recieves the @font-face declarations returned from the next/font loaders.
*
* It hashes the font-family name to make it unguessable, it shouldn't be globally accessible.
* If it were global, we wouldn't be able to tell which pages are using which fonts when generating preload tags.
*
* If the font loader returned fallback metrics, generate a fallback @font-face.
*
* If the font loader returned a variable name, add a CSS class that declares a variable containing the font and fallback fonts.
*
* Lastly, it adds the font-family to the exports object.
* This enables you to access the actual font-family name, not just through the CSS class.
* e.g:
* const inter = Inter({ subsets: ['latin'] })
* inter.style.fontFamily // => '__Inter_123456'
*/
const postcssNextFontPlugin = ({
exports,
fontFamilyHash,
......@@ -54,7 +70,7 @@ const postcssNextFontPlugin = ({
throw new Error("Font loaders must return one or more @font-face's")
}
// Add fallback font with override values
// Add fallback @font-face with the provided override values
let adjustFontFallbackFamily: string | undefined
if (adjustFontFallback) {
adjustFontFallbackFamily = formatFamily(`${fontFamily} Fallback`)
......@@ -113,6 +129,8 @@ const postcssNextFontPlugin = ({
// Variable fonts can define ranges of values
const isRange = (value: string) => value.trim().includes(' ')
// Format the font families to be used in the CSS
const formattedFontFamilies = [
formatFamily(fontFamily),
...(adjustFontFallbackFamily ? [adjustFontFallbackFamily] : []),
......@@ -126,6 +144,7 @@ const postcssNextFontPlugin = ({
prop: 'font-family',
value: formattedFontFamilies,
}),
// If the font only has one weight or style, we can set it on the class
...(weight && !isRange(weight)
? [
new postcss.Declaration({
......@@ -145,7 +164,7 @@ const postcssNextFontPlugin = ({
]
root.nodes.push(classRule)
// Add class that defines a variable with the font family
// Add CSS class that defines a variable with the font families
if (variable) {
const varialbeRule = new postcss.Rule({ selector: '.variable' })
varialbeRule.nodes = [
......
......@@ -19,7 +19,7 @@ import {
NEXT_CLIENT_SSR_ENTRY_SUFFIX,
FLIGHT_SERVER_CSS_MANIFEST,
SUBRESOURCE_INTEGRITY_MANIFEST,
FONT_LOADER_MANIFEST,
NEXT_FONT_MANIFEST,
SERVER_REFERENCE_MANIFEST,
} from '../../../shared/lib/constants'
import {
......@@ -126,7 +126,7 @@ function getEntryFiles(
`server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`
)
files.push(`server/${FONT_LOADER_MANIFEST}.js`)
files.push(`server/${NEXT_FONT_MANIFEST}.js`)
if (NextBuildContext!.hasInstrumentationHook) {
files.push(`server/edge-${INSTRUMENTATION_HOOK_FILENAME}.js`)
......
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { FONT_LOADER_MANIFEST } from '../../../shared/lib/constants'
import { NEXT_FONT_MANIFEST } from '../../../shared/lib/constants'
export type FontLoaderManifest = {
export type NextFontManifest = {
pages: {
[path: string]: string[]
}
......@@ -12,18 +12,45 @@ export type FontLoaderManifest = {
appUsingSizeAdjust: boolean
pagesUsingSizeAdjust: boolean
}
const PLUGIN_NAME = 'FontLoaderManifestPlugin'
const fontLoaderTargets = [
require.resolve('next/font/google/target.css'),
require.resolve('next/font/local/target.css'),
// TODO: remove this in the next major version
/node_modules\/@next\/font\/google\/target\.css\?{.+}$/,
/node_modules\/@next\/font\/local\/target\.css\?{.+}$/,
]
// Creates a manifest of all fonts that should be preloaded given a route
export class FontLoaderManifestPlugin {
const PLUGIN_NAME = 'NextFontManifestPlugin'
/**
* When calling font functions with next/font, you can specify if you'd like the font to be preloaded (true by default).
* e.g.: const inter = Inter({ subsets: ['latin'], preload: true })
*
* In that case, next-font-loader will emit the font file as [name].p.[ext] instead of [name].[ext]
* This function returns those files from an array that can include both preloaded and non-preloaded files.
*/
function getPreloadedFontFiles(fontFiles: string[]) {
return fontFiles.filter((file: string) =>
/\.p.(woff|woff2|eot|ttf|otf)$/.test(file)
)
}
/**
* Similarly to getPreloadedFontFiles, but returns true if some of the files includes -s in the name.
* This means that a font is using size adjust in its fallback font.
* This was added to enable adding data-size-adjust="true" to the dom, used by the Google Aurora team to collect statistics.
*/
function getPageIsUsingSizeAdjust(fontFiles: string[]) {
return fontFiles.some((file) => file.includes('-s'))
}
/**
* The NextFontManifestPlugin collects all font files emitted by next-font-loader and creates a manifest file.
* The manifest file is used in the Next.js render functions (_document.tsx for pages/ and app-render for app/) to add preload tags for the font files.
* We only want to att preload fonts that are used by the current route.
*
* For pages/ the plugin finds the fonts imported in the entrypoint chunks and creates a map:
* { [route]: fontFile[] }
* When rendering the app in _document.tsx, it gets the font files to preload: manifest.pages[currentRouteBeingRendered].
*
* For app/, the manifest is a bit different.
* Instead of creating a map of route to font files, it creates a map of the webpack module request to font files.
* { [webpackModuleRequest]: fontFile[]]}
* When creating the component tree in app-render it looks for font files to preload: manifest.app[moduleBeingRendered]
*/
export class NextFontManifestPlugin {
private appDirEnabled: boolean
constructor(options: { appDirEnabled: boolean }) {
......@@ -32,17 +59,15 @@ export class FontLoaderManifestPlugin {
apply(compiler: webpack.Compiler) {
compiler.hooks.make.tap(PLUGIN_NAME, (compilation) => {
let fontLoaderModules: webpack.Module[]
let nextFontModules: webpack.Module[]
// Get all font loader modules
// After all modules are created, we collect the modules that was created by next-font-loader.
if (this.appDirEnabled) {
compilation.hooks.finishModules.tap(PLUGIN_NAME, (modules) => {
const modulesArr = Array.from(modules)
fontLoaderModules = modulesArr.filter((mod: any) =>
fontLoaderTargets.some((fontLoaderTarget) =>
typeof fontLoaderTarget === 'string'
? mod.userRequest?.startsWith(`${fontLoaderTarget}?`)
: fontLoaderTarget.test(mod.userRequest)
nextFontModules = modulesArr.filter((mod: any) =>
mod?.loaders?.some(({ loader }: any) =>
loader.includes('next-font-loader/index.js')
)
)
})
......@@ -54,7 +79,7 @@ export class FontLoaderManifestPlugin {
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
(assets: any) => {
const fontLoaderManifest: FontLoaderManifest = {
const nextFontManifest: NextFontManifest = {
pages: {},
app: {},
appUsingSizeAdjust: false,
......@@ -62,32 +87,33 @@ export class FontLoaderManifestPlugin {
}
if (this.appDirEnabled) {
for (const mod of fontLoaderModules) {
// In this stage the font files are emitted and we can collect all files emitted by each next/font module.
for (const mod of nextFontModules) {
if (!mod.buildInfo?.assets) continue
const modAssets = Object.keys(mod.buildInfo.assets)
const fontFiles: string[] = modAssets.filter((file: string) =>
/\.(woff|woff2|eot|ttf|otf)$/.test(file)
)
if (!fontLoaderManifest.appUsingSizeAdjust) {
fontLoaderManifest.appUsingSizeAdjust = fontFiles.some((file) =>
file.includes('-s')
)
// Look if size-adjust fallback font is being used
if (!nextFontManifest.appUsingSizeAdjust) {
nextFontManifest.appUsingSizeAdjust =
getPageIsUsingSizeAdjust(fontFiles)
}
// Font files ending with .p.(woff|woff2|eot|ttf|otf) are preloaded
const preloadedFontFiles: string[] = fontFiles.filter(
(file: string) => /\.p.(woff|woff2|eot|ttf|otf)$/.test(file)
)
const preloadedFontFiles = getPreloadedFontFiles(fontFiles)
// Create an entry for the request even if no files should preload. If that's the case a preconnect tag is added.
// Add an entry of the module's font files in the manifest.
// We'll add an entry even if no files should preload.
// When an entry is present but empty, instead of preloading the font files, a preconnect tag is added.
if (fontFiles.length > 0) {
fontLoaderManifest.app[(mod as any).userRequest] =
nextFontManifest.app[(mod as any).userRequest] =
preloadedFontFiles
}
}
}
// Look at all the entrypoints created for pages/.
for (const entrypoint of compilation.entrypoints.values()) {
const pagePath = getRouteFromEntrypoint(entrypoint.name!)
......@@ -95,34 +121,36 @@ export class FontLoaderManifestPlugin {
continue
}
// Get font files from the chunks included in the entrypoint.
const fontFiles: string[] = entrypoint.chunks
.flatMap((chunk: any) => [...chunk.auxiliaryFiles])
.filter((file: string) =>
/\.(woff|woff2|eot|ttf|otf)$/.test(file)
)
if (!fontLoaderManifest.pagesUsingSizeAdjust) {
fontLoaderManifest.pagesUsingSizeAdjust = fontFiles.some((file) =>
file.includes('-s')
)
// Look if size-adjust fallback font is being used
if (!nextFontManifest.pagesUsingSizeAdjust) {
nextFontManifest.pagesUsingSizeAdjust =
getPageIsUsingSizeAdjust(fontFiles)
}
// Font files ending with .p.(woff|woff2|eot|ttf|otf) are preloaded
const preloadedFontFiles: string[] = fontFiles.filter(
(file: string) => /\.p.(woff|woff2|eot|ttf|otf)$/.test(file)
)
const preloadedFontFiles = getPreloadedFontFiles(fontFiles)
// Create an entry for the path even if no files should preload. If that's the case a preconnect tag is added.
// Add an entry of the route's font files in the manifest.
// We'll add an entry even if no files should preload.
// When an entry is present but empty, instead of preloading the font files, a preconnect tag is added.
if (fontFiles.length > 0) {
fontLoaderManifest.pages[pagePath] = preloadedFontFiles
nextFontManifest.pages[pagePath] = preloadedFontFiles
}
}
const manifest = JSON.stringify(fontLoaderManifest, null, 2)
assets[`server/${FONT_LOADER_MANIFEST}.js`] = new sources.RawSource(
`self.__FONT_LOADER_MANIFEST=${manifest}`
const manifest = JSON.stringify(nextFontManifest, null, 2)
// Create manifest for edge
assets[`server/${NEXT_FONT_MANIFEST}.js`] = new sources.RawSource(
`self.__NEXT_FONT_MANIFEST=${manifest}`
)
assets[`server/${FONT_LOADER_MANIFEST}.json`] = new sources.RawSource(
// Create manifest for server
assets[`server/${NEXT_FONT_MANIFEST}.json`] = new sources.RawSource(
manifest
)
}
......
......@@ -24,7 +24,7 @@ import {
EXPORT_MARKER,
CLIENT_REFERENCE_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
FONT_LOADER_MANIFEST,
NEXT_FONT_MANIFEST,
MIDDLEWARE_MANIFEST,
PAGES_MANIFEST,
PHASE_EXPORT,
......@@ -405,10 +405,10 @@ export default async function exportApp(
optimizeFonts: nextConfig.optimizeFonts as FontConfig,
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverComponents: hasAppDir,
fontLoaderManifest: require(join(
nextFontManifest: require(join(
distDir,
'server',
`${FONT_LOADER_MANIFEST}.json`
`${NEXT_FONT_MANIFEST}.json`
)),
}
......
......@@ -11,7 +11,7 @@ import type {
NEXT_DATA,
} from '../shared/lib/utils'
import type { ScriptProps } from '../client/script'
import type { FontLoaderManifest } from '../build/webpack/plugins/font-loader-manifest-plugin'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import { BuildManifest, getPageFiles } from '../server/get-page-files'
import { htmlEscapeJsonString } from '../server/htmlescape'
......@@ -357,20 +357,20 @@ function getAmpPath(ampPath: string, asPath: string): string {
return ampPath || `${asPath}${asPath.includes('?') ? '&' : '?'}amp=1`
}
function getFontLoaderLinks(
fontLoaderManifest: FontLoaderManifest | undefined,
function getNextFontLinkTags(
nextFontManifest: NextFontManifest | undefined,
dangerousAsPath: string,
assetPrefix: string = ''
) {
if (!fontLoaderManifest) {
if (!nextFontManifest) {
return {
preconnect: null,
preload: null,
}
}
const appFontsEntry = fontLoaderManifest.pages['/_app']
const pageFontsEntry = fontLoaderManifest.pages[dangerousAsPath]
const appFontsEntry = nextFontManifest.pages['/_app']
const pageFontsEntry = nextFontManifest.pages[dangerousAsPath]
const preloadedFontFiles = [
...(appFontsEntry ?? []),
......@@ -387,7 +387,7 @@ function getFontLoaderLinks(
preconnect: preconnectToSelf ? (
<link
data-next-font={
fontLoaderManifest.pagesUsingSizeAdjust ? 'size-adjust' : ''
nextFontManifest.pagesUsingSizeAdjust ? 'size-adjust' : ''
}
rel="preconnect"
href="/"
......@@ -669,7 +669,7 @@ export class Head extends React.Component<HeadProps> {
optimizeCss,
optimizeFonts,
assetPrefix,
fontLoaderManifest,
nextFontManifest,
} = this.context
const disableRuntimeJS = unstable_runtimeJS === false
......@@ -784,8 +784,8 @@ export class Head extends React.Component<HeadProps> {
process.env.NEXT_RUNTIME !== 'edge' && inAmpMode
)
const fontLoaderLinks = getFontLoaderLinks(
fontLoaderManifest,
const nextFontLinkTags = getNextFontLinkTags(
nextFontManifest,
dangerousAsPath,
assetPrefix
)
......@@ -830,8 +830,8 @@ export class Head extends React.Component<HeadProps> {
{children}
{optimizeFonts && <meta name="next-font-preconnect" />}
{fontLoaderLinks.preconnect}
{fontLoaderLinks.preload}
{nextFontLinkTags.preconnect}
{nextFontLinkTags.preload}
{process.env.NEXT_RUNTIME !== 'edge' && inAmpMode && (
<>
......
import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http'
import type { LoadComponentsReturnType } from './load-components'
import type { ServerRuntime } from '../../types'
import type { FontLoaderManifest } from '../build/webpack/plugins/font-loader-manifest-plugin'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
// Import builtin react directly to avoid require cache conflicts
import React, { use } from 'next/dist/compiled/react'
......@@ -188,7 +188,7 @@ export type RenderOptsPartial = {
runtime?: ServerRuntime
serverComponents?: boolean
assetPrefix?: string
fontLoaderManifest?: FontLoaderManifest
nextFontManifest?: NextFontManifest
isBot?: boolean
incrementalCache?: import('./lib/incremental-cache').IncrementalCache
isRevalidate?: boolean
......@@ -632,16 +632,16 @@ function getServerCSSForEntries(
}
/**
* Get inline <link rel="preload" as="font"> tags based on server CSS manifest and font loader manifest. Only used when rendering to HTML.
* 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,
fontLoaderManifest: FontLoaderManifest | undefined,
nextFontManifest: NextFontManifest | undefined,
serverCSSForEntries: string[],
filePath: string | undefined,
injectedFontPreloadTags: Set<string>
): string[] | null {
if (!fontLoaderManifest || !filePath) {
if (!nextFontManifest || !filePath) {
return null
}
const layoutOrPageCss = serverCSSManifest[filePath]
......@@ -656,7 +656,7 @@ function getPreloadedFontFilesInlineLinkTags(
for (const css of layoutOrPageCss) {
// We only include the CSS if it is used by this entrypoint.
if (serverCSSForEntries.includes(css)) {
const preloadedFontFiles = fontLoaderManifest.app[css]
const preloadedFontFiles = nextFontManifest.app[css]
if (preloadedFontFiles) {
foundFontUsage = true
for (const fontFile of preloadedFontFiles) {
......@@ -790,7 +790,7 @@ export async function renderToHTMLOrFlight(
serverCSSManifest = {},
ComponentMod,
dev,
fontLoaderManifest,
nextFontManifest,
supportsDynamicHTML,
} = renderOpts
......@@ -1152,7 +1152,7 @@ export async function renderToHTMLOrFlight(
const preloadedFontFiles = layoutOrPagePath
? getPreloadedFontFilesInlineLinkTags(
serverCSSManifest!,
fontLoaderManifest,
nextFontManifest,
serverCSSForEntries,
layoutOrPagePath,
injectedFontPreloadTagsWithCurrentLayout
......@@ -1450,7 +1450,7 @@ export async function renderToHTMLOrFlight(
{preloadedFontFiles?.length === 0 ? (
<link
data-next-font={
fontLoaderManifest?.appUsingSizeAdjust ? 'size-adjust' : ''
nextFontManifest?.appUsingSizeAdjust ? 'size-adjust' : ''
}
rel="preconnect"
href="/"
......@@ -1640,7 +1640,7 @@ export async function renderToHTMLOrFlight(
)
getPreloadedFontFilesInlineLinkTags(
serverCSSManifest!,
fontLoaderManifest,
nextFontManifest,
serverCSSForEntries,
layoutPath,
injectedFontPreloadTagsWithCurrentLayout
......
......@@ -28,7 +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 { FontLoaderManifest } from '../build/webpack/plugins/font-loader-manifest-plugin'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/redirect-status'
......@@ -230,7 +230,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
serverComponentManifest?: any
serverCSSManifest?: any
serverActionsManifest?: any
fontLoaderManifest?: FontLoaderManifest
nextFontManifest?: NextFontManifest
renderServerComponentData?: boolean
serverComponentProps?: any
largePageDataBytes?: number
......@@ -243,7 +243,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected customRoutes: CustomRoutes
protected serverComponentManifest?: any
protected serverCSSManifest?: any
protected fontLoaderManifest?: FontLoaderManifest
protected nextFontManifest?: NextFontManifest
public readonly hostname?: string
public readonly port?: number
......@@ -268,7 +268,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected abstract getPrerenderManifest(): PrerenderManifest
protected abstract getServerComponentManifest(): any
protected abstract getServerCSSManifest(): any
protected abstract getFontLoaderManifest(): FontLoaderManifest | undefined
protected abstract getNextFontManifest(): NextFontManifest | undefined
protected abstract attachRequestMeta(
req: BaseNextRequest,
parsedUrl: NextUrlWithParsedQuery
......@@ -392,7 +392,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
this.serverCSSManifest = serverComponents
? this.getServerCSSManifest()
: undefined
this.fontLoaderManifest = this.getFontLoaderManifest()
this.nextFontManifest = this.getNextFontManifest()
this.renderOpts = {
poweredByHeader: this.nextConfig.poweredByHeader,
......
......@@ -1352,7 +1352,7 @@ export default class DevServer extends Server {
return undefined
}
protected getFontLoaderManifest() {
protected getNextFontManifest() {
return undefined
}
......@@ -1628,7 +1628,7 @@ export default class DevServer extends Server {
this.serverComponentManifest = super.getServerComponentManifest()
this.serverCSSManifest = super.getServerCSSManifest()
}
this.fontLoaderManifest = super.getFontLoaderManifest()
this.nextFontManifest = super.getNextFontManifest()
// before we re-evaluate a route module, we want to restore globals that might
// have been patched previously to their original state so that we don't
// patch on top of the previous patch, which would keep the context of the previous
......
......@@ -39,7 +39,7 @@ import {
APP_PATHS_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
SERVER_DIRECTORY,
FONT_LOADER_MANIFEST,
NEXT_FONT_MANIFEST,
} from '../shared/lib/constants'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { findDir } from '../lib/find-pages-dir'
......@@ -856,7 +856,7 @@ export default class NextNodeServer extends BaseServer {
// https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952
renderOpts.serverComponentManifest = this.serverComponentManifest
renderOpts.serverCSSManifest = this.serverCSSManifest
renderOpts.fontLoaderManifest = this.fontLoaderManifest
renderOpts.nextFontManifest = this.nextFontManifest
if (this.hasAppDir && renderOpts.isAppPath) {
return appRenderToHTMLOrFlight(
......@@ -1058,8 +1058,8 @@ export default class NextNodeServer extends BaseServer {
))
}
protected getFontLoaderManifest() {
return require(join(this.distDir, 'server', `${FONT_LOADER_MANIFEST}.json`))
protected getNextFontManifest() {
return require(join(this.distDir, 'server', `${NEXT_FONT_MANIFEST}.json`))
}
protected getFallback(page: string): Promise<string> {
......
......@@ -26,7 +26,7 @@ import type {
} from 'next/types'
import type { UnwrapPromise } from '../lib/coalesced-function'
import type { ReactReadableStream } from './node-web-streams-helper'
import type { FontLoaderManifest } from '../build/webpack/plugins/font-loader-manifest-plugin'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import React from 'react'
import ReactDOMServer from 'react-dom/server.browser'
......@@ -248,7 +248,7 @@ export type RenderOptsPartial = {
resolvedAsPath?: string
serverComponentManifest?: any
serverCSSManifest?: any
fontLoaderManifest?: FontLoaderManifest
nextFontManifest?: NextFontManifest
distDir?: string
locale?: string
locales?: string[]
......@@ -1416,7 +1416,7 @@ export async function renderToHTML(
nextScriptWorkers: renderOpts.nextScriptWorkers,
runtime: globalRuntime,
largePageDataBytes: renderOpts.largePageDataBytes,
fontLoaderManifest: renderOpts.fontLoaderManifest,
nextFontManifest: renderOpts.nextFontManifest,
}
const document = (
......
......@@ -176,9 +176,8 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
return this.serverOptions.webServerConfig.extendRenderOpts.serverCSSManifest
}
protected getFontLoaderManifest() {
return this.serverOptions.webServerConfig.extendRenderOpts
.fontLoaderManifest
protected getNextFontManifest() {
return this.serverOptions.webServerConfig.extendRenderOpts.nextFontManifest
}
protected generateRoutes(): RouterOptions {
......
......@@ -27,7 +27,7 @@ export const APP_PATH_ROUTES_MANIFEST = 'app-path-routes-manifest.json'
export const BUILD_MANIFEST = 'build-manifest.json'
export const APP_BUILD_MANIFEST = 'app-build-manifest.json'
export const SUBRESOURCE_INTEGRITY_MANIFEST = 'subresource-integrity-manifest'
export const FONT_LOADER_MANIFEST = 'font-loader-manifest'
export const NEXT_FONT_MANIFEST = 'next-font-manifest'
export const EXPORT_MARKER = 'export-marker.json'
export const EXPORT_DETAIL = 'export-detail.json'
export const PRERENDER_MANIFEST = 'prerender-manifest.json'
......
......@@ -2,7 +2,7 @@ import type { BuildManifest } from '../../server/get-page-files'
import type { ServerRuntime } from 'next/types'
import type { NEXT_DATA } from './utils'
import type { FontConfig } from '../../server/font-utils'
import type { FontLoaderManifest } from '../../build/webpack/plugins/font-loader-manifest-plugin'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import { createContext } from 'react'
......@@ -44,7 +44,7 @@ export type HtmlProps = {
runtime?: ServerRuntime
hasConcurrentFeatures?: boolean
largePageDataBytes?: number
fontLoaderManifest?: FontLoaderManifest
nextFontManifest?: NextFontManifest
}
export const HtmlContext = createContext<HtmlProps>(null as any)
......
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