forked from vercel/next.js
/
utils.ts
283 lines (256 loc) · 7.49 KB
/
utils.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import fs from 'fs'
// @ts-ignore
import fetch from 'next/dist/compiled/node-fetch'
import fontData from './font-data.json'
const allowedDisplayValues = ['auto', 'block', 'swap', 'fallback', 'optional']
const formatValues = (values: string[]) =>
values.map((val) => `\`${val}\``).join(', ')
type FontOptions = {
fontFamily: string
weights: string[]
styles: string[]
display: string
preload: boolean
selectedVariableAxes?: string[]
fallback?: string[]
adjustFontFallback: boolean
variable?: string
subsets?: string[]
}
export function validateData(functionName: string, data: any): FontOptions {
let {
weight,
style,
display = 'optional',
preload = true,
axes,
fallback,
adjustFontFallback = true,
variable,
subsets,
} = data[0] || ({} as any)
if (functionName === '') {
throw new Error(`@next/font/google has no default export`)
}
const fontFamily = functionName.replace(/_/g, ' ')
const fontFamilyData = (fontData as any)[fontFamily]
const fontWeights = fontFamilyData?.weights
if (!fontWeights) {
throw new Error(`Unknown font \`${fontFamily}\``)
}
const fontStyles = fontFamilyData.styles
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 {
throw new Error(
`Missing weight for font \`${fontFamily}\`.\nAvailable weights: ${formatValues(
fontWeights
)}`
)
}
}
if (weights.length > 1 && weights.includes('variable')) {
throw new Error(
`Unexpected \`variable\` in weight array for font \`${fontFamily}\`. You only need \`variable\`, it includes all available weights.`
)
}
weights.forEach((selectedWeight) => {
if (!fontWeights.includes(selectedWeight)) {
throw new Error(
`Unknown weight \`${selectedWeight}\` for font \`${fontFamily}\`.\nAvailable weights: ${formatValues(
fontWeights
)}`
)
}
})
if (styles.length === 0) {
if (fontStyles.length === 1) {
styles.push(fontStyles[0])
} else {
styles.push('normal')
}
}
styles.forEach((selectedStyle) => {
if (!fontStyles.includes(selectedStyle)) {
throw new Error(
`Unknown style \`${selectedStyle}\` for font \`${fontFamily}\`.\nAvailable styles: ${formatValues(
fontStyles
)}`
)
}
})
if (!allowedDisplayValues.includes(display)) {
throw new Error(
`Invalid display value \`${display}\` for font \`${fontFamily}\`.\nAvailable display values: ${formatValues(
allowedDisplayValues
)}`
)
}
if (weights[0] !== 'variable' && axes) {
throw new Error('Axes can only be defined for variable fonts')
}
return {
fontFamily,
weights,
styles,
display,
preload,
selectedVariableAxes: axes,
fallback,
adjustFontFallback,
variable,
subsets,
}
}
export function getUrl(
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][]> = []
for (const wgth of axes.wght) {
if (axes.ital.length === 0) {
variants.push([['wght', wgth], ...(axes.variableAxes ?? [])])
} else {
for (const ital of axes.ital) {
variants.push([
['ital', ital],
['wght', wgth],
...(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
})
})
}
return `https://fonts.googleapis.com/css2?family=${fontFamily.replace(
/ /g,
'+'
)}:${variants[0].map(([key]) => key).join(',')}@${variants
.map((variant) => variant.map(([, val]) => val).join(','))
.sort()
.join(';')}&display=${display}`
}
export async function fetchCSSFromGoogleFonts(url: string, fontFamily: string) {
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) {
throw new Error('Missing mocked response for URL: ' + url)
}
}
let cssResponse
if (mockedResponse) {
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) {
throw new Error(`Failed to fetch font \`${fontFamily}\`.\nURL: ${url}`)
}
cssResponse = await res.text()
}
return cssResponse
}
export async function fetchFontFile(url: string) {
if (process.env.NEXT_FONT_GOOGLE_MOCKED_RESPONSES) {
if (url.startsWith('/')) {
return fs.readFileSync(url)
}
return Buffer.from(url)
}
const arrayBuffer = await fetch(url).then((r: any) => r.arrayBuffer())
return Buffer.from(arrayBuffer)
}
export function getFontAxes(
fontFamily: string,
weights: string[],
styles: string[],
selectedVariableAxes?: string[]
): {
wght: string[]
ital: string[]
variableAxes?: [string, string][]
} {
const allAxes: Array<{ tag: string; min: number; max: number }> = (
fontData as any
)[fontFamily].axes
const hasItalic = styles.includes('italic')
const hasNormal = styles.includes('normal')
const ital = hasItalic ? [...(hasNormal ? ['0'] : []), '1'] : []
// Weights will always contain one element if it's a variable font
if (weights[0] === 'variable') {
if (selectedVariableAxes) {
const defineAbleAxes: string[] = allAxes
.map(({ tag }) => tag)
.filter((tag) => tag !== 'wght')
if (defineAbleAxes.length === 0) {
throw new Error(`Font \`${fontFamily}\` has no definable \`axes\``)
}
if (!Array.isArray(selectedVariableAxes)) {
throw new Error(
`Invalid axes value for font \`${fontFamily}\`, expected an array of axes.\nAvailable axes: ${formatValues(
defineAbleAxes
)}`
)
}
selectedVariableAxes.forEach((key) => {
if (!defineAbleAxes.some((tag) => tag === key)) {
throw new Error(
`Invalid axes value \`${key}\` for font \`${fontFamily}\`.\nAvailable axes: ${formatValues(
defineAbleAxes
)}`
)
}
})
}
let weightAxis: string
const variableAxes: [string, string][] = []
for (const { tag, min, max } of allAxes) {
if (tag === 'wght') {
weightAxis = `${min}..${max}`
} else if (selectedVariableAxes?.includes(tag)) {
variableAxes.push([tag, `${min}..${max}`])
}
}
return {
wght: [weightAxis!],
ital,
variableAxes,
}
} else {
return {
ital,
wght: weights,
}
}
}