@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.
- package/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/src/index.js +2472 -0
- package/dist/src/providers/index.js +386 -0
- package/dist/src/server/index.js +22 -0
- package/dist/types/src/build/cache.d.ts +17 -0
- package/dist/types/src/build/data.d.ts +19 -0
- package/dist/types/src/build/fallbacks.d.ts +49 -0
- package/dist/types/src/build/files.d.ts +7 -0
- package/dist/types/src/build/global.d.ts +3 -0
- package/dist/types/src/build/preload.d.ts +25 -0
- package/dist/types/src/build/providers.d.ts +5 -0
- package/dist/types/src/build/public-url.d.ts +2 -0
- package/dist/types/src/build/scan.d.ts +6 -0
- package/dist/types/src/build/subset.d.ts +7 -0
- package/dist/types/src/index.d.ts +18 -0
- package/dist/types/src/inject.d.ts +21 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/options.d.ts +46 -0
- package/dist/types/src/providers/adobe.d.ts +2 -0
- package/dist/types/src/providers/bunny.d.ts +4 -0
- package/dist/types/src/providers/css.d.ts +27 -0
- package/dist/types/src/providers/fontshare.d.ts +4 -0
- package/dist/types/src/providers/fontsource.d.ts +18 -0
- package/dist/types/src/providers/google.d.ts +4 -0
- package/dist/types/src/providers/googleicons.d.ts +2 -0
- package/dist/types/src/providers/index.d.ts +3 -0
- package/dist/types/src/providers/local.d.ts +17 -0
- package/dist/types/src/providers/npm.d.ts +5 -0
- package/dist/types/src/resolve.d.ts +32 -0
- package/dist/types/src/runtime/global.d.ts +3 -0
- package/dist/types/src/scan.d.ts +29 -0
- package/dist/types/src/server/data.d.ts +11 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/index.d.ts +9 -0
- package/dist/types/src/server/preload.d.ts +2 -0
- package/dist/types/src/subset/cmap.d.ts +2 -0
- package/dist/types/src/subset/glyf.d.ts +15 -0
- package/dist/types/src/subset/sfnt.d.ts +21 -0
- package/dist/types/src/subset/woff2.d.ts +7 -0
- package/dist/types/src/types.d.ts +71 -0
- package/package.json +32 -4
- package/src/build/cache.ts +50 -0
- package/src/build/data.ts +145 -0
- package/src/build/fallbacks.ts +384 -0
- package/src/build/files.ts +102 -0
- package/src/build/global.ts +14 -0
- package/src/build/preload.ts +104 -0
- package/src/build/providers.ts +19 -0
- package/src/build/public-url.ts +21 -0
- package/src/build/scan.ts +172 -0
- package/src/build/subset.ts +74 -0
- package/src/env.d.ts +13 -0
- package/src/index.ts +25 -0
- package/src/inject.ts +59 -0
- package/src/module.ts +29 -0
- package/src/options.ts +375 -0
- package/src/providers/adobe.ts +18 -0
- package/src/providers/bunny.ts +35 -0
- package/src/providers/css.ts +154 -0
- package/src/providers/fontshare.ts +37 -0
- package/src/providers/fontsource.ts +53 -0
- package/src/providers/google.ts +31 -0
- package/src/providers/googleicons.ts +20 -0
- package/src/providers/index.ts +17 -0
- package/src/providers/local.ts +141 -0
- package/src/providers/npm.ts +96 -0
- package/src/resolve.ts +134 -0
- package/src/runtime/global.ts +5 -0
- package/src/scan.ts +275 -0
- package/src/server/data.ts +20 -0
- package/src/server/door.ts +13 -0
- package/src/server/index.ts +9 -0
- package/src/server/preload.ts +50 -0
- package/src/subset/cmap.ts +79 -0
- package/src/subset/glyf.ts +93 -0
- package/src/subset/sfnt.ts +196 -0
- package/src/subset/woff2.ts +68 -0
- package/src/types.ts +71 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { FontProvider, ResolveFontOptions } from "../types.ts"
|
|
2
|
+
import { glyphsParam, isRange, keepRequested, parseFontFaces, requestText } from "./css.ts"
|
|
3
|
+
|
|
4
|
+
const unique = (values: string[]): string[] => [...new Set(values)]
|
|
5
|
+
|
|
6
|
+
/** The `family=` value of the CSS2 API: axes and tuples sorted, as the API requires. */
|
|
7
|
+
export function googleFamilyParam(family: string, options: Pick<ResolveFontOptions, "weights" | "styles">): string {
|
|
8
|
+
const name = encodeURIComponent(family).replace(/%20/g, "+")
|
|
9
|
+
const weights = unique(options.weights.map((weight) => (isRange(weight) ? weight.replace(" ", "..") : weight))).sort(
|
|
10
|
+
(a, b) => parseInt(a) - parseInt(b),
|
|
11
|
+
)
|
|
12
|
+
const italic = options.styles.includes("italic")
|
|
13
|
+
const upright = options.styles.some((style) => style !== "italic")
|
|
14
|
+
if (!italic) return `${name}:wght@${weights.join(";")}`
|
|
15
|
+
const tuples = [...(upright ? weights.map((weight) => `0,${weight}`) : []), ...weights.map((weight) => `1,${weight}`)]
|
|
16
|
+
return `${name}:ital,wght@${tuples.join(";")}`
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const google: FontProvider = {
|
|
20
|
+
name: "google",
|
|
21
|
+
async resolveFont(family, options) {
|
|
22
|
+
const url = `https://fonts.googleapis.com/css2?family=${googleFamilyParam(family, options)}&display=swap${glyphsParam(options.glyphs)}`
|
|
23
|
+
const css = await requestText(options.fetch, url, { missing: [400, 404] })
|
|
24
|
+
if (!css) return undefined
|
|
25
|
+
const fonts = keepRequested(
|
|
26
|
+
parseFontFaces(css).map(({ face }) => face),
|
|
27
|
+
options,
|
|
28
|
+
)
|
|
29
|
+
return fonts.length ? { fonts } : undefined
|
|
30
|
+
},
|
|
31
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { FontProvider } from "../types.ts"
|
|
2
|
+
import { glyphsParam, normalizeFamily, parseFontFaces, requestText, withoutSubset } from "./css.ts"
|
|
3
|
+
|
|
4
|
+
const FAMILIES = ["Material Symbols Outlined", "Material Symbols Rounded", "Material Symbols Sharp", "Material Icons"]
|
|
5
|
+
|
|
6
|
+
export const googleicons: FontProvider = {
|
|
7
|
+
name: "googleicons",
|
|
8
|
+
async resolveFont(family, options) {
|
|
9
|
+
const known = FAMILIES.find((name) => normalizeFamily(name) === normalizeFamily(family))
|
|
10
|
+
if (!known) return undefined
|
|
11
|
+
const css = await requestText(
|
|
12
|
+
options.fetch,
|
|
13
|
+
`https://fonts.googleapis.com/css2?family=${known.replace(/ /g, "+")}&display=swap${glyphsParam(options.glyphs)}`,
|
|
14
|
+
{ missing: [400, 404] },
|
|
15
|
+
)
|
|
16
|
+
if (!css) return undefined
|
|
17
|
+
const fonts = parseFontFaces(css).map(({ face }) => withoutSubset(face))
|
|
18
|
+
return fonts.length ? { fonts } : undefined
|
|
19
|
+
},
|
|
20
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { FontProvider } from "../types.ts"
|
|
2
|
+
import { adobe } from "./adobe.ts"
|
|
3
|
+
import { bunny } from "./bunny.ts"
|
|
4
|
+
import { fontshare } from "./fontshare.ts"
|
|
5
|
+
import { fontsource } from "./fontsource.ts"
|
|
6
|
+
import { google } from "./google.ts"
|
|
7
|
+
import { googleicons } from "./googleicons.ts"
|
|
8
|
+
|
|
9
|
+
export const remoteProviders: Record<string, FontProvider> = {
|
|
10
|
+
google,
|
|
11
|
+
googleicons,
|
|
12
|
+
bunny,
|
|
13
|
+
fontshare,
|
|
14
|
+
fontsource,
|
|
15
|
+
adobe,
|
|
16
|
+
}
|
|
17
|
+
export { createNpmProvider } from "./npm.ts"
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import type { Dirent } from "node:fs"
|
|
2
|
+
import { readdir } from "node:fs/promises"
|
|
3
|
+
import { basename, join, sep } from "node:path"
|
|
4
|
+
import type { FontFaceData, FontFormat, FontProvider } from "../types.ts"
|
|
5
|
+
|
|
6
|
+
export interface LocalScope {
|
|
7
|
+
/** `<srcDir>/assets/fonts` of the app and each layer: files the asset pipeline hashes. */
|
|
8
|
+
assetDirs: string[]
|
|
9
|
+
/** `public/` of the app and each layer: files that keep their public URL. */
|
|
10
|
+
publicDirs: string[]
|
|
11
|
+
baseURL: string
|
|
12
|
+
/** Whether Bun leaves a root-absolute `url(/x.woff2)` alone; when it does not, a public file is written with its absolute path, which the asset pipeline resolves. */
|
|
13
|
+
publicUrlsKept(): Promise<boolean>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const EXTENSION = /\.(woff2|woff|ttf|otf)$/i
|
|
17
|
+
const FORMAT_ORDER: FontFormat[] = ["woff2", "woff", "ttf", "otf"]
|
|
18
|
+
const WEIGHT_NAMES: Record<string, number> = {
|
|
19
|
+
thin: 100,
|
|
20
|
+
hairline: 100,
|
|
21
|
+
extralight: 200,
|
|
22
|
+
ultralight: 200,
|
|
23
|
+
light: 300,
|
|
24
|
+
regular: 400,
|
|
25
|
+
normal: 400,
|
|
26
|
+
book: 400,
|
|
27
|
+
medium: 500,
|
|
28
|
+
semibold: 600,
|
|
29
|
+
demibold: 600,
|
|
30
|
+
bold: 700,
|
|
31
|
+
extrabold: 800,
|
|
32
|
+
ultrabold: 800,
|
|
33
|
+
black: 900,
|
|
34
|
+
heavy: 900,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const normal = (text: string): string => text.toLowerCase().replace(/[\s_-]+/g, "")
|
|
38
|
+
|
|
39
|
+
function modifiers(rest: string): { weight?: string; style: string } | undefined {
|
|
40
|
+
let weight: string | undefined
|
|
41
|
+
let style = "normal"
|
|
42
|
+
for (const raw of rest.split(/[-_ ]+/).filter(Boolean)) {
|
|
43
|
+
let token = raw.toLowerCase()
|
|
44
|
+
const slanted = /^(.*?)(italic|oblique)$/.exec(token)
|
|
45
|
+
if (slanted) {
|
|
46
|
+
style = slanted[2]!
|
|
47
|
+
token = slanted[1]!
|
|
48
|
+
if (token === "") continue
|
|
49
|
+
}
|
|
50
|
+
if (/^\d{1,4}$/.test(token) && Number(token) >= 1 && Number(token) <= 1000) weight = String(Number(token))
|
|
51
|
+
else if (token in WEIGHT_NAMES) weight = String(WEIGHT_NAMES[token])
|
|
52
|
+
else return undefined
|
|
53
|
+
}
|
|
54
|
+
return { ...(weight ? { weight } : {}), style }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** `local`: `<Family>.<ext>` or `<Family>-<weight>[-<style>].<ext>`, the family compared without case, spaces and hyphens; a weight is a number or `thin` to `black`. */
|
|
58
|
+
export function parseFontFile(
|
|
59
|
+
file: string,
|
|
60
|
+
family: string,
|
|
61
|
+
): { weight?: string; style: string; format: FontFormat } | undefined {
|
|
62
|
+
const extension = EXTENSION.exec(file)
|
|
63
|
+
if (!extension) return undefined
|
|
64
|
+
const stem = basename(file).slice(0, -extension[0].length)
|
|
65
|
+
const target = normal(family)
|
|
66
|
+
for (let at = 0; at <= stem.length; at++) {
|
|
67
|
+
if (at < stem.length && !/[-_ ]/.test(stem[at]!)) continue
|
|
68
|
+
if (normal(stem.slice(0, at)) !== target) continue
|
|
69
|
+
const parsed = modifiers(stem.slice(at + 1))
|
|
70
|
+
if (parsed) return { ...parsed, format: extension[1]!.toLowerCase() as FontFormat }
|
|
71
|
+
}
|
|
72
|
+
return undefined
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface Found {
|
|
76
|
+
absolute: string
|
|
77
|
+
/** The path below its directory, `/`-separated. */
|
|
78
|
+
relative: string
|
|
79
|
+
pub: boolean
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function list(dir: string, pub: boolean): Promise<Found[]> {
|
|
83
|
+
const entries = await readdir(dir, { recursive: true, withFileTypes: true }).catch((): Dirent[] => [])
|
|
84
|
+
return entries
|
|
85
|
+
.filter((entry) => entry.isFile() && EXTENSION.test(entry.name))
|
|
86
|
+
.map((entry) => {
|
|
87
|
+
const absolute = join(entry.parentPath, entry.name)
|
|
88
|
+
return {
|
|
89
|
+
absolute,
|
|
90
|
+
relative: absolute
|
|
91
|
+
.slice(dir.length + 1)
|
|
92
|
+
.split(sep)
|
|
93
|
+
.join("/"),
|
|
94
|
+
pub,
|
|
95
|
+
}
|
|
96
|
+
})
|
|
97
|
+
.sort((a, b) => a.relative.localeCompare(b.relative))
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function createLocalProvider(scope: LocalScope): FontProvider {
|
|
101
|
+
let index: Promise<Found[]> | undefined
|
|
102
|
+
const files = () =>
|
|
103
|
+
(index ??= Promise.all([
|
|
104
|
+
...scope.assetDirs.map((dir) => list(dir, false)),
|
|
105
|
+
...scope.publicDirs.map((dir) => list(dir, true)),
|
|
106
|
+
]).then((lists) => lists.flat()))
|
|
107
|
+
const publicUrl = (relative: string): string => `${scope.baseURL.replace(/\/+$/, "")}/${encodeURI(relative)}`
|
|
108
|
+
return {
|
|
109
|
+
name: "local",
|
|
110
|
+
async resolveFont(family) {
|
|
111
|
+
const faces = new Map<string, { weight?: string; style: string; src: Map<FontFormat, string> }>()
|
|
112
|
+
let kept: boolean | undefined
|
|
113
|
+
for (const file of await files()) {
|
|
114
|
+
const parsed = parseFontFile(file.relative, family)
|
|
115
|
+
if (!parsed) continue
|
|
116
|
+
const key = `${parsed.weight ?? ""}\0${parsed.style}`
|
|
117
|
+
const face = faces.get(key) ?? {
|
|
118
|
+
...(parsed.weight ? { weight: parsed.weight } : {}),
|
|
119
|
+
style: parsed.style,
|
|
120
|
+
src: new Map(),
|
|
121
|
+
}
|
|
122
|
+
faces.set(key, face)
|
|
123
|
+
if (face.src.has(parsed.format)) continue
|
|
124
|
+
if (file.pub) kept ??= await scope.publicUrlsKept()
|
|
125
|
+
face.src.set(parsed.format, file.pub && kept ? publicUrl(file.relative) : file.absolute)
|
|
126
|
+
}
|
|
127
|
+
if (faces.size === 0) return undefined
|
|
128
|
+
const fonts: FontFaceData[] = [...faces.values()]
|
|
129
|
+
.sort((a, b) => Number(a.weight ?? 400) - Number(b.weight ?? 400) || a.style.localeCompare(b.style))
|
|
130
|
+
.map((face) => ({
|
|
131
|
+
src: FORMAT_ORDER.filter((format) => face.src.has(format)).map((format) => ({
|
|
132
|
+
url: face.src.get(format)!,
|
|
133
|
+
format,
|
|
134
|
+
})),
|
|
135
|
+
...(face.weight ? { weight: face.weight } : {}),
|
|
136
|
+
style: face.style,
|
|
137
|
+
}))
|
|
138
|
+
return { fonts }
|
|
139
|
+
},
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { existsSync } from "node:fs"
|
|
2
|
+
import { readFile, readdir } from "node:fs/promises"
|
|
3
|
+
import { dirname, join } from "node:path"
|
|
4
|
+
import type { FontFaceData, FontFormat, FontProvider, FontStyle } from "../types.ts"
|
|
5
|
+
import { weightRange } from "./css.ts"
|
|
6
|
+
|
|
7
|
+
const escape = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
|
8
|
+
const FORMATS: FontFormat[] = ["woff2", "woff"]
|
|
9
|
+
|
|
10
|
+
async function packageDir(rootDir: string, scope: string, id: string): Promise<string | undefined> {
|
|
11
|
+
for (let dir = rootDir; ; dir = dirname(dir)) {
|
|
12
|
+
const found = join(dir, "node_modules", scope, id)
|
|
13
|
+
if (existsSync(join(found, "files"))) return found
|
|
14
|
+
if (dirname(dir) === dir) return undefined
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function readJson(file: string): Promise<Record<string, any> | undefined> {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(await readFile(file, "utf8"))
|
|
21
|
+
} catch {
|
|
22
|
+
return undefined
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** `npm`: the app's installed `@fontsource/<id>` and `@fontsource-variable/<id>`; a weight range takes the variable package when it is installed. */
|
|
27
|
+
export function createNpmProvider(scope: { rootDir: string }): FontProvider {
|
|
28
|
+
return {
|
|
29
|
+
name: "npm",
|
|
30
|
+
async resolveFont(family, options) {
|
|
31
|
+
const id = family.toLowerCase().trim().replace(/\s+/g, "-")
|
|
32
|
+
const [staticDir, variableDir] = await Promise.all([
|
|
33
|
+
packageDir(scope.rootDir, "@fontsource", id),
|
|
34
|
+
packageDir(scope.rootDir, "@fontsource-variable", id),
|
|
35
|
+
])
|
|
36
|
+
if (!staticDir && !variableDir) return undefined
|
|
37
|
+
const wanted = options.weights.map(weightRange)
|
|
38
|
+
const useVariable =
|
|
39
|
+
variableDir !== undefined && (staticDir === undefined || options.weights.some((weight) => weight.includes(" ")))
|
|
40
|
+
const dir = useVariable ? variableDir! : staticDir!
|
|
41
|
+
const [files, unicode, metadata] = await Promise.all([
|
|
42
|
+
readdir(join(dir, "files")),
|
|
43
|
+
readJson(join(dir, "unicode.json")),
|
|
44
|
+
readJson(join(dir, "metadata.json")),
|
|
45
|
+
])
|
|
46
|
+
const pattern = new RegExp(
|
|
47
|
+
`^${escape(id)}-(.+)-(${useVariable ? "wght" : "\\d+"})-(normal|italic)\\.(woff2|woff)$`,
|
|
48
|
+
)
|
|
49
|
+
const range = metadata?.variable?.wght
|
|
50
|
+
const groups = new Map<string, FontFaceData & { subset: string }>()
|
|
51
|
+
for (const file of files) {
|
|
52
|
+
const match = pattern.exec(file)
|
|
53
|
+
if (!match) continue
|
|
54
|
+
const [, subset, axis, style, extension] = match as unknown as [string, string, string, string, FontFormat]
|
|
55
|
+
if (
|
|
56
|
+
!options.subsets.includes(subset) ||
|
|
57
|
+
!options.styles.includes(style as FontStyle) ||
|
|
58
|
+
!options.formats.includes(extension)
|
|
59
|
+
)
|
|
60
|
+
continue
|
|
61
|
+
if (!useVariable && !wanted.some(([low, high]) => Number(axis) >= low && Number(axis) <= high)) continue
|
|
62
|
+
if (useVariable && extension !== "woff2") continue
|
|
63
|
+
const weight = useVariable ? (range ? `${range.min} ${range.max}` : undefined) : axis
|
|
64
|
+
const key = `${weight ?? ""}\0${style}\0${subset}`
|
|
65
|
+
const face: FontFaceData & { subset: string } = groups.get(key) ?? {
|
|
66
|
+
src: [],
|
|
67
|
+
style,
|
|
68
|
+
subset,
|
|
69
|
+
...(weight ? { weight } : {}),
|
|
70
|
+
...(unicode?.[subset] ? { unicodeRange: unicode[subset] } : {}),
|
|
71
|
+
}
|
|
72
|
+
face.src.push({ url: join(dir, "files", file), format: extension })
|
|
73
|
+
groups.set(key, face)
|
|
74
|
+
}
|
|
75
|
+
const order = (face: FontFaceData) => [
|
|
76
|
+
Number(weightRange(face.weight ?? "400")[0]),
|
|
77
|
+
face.style === "italic" ? 1 : 0,
|
|
78
|
+
options.subsets.indexOf(face.subset!),
|
|
79
|
+
]
|
|
80
|
+
const fonts = [...groups.values()]
|
|
81
|
+
.map((face) => ({
|
|
82
|
+
...face,
|
|
83
|
+
src: [...face.src].sort(
|
|
84
|
+
(a, b) =>
|
|
85
|
+
FORMATS.indexOf((a as { format: FontFormat }).format) -
|
|
86
|
+
FORMATS.indexOf((b as { format: FontFormat }).format),
|
|
87
|
+
),
|
|
88
|
+
}))
|
|
89
|
+
.sort((a, b) => {
|
|
90
|
+
const [x, y] = [order(a), order(b)]
|
|
91
|
+
return x[0]! - y[0]! || x[1]! - y[1]! || x[2]! - y[2]!
|
|
92
|
+
})
|
|
93
|
+
return fonts.length ? { fonts } : undefined
|
|
94
|
+
},
|
|
95
|
+
}
|
|
96
|
+
}
|
package/src/resolve.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { extname } from "node:path"
|
|
2
|
+
import { familyKey } from "./scan.ts"
|
|
3
|
+
import { metaKey, type MetaCache } from "./build/cache.ts"
|
|
4
|
+
import type { ResolvedFamily, ResolvedFontsOptions } from "./options.ts"
|
|
5
|
+
import type { FontFaceData, FontFormat, FontProvider } from "./types.ts"
|
|
6
|
+
import { DiagnosticError } from "hamur/kit"
|
|
7
|
+
|
|
8
|
+
export interface ResolvedFamilyFaces {
|
|
9
|
+
/** The name written in the `font-family` descriptor. */
|
|
10
|
+
name: string
|
|
11
|
+
faces: FontFaceData[]
|
|
12
|
+
entry?: ResolvedFamily
|
|
13
|
+
/** The provider that answered; none for a family with `src`. */
|
|
14
|
+
provider?: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface FontResolver {
|
|
18
|
+
/** The faces of a family the CSS names, or `undefined` when none are found or the family is left to the app. */
|
|
19
|
+
resolve(name: string): Promise<ResolvedFamilyFaces | undefined>
|
|
20
|
+
/** The family's options when `fonts.families` lists it. */
|
|
21
|
+
listed(name: string): ResolvedFamily | undefined
|
|
22
|
+
/** Changes when an answer is added, for the dev cache of the transform chain. */
|
|
23
|
+
version(): number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ResolverScope {
|
|
27
|
+
options: ResolvedFontsOptions
|
|
28
|
+
builtIn: Record<string, FontProvider>
|
|
29
|
+
/** A warning; the caller logs it once or, with `throwOnError`, throws it. */
|
|
30
|
+
report(message: string): void
|
|
31
|
+
fetch?: typeof fetch
|
|
32
|
+
/** Provider answers of these providers are kept between builds; the others are asked each time. */
|
|
33
|
+
cache?: { store: MetaCache; providers: ReadonlySet<string> }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
class Unreachable extends Error {
|
|
37
|
+
constructor(readonly host: string) {
|
|
38
|
+
super(`cannot reach ${host}`)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const FORMATS: Record<string, FontFormat> = { ".woff2": "woff2", ".woff": "woff", ".ttf": "ttf", ".otf": "otf" }
|
|
43
|
+
|
|
44
|
+
function sourceFaces(entry: ResolvedFamily): FontFaceData[] {
|
|
45
|
+
return entry.src!.map((file, index) => {
|
|
46
|
+
const format = FORMATS[extname(file).toLowerCase()]
|
|
47
|
+
const weight = entry.ownWeights ? entry.weights[index] : undefined
|
|
48
|
+
return {
|
|
49
|
+
src: [{ url: file, ...(format ? { format } : {}) }],
|
|
50
|
+
...(weight !== undefined ? { weight: String(weight) } : {}),
|
|
51
|
+
style: entry.styles[index] ?? entry.styles[0] ?? "normal",
|
|
52
|
+
}
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function createResolver({
|
|
57
|
+
options,
|
|
58
|
+
builtIn,
|
|
59
|
+
report,
|
|
60
|
+
fetch: given = globalThis.fetch,
|
|
61
|
+
cache,
|
|
62
|
+
}: ResolverScope): FontResolver {
|
|
63
|
+
const entries = new Map(options.families.map((family) => [familyKey(family.name), family]))
|
|
64
|
+
const answers = new Map<string, Promise<ResolvedFamilyFaces | undefined>>()
|
|
65
|
+
let version = 0
|
|
66
|
+
const fetchFn = (async (input, init) => {
|
|
67
|
+
try {
|
|
68
|
+
return await given(input, init)
|
|
69
|
+
} catch (error) {
|
|
70
|
+
throw new Unreachable(new URL(input instanceof Request ? input.url : String(input)).host)
|
|
71
|
+
}
|
|
72
|
+
}) as typeof fetch
|
|
73
|
+
|
|
74
|
+
const ask = async (name: string): Promise<ResolvedFamilyFaces | undefined> => {
|
|
75
|
+
const entry = entries.get(familyKey(name))
|
|
76
|
+
const written = entry?.name ?? name
|
|
77
|
+
if (entry?.src) return { name: written, faces: sourceFaces(entry), entry }
|
|
78
|
+
if (entry?.provider === "none") return undefined
|
|
79
|
+
const defaults = entry ?? options.defaults
|
|
80
|
+
const names = entry?.provider
|
|
81
|
+
? [entry.provider]
|
|
82
|
+
: options.priority.filter((provider) => !options.disabled.has(provider))
|
|
83
|
+
for (const provider of names) {
|
|
84
|
+
const found = options.custom[provider] ?? builtIn[provider]
|
|
85
|
+
if (!found) continue
|
|
86
|
+
try {
|
|
87
|
+
const request = {
|
|
88
|
+
weights: defaults.weights.map(String),
|
|
89
|
+
styles: defaults.styles,
|
|
90
|
+
subsets: defaults.subsets,
|
|
91
|
+
formats: defaults.formats,
|
|
92
|
+
...(entry?.glyphs !== undefined ? { glyphs: entry.glyphs } : {}),
|
|
93
|
+
...(options.providerOptions[provider] ? { options: options.providerOptions[provider] } : {}),
|
|
94
|
+
}
|
|
95
|
+
const stored = cache?.providers.has(provider) ? cache.store : undefined
|
|
96
|
+
const key = stored ? metaKey(provider, written, request) : ""
|
|
97
|
+
const hit = await stored?.get(key)
|
|
98
|
+
if (hit) return { name: written, faces: hit.fonts, provider, ...(entry ? { entry } : {}) }
|
|
99
|
+
const resolution = await found.resolveFont(written, { ...request, fetch: fetchFn })
|
|
100
|
+
if (resolution && stored) await stored.set(key, resolution).catch(() => {})
|
|
101
|
+
if (resolution) return { name: written, faces: resolution.fonts, provider, ...(entry ? { entry } : {}) }
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (error instanceof Unreachable)
|
|
104
|
+
throw new DiagnosticError(
|
|
105
|
+
"HAMUR_E5702",
|
|
106
|
+
`[fonts] cannot reach ${error.host} and no cached copy of ${JSON.stringify(written)} exists`,
|
|
107
|
+
)
|
|
108
|
+
report(
|
|
109
|
+
`[fonts] ${provider} failed for ${JSON.stringify(written)}: ${error instanceof Error ? error.message : String(error)}`,
|
|
110
|
+
)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
report(`[fonts] no provider found for ${JSON.stringify(written)}`)
|
|
114
|
+
return undefined
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
resolve(name) {
|
|
119
|
+
const key = familyKey(name)
|
|
120
|
+
let answer = answers.get(key)
|
|
121
|
+
if (!answer) {
|
|
122
|
+
answer = ask(name)
|
|
123
|
+
answers.set(key, answer)
|
|
124
|
+
void answer.then(
|
|
125
|
+
() => void version++,
|
|
126
|
+
() => {},
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
return answer
|
|
130
|
+
},
|
|
131
|
+
listed: (name) => entries.get(familyKey(name)),
|
|
132
|
+
version: () => version,
|
|
133
|
+
}
|
|
134
|
+
}
|