-
Notifications
You must be signed in to change notification settings - Fork 26k
/
loader.ts
180 lines (164 loc) · 4.94 KB
/
loader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import type { AdjustFontFallback, FontLoader } from 'next/font'
// @ts-ignore
import { calculateSizeAdjustValues } from 'next/dist/server/font-utils'
// @ts-ignore
import * as Log from 'next/dist/build/output/log'
// @ts-ignore
import chalk from 'next/dist/compiled/chalk'
// @ts-ignore
import {
fetchCSSFromGoogleFonts,
fetchFontFile,
getFontAxes,
getUrl,
validateData,
} from './utils'
const cssCache = new Map<string, Promise<string>>()
const fontCache = new Map<string, any>()
// regexp is based on https://github.com/sindresorhus/escape-string-regexp
const reHasRegExp = /[|\\{}()[\]^$+*?.-]/
const reReplaceRegExp = /[|\\{}()[\]^$+*?.-]/g
function escapeStringRegexp(str: string) {
// see also: https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/escapeRegExp.js#L23
if (reHasRegExp.test(str)) {
return str.replace(reReplaceRegExp, '\\$&')
}
return str
}
const downloadGoogleFonts: FontLoader = async ({
functionName,
data,
config,
emitFontFile,
isServer,
}) => {
const subsets = config?.subsets || []
const {
fontFamily,
weights,
styles,
display,
preload,
selectedVariableAxes,
fallback,
adjustFontFallback,
variable,
subsets: callSubsets,
} = validateData(functionName, data)
if (isServer && preload && !callSubsets && !config?.subsets) {
Log.warn(
`The ${chalk.bold('@next/font/google')} font ${chalk.bold(
fontFamily
)} has no selected subsets. Please specify subsets in the function call or in your ${chalk.bold(
'next.config.js'
)}, otherwise no fonts will be preloaded. Read more: https://nextjs.org/docs/messages/google-fonts-missing-subsets`
)
}
const fontAxes = getFontAxes(
fontFamily,
weights,
styles,
selectedVariableAxes
)
const url = getUrl(fontFamily, fontAxes, display)
let cachedCssRequest = cssCache.get(url)
const fontFaceDeclarations =
cachedCssRequest ?? (await fetchCSSFromGoogleFonts(url, fontFamily))
if (!cachedCssRequest) {
cssCache.set(url, fontFaceDeclarations)
} else {
cssCache.delete(url)
}
// Find font files to download
const fontFiles: Array<{
googleFontFileUrl: string
preloadFontFile: boolean
}> = []
let currentSubset = ''
for (const line of fontFaceDeclarations.split('\n')) {
// Each @font-face has the subset above it in a comment
const newSubset = /\/\* (.+?) \*\//.exec(line)?.[1]
if (newSubset) {
currentSubset = newSubset
} else {
const googleFontFileUrl = /src: url\((.+?)\)/.exec(line)?.[1]
if (
googleFontFileUrl &&
!fontFiles.some(
(foundFile) => foundFile.googleFontFileUrl === googleFontFileUrl
)
) {
fontFiles.push({
googleFontFileUrl,
preloadFontFile:
!!preload && (callSubsets ?? subsets).includes(currentSubset),
})
}
}
}
// Download font files
const downloadedFiles = await Promise.all(
fontFiles.map(async ({ googleFontFileUrl, preloadFontFile }) => {
let cachedFontRequest = fontCache.get(googleFontFileUrl)
const fontFileBuffer =
cachedFontRequest ?? (await fetchFontFile(googleFontFileUrl))
if (!cachedFontRequest) {
fontCache.set(googleFontFileUrl, fontFileBuffer)
} else {
fontCache.delete(googleFontFileUrl)
}
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(googleFontFileUrl)![1]
// Emit font file to .next/static/fonts
const selfHostedFileUrl = emitFontFile(
fontFileBuffer,
ext,
preloadFontFile
)
return {
googleFontFileUrl,
selfHostedFileUrl,
}
})
)
// Replace @font-face sources with self-hosted files
let updatedCssResponse = fontFaceDeclarations
for (const { googleFontFileUrl, selfHostedFileUrl } of downloadedFiles) {
updatedCssResponse = updatedCssResponse.replace(
new RegExp(escapeStringRegexp(googleFontFileUrl), 'g'),
selfHostedFileUrl
)
}
// Add fallback font
let adjustFontFallbackMetrics: AdjustFontFallback | undefined
if (adjustFontFallback) {
try {
const { ascent, descent, lineGap, fallbackFont, sizeAdjust } =
calculateSizeAdjustValues(
require('next/dist/server/google-font-metrics.json')[fontFamily]
)
adjustFontFallbackMetrics = {
fallbackFont,
ascentOverride: `${ascent}%`,
descentOverride: `${descent}%`,
lineGapOverride: `${lineGap}%`,
sizeAdjust: `${sizeAdjust}%`,
}
} catch {
Log.error(
`Failed to find font override values for font \`${fontFamily}\``
)
}
}
return {
css: updatedCssResponse,
fallbackFonts: fallback,
weight:
weights.length === 1 && weights[0] !== 'variable'
? weights[0]
: undefined,
style: styles.length === 1 ? styles[0] : undefined,
variable,
adjustFontFallback: adjustFontFallbackMetrics,
}
}
export default downloadGoogleFonts