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

next/font refactoring and additional unit tests (#46731)

Currently all helper functions are exported from huge utils files. This
moves the helper functions to their own files, this approach aligns
better with the rest of the codebase.

The unit tests are split up and colocated with the function it tests.
Also added some missing tests.

Plus some overall cleanup, added comments and fixed types.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/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`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 003b3af7
# Missing specified subset for a `@next/font/google` font # Missing specified subset for a `next/font/google` font
#### Why This Error Occurred #### Why This Error Occurred
...@@ -21,7 +21,7 @@ const inter = Inter({ subsets: ['latin'] }) ...@@ -21,7 +21,7 @@ const inter = Inter({ subsets: ['latin'] })
module.exports = { module.exports = {
experimental: { experimental: {
fontLoaders: [ fontLoaders: [
{ loader: '@next/font/google', options: { subsets: ['latin'] } }, { loader: 'next/font/google', options: { subsets: ['latin'] } },
], ],
}, },
} }
......
export const allowedDisplayValues = [
'auto',
'block',
'swap',
'fallback',
'optional',
]
/**
* Formats an array of values into a string that can be used error messages.
* ["a", "b", "c"] => "`a`, `b`, `c`"
*/
export const formatAvailableValues = (values: string[]) =>
values.map((val) => `\`${val}\``).join(', ')
// @ts-ignore
import fetch from 'next/dist/compiled/node-fetch'
import { nextFontError } from '../next-font-error'
/**
* Fetches the CSS containing the @font-face declarations from Google Fonts.
* The fetch has a user agent header with a modern browser to ensure we'll get .woff2 files.
*
* The env variable NEXT_FONT_GOOGLE_MOCKED_RESPONSES may be set containing a path to mocked data.
* It's used to defined mocked data to avoid hitting the Google Fonts API during tests.
*/
export async function fetchCSSFromGoogleFonts(
url: string,
fontFamily: string
): Promise<string> {
// Check if mocked responses are defined, if so use them instead of fetching from Google Fonts
let mockedResponse: string | undefined
if (process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES) {
const mockFile = require(process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES)
mockedResponse = mockFile[url]
if (!mockedResponse) {
nextFontError('Missing mocked response for URL: ' + url)
}
}
let cssResponse: string
if (mockedResponse) {
// Just use the mocked CSS if it's set
cssResponse = mockedResponse
} else {
const res = await fetch(url, {
headers: {
// The file format is based off of the user agent, make sure woff2 files are fetched
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
},
})
if (!res.ok) {
nextFontError(`Failed to fetch font \`${fontFamily}\`.\nURL: ${url}`)
}
cssResponse = await res.text()
}
return cssResponse
}
// @ts-ignore
import fetch from 'next/dist/compiled/node-fetch'
/**
* Fetch the url and return a buffer with the font file.
*/
export async function fetchFontFile(url: string) {
// Check if we're using mocked data
if (process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES) {
// If it's an absolute path, read the file from the filesystem
if (url.startsWith('/')) {
return require('fs').readFileSync(url)
}
// Otherwise just return a unique buffer
return Buffer.from(url)
}
const arrayBuffer = await fetch(url).then((r: any) => r.arrayBuffer())
return Buffer.from(arrayBuffer)
}
import { findFontFilesInCss } from './find-font-files-in-css'
describe('findFontFilesInCss', () => {
it('should find all font files and preload requested subsets', () => {
const css = `/* latin */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 300;
src: url(latin1.woff2) format('woff2');
}
/* greek */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 300;
src: url(greek1.woff2) format('woff2');
}
/* latin */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 400;
src: url(latin2.woff2) format('woff2');
}
/* greek */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 400;
src: url(greek2.woff2) format('woff2');
}
/* cyrilic */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 400;
src: url(cyrilic.woff2) format('woff2');
}
`
expect(findFontFilesInCss(css, ['latin', 'cyrilic'])).toEqual([
{ googleFontFileUrl: 'latin1.woff2', preloadFontFile: true },
{ googleFontFileUrl: 'greek1.woff2', preloadFontFile: false },
{ googleFontFileUrl: 'latin2.woff2', preloadFontFile: true },
{ googleFontFileUrl: 'greek2.woff2', preloadFontFile: false },
{ googleFontFileUrl: 'cyrilic.woff2', preloadFontFile: true },
])
})
it('should not return duplicate font files when several variants use the same font file', () => {
const css = `/* latin */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 100;
font-display: swap;
src: url(https://fonts.gstatic.com/s/fraunces/v24/6NUu8FyLNQOQZAnv9bYEvDiIdE9Ea92uemAk_WBq8U_9v0c2Wa0K7iN7hzFUPJH58nib14c7qv8oRcTn.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* latin */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(https://fonts.gstatic.com/s/fraunces/v24/6NUu8FyLNQOQZAnv9bYEvDiIdE9Ea92uemAk_WBq8U_9v0c2Wa0K7iN7hzFUPJH58nib14c7qv8oRcTn.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* latin */
@font-face {
font-family: 'Fraunces';
font-style: normal;
font-weight: 900;
font-display: swap;
src: url(https://fonts.gstatic.com/s/fraunces/v24/6NUu8FyLNQOQZAnv9bYEvDiIdE9Ea92uemAk_WBq8U_9v0c2Wa0K7iN7hzFUPJH58nib14c7qv8oRcTn.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
`
expect(findFontFilesInCss(css)).toEqual([
{
googleFontFileUrl:
'https://fonts.gstatic.com/s/fraunces/v24/6NUu8FyLNQOQZAnv9bYEvDiIdE9Ea92uemAk_WBq8U_9v0c2Wa0K7iN7hzFUPJH58nib14c7qv8oRcTn.woff2',
preloadFontFile: false,
},
])
})
})
/**
* Find all font files in the CSS response and determine which files should be preloaded.
* In Google Fonts responses, the @font-face's subset is above it in a comment.
* Walk through the CSS from top to bottom, keeping track of the current subset.
*/
export function findFontFilesInCss(css: string, subsetsToPreload?: string[]) {
// Find font files to download
const fontFiles: Array<{
googleFontFileUrl: string
preloadFontFile: boolean
}> = []
// Keep track of the current subset
let currentSubset = ''
for (const line of css.split('\n')) {
const newSubset = /\/\* (.+?) \*\//.exec(line)?.[1]
if (newSubset) {
// Found new subset in a comment above the next @font-face declaration
currentSubset = newSubset
} else {
const googleFontFileUrl = /src: url\((.+?)\)/.exec(line)?.[1]
if (
googleFontFileUrl &&
!fontFiles.some(
(foundFile) => foundFile.googleFontFileUrl === googleFontFileUrl
)
) {
// Found the font file in the @font-face declaration.
fontFiles.push({
googleFontFileUrl,
preloadFontFile: !!subsetsToPreload?.includes(currentSubset),
})
}
}
}
return fontFiles
}
// @ts-ignore
import { calculateSizeAdjustValues } from 'next/dist/server/font-utils'
// @ts-ignore
import * as Log from 'next/dist/build/output/log'
/**
* Get precalculated fallback font metrics for the Google Fonts family.
*
* TODO:
* We might want to calculate these values with fontkit instead (like in next/font/local).
* That way we don't have to update the precalculated values every time a new font is added to Google Fonts.
*/
export function getFallbackFontOverrideMetrics(fontFamily: string) {
try {
const { ascent, descent, lineGap, fallbackFont, sizeAdjust } =
calculateSizeAdjustValues(
require('next/dist/server/google-font-metrics.json')[fontFamily]
)
return {
fallbackFont,
ascentOverride: `${ascent}%`,
descentOverride: `${descent}%`,
lineGapOverride: `${lineGap}%`,
sizeAdjust: `${sizeAdjust}%`,
}
} catch {
Log.error(`Failed to find font override values for font \`${fontFamily}\``)
}
}
import { getFontAxes } from './get-font-axes'
describe('getFontAxes errors', () => {
test('Setting axes on font without definable axes', () => {
expect(() =>
getFontAxes('Lora', ['variable'], [], [])
).toThrowErrorMatchingInlineSnapshot(
`"Font \`Lora\` has no definable \`axes\`"`
)
})
test('Invalid axes value', async () => {
expect(() => getFontAxes('Inter', ['variable'], [], true as any))
.toThrowErrorMatchingInlineSnapshot(`
"Invalid axes value for font \`Inter\`, expected an array of axes.
Available axes: \`slnt\`"
`)
})
test('Invalid value in axes array', async () => {
expect(() => getFontAxes('Roboto Flex', ['variable'], [], ['INVALID']))
.toThrowErrorMatchingInlineSnapshot(`
"Invalid axes value \`INVALID\` for font \`Roboto Flex\`.
Available axes: \`GRAD\`, \`XTRA\`, \`YOPQ\`, \`YTAS\`, \`YTDE\`, \`YTFI\`, \`YTLC\`, \`YTUC\`, \`opsz\`, \`slnt\`, \`wdth\`"
`)
})
})
import { formatAvailableValues } from '../format-available-values'
import { nextFontError } from '../next-font-error'
import { googleFontsMetadata } from './google-fonts-metadata'
/**
* Validates and gets the data for each font axis required to generate the Google Fonts URL.
*/
export function getFontAxes(
fontFamily: string,
weights: string[],
styles: string[],
selectedVariableAxes?: string[]
): {
wght?: string[]
ital?: string[]
variableAxes?: [string, string][]
} {
const hasItalic = styles.includes('italic')
const hasNormal = styles.includes('normal')
// Make sure the order is correct, otherwise Google Fonts will return an error
// If only normal is set, we can skip returning the ital axis as normal is the default
const ital = hasItalic ? [...(hasNormal ? ['0'] : []), '1'] : undefined
// Weights will always contain one element if it's a variable font
if (weights[0] === 'variable') {
// Get all the available axes for the current font from the metadata file
const allAxes = googleFontsMetadata[fontFamily].axes
if (!allAxes) {
throw new Error('invariant variable font without axes')
}
if (selectedVariableAxes) {
// The axes other than weight and style that can be defined for the current variable font
const defineAbleAxes: string[] = allAxes
.map(({ tag }) => tag)
.filter((tag) => tag !== 'wght')
if (defineAbleAxes.length === 0) {
nextFontError(`Font \`${fontFamily}\` has no definable \`axes\``)
}
if (!Array.isArray(selectedVariableAxes)) {
nextFontError(
`Invalid axes value for font \`${fontFamily}\`, expected an array of axes.\nAvailable axes: ${formatAvailableValues(
defineAbleAxes
)}`
)
}
selectedVariableAxes.forEach((key) => {
if (!defineAbleAxes.some((tag) => tag === key)) {
nextFontError(
`Invalid axes value \`${key}\` for font \`${fontFamily}\`.\nAvailable axes: ${formatAvailableValues(
defineAbleAxes
)}`
)
}
})
}
let weightAxis: string | undefined
let variableAxes: [string, string][] | undefined
for (const { tag, min, max } of allAxes) {
if (tag === 'wght') {
// In variable fonts the weight is a range
weightAxis = `${min}..${max}`
} else if (selectedVariableAxes?.includes(tag)) {
if (!variableAxes) {
variableAxes = []
}
variableAxes.push([tag, `${min}..${max}`])
}
}
return {
wght: weightAxis ? [weightAxis] : undefined,
ital,
variableAxes,
}
} else {
return {
ital,
wght: weights,
}
}
}
/**
* Generate the Google Fonts URL given the requested weight(s), style(s) and additional variable axes
*/
export function getGoogleFontsUrl(
fontFamily: string,
axes: {
wght?: string[]
ital?: string[]
variableAxes?: [string, string][]
},
display: string
) {
// Variants are all combinations of weight and style, each variant will result in a separate font file
const variants: Array<[string, string][]> = []
if (axes.wght) {
for (const wght of axes.wght) {
if (!axes.ital) {
variants.push([['wght', wght], ...(axes.variableAxes ?? [])])
} else {
for (const ital of axes.ital) {
variants.push([
['ital', ital],
['wght', wght],
...(axes.variableAxes ?? []),
])
}
}
}
} else if (axes.variableAxes) {
// Variable fonts might not have a range of weights, just add optional variable axes in that case
variants.push([...axes.variableAxes])
}
// Google api requires the axes to be sorted, starting with lowercase words
if (axes.variableAxes) {
variants.forEach((variant) => {
variant.sort(([a], [b]) => {
const aIsLowercase = a.charCodeAt(0) > 96
const bIsLowercase = b.charCodeAt(0) > 96
if (aIsLowercase && !bIsLowercase) return -1
if (bIsLowercase && !aIsLowercase) return 1
return a > b ? 1 : -1
})
})
}
let url = `https://fonts.googleapis.com/css2?family=${fontFamily.replace(
/ /g,
'+'
)}`
if (variants.length > 0) {
url = `${url}:${variants[0].map(([key]) => key).join(',')}@${variants
.map((variant) => variant.map(([, val]) => val).join(','))
.sort()
.join(';')}`
}
url = `${url}&display=${display}`
return url
}
import fontData from './font-data.json'
type GoogleFontsMetadata = {
[fontFamily: string]: {
weights: string[]
styles: string[]
subsets: string[]
axes?: Array<{
tag: string
min: number
max: number
defaultValue: number
}>
}
}
export const googleFontsMetadata: GoogleFontsMetadata = fontData
import nextFontGoogleFontLoader from './loader'
// @ts-ignore
import fetch from 'next/dist/compiled/node-fetch'
jest.mock('next/dist/compiled/node-fetch')
describe('next/font/google loader', () => {
afterEach(() => {
jest.resetAllMocks()
})
describe('URL from options', () => {
const fixtures: Array<[string, any, string]> = [
[
'Inter',
{},
'https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap',
],
[
'Inter',
{ weight: '400' },
'https://fonts.googleapis.com/css2?family=Inter:wght@400&display=swap',
],
[
'Inter',
{ weight: '900', display: 'block' },
'https://fonts.googleapis.com/css2?family=Inter:wght@900&display=block',
],
[
'Source_Sans_Pro',
{ weight: '900', display: 'auto' },
'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@900&display=auto',
],
[
'Source_Sans_Pro',
{ weight: '200', style: 'italic' },
'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@1,200&display=swap',
],
[
'Roboto_Flex',
{ display: 'swap' },
'https://fonts.googleapis.com/css2?family=Roboto+Flex:wght@100..1000&display=swap',
],
[
'Roboto_Flex',
{ display: 'fallback', weight: 'variable', axes: ['opsz'] },
'https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=fallback',
],
[
'Roboto_Flex',
{
display: 'optional',
axes: ['YTUC', 'slnt', 'wdth', 'opsz', 'XTRA', 'YTAS'],
},
'https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,slnt,wdth,wght,XTRA,YTAS,YTUC@8..144,-10..0,25..151,100..1000,323..603,649..854,528..760&display=optional',
],
[
'Oooh_Baby',
{ weight: '400' },
'https://fonts.googleapis.com/css2?family=Oooh+Baby:wght@400&display=swap',
],
[
'Albert_Sans',
{ weight: 'variable', style: 'italic' },
'https://fonts.googleapis.com/css2?family=Albert+Sans:ital,wght@1,100..900&display=swap',
],
[
'Fraunces',
{ weight: 'variable', style: 'italic', axes: ['WONK', 'opsz', 'SOFT'] },
'https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght,SOFT,WONK@1,9..144,100..900,0..100,0..1&display=swap',
],
[
'Molle',
{ weight: '400' },
'https://fonts.googleapis.com/css2?family=Molle:ital,wght@1,400&display=swap',
],
[
'Roboto',
{ weight: ['500', '300', '400'], style: ['normal', 'italic'] },
'https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap',
],
[
'Roboto Mono',
{ style: ['italic', 'normal'] },
'https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@0,100..700;1,100..700&display=swap',
],
[
'Fraunces',
{
style: ['normal', 'italic'],
axes: ['WONK', 'opsz', 'SOFT'],
},
'https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght,SOFT,WONK@0,9..144,100..900,0..100,0..1;1,9..144,100..900,0..100,0..1&display=swap',
],
[
'Poppins',
{ weight: ['900', '400', '100'] },
'https://fonts.googleapis.com/css2?family=Poppins:wght@100;400;900&display=swap',
],
[
'Nabla',
{},
'https://fonts.googleapis.com/css2?family=Nabla&display=swap',
],
[
'Nabla',
{ axes: ['EDPT', 'EHLT'] },
'https://fonts.googleapis.com/css2?family=Nabla:EDPT,EHLT@0..200,0..24&display=swap',
],
[
'Ballet',
{},
'https://fonts.googleapis.com/css2?family=Ballet&display=swap',
],
]
test.each(fixtures)(
'%s',
async (
functionName: string,
fontFunctionArguments: any,
expectedUrl: any
) => {
fetch.mockResolvedValue({
ok: true,
text: async () => 'OK',
})
const { css } = await nextFontGoogleFontLoader({
functionName,
data: [{ adjustFontFallback: false, ...fontFunctionArguments }],
config: { subsets: [] },
emitFontFile: jest.fn(),
resolve: jest.fn(),
loaderContext: {} as any,
isDev: false,
isServer: true,
variableName: 'myFont',
})
expect(css).toBe('OK')
expect(fetch).toHaveBeenCalledTimes(1)
expect(fetch).toHaveBeenCalledWith(expectedUrl, expect.any(Object))
}
)
})
})
import type { AdjustFontFallback, FontLoader } from 'next/font' import type { AdjustFontFallback, FontLoader } from 'next/font'
// @ts-ignore // @ts-ignore
import * as Log from 'next/dist/build/output/log' import * as Log from 'next/dist/build/output/log'
import { import { validateGoogleFontFunctionCall } from './validate-google-font-function-call'
fetchCSSFromGoogleFonts, import { getFontAxes } from './get-font-axes'
fetchFontFile, import { getGoogleFontsUrl } from './get-google-fonts-url'
findFontFilesInCss, import { nextFontError } from '../next-font-error'
getFallbackFontOverrideMetrics, import { findFontFilesInCss } from './find-font-files-in-css'
getFontAxes, import { getFallbackFontOverrideMetrics } from './get-fallback-font-override-metrics'
getUrl, import { fetchCSSFromGoogleFonts } from './fetch-css-from-google-fonts'
validateData, import { fetchFontFile } from './fetch-font-file'
} from './utils'
import { nextFontError } from '../utils'
const cssCache = new Map<string, string | null>() const cssCache = new Map<string, string | null>()
const fontCache = new Map<string, Buffer | null>() const fontCache = new Map<string, Buffer | null>()
...@@ -47,7 +45,7 @@ const nextFontGoogleFontLoader: FontLoader = async ({ ...@@ -47,7 +45,7 @@ const nextFontGoogleFontLoader: FontLoader = async ({
adjustFontFallback, adjustFontFallback,
variable, variable,
subsets, subsets,
} = validateData(functionName, data, config) } = validateGoogleFontFunctionCall(functionName, data[0], config)
// Validate and get the font axes required to generated the URL // Validate and get the font axes required to generated the URL
const fontAxes = getFontAxes( const fontAxes = getFontAxes(
...@@ -58,7 +56,7 @@ const nextFontGoogleFontLoader: FontLoader = async ({ ...@@ -58,7 +56,7 @@ const nextFontGoogleFontLoader: FontLoader = async ({
) )
// Generate the Google Fonts URL from the font family, axes and display value // Generate the Google Fonts URL from the font family, axes and display value
const url = getUrl(fontFamily, fontAxes, display) const url = getGoogleFontsUrl(fontFamily, fontAxes, display)
// Get precalculated fallback font metrics, used to generate the fallback font CSS // Get precalculated fallback font metrics, used to generate the fallback font CSS
const adjustFontFallbackMetrics: AdjustFontFallback | undefined = const adjustFontFallbackMetrics: AdjustFontFallback | undefined =
......
This diff is collapsed.
import { validateGoogleFontFunctionCall } from './validate-google-font-function-call'
describe('validateFontFunctionCall errors', () => {
test('Missing function name', () => {
expect(() =>
validateGoogleFontFunctionCall(
'', // default import
undefined,
{ subsets: [] }
)
).toThrowErrorMatchingInlineSnapshot(
`"next/font/google has no default export"`
)
})
test('Unknown font', () => {
expect(() =>
validateGoogleFontFunctionCall('Unknown_Font', undefined, { subsets: [] })
).toThrowErrorMatchingInlineSnapshot(`"Unknown font \`Unknown Font\`"`)
})
test('Unknown weight', () => {
expect(() =>
validateGoogleFontFunctionCall(
'Inter',
{ weight: '123' },
{
subsets: [],
}
)
).toThrowErrorMatchingInlineSnapshot(`
"Unknown weight \`123\` for font \`Inter\`.
Available weights: \`100\`, \`200\`, \`300\`, \`400\`, \`500\`, \`600\`, \`700\`, \`800\`, \`900\`, \`variable\`"
`)
})
test('Missing weight for non variable font', () => {
expect(() => validateGoogleFontFunctionCall('Abel', {}, { subsets: [] }))
.toThrowErrorMatchingInlineSnapshot(`
"Missing weight for font \`Abel\`.
Available weights: \`400\`"
`)
})
test('Unknown style', () => {
expect(() =>
validateGoogleFontFunctionCall(
'Molle',
{ weight: '400', style: 'normal' },
{
subsets: [],
}
)
).toThrowErrorMatchingInlineSnapshot(`
"Unknown style \`normal\` for font \`Molle\`.
Available styles: \`italic\`"
`)
})
test('Invalid display value', () => {
expect(() =>
validateGoogleFontFunctionCall(
'Inter',
{ display: 'Invalid' },
{
subsets: [],
}
)
).toThrowErrorMatchingInlineSnapshot(`
"Invalid display value \`Invalid\` for font \`Inter\`.
Available display values: \`auto\`, \`block\`, \`swap\`, \`fallback\`, \`optional\`"
`)
})
test('Variable in weight array', async () => {
expect(() =>
validateGoogleFontFunctionCall(
'Inter',
{ weight: ['100', 'variable'] },
{
subsets: [],
}
)
).toThrowErrorMatchingInlineSnapshot(
`"Unexpected \`variable\` in weight array for font \`Inter\`. You only need \`variable\`, it includes all available weights."`
)
})
test('Invalid subset in call', async () => {
expect(() =>
validateGoogleFontFunctionCall(
'Inter',
{ subsets: ['latin', 'oops'] },
{
subsets: [],
}
)
).toThrowErrorMatchingInlineSnapshot(`
"Unknown subset \`oops\` for font \`Inter\`.
Available subsets: \`cyrillic\`, \`cyrillic-ext\`, \`greek\`, \`greek-ext\`, \`latin\`, \`latin-ext\`, \`vietnamese\`"
`)
})
test('Invalid subset in config', async () => {
expect(() =>
validateGoogleFontFunctionCall(
'Inter',
{},
{
subsets: ['latin', 'oops'],
}
)
).toThrowErrorMatchingInlineSnapshot(`
"Unknown subset \`oops\` for font \`Inter\`.
Available subsets: \`cyrillic\`, \`cyrillic-ext\`, \`greek\`, \`greek-ext\`, \`latin\`, \`latin-ext\`, \`vietnamese\`"
`)
})
test('Missing subsets in config and call', async () => {
expect(() =>
validateGoogleFontFunctionCall('Inter', {}, {})
).toThrowErrorMatchingInlineSnapshot(
`"Missing selected subsets for font \`Inter\`. Please specify subsets in the function call or in your \`next.config.js\`. Read more: https://nextjs.org/docs/messages/google-fonts-missing-subsets"`
)
})
test('Setting axes on non variable font', async () => {
expect(() =>
validateGoogleFontFunctionCall(
'Abel',
{ weight: '400', axes: [] },
{
subsets: [],
}
)
).toThrowErrorMatchingInlineSnapshot(
`"Axes can only be defined for variable fonts"`
)
})
})
import { allowedDisplayValues } from '../constants'
import { formatAvailableValues } from '../format-available-values'
import { nextFontError } from '../next-font-error'
import { googleFontsMetadata } from './google-fonts-metadata'
type FontOptions = {
fontFamily: string
weights: string[]
styles: string[]
display: string
preload: boolean
selectedVariableAxes?: string[]
fallback?: string[]
adjustFontFallback: boolean
variable?: string
subsets: string[]
}
/**
* Validate the data recieved from next-swc next_font_loaders on next/font/google calls
*/
export function validateGoogleFontFunctionCall(
functionName: string,
fontFunctionArgument: any,
config: any
): FontOptions {
let {
weight,
style,
preload = true,
display = 'swap',
axes,
fallback,
adjustFontFallback = true,
variable,
subsets: callSubsets,
} = fontFunctionArgument || ({} as any)
// Get the subsets defined for the font from either next.config.js or the function call. If both are present, pick the function call subsets.
const subsets = callSubsets ?? config?.subsets ?? []
if (functionName === '') {
nextFontError(`next/font/google has no default export`)
}
const fontFamily = functionName.replace(/_/g, ' ')
// Get the Google font metadata, we'll use this to validate the font arguments and to print better error messages
const fontFamilyData = googleFontsMetadata[fontFamily]
if (!fontFamilyData) {
nextFontError(`Unknown font \`${fontFamily}\``)
}
const availableSubsets = fontFamilyData.subsets
if (availableSubsets.length === 0) {
// If the font doesn't have any preloadeable subsets, disable preload
preload = false
} else {
if (preload && !callSubsets && !config?.subsets) {
nextFontError(
`Missing selected subsets for font \`${fontFamily}\`. Please specify subsets in the function call or in your \`next.config.js\`. Read more: https://nextjs.org/docs/messages/google-fonts-missing-subsets`
)
}
subsets.forEach((subset: string) => {
if (!availableSubsets.includes(subset)) {
nextFontError(
`Unknown subset \`${subset}\` for font \`${fontFamily}\`.\nAvailable subsets: ${formatAvailableValues(
availableSubsets
)}`
)
}
})
}
const fontWeights = fontFamilyData.weights
const fontStyles = fontFamilyData.styles
// Get the unique weights and styles from the function call
const weights = !weight
? []
: [...new Set(Array.isArray(weight) ? weight : [weight])]
const styles = !style
? []
: [...new Set(Array.isArray(style) ? style : [style])]
if (weights.length === 0) {
// Set variable as default, throw if not available
if (fontWeights.includes('variable')) {
weights.push('variable')
} else {
nextFontError(
`Missing weight for font \`${fontFamily}\`.\nAvailable weights: ${formatAvailableValues(
fontWeights
)}`
)
}
}
if (weights.length > 1 && weights.includes('variable')) {
nextFontError(
`Unexpected \`variable\` in weight array for font \`${fontFamily}\`. You only need \`variable\`, it includes all available weights.`
)
}
weights.forEach((selectedWeight) => {
if (!fontWeights.includes(selectedWeight)) {
nextFontError(
`Unknown weight \`${selectedWeight}\` for font \`${fontFamily}\`.\nAvailable weights: ${formatAvailableValues(
fontWeights
)}`
)
}
})
if (styles.length === 0) {
if (fontStyles.length === 1) {
// Handle default style for fonts that only have italic
styles.push(fontStyles[0])
} else {
// Otherwise set default style to normal
styles.push('normal')
}
}
styles.forEach((selectedStyle) => {
if (!fontStyles.includes(selectedStyle)) {
nextFontError(
`Unknown style \`${selectedStyle}\` for font \`${fontFamily}\`.\nAvailable styles: ${formatAvailableValues(
fontStyles
)}`
)
}
})
if (!allowedDisplayValues.includes(display)) {
nextFontError(
`Invalid display value \`${display}\` for font \`${fontFamily}\`.\nAvailable display values: ${formatAvailableValues(
allowedDisplayValues
)}`
)
}
if (weights[0] !== 'variable' && axes) {
nextFontError('Axes can only be defined for variable fonts')
}
return {
fontFamily,
weights,
styles,
display,
preload,
selectedVariableAxes: axes,
fallback,
adjustFontFallback,
variable,
subsets,
}
}
...@@ -66,10 +66,11 @@ function formatOverrideValue(val: number) { ...@@ -66,10 +66,11 @@ function formatOverrideValue(val: number) {
* size-adjust: 90%; * size-adjust: 90%;
* } * }
* *
* Read more about this technique in this document by the Google Aurora team: * Read more about this technique in these texts by the Google Aurora team:
* https://developer.chrome.com/blog/font-fallbacks/
* https://docs.google.com/document/d/e/2PACX-1vRsazeNirATC7lIj2aErSHpK26hZ6dA9GsQ069GEbq5fyzXEhXbvByoftSfhG82aJXmrQ_sJCPBqcx_/pub * https://docs.google.com/document/d/e/2PACX-1vRsazeNirATC7lIj2aErSHpK26hZ6dA9GsQ069GEbq5fyzXEhXbvByoftSfhG82aJXmrQ_sJCPBqcx_/pub
*/ */
export function calculateFallbackFontValues( export function getFallbackMetricsFromFontFile(
font: Font, font: Font,
category = 'serif' category = 'serif'
): AdjustFontFallback { ): AdjustFontFallback {
...@@ -92,9 +93,3 @@ export function calculateFallbackFontValues( ...@@ -92,9 +93,3 @@ export function calculateFallbackFontValues(
sizeAdjust: formatOverrideValue(sizeAdjust), sizeAdjust: formatOverrideValue(sizeAdjust),
} }
} }
export function nextFontError(message: string): never {
const err = new Error(message)
err.name = 'NextFontError'
throw err
}
import loader from '@next/font/local/loader' import nextFontLocalFontLoader from './loader'
describe('next/font/local', () => { describe('next/font/local loader', () => {
describe('generated CSS', () => { describe('generated CSS', () => {
test('Default CSS', async () => { test('Default CSS', async () => {
const { css } = await loader({ const { css } = await nextFontLocalFontLoader({
functionName: '', functionName: '',
data: [{ src: './my-font.woff2' }], data: [{ src: './my-font.woff2' }],
config: {}, config: {},
...@@ -14,7 +14,7 @@ describe('next/font/local', () => { ...@@ -14,7 +14,7 @@ describe('next/font/local', () => {
variableName: 'myFont', variableName: 'myFont',
loaderContext: { loaderContext: {
fs: { fs: {
readFile: (_, cb) => cb(null, 'fontdata'), readFile: (_: string, cb: any) => cb(null, 'fontdata'),
}, },
} as any, } as any,
}) })
...@@ -30,7 +30,7 @@ describe('next/font/local', () => { ...@@ -30,7 +30,7 @@ describe('next/font/local', () => {
}) })
test('Weight and style', async () => { test('Weight and style', async () => {
const { css } = await loader({ const { css } = await nextFontLocalFontLoader({
functionName: '', functionName: '',
data: [{ src: './my-font.woff2', weight: '100 900', style: 'italic' }], data: [{ src: './my-font.woff2', weight: '100 900', style: 'italic' }],
config: {}, config: {},
...@@ -41,7 +41,7 @@ describe('next/font/local', () => { ...@@ -41,7 +41,7 @@ describe('next/font/local', () => {
variableName: 'myFont', variableName: 'myFont',
loaderContext: { loaderContext: {
fs: { fs: {
readFile: (_, cb) => cb(null, 'fontdata'), readFile: (_: string, cb: any) => cb(null, 'fontdata'),
}, },
} as any, } as any,
}) })
...@@ -59,7 +59,7 @@ describe('next/font/local', () => { ...@@ -59,7 +59,7 @@ describe('next/font/local', () => {
}) })
test('Other properties', async () => { test('Other properties', async () => {
const { css } = await loader({ const { css } = await nextFontLocalFontLoader({
functionName: '', functionName: '',
data: [ data: [
{ {
...@@ -78,7 +78,7 @@ describe('next/font/local', () => { ...@@ -78,7 +78,7 @@ describe('next/font/local', () => {
variableName: 'myFont', variableName: 'myFont',
loaderContext: { loaderContext: {
fs: { fs: {
readFile: (_, cb) => cb(null, 'fontdata'), readFile: (_: string, cb: any) => cb(null, 'fontdata'),
}, },
} as any, } as any,
}) })
...@@ -96,7 +96,7 @@ describe('next/font/local', () => { ...@@ -96,7 +96,7 @@ describe('next/font/local', () => {
}) })
test('Multiple weights default style', async () => { test('Multiple weights default style', async () => {
const { css } = await loader({ const { css } = await nextFontLocalFontLoader({
functionName: '', functionName: '',
data: [ data: [
{ {
...@@ -124,14 +124,14 @@ describe('next/font/local', () => { ...@@ -124,14 +124,14 @@ describe('next/font/local', () => {
}, },
], ],
config: {}, config: {},
emitFontFile: (buffer) => `/_next/static/media/my-font.woff2`, emitFontFile: () => `/_next/static/media/my-font.woff2`,
resolve: jest.fn(), resolve: jest.fn(),
isDev: false, isDev: false,
isServer: true, isServer: true,
variableName: 'myFont', variableName: 'myFont',
loaderContext: { loaderContext: {
fs: { fs: {
readFile: (path, cb) => cb(null, path), readFile: (path: string, cb: any) => cb(null, path),
}, },
} as any, } as any,
}) })
...@@ -173,7 +173,7 @@ describe('next/font/local', () => { ...@@ -173,7 +173,7 @@ describe('next/font/local', () => {
}) })
test('Multiple styles default weight', async () => { test('Multiple styles default weight', async () => {
const { css } = await loader({ const { css } = await nextFontLocalFontLoader({
functionName: '', functionName: '',
data: [ data: [
{ {
...@@ -196,14 +196,14 @@ describe('next/font/local', () => { ...@@ -196,14 +196,14 @@ describe('next/font/local', () => {
}, },
], ],
config: {}, config: {},
emitFontFile: (buffer) => `/_next/static/media/my-font.woff2`, emitFontFile: () => `/_next/static/media/my-font.woff2`,
resolve: jest.fn(), resolve: jest.fn(),
isDev: false, isDev: false,
isServer: true, isServer: true,
variableName: 'myFont', variableName: 'myFont',
loaderContext: { loaderContext: {
fs: { fs: {
readFile: (path, cb) => cb(null, path), readFile: (path: string, cb: any) => cb(null, path),
}, },
} as any, } as any,
}) })
...@@ -235,183 +235,4 @@ describe('next/font/local', () => { ...@@ -235,183 +235,4 @@ describe('next/font/local', () => {
`) `)
}) })
}) })
describe('Errors', () => {
test('Not using default export', async () => {
await expect(
loader({
functionName: 'Named',
data: [],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isDev: false,
isServer: true,
variableName: 'myFont',
loaderContext: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"next/font/local has no named exports"`
)
})
test('Missing src', async () => {
await expect(
loader({
functionName: '',
data: [],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isDev: false,
isServer: true,
variableName: 'myFont',
loaderContext: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Missing required \`src\` property"`
)
})
test('Invalid file extension', async () => {
await expect(
loader({
functionName: '',
data: [{ src: './font/font-file.abc' }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn().mockResolvedValue(''),
isDev: false,
isServer: true,
variableName: 'myFont',
loaderContext: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unexpected file \`./font/font-file.abc\`"`
)
})
test('Invalid display value', async () => {
await expect(
loader({
functionName: '',
data: [{ src: './font-file.woff2', display: 'invalid' }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isDev: false,
isServer: true,
variableName: 'myFont',
loaderContext: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid display value \`invalid\`.
Available display values: \`auto\`, \`block\`, \`swap\`, \`fallback\`, \`optional\`"
`)
})
test('Invalid declaration', async () => {
await expect(
loader({
functionName: '',
data: [
{
src: './font-file.woff2',
declarations: [{ prop: 'src', value: '/hello.woff2' }],
},
],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isDev: false,
isServer: true,
variableName: 'myFont',
loaderContext: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Invalid declaration prop: \`src\`"`
)
})
test('Empty src array', async () => {
await expect(
loader({
functionName: '',
data: [{ src: [] }],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isDev: false,
isServer: true,
variableName: 'myFont',
loaderContext: {} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unexpected empty \`src\` array."`
)
})
test('Invalid weight in array', async () => {
await expect(
loader({
functionName: '',
data: [
{
src: [
{ path: './font1.woff2', weight: 'normal' },
{ path: './font2.woff2', weight: 'normal' },
{ path: './font3.woff2', weight: '400' },
{ path: './font3.woff2', weight: 'abc' },
],
},
],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isDev: false,
isServer: true,
variableName: 'myFont',
loaderContext: {
fs: { readFile: (path, cb) => cb(null, path) },
} as any,
} as any)
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid weight value in src array: \`abc\`.
Expected \`normal\`, \`bold\` or a number."
`)
})
test('Invalid variable weight in array', async () => {
await expect(
loader({
functionName: '',
data: [
{
src: [
{ path: './font1.woff2', weight: 'normal bold' },
{ path: './font2.woff2', weight: '400 bold' },
{ path: './font3.woff2', weight: 'normal 700' },
{ path: './font4.woff2', weight: '100 abc' },
],
},
],
config: {},
emitFontFile: jest.fn(),
resolve: jest.fn(),
isDev: false,
isServer: true,
variableName: 'myFont',
loaderContext: {
fs: { readFile: (path, cb) => cb(null, path) },
} as any,
})
).rejects.toThrowErrorMatchingInlineSnapshot(`
"Invalid weight value in src array: \`100 abc\`.
Expected \`normal\`, \`bold\` or a number."
`)
})
})
}) })
// @ts-ignore // @ts-ignore
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import fontFromBuffer from '../fontkit' let fontFromBuffer: any
try {
const mod = require('../fontkit').default
fontFromBuffer = mod.default || mod
} catch {}
import type { AdjustFontFallback, FontLoader } from 'next/font' import type { AdjustFontFallback, FontLoader } from 'next/font'
import { promisify } from 'util' import { promisify } from 'util'
import { validateData } from './utils'
import { calculateFallbackFontValues } from '../utils'
import { pickFontFileForFallbackGeneration } from './pick-font-file-for-fallback-generation' import { pickFontFileForFallbackGeneration } from './pick-font-file-for-fallback-generation'
import { getFallbackMetricsFromFontFile } from './get-fallback-metrics-from-font-file'
import { validateLocalFontFunctionCall } from './validate-local-font-function-call'
const nextFontLocalFontLoader: FontLoader = async ({ const nextFontLocalFontLoader: FontLoader = async ({
functionName, functionName,
...@@ -26,7 +30,7 @@ const nextFontLocalFontLoader: FontLoader = async ({ ...@@ -26,7 +30,7 @@ const nextFontLocalFontLoader: FontLoader = async ({
declarations, declarations,
weight: defaultWeight, weight: defaultWeight,
style: defaultStyle, style: defaultStyle,
} = validateData(functionName, data[0]) } = validateLocalFontFunctionCall(functionName, data[0])
// Load all font files and emit them to the .next output directory // Load all font files and emit them to the .next output directory
// Also generate a @font-face CSS for each font file // Also generate a @font-face CSS for each font file
...@@ -45,7 +49,7 @@ const nextFontLocalFontLoader: FontLoader = async ({ ...@@ -45,7 +49,7 @@ const nextFontLocalFontLoader: FontLoader = async ({
// The data is used to calculate the fallback font override values. // The data is used to calculate the fallback font override values.
let fontMetadata: any let fontMetadata: any
try { try {
fontMetadata = fontFromBuffer(fileBuffer) fontMetadata = fontFromBuffer?.(fileBuffer)
} catch (e) { } catch (e) {
console.error(`Failed to load font file: ${resolved}\n${e}`) console.error(`Failed to load font file: ${resolved}\n${e}`)
} }
...@@ -85,7 +89,7 @@ const nextFontLocalFontLoader: FontLoader = async ({ ...@@ -85,7 +89,7 @@ const nextFontLocalFontLoader: FontLoader = async ({
if (adjustFontFallback !== false) { if (adjustFontFallback !== false) {
const fallbackFontFile = pickFontFileForFallbackGeneration(fontFiles) const fallbackFontFile = pickFontFileForFallbackGeneration(fontFiles)
if (fallbackFontFile.fontMetadata) { if (fallbackFontFile.fontMetadata) {
adjustFontFallbackMetrics = calculateFallbackFontValues( adjustFontFallbackMetrics = getFallbackMetricsFromFontFile(
fallbackFontFile.fontMetadata, fallbackFontFile.fontMetadata,
adjustFontFallback === 'Times New Roman' ? 'serif' : 'sans-serif' adjustFontFallback === 'Times New Roman' ? 'serif' : 'sans-serif'
) )
......
...@@ -113,4 +113,32 @@ describe('pickFontFileForFallbackGeneration', () => { ...@@ -113,4 +113,32 @@ describe('pickFontFileForFallbackGeneration', () => {
]) ])
).toEqual({ weight: '400', style: 'normal' }) ).toEqual({ weight: '400', style: 'normal' })
}) })
it('should error on invalid weight in array', async () => {
expect(() =>
pickFontFileForFallbackGeneration([
{ path: './font1.woff2', weight: 'normal bold' },
{ path: './font2.woff2', weight: '400 bold' },
{ path: './font3.woff2', weight: 'normal 700' },
{ path: './font4.woff2', weight: '100 abc' },
])
).toThrowErrorMatchingInlineSnapshot(`
"Invalid weight value in src array: \`100 abc\`.
Expected \`normal\`, \`bold\` or a number."
`)
})
test('Invalid variable weight in array', async () => {
expect(() =>
pickFontFileForFallbackGeneration([
{ path: './font1.woff2', weight: 'normal bold' },
{ path: './font2.woff2', weight: '400 bold' },
{ path: './font3.woff2', weight: 'normal 700' },
{ path: './font4.woff2', weight: '100 abc' },
])
).toThrowErrorMatchingInlineSnapshot(`
"Invalid weight value in src array: \`100 abc\`.
Expected \`normal\`, \`bold\` or a number."
`)
})
}) })
import { nextFontError } from '../utils' import { nextFontError } from '../next-font-error'
const NORMAL_WEIGHT = 400 const NORMAL_WEIGHT = 400
const BOLD_WEIGHT = 700 const BOLD_WEIGHT = 700
......
import { validateLocalFontFunctionCall } from './validate-local-font-function-call'
describe('validateLocalFontFunctionCall', () => {
test('Not using default export', async () => {
expect(() =>
validateLocalFontFunctionCall('Named', {})
).toThrowErrorMatchingInlineSnapshot(
`"next/font/local has no named exports"`
)
})
test('Missing src', async () => {
expect(() =>
validateLocalFontFunctionCall('', {})
).toThrowErrorMatchingInlineSnapshot(`"Missing required \`src\` property"`)
})
test('Invalid file extension', async () => {
expect(() =>
validateLocalFontFunctionCall('', { src: './font/font-file.abc' })
).toThrowErrorMatchingInlineSnapshot(
`"Unexpected file \`./font/font-file.abc\`"`
)
})
test('Invalid display value', async () => {
expect(() =>
validateLocalFontFunctionCall('', {
src: './font-file.woff2',
display: 'invalid',
})
).toThrowErrorMatchingInlineSnapshot(`
"Invalid display value \`invalid\`.
Available display values: \`auto\`, \`block\`, \`swap\`, \`fallback\`, \`optional\`"
`)
})
test('Invalid declaration', async () => {
expect(() =>
validateLocalFontFunctionCall('', {
src: './font-file.woff2',
declarations: [{ prop: 'src', value: '/hello.woff2' }],
})
).toThrowErrorMatchingInlineSnapshot(`"Invalid declaration prop: \`src\`"`)
})
test('Empty src array', async () => {
expect(() =>
validateLocalFontFunctionCall('', {
src: [],
})
).toThrowErrorMatchingInlineSnapshot(`"Unexpected empty \`src\` array."`)
})
})
import { nextFontError } from '../utils' import { allowedDisplayValues } from '../constants'
import { formatAvailableValues } from '../format-available-values'
const allowedDisplayValues = ['auto', 'block', 'swap', 'fallback', 'optional'] import { nextFontError } from '../next-font-error'
const formatValues = (values: string[]) =>
values.map((val) => `\`${val}\``).join(', ')
const extToFormat = { const extToFormat = {
woff: 'woff', woff: 'woff',
...@@ -30,7 +27,14 @@ type FontOptions = { ...@@ -30,7 +27,14 @@ type FontOptions = {
adjustFontFallback?: string | false adjustFontFallback?: string | false
declarations?: Array<{ prop: string; value: string }> declarations?: Array<{ prop: string; value: string }>
} }
export function validateData(functionName: string, fontData: any): FontOptions {
/**
* Validate the data recieved from next-swc next_font_loaders on next/font/local calls
*/
export function validateLocalFontFunctionCall(
functionName: string,
fontData: any
): FontOptions {
if (functionName) { if (functionName) {
nextFontError(`next/font/local has no named exports`) nextFontError(`next/font/local has no named exports`)
} }
...@@ -48,7 +52,7 @@ export function validateData(functionName: string, fontData: any): FontOptions { ...@@ -48,7 +52,7 @@ export function validateData(functionName: string, fontData: any): FontOptions {
if (!allowedDisplayValues.includes(display)) { if (!allowedDisplayValues.includes(display)) {
nextFontError( nextFontError(
`Invalid display value \`${display}\`.\nAvailable display values: ${formatValues( `Invalid display value \`${display}\`.\nAvailable display values: ${formatAvailableValues(
allowedDisplayValues allowedDisplayValues
)}` )}`
) )
......
/**
* Throw NextFontError error. Used by the WellKnownErrorsPlugin to format errors thrown by next/font.
*/
export function nextFontError(message: string): never {
const err = new Error(message)
err.name = 'NextFontError'
throw err
}
This diff is collapsed.
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