@hamur/fonts 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/src/index.js +2472 -0
  4. package/dist/src/providers/index.js +386 -0
  5. package/dist/src/server/index.js +22 -0
  6. package/dist/types/src/build/cache.d.ts +17 -0
  7. package/dist/types/src/build/data.d.ts +19 -0
  8. package/dist/types/src/build/fallbacks.d.ts +49 -0
  9. package/dist/types/src/build/files.d.ts +7 -0
  10. package/dist/types/src/build/global.d.ts +3 -0
  11. package/dist/types/src/build/preload.d.ts +25 -0
  12. package/dist/types/src/build/providers.d.ts +5 -0
  13. package/dist/types/src/build/public-url.d.ts +2 -0
  14. package/dist/types/src/build/scan.d.ts +6 -0
  15. package/dist/types/src/build/subset.d.ts +7 -0
  16. package/dist/types/src/index.d.ts +18 -0
  17. package/dist/types/src/inject.d.ts +21 -0
  18. package/dist/types/src/module.d.ts +3 -0
  19. package/dist/types/src/options.d.ts +46 -0
  20. package/dist/types/src/providers/adobe.d.ts +2 -0
  21. package/dist/types/src/providers/bunny.d.ts +4 -0
  22. package/dist/types/src/providers/css.d.ts +27 -0
  23. package/dist/types/src/providers/fontshare.d.ts +4 -0
  24. package/dist/types/src/providers/fontsource.d.ts +18 -0
  25. package/dist/types/src/providers/google.d.ts +4 -0
  26. package/dist/types/src/providers/googleicons.d.ts +2 -0
  27. package/dist/types/src/providers/index.d.ts +3 -0
  28. package/dist/types/src/providers/local.d.ts +17 -0
  29. package/dist/types/src/providers/npm.d.ts +5 -0
  30. package/dist/types/src/resolve.d.ts +32 -0
  31. package/dist/types/src/runtime/global.d.ts +3 -0
  32. package/dist/types/src/scan.d.ts +29 -0
  33. package/dist/types/src/server/data.d.ts +11 -0
  34. package/dist/types/src/server/door.d.ts +2 -0
  35. package/dist/types/src/server/index.d.ts +9 -0
  36. package/dist/types/src/server/preload.d.ts +2 -0
  37. package/dist/types/src/subset/cmap.d.ts +2 -0
  38. package/dist/types/src/subset/glyf.d.ts +15 -0
  39. package/dist/types/src/subset/sfnt.d.ts +21 -0
  40. package/dist/types/src/subset/woff2.d.ts +7 -0
  41. package/dist/types/src/types.d.ts +71 -0
  42. package/package.json +32 -4
  43. package/src/build/cache.ts +50 -0
  44. package/src/build/data.ts +145 -0
  45. package/src/build/fallbacks.ts +384 -0
  46. package/src/build/files.ts +102 -0
  47. package/src/build/global.ts +14 -0
  48. package/src/build/preload.ts +104 -0
  49. package/src/build/providers.ts +19 -0
  50. package/src/build/public-url.ts +21 -0
  51. package/src/build/scan.ts +172 -0
  52. package/src/build/subset.ts +74 -0
  53. package/src/env.d.ts +13 -0
  54. package/src/index.ts +25 -0
  55. package/src/inject.ts +59 -0
  56. package/src/module.ts +29 -0
  57. package/src/options.ts +375 -0
  58. package/src/providers/adobe.ts +18 -0
  59. package/src/providers/bunny.ts +35 -0
  60. package/src/providers/css.ts +154 -0
  61. package/src/providers/fontshare.ts +37 -0
  62. package/src/providers/fontsource.ts +53 -0
  63. package/src/providers/google.ts +31 -0
  64. package/src/providers/googleicons.ts +20 -0
  65. package/src/providers/index.ts +17 -0
  66. package/src/providers/local.ts +141 -0
  67. package/src/providers/npm.ts +96 -0
  68. package/src/resolve.ts +134 -0
  69. package/src/runtime/global.ts +5 -0
  70. package/src/scan.ts +275 -0
  71. package/src/server/data.ts +20 -0
  72. package/src/server/door.ts +13 -0
  73. package/src/server/index.ts +9 -0
  74. package/src/server/preload.ts +50 -0
  75. package/src/subset/cmap.ts +79 -0
  76. package/src/subset/glyf.ts +93 -0
  77. package/src/subset/sfnt.ts +196 -0
  78. package/src/subset/woff2.ts +68 -0
  79. package/src/types.ts +71 -0
