|
|
import type { AdjustFontFallback, FontLoader } from 'next/font' |
|
|
|
|
|
import * as Log from 'next/dist/build/output/log' |
|
|
import { validateGoogleFontFunctionCall } from './validate-google-font-function-call' |
|
|
import { getFontAxes } from './get-font-axes' |
|
|
import { getGoogleFontsUrl } from './get-google-fonts-url' |
|
|
import { nextFontError } from '../next-font-error' |
|
|
import { findFontFilesInCss } from './find-font-files-in-css' |
|
|
import { getFallbackFontOverrideMetrics } from './get-fallback-font-override-metrics' |
|
|
import { fetchCSSFromGoogleFonts } from './fetch-css-from-google-fonts' |
|
|
import { fetchFontFile } from './fetch-font-file' |
|
|
|
|
|
const cssCache = new Map<string, string | null>() |
|
|
const fontCache = new Map<string, Buffer | null>() |
|
|
|
|
|
|
|
|
const reHasRegExp = /[|\\{}()[\]^$+*?.-]/ |
|
|
const reReplaceRegExp = /[|\\{}()[\]^$+*?.-]/g |
|
|
|
|
|
function escapeStringRegexp(str: string) { |
|
|
|
|
|
if (reHasRegExp.test(str)) { |
|
|
return str.replace(reReplaceRegExp, '\\$&') |
|
|
} |
|
|
return str |
|
|
} |
|
|
|
|
|
const nextFontGoogleFontLoader: FontLoader = async ({ |
|
|
functionName, |
|
|
data, |
|
|
emitFontFile, |
|
|
isDev, |
|
|
isServer, |
|
|
}) => { |
|
|
const { |
|
|
fontFamily, |
|
|
weights, |
|
|
styles, |
|
|
display, |
|
|
preload, |
|
|
selectedVariableAxes, |
|
|
fallback, |
|
|
adjustFontFallback, |
|
|
variable, |
|
|
subsets, |
|
|
} = validateGoogleFontFunctionCall(functionName, data[0]) |
|
|
|
|
|
|
|
|
const fontAxes = getFontAxes( |
|
|
fontFamily, |
|
|
weights, |
|
|
styles, |
|
|
selectedVariableAxes |
|
|
) |
|
|
|
|
|
|
|
|
const url = getGoogleFontsUrl(fontFamily, fontAxes, display) |
|
|
|
|
|
|
|
|
const adjustFontFallbackMetrics: AdjustFontFallback | undefined = |
|
|
adjustFontFallback ? getFallbackFontOverrideMetrics(fontFamily) : undefined |
|
|
|
|
|
const result = { |
|
|
fallbackFonts: fallback, |
|
|
weight: |
|
|
weights.length === 1 && weights[0] !== 'variable' |
|
|
? weights[0] |
|
|
: undefined, |
|
|
style: styles.length === 1 ? styles[0] : undefined, |
|
|
variable, |
|
|
adjustFontFallback: adjustFontFallbackMetrics, |
|
|
} |
|
|
|
|
|
try { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const hasCachedCSS = cssCache.has(url) |
|
|
|
|
|
let fontFaceDeclarations = hasCachedCSS |
|
|
? cssCache.get(url) |
|
|
: await fetchCSSFromGoogleFonts(url, fontFamily, isDev).catch((err) => { |
|
|
console.error(err) |
|
|
return null |
|
|
}) |
|
|
if (!hasCachedCSS) { |
|
|
cssCache.set(url, fontFaceDeclarations ?? null) |
|
|
} else { |
|
|
cssCache.delete(url) |
|
|
} |
|
|
if (fontFaceDeclarations == null) { |
|
|
nextFontError(`Failed to fetch \`${fontFamily}\` from Google Fonts.`) |
|
|
} |
|
|
|
|
|
|
|
|
fontFaceDeclarations = fontFaceDeclarations.split('body {', 1)[0] |
|
|
|
|
|
|
|
|
const fontFiles = findFontFilesInCss( |
|
|
fontFaceDeclarations, |
|
|
preload ? subsets : undefined |
|
|
) |
|
|
|
|
|
|
|
|
const downloadedFiles = await Promise.all( |
|
|
fontFiles.map(async ({ googleFontFileUrl, preloadFontFile }) => { |
|
|
const hasCachedFont = fontCache.has(googleFontFileUrl) |
|
|
|
|
|
const fontFileBuffer = hasCachedFont |
|
|
? fontCache.get(googleFontFileUrl) |
|
|
: await fetchFontFile(googleFontFileUrl, isDev).catch((err) => { |
|
|
console.error(err) |
|
|
return null |
|
|
}) |
|
|
if (!hasCachedFont) { |
|
|
fontCache.set(googleFontFileUrl, fontFileBuffer ?? null) |
|
|
} else { |
|
|
fontCache.delete(googleFontFileUrl) |
|
|
} |
|
|
if (fontFileBuffer == null) { |
|
|
nextFontError(`Failed to fetch \`${fontFamily}\` from Google Fonts.`) |
|
|
} |
|
|
|
|
|
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(googleFontFileUrl)![1] |
|
|
|
|
|
const selfHostedFileUrl = emitFontFile( |
|
|
fontFileBuffer, |
|
|
ext, |
|
|
preloadFontFile, |
|
|
!!adjustFontFallbackMetrics |
|
|
) |
|
|
|
|
|
return { |
|
|
googleFontFileUrl, |
|
|
selfHostedFileUrl, |
|
|
} |
|
|
}) |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let updatedCssResponse = fontFaceDeclarations |
|
|
for (const { googleFontFileUrl, selfHostedFileUrl } of downloadedFiles) { |
|
|
updatedCssResponse = updatedCssResponse.replace( |
|
|
new RegExp(escapeStringRegexp(googleFontFileUrl), 'g'), |
|
|
selfHostedFileUrl |
|
|
) |
|
|
} |
|
|
|
|
|
return { |
|
|
...result, |
|
|
css: updatedCssResponse, |
|
|
} |
|
|
} catch (err) { |
|
|
if (isDev) { |
|
|
if (isServer) { |
|
|
Log.error( |
|
|
`Failed to download \`${fontFamily}\` from Google Fonts. Using fallback font instead.\n\n${ |
|
|
(err as Error).message |
|
|
}}` |
|
|
) |
|
|
} |
|
|
|
|
|
|
|
|
let css = `@font-face { |
|
|
font-family: '${fontFamily} Fallback'; |
|
|
src: local("${adjustFontFallbackMetrics?.fallbackFont ?? 'Arial'}");` |
|
|
if (adjustFontFallbackMetrics) { |
|
|
css += ` |
|
|
ascent-override:${adjustFontFallbackMetrics.ascentOverride}; |
|
|
descent-override:${adjustFontFallbackMetrics.descentOverride}; |
|
|
line-gap-override:${adjustFontFallbackMetrics.lineGapOverride}; |
|
|
size-adjust:${adjustFontFallbackMetrics.sizeAdjust};` |
|
|
} |
|
|
css += '\n}' |
|
|
|
|
|
return { |
|
|
...result, |
|
|
css, |
|
|
} |
|
|
} else { |
|
|
throw err |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
export default nextFontGoogleFontLoader |
|
|
|