package/src/options.ts ADDED
@@ -0,0 +1,375 @@
1
+ import { isAbsolute, resolve } from "node:path"
2
+ import { SYSTEM_METRICS } from "./build/fallbacks.ts"
3
+ import type { FontDefaults, FontDisplay, FontFormat, FontProvider, FontStyle, FontWeight } from "./types.ts"
4
+ import { DiagnosticError } from "hamur/kit"
5
+
6
+ export const BUILT_IN_PROVIDERS = ["local", "npm", "google", "bunny", "fontshare", "fontsource", "googleicons", "adobe"]
7
+ export const FALLBACK_SYSTEM_FONTS = Object.keys(SYSTEM_METRICS)
8
+
9
+ const OPTION_KEYS = [
10
+ "enabled",
11
+ "priority",
12
+ "providers",
13
+ "defaults",
14
+ "families",
15
+ "processCSSVariables",
16
+ "fallbacks",
17
+ "localSources",
18
+ "cache",
19
+ "throwOnError",
20
+ ]
21
+ const DEFAULT_KEYS = ["weights", "styles", "subsets", "display", "formats", "preload"]
22
+ const FAMILY_KEYS = [
23
+ "name",
24
+ "provider",
25
+ "src",
26
+ ...DEFAULT_KEYS,
27
+ "unicodeRange",
28
+ "stretch",
29
+ "featureSettings",
30
+ "variationSettings",
31
+ "glyphs",
32
+ "global",
33
+ ]
34
+ const STYLES = ["normal", "italic", "oblique"]
35
+ const DISPLAYS = ["auto", "block", "swap", "fallback", "optional"]
36
+ const FORMATS = ["woff2", "woff", "ttf", "otf"]
37
+
38
+ const DEFAULTS: FontDefaults = {
39
+ weights: [400],
40
+ styles: ["normal"],
41
+ subsets: ["latin", "latin-ext"],
42
+ display: "swap",
43
+ formats: ["woff2"],
44
+ preload: true,
45
+ }
46
+ const FALLBACKS: Record<string, string[]> = {
47
+ "sans-serif": ["Arial"],
48
+ serif: ["Times New Roman"],
49
+ monospace: ["Courier New"],
50
+ }
51
+
52
+ export interface ResolvedFamily extends FontDefaults {
53
+ name: string
54
+ provider?: string
55
+ /** Absolute paths. */
56
+ src?: string[]
57
+ /** The family lists its own `weights`, not the defaults'. */
58
+ ownWeights: boolean
59
+ unicodeRange?: string
60
+ stretch?: string
61
+ featureSettings?: string
62
+ variationSettings?: string
63
+ glyphs?: string
64
+ global: boolean
65
+ }
66
+
67
+ export interface ResolvedFontsOptions {
68
+ enabled: boolean
69
+ priority: string[]
70
+ /** Built-in providers set to `false`. */
71
+ disabled: Set<string>
72
+ /** `providers.<name>.options`. */
73
+ providerOptions: Record<string, Record<string, unknown>>
74
+ /** The default export of each file of `providers`, by key. */
75
+ custom: Record<string, FontProvider>
76
+ defaults: FontDefaults
77
+ families: ResolvedFamily[]
78
+ processCSSVariables: boolean | "font-prefixed-only"
79
+ fallbacks: false | Record<string, string[]>
80
+ localSources: boolean
81
+ cache: boolean
82
+ throwOnError: boolean
83
+ }
84
+
85
+ export interface OptionsContext {
86
+ rootDir: string
87
+ exists(path: string): boolean
88
+ /** The default export of the file. */
89
+ load(file: string): Promise<unknown>
90
+ }
91
+
92
+ const isObject = (value: unknown): value is Record<string, unknown> =>
93
+ typeof value === "object" && value !== null && !Array.isArray(value)
94
+ const shown = (value: unknown): string =>
95
+ typeof value === "function" ? "a function" : (JSON.stringify(value) ?? String(value))
96
+ const list = (values: readonly string[]): string => values.join(", ")
97
+
98
+ function fail(message: string): never {
99
+ throw new DiagnosticError("HAMUR_E5701", message)
100
+ }
101
+
102
+ /** A path of the config: a `package.json` `imports` key, an absolute path or a path from the app root. */
103
+ export function resolveConfigPath(ctx: Pick<OptionsContext, "rootDir">, path: string): string {
104
+ if (path.startsWith("#")) {
105
+ try {
106
+ return Bun.resolveSync(path, ctx.rootDir)
107
+ } catch {
108
+ return path
109
+ }
110
+ }
111
+ return isAbsolute(path) ? path : resolve(ctx.rootDir, path)
112
+ }
113
+
114
+ const isCssWeight = (value: unknown): boolean => {
115
+ const inRange = (n: number) => Number.isFinite(n) && n >= 1 && n <= 1000
116
+ if (typeof value === "number") return inRange(value)
117
+ if (typeof value !== "string") return false
118
+ const parts = value.split(" ")
119
+ if (parts.length > 2 || !parts.every((part) => /^\d+(?:\.\d+)?$/.test(part))) return false
120
+ return parts.every((part) => inRange(Number(part)))
121
+ }
122
+
123
+ function oneOf<T extends string>(value: unknown, allowed: readonly string[], at: string, what: string): T {
124
+ if (typeof value !== "string" || !allowed.includes(value))
125
+ fail(`${at} ${shown(value)} is not ${what} (${list(allowed)})`)
126
+ return value as T
127
+ }
128
+
129
+ function checkBoolean(value: unknown, at: string): boolean {
130
+ if (typeof value !== "boolean") fail(`${at} must be a boolean (got ${shown(value)})`)
131
+ return value
132
+ }
133
+
134
+ /** The keys of `FontDefaults` in `input`, checked; `at` is `fonts.defaults` or `fonts.families[<i>]`. */
135
+ function resolveDefaultKeys(input: Record<string, unknown>, at: string): Partial<FontDefaults> {
136
+ const out: Partial<FontDefaults> = {}
137
+ if (input.weights !== undefined) {
138
+ if (!Array.isArray(input.weights))
139
+ fail(`${at}.weights must be an array of CSS weights (got ${shown(input.weights)})`)
140
+ input.weights.forEach((weight, i) => {
141
+ if (!isCssWeight(weight))
142
+ fail(`${at}.weights[${i}] must be a CSS weight, 1 to 1000, or a range such as "100 900" (got ${shown(weight)})`)
143
+ })
144
+ out.weights = [...input.weights] as FontWeight[]
145
+ }
146
+ if (input.styles !== undefined) {
147
+ if (!Array.isArray(input.styles)) fail(`${at}.styles must be an array of styles (got ${shown(input.styles)})`)
148
+ out.styles = input.styles.map((style, i) => oneOf<FontStyle>(style, STYLES, `${at}.styles[${i}]`, "a style"))
149
+ }
150
+ if (input.subsets !== undefined) {
151
+ if (!Array.isArray(input.subsets))
152
+ fail(`${at}.subsets must be an array of subset names (got ${shown(input.subsets)})`)
153
+ if (!input.subsets.length) fail(`${at}.subsets must list at least one subset`)
154
+ input.subsets.forEach((subset, i) => {
155
+ if (typeof subset !== "string" || subset === "")
156
+ fail(`${at}.subsets[${i}] must be a subset name (got ${shown(subset)})`)
157
+ })
158
+ out.subsets = [...(input.subsets as string[])]
159
+ }
160
+ if (input.display !== undefined)
161
+ out.display = oneOf<FontDisplay>(input.display, DISPLAYS, `${at}.display`, "a font-display value")
162
+ if (input.formats !== undefined) {
163
+ if (!Array.isArray(input.formats))
164
+ fail(`${at}.formats must be an array of font formats (got ${shown(input.formats)})`)
165
+ out.formats = input.formats.map((format, i) =>
166
+ oneOf<FontFormat>(format, FORMATS, `${at}.formats[${i}]`, "a font format"),
167
+ )
168
+ }
169
+ if (input.preload !== undefined) out.preload = checkBoolean(input.preload, `${at}.preload`)
170
+ return out
171
+ }
172
+
173
+ async function resolveProviders(
174
+ input: unknown,
175
+ ctx: OptionsContext,
176
+ ): Promise<Pick<ResolvedFontsOptions, "disabled" | "providerOptions" | "custom">> {
177
+ const out = {
178
+ disabled: new Set<string>(),
179
+ providerOptions: {} as Record<string, Record<string, unknown>>,
180
+ custom: {} as Record<string, FontProvider>,
181
+ }
182
+ if (input === undefined) return out
183
+ if (!isObject(input)) return fail(`fonts.providers must be an object (got ${shown(input)})`)
184
+ for (const [name, value] of Object.entries(input)) {
185
+ const at = `fonts.providers.${name}`
186
+ if (value === false) {
187
+ out.disabled.add(name)
188
+ } else if (typeof value === "string") {
189
+ const file = resolveConfigPath(ctx, value)
190
+ if (!ctx.exists(file)) fail(`${at} ${JSON.stringify(value)} does not exist`)
191
+ let exported: unknown
192
+ try {
193
+ exported = await ctx.load(file)
194
+ } catch (error) {
195
+ fail(
196
+ `${at} ${JSON.stringify(value)} could not be loaded: ${error instanceof Error ? error.message : String(error)}`,
197
+ )
198
+ }
199
+ if (!isObject(exported) || typeof exported.name !== "string" || typeof exported.resolveFont !== "function") {
200
+ fail(`${at} ${JSON.stringify(value)} must default-export { name, resolveFont } (got ${shown(exported)})`)
201
+ }
202
+ if (exported.name !== name)
203
+ fail(
204
+ `${at} ${JSON.stringify(value)} exports name ${JSON.stringify(exported.name)}; the key and the name must match`,
205
+ )
206
+ out.custom[name] = exported as unknown as FontProvider
207
+ } else if (isObject(value) && Object.keys(value).every((key) => key === "options")) {
208
+ const options = value.options
209
+ if (options !== undefined && !isObject(options)) fail(`${at}.options must be an object (got ${shown(options)})`)
210
+ if (options) out.providerOptions[name] = options
211
+ if (name === "adobe" && (typeof options?.id !== "string" || options.id === ""))
212
+ fail("fonts.providers.adobe.options.id is required (the Adobe Fonts kit id)")
213
+ } else {
214
+ fail(`${at} must be false, a file path or { options } (got ${shown(value)})`)
215
+ }
216
+ }
217
+ return out
218
+ }
219
+
220
+ function resolveFallbacks(input: unknown): false | Record<string, string[]> {
221
+ if (input === undefined) return { ...FALLBACKS }
222
+ if (input === false) return false
223
+ if (!isObject(input))
224
+ return fail(`fonts.fallbacks must be false or an object of system font lists (got ${shown(input)})`)
225
+ const out = { ...FALLBACKS }
226
+ for (const [generic, fonts] of Object.entries(input)) {
227
+ if (!Array.isArray(fonts)) fail(`fonts.fallbacks.${generic} must be an array of system fonts (got ${shown(fonts)})`)
228
+ fonts.forEach((font, i) => {
229
+ if (typeof font !== "string" || !FALLBACK_SYSTEM_FONTS.includes(font))
230
+ fail(`fonts.fallbacks.${generic}[${i}] ${shown(font)} has no metrics here (${list(FALLBACK_SYSTEM_FONTS)})`)
231
+ })
232
+ out[generic] = [...(fonts as string[])]
233
+ }
234
+ return out
235
+ }
236
+
237
+ function resolveFamilies(
238
+ input: unknown,
239
+ defaults: FontDefaults,
240
+ providerNames: Set<string>,
241
+ ctx: OptionsContext,
242
+ adobeId: boolean,
243
+ ): ResolvedFamily[] {
244
+ if (input === undefined) return []
245
+ if (!Array.isArray(input)) return fail(`fonts.families must be an array (got ${shown(input)})`)
246
+ const seen = new Set<string>()
247
+ return input.map((entry: unknown, index) => {
248
+ const at = `fonts.families[${index}]`
249
+ if (!isObject(entry)) return fail(`${at} must be an object (got ${shown(entry)})`)
250
+ for (const key of Object.keys(entry))
251
+ if (!FAMILY_KEYS.includes(key)) fail(`${at}.${key} is not an option; use ${list(FAMILY_KEYS)}`)
252
+ const { name } = entry
253
+ if (typeof name !== "string" || name.trim() === "")
254
+ fail(`${at}.name must be a non-empty string (got ${shown(name)})`)
255
+ const key = name.trim().toLowerCase()
256
+ if (seen.has(key)) fail(`${at} ${JSON.stringify(name)} is listed twice; merge the entries`)
257
+ seen.add(key)
258
+ if (
259
+ entry.provider !== undefined &&
260
+ (typeof entry.provider !== "string" || (entry.provider !== "none" && !providerNames.has(entry.provider)))
261
+ ) {
262
+ fail(`${at}.provider ${shown(entry.provider)} is not "none", a built-in provider or a key of fonts.providers`)
263
+ }
264
+ if (entry.provider === "adobe" && !adobeId)
265
+ fail("fonts.providers.adobe.options.id is required (the Adobe Fonts kit id)")
266
+ if (entry.src !== undefined && entry.provider !== undefined)
267
+ fail(`${at} sets src and provider; src means no provider is asked`)
268
+ let src: string[] | undefined
269
+ if (entry.src !== undefined) {
270
+ const given = typeof entry.src === "string" ? [entry.src] : entry.src
271
+ if (!Array.isArray(given) || !given.length || given.some((file) => typeof file !== "string" || file === "")) {
272
+ fail(`${at}.src must be a file path or a list of file paths (got ${shown(entry.src)})`)
273
+ }
274
+ src = (given as string[]).map((file) => {
275
+ const path = resolveConfigPath(ctx, file)
276
+ if (!ctx.exists(path)) fail(`${at}.src ${JSON.stringify(file)} does not exist`)
277
+ return path
278
+ })
279
+ }
280
+ if (entry.glyphs !== undefined && typeof entry.glyphs !== "string")
281
+ fail(`${at}.glyphs must be a string (got ${shown(entry.glyphs)})`)
282
+ if (entry.global !== undefined) checkBoolean(entry.global, `${at}.global`)
283
+ for (const descriptor of ["unicodeRange", "stretch", "featureSettings", "variationSettings"]) {
284
+ if (entry[descriptor] !== undefined && typeof entry[descriptor] !== "string")
285
+ fail(`${at}.${descriptor} must be a string (got ${shown(entry[descriptor])})`)
286
+ }
287
+ const own = resolveDefaultKeys(entry, at)
288
+ if (src && own.weights && own.weights.length > src.length)
289
+ fail(
290
+ `${at}.weights lists ${own.weights.length} weights for ${src.length} src file${src.length === 1 ? "" : "s"}; list one weight per file`,
291
+ )
292
+ const text = (key: string): string | undefined =>
293
+ typeof entry[key] === "string" ? (entry[key] as string) : undefined
294
+ const optional = {
295
+ provider: text("provider"),
296
+ glyphs: text("glyphs"),
297
+ unicodeRange: text("unicodeRange"),
298
+ stretch: text("stretch"),
299
+ featureSettings: text("featureSettings"),
300
+ variationSettings: text("variationSettings"),
301
+ }
302
+ return {
303
+ ...defaults,
304
+ ...own,
305
+ name,
306
+ ownWeights: own.weights !== undefined,
307
+ global: entry.global === true,
308
+ ...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)),
309
+ ...(src ? { src } : {}),
310
+ }
311
+ })
312
+ }
313
+
314
+ /** Run after `fonts:providers`, which may add the names `priority` lists. */
315
+ export function checkPriority(priority: readonly string[], providers: Iterable<string>): void {
316
+ const known = new Set([...BUILT_IN_PROVIDERS, ...providers])
317
+ priority.forEach((name, i) => {
318
+ if (!known.has(name))
319
+ fail(
320
+ `fonts.priority[${i}] ${shown(name)} is not a provider (${list(BUILT_IN_PROVIDERS)}, or a key of fonts.providers)`,
321
+ )
322
+ })
323
+ }
324
+
325
+ /** Checks the `fonts` config key and fills in its defaults; the first wrong value throws a message naming its key. */
326
+ export async function resolveOptions(input: unknown, ctx: OptionsContext): Promise<ResolvedFontsOptions> {
327
+ const given = input ?? {}
328
+ if (!isObject(given)) return fail(`fonts must be an object (got ${shown(given)})`)
329
+ for (const key of Object.keys(given))
330
+ if (!OPTION_KEYS.includes(key)) fail(`fonts.${key} is not an option; use ${list(OPTION_KEYS)}`)
331
+ const enabled = given.enabled === undefined ? true : checkBoolean(given.enabled, "fonts.enabled")
332
+ const providers = await resolveProviders(given.providers, ctx)
333
+ const providerNames = new Set([
334
+ ...BUILT_IN_PROVIDERS,
335
+ ...Object.keys(isObject(given.providers) ? given.providers : {}),
336
+ ])
337
+ let priority = [...BUILT_IN_PROVIDERS]
338
+ if (given.priority !== undefined) {
339
+ if (!Array.isArray(given.priority))
340
+ fail(`fonts.priority must be an array of provider names (got ${shown(given.priority)})`)
341
+ given.priority.forEach((name, i) => {
342
+ if (typeof name !== "string") fail(`fonts.priority[${i}] ${shown(name)} is not a provider name`)
343
+ })
344
+ priority = [...(given.priority as string[])]
345
+ }
346
+ let defaults = DEFAULTS
347
+ if (given.defaults !== undefined) {
348
+ if (!isObject(given.defaults)) fail(`fonts.defaults must be an object (got ${shown(given.defaults)})`)
349
+ for (const key of Object.keys(given.defaults))
350
+ if (!DEFAULT_KEYS.includes(key)) fail(`fonts.defaults.${key} is not an option; use ${list(DEFAULT_KEYS)}`)
351
+ defaults = { ...DEFAULTS, ...resolveDefaultKeys(given.defaults, "fonts.defaults") }
352
+ }
353
+ const families = resolveFamilies(
354
+ given.families,
355
+ defaults,
356
+ providerNames,
357
+ ctx,
358
+ providers.providerOptions.adobe?.id !== undefined,
359
+ )
360
+ const css = given.processCSSVariables
361
+ if (css !== undefined && css !== true && css !== false && css !== "font-prefixed-only")
362
+ fail(`fonts.processCSSVariables must be true, false or "font-prefixed-only" (got ${shown(css)})`)
363
+ return {
364
+ enabled,
365
+ priority,
366
+ ...providers,
367
+ defaults,
368
+ families,
369
+ processCSSVariables: css ?? "font-prefixed-only",
370
+ fallbacks: resolveFallbacks(given.fallbacks),
371
+ localSources: given.localSources === undefined ? true : checkBoolean(given.localSources, "fonts.localSources"),
372
+ cache: given.cache === undefined ? true : checkBoolean(given.cache, "fonts.cache"),
373
+ throwOnError: given.throwOnError === undefined ? false : checkBoolean(given.throwOnError, "fonts.throwOnError"),
374
+ }
375
+ }
@@ -0,0 +1,18 @@
1
+ import type { FontProvider } from "../types.ts"
2
+ import { normalizeFamily, parseFontFaces, requestText } from "./css.ts"
3
+
4
+ export const adobe: FontProvider = {
5
+ name: "adobe",
6
+ async resolveFont(family, options) {
7
+ const id = options.options?.id
8
+ if (typeof id !== "string" || id === "") return undefined
9
+ const css = await requestText(options.fetch, `https://use.typekit.net/${encodeURIComponent(id)}.css`, {
10
+ missing: [404],
11
+ })
12
+ if (!css) return undefined
13
+ const fonts = parseFontFaces(css)
14
+ .filter((parsed) => normalizeFamily(parsed.family) === normalizeFamily(family))
15
+ .map(({ face }) => face)
16
+ return fonts.length ? { fonts } : undefined
17
+ },
18
+ }
@@ -0,0 +1,35 @@
1
+ import type { FontProvider, ResolveFontOptions } from "../types.ts"
2
+ import { keepRequested, parseFontFaces, requestText, weightRange } from "./css.ts"
3
+
4
+ /** `inter:400,400i,700`; a range asks every hundred inside it, because Bunny serves static weights. */
5
+ export function bunnyFamilyParam(family: string, options: Pick<ResolveFontOptions, "weights" | "styles">): string {
6
+ const weights = new Set<number>()
7
+ for (const weight of options.weights) {
8
+ const [low, high] = weightRange(weight)
9
+ if (low === high) weights.add(low)
10
+ else for (let at = Math.ceil(low / 100) * 100; at <= high; at += 100) weights.add(at)
11
+ }
12
+ const tokens: string[] = []
13
+ for (const weight of [...weights].sort((a, b) => a - b)) {
14
+ if (options.styles.some((style) => style !== "italic")) tokens.push(String(weight))
15
+ if (options.styles.includes("italic")) tokens.push(`${weight}i`)
16
+ }
17
+ return `${family.toLowerCase().trim().replace(/\s+/g, "-")}:${tokens.join(",")}`
18
+ }
19
+
20
+ export const bunny: FontProvider = {
21
+ name: "bunny",
22
+ async resolveFont(family, options) {
23
+ const css = await requestText(
24
+ options.fetch,
25
+ `https://fonts.bunny.net/css?family=${bunnyFamilyParam(family, options)}`,
26
+ { missing: [404] },
27
+ )
28
+ if (!css) return undefined
29
+ const fonts = keepRequested(
30
+ parseFontFaces(css).map(({ face }) => face),
31
+ options,
32
+ )
33
+ return fonts.length ? { fonts } : undefined
34
+ },
35
+ }
@@ -0,0 +1,154 @@
1
+ import type { FontFaceData, FontFormat, FontStyle, ResolveFontOptions } from "../types.ts"
2
+
3
+ export interface ParsedFace {
4
+ family: string
5
+ face: FontFaceData
6
+ }
7
+
8
+ /** The woff2-capable user agent: Google and Bunny answer by it. */
9
+ export const CHROME_UA =
10
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
11
+
12
+ const FORMATS: Record<string, FontFormat> = {
13
+ woff2: "woff2",
14
+ "woff2-variations": "woff2",
15
+ woff: "woff",
16
+ truetype: "ttf",
17
+ "truetype-variations": "ttf",
18
+ opentype: "otf",
19
+ "opentype-variations": "otf",
20
+ }
21
+
22
+ export const normalizeFamily = (name: string): string => name.toLowerCase().replace(/[\s_-]+/g, "")
23
+
24
+ function splitTop(text: string, separator: string): string[] {
25
+ const parts: string[] = []
26
+ let depth = 0
27
+ let quote = ""
28
+ let start = 0
29
+ for (let at = 0; at < text.length; at++) {
30
+ const char = text[at]!
31
+ if (quote) {
32
+ if (char === "\\") at++
33
+ else if (char === quote) quote = ""
34
+ } else if (char === '"' || char === "'") quote = char
35
+ else if (char === "(") depth++
36
+ else if (char === ")") depth--
37
+ else if (char === separator && depth === 0) {
38
+ parts.push(text.slice(start, at))
39
+ start = at + 1
40
+ }
41
+ }
42
+ parts.push(text.slice(start))
43
+ return parts.map((part) => part.trim()).filter(Boolean)
44
+ }
45
+
46
+ const unquote = (value: string): string => value.trim().replace(/^(["'])(.*)\1$/s, "$2")
47
+
48
+ function absoluteUrl(url: string): string {
49
+ return url.startsWith("//") ? `https:${url}` : url
50
+ }
51
+
52
+ function parseSrc(value: string): FontFaceData["src"] {
53
+ const out: FontFaceData["src"] = []
54
+ for (const item of splitTop(value, ",")) {
55
+ const local = /^local\(\s*(.*?)\s*\)$/s.exec(item)
56
+ if (local) {
57
+ out.push({ name: unquote(local[1]!) })
58
+ continue
59
+ }
60
+ const url = /^url\(\s*(.*?)\s*\)\s*(?:format\(\s*(.*?)\s*\))?$/s.exec(item)
61
+ if (!url) continue
62
+ const format = url[2] ? FORMATS[unquote(url[2]).toLowerCase()] : undefined
63
+ out.push({ url: absoluteUrl(unquote(url[1]!)), ...(format ? { format } : {}) })
64
+ }
65
+ return out
66
+ }
67
+
68
+ /** The characters of `glyphs`, each once, in first-seen order. */
69
+ export const uniqueGlyphs = (glyphs: string): string => [...new Set(Array.from(glyphs))].join("")
70
+
71
+ /** The `&text=` suffix of a Google CSS2 request, empty without glyphs. */
72
+ export const glyphsParam = (glyphs: string | undefined): string => {
73
+ const text = uniqueGlyphs(glyphs ?? "")
74
+ return text ? `&text=${encodeURIComponent(text)}` : ""
75
+ }
76
+
77
+ /** The `@font-face` rules of a provider's CSS; the `/* latin *\/` comment before a rule is its subset. */
78
+ export function parseFontFaces(css: string): ParsedFace[] {
79
+ const out: ParsedFace[] = []
80
+ const rule = /(?:\/\*\s*([^*]*?)\s*\*\/\s*)?@font-face\s*\{([^}]*)\}/g
81
+ for (let match = rule.exec(css); match; match = rule.exec(css)) {
82
+ const declarations = new Map<string, string>()
83
+ for (const declaration of splitTop(match[2]!, ";")) {
84
+ const colon = declaration.indexOf(":")
85
+ if (colon > 0)
86
+ declarations.set(declaration.slice(0, colon).trim().toLowerCase(), declaration.slice(colon + 1).trim())
87
+ }
88
+ const family = declarations.get("font-family")
89
+ const src = parseSrc(declarations.get("src") ?? "")
90
+ if (!family || !src.length) continue
91
+ const field = (key: string, name: keyof FontFaceData): Partial<FontFaceData> => {
92
+ const value = declarations.get(key)
93
+ return value ? { [name]: value } : {}
94
+ }
95
+ const subset = match[1]
96
+ out.push({
97
+ family: unquote(family),
98
+ face: {
99
+ src,
100
+ ...field("font-weight", "weight"),
101
+ ...field("font-style", "style"),
102
+ ...field("font-stretch", "stretch"),
103
+ ...field("unicode-range", "unicodeRange"),
104
+ ...field("font-display", "display"),
105
+ ...field("font-feature-settings", "featureSettings"),
106
+ ...field("font-variation-settings", "variationSettings"),
107
+ ...(subset ? { subset } : {}),
108
+ },
109
+ })
110
+ }
111
+ return out
112
+ }
113
+
114
+ /** A face of a service with no subsets: a leading `/* Satoshi *\/` comment is not one. */
115
+ export function withoutSubset({ subset: _subset, ...face }: FontFaceData): FontFaceData {
116
+ return face
117
+ }
118
+
119
+ /** A request that is not 2xx throws; `missing` statuses mean the service has no such family. */
120
+ export async function requestText(
121
+ fetchFn: typeof fetch,
122
+ url: string,
123
+ options: { missing?: number[]; headers?: Record<string, string> } = {},
124
+ ): Promise<string | undefined> {
125
+ const response = await fetchFn(url, { headers: options.headers ?? { "user-agent": CHROME_UA } })
126
+ if (options.missing?.includes(response.status)) return undefined
127
+ if (!response.ok) throw new Error(`${new URL(url).host} answered ${response.status}`)
128
+ return response.text()
129
+ }
130
+
131
+ export const weightRange = (weight: string): [number, number] => {
132
+ const [low, high] = weight.split(" ").map(Number)
133
+ return [low!, high ?? low!]
134
+ }
135
+
136
+ export const isRange = (weight: string): boolean => weight.includes(" ")
137
+
138
+ /** The faces a request asked for: styles, formats and the subsets a face names (a numbered `[0]` subset is a slice of a large family and stays). */
139
+ export function keepRequested(
140
+ faces: FontFaceData[],
141
+ options: Pick<ResolveFontOptions, "styles" | "subsets" | "formats">,
142
+ only: { subsets?: boolean } = { subsets: true },
143
+ ): FontFaceData[] {
144
+ const out: FontFaceData[] = []
145
+ for (const face of faces) {
146
+ if (!options.styles.includes((face.style ?? "normal") as FontStyle)) continue
147
+ if (only.subsets && face.subset && !/^\[\d+\]$/.test(face.subset) && !options.subsets.includes(face.subset))
148
+ continue
149
+ const src = face.src.filter((entry) => !("url" in entry) || !entry.format || options.formats.includes(entry.format))
150
+ if (!src.some((entry) => "url" in entry)) continue
151
+ out.push(only.subsets ? { ...face, src } : { ...withoutSubset(face), src })
152
+ }
153
+ return out
154
+ }
@@ -0,0 +1,37 @@
1
+ import type { FontProvider, ResolveFontOptions } from "../types.ts"
2
+ import { isRange, keepRequested, parseFontFaces, requestText, weightRange } from "./css.ts"
3
+
4
+ /** `satoshi@400;400i;700`; a range is `300..900`. */
5
+ export function fontshareParam(family: string, options: Pick<ResolveFontOptions, "weights" | "styles">): string {
6
+ const slug = family.toLowerCase().trim().replace(/\s+/g, "-")
7
+ const tokens: string[] = []
8
+ for (const weight of options.weights) {
9
+ const base = isRange(weight) ? weight.replace(" ", "..") : weight
10
+ if (options.styles.some((style) => style !== "italic")) tokens.push(base)
11
+ if (options.styles.includes("italic")) tokens.push(`${base}i`)
12
+ }
13
+ return `${slug}@${tokens.join(";")}`
14
+ }
15
+
16
+ export const fontshare: FontProvider = {
17
+ name: "fontshare",
18
+ async resolveFont(family, options) {
19
+ const css = await requestText(
20
+ options.fetch,
21
+ `https://api.fontshare.com/v2/css?f[]=${fontshareParam(family, options)}&display=swap`,
22
+ { missing: [404] },
23
+ )
24
+ if (!css) return undefined
25
+ const wanted = options.weights.map(weightRange)
26
+ const fonts = keepRequested(
27
+ parseFontFaces(css).map(({ face }) => face),
28
+ options,
29
+ { subsets: false },
30
+ ).filter(({ weight }) => {
31
+ if (!weight) return true
32
+ const [low, high] = weightRange(weight)
33
+ return wanted.some(([from, to]) => low >= from && high <= to)
34
+ })
35
+ return fonts.length ? { fonts } : undefined
36
+ },
37
+ }
@@ -0,0 +1,53 @@
1
+ import type { FontFaceData, FontFormat, FontProvider } from "../types.ts"
2
+ import { requestText, weightRange } from "./css.ts"
3
+
4
+ type Variants = Record<string, Record<string, Record<string, { url?: Partial<Record<FontFormat, string>> }>>>
5
+ interface FontsourceFont {
6
+ variants?: Variants
7
+ unicodeRange?: Record<string, string>
8
+ }
9
+
10
+ export const fontsourceId = (family: string): string => family.toLowerCase().trim().replace(/\s+/g, "-")
11
+
12
+ /** The faces of `api.fontsource.org/v1/fonts/<id>`; a weight range takes every static weight inside it. */
13
+ export function parseFontsource(
14
+ answer: FontsourceFont,
15
+ options: { weights: string[]; styles: string[]; subsets: string[]; formats: FontFormat[] },
16
+ ): FontFaceData[] {
17
+ const wanted = options.weights.map(weightRange)
18
+ const out: FontFaceData[] = []
19
+ for (const weight of Object.keys(answer.variants ?? {}).sort((a, b) => Number(a) - Number(b))) {
20
+ if (!wanted.some(([low, high]) => Number(weight) >= low && Number(weight) <= high)) continue
21
+ for (const style of options.styles) {
22
+ for (const subset of options.subsets) {
23
+ const urls = answer.variants![weight]![style]?.[subset]?.url
24
+ if (!urls) continue
25
+ const src = options.formats.filter((format) => urls[format]).map((format) => ({ url: urls[format]!, format }))
26
+ if (!src.length) continue
27
+ const unicodeRange = answer.unicodeRange?.[subset]
28
+ out.push({ src, weight, style, subset, ...(unicodeRange ? { unicodeRange } : {}) })
29
+ }
30
+ }
31
+ }
32
+ return out
33
+ }
34
+
35
+ export const fontsource: FontProvider = {
36
+ name: "fontsource",
37
+ async resolveFont(family, options) {
38
+ const text = await requestText(
39
+ options.fetch,
40
+ `https://api.fontsource.org/v1/fonts/${encodeURIComponent(fontsourceId(family))}`,
41
+ { missing: [404], headers: { accept: "application/json" } },
42
+ )
43
+ if (!text) return undefined
44
+ let answer: FontsourceFont
45
+ try {
46
+ answer = JSON.parse(text) as FontsourceFont
47
+ } catch {
48
+ throw new Error("api.fontsource.org answered something that is not JSON")
49
+ }
50
+ const fonts = parseFontsource(answer, options)
51
+ return fonts.length ? { fonts } : undefined
52
+ },
53
+ }