@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
@@ -0,0 +1,386 @@
1
+ // @bun
2
+ // packages/fonts/src/providers/css.ts
3
+ var CHROME_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36";
4
+ var FORMATS = {
5
+ woff2: "woff2",
6
+ "woff2-variations": "woff2",
7
+ woff: "woff",
8
+ truetype: "ttf",
9
+ "truetype-variations": "ttf",
10
+ opentype: "otf",
11
+ "opentype-variations": "otf"
12
+ };
13
+ var normalizeFamily = (name) => name.toLowerCase().replace(/[\s_-]+/g, "");
14
+ function splitTop(text, separator) {
15
+ const parts = [];
16
+ let depth = 0;
17
+ let quote = "";
18
+ let start = 0;
19
+ for (let at = 0;at < text.length; at++) {
20
+ const char = text[at];
21
+ if (quote) {
22
+ if (char === "\\")
23
+ at++;
24
+ else if (char === quote)
25
+ quote = "";
26
+ } else if (char === '"' || char === "'")
27
+ quote = char;
28
+ else if (char === "(")
29
+ depth++;
30
+ else if (char === ")")
31
+ depth--;
32
+ else if (char === separator && depth === 0) {
33
+ parts.push(text.slice(start, at));
34
+ start = at + 1;
35
+ }
36
+ }
37
+ parts.push(text.slice(start));
38
+ return parts.map((part) => part.trim()).filter(Boolean);
39
+ }
40
+ var unquote = (value) => value.trim().replace(/^(["'])(.*)\1$/s, "$2");
41
+ function absoluteUrl(url) {
42
+ return url.startsWith("//") ? `https:${url}` : url;
43
+ }
44
+ function parseSrc(value) {
45
+ const out = [];
46
+ for (const item of splitTop(value, ",")) {
47
+ const local = /^local\(\s*(.*?)\s*\)$/s.exec(item);
48
+ if (local) {
49
+ out.push({ name: unquote(local[1]) });
50
+ continue;
51
+ }
52
+ const url = /^url\(\s*(.*?)\s*\)\s*(?:format\(\s*(.*?)\s*\))?$/s.exec(item);
53
+ if (!url)
54
+ continue;
55
+ const format = url[2] ? FORMATS[unquote(url[2]).toLowerCase()] : undefined;
56
+ out.push({ url: absoluteUrl(unquote(url[1])), ...format ? { format } : {} });
57
+ }
58
+ return out;
59
+ }
60
+ var uniqueGlyphs = (glyphs) => [...new Set(Array.from(glyphs))].join("");
61
+ var glyphsParam = (glyphs) => {
62
+ const text = uniqueGlyphs(glyphs ?? "");
63
+ return text ? `&text=${encodeURIComponent(text)}` : "";
64
+ };
65
+ function parseFontFaces(css) {
66
+ const out = [];
67
+ const rule = /(?:\/\*\s*([^*]*?)\s*\*\/\s*)?@font-face\s*\{([^}]*)\}/g;
68
+ for (let match = rule.exec(css);match; match = rule.exec(css)) {
69
+ const declarations = new Map;
70
+ for (const declaration of splitTop(match[2], ";")) {
71
+ const colon = declaration.indexOf(":");
72
+ if (colon > 0)
73
+ declarations.set(declaration.slice(0, colon).trim().toLowerCase(), declaration.slice(colon + 1).trim());
74
+ }
75
+ const family = declarations.get("font-family");
76
+ const src = parseSrc(declarations.get("src") ?? "");
77
+ if (!family || !src.length)
78
+ continue;
79
+ const field = (key, name) => {
80
+ const value = declarations.get(key);
81
+ return value ? { [name]: value } : {};
82
+ };
83
+ const subset = match[1];
84
+ out.push({
85
+ family: unquote(family),
86
+ face: {
87
+ src,
88
+ ...field("font-weight", "weight"),
89
+ ...field("font-style", "style"),
90
+ ...field("font-stretch", "stretch"),
91
+ ...field("unicode-range", "unicodeRange"),
92
+ ...field("font-display", "display"),
93
+ ...field("font-feature-settings", "featureSettings"),
94
+ ...field("font-variation-settings", "variationSettings"),
95
+ ...subset ? { subset } : {}
96
+ }
97
+ });
98
+ }
99
+ return out;
100
+ }
101
+ function withoutSubset({ subset: _subset, ...face }) {
102
+ return face;
103
+ }
104
+ async function requestText(fetchFn, url, options = {}) {
105
+ const response = await fetchFn(url, { headers: options.headers ?? { "user-agent": CHROME_UA } });
106
+ if (options.missing?.includes(response.status))
107
+ return;
108
+ if (!response.ok)
109
+ throw new Error(`${new URL(url).host} answered ${response.status}`);
110
+ return response.text();
111
+ }
112
+ var weightRange = (weight) => {
113
+ const [low, high] = weight.split(" ").map(Number);
114
+ return [low, high ?? low];
115
+ };
116
+ var isRange = (weight) => weight.includes(" ");
117
+ function keepRequested(faces, options, only = { subsets: true }) {
118
+ const out = [];
119
+ for (const face of faces) {
120
+ if (!options.styles.includes(face.style ?? "normal"))
121
+ continue;
122
+ if (only.subsets && face.subset && !/^\[\d+\]$/.test(face.subset) && !options.subsets.includes(face.subset))
123
+ continue;
124
+ const src = face.src.filter((entry) => !("url" in entry) || !entry.format || options.formats.includes(entry.format));
125
+ if (!src.some((entry) => ("url" in entry)))
126
+ continue;
127
+ out.push(only.subsets ? { ...face, src } : { ...withoutSubset(face), src });
128
+ }
129
+ return out;
130
+ }
131
+
132
+ // packages/fonts/src/providers/adobe.ts
133
+ var adobe = {
134
+ name: "adobe",
135
+ async resolveFont(family, options) {
136
+ const id = options.options?.id;
137
+ if (typeof id !== "string" || id === "")
138
+ return;
139
+ const css = await requestText(options.fetch, `https://use.typekit.net/${encodeURIComponent(id)}.css`, {
140
+ missing: [404]
141
+ });
142
+ if (!css)
143
+ return;
144
+ const fonts = parseFontFaces(css).filter((parsed) => normalizeFamily(parsed.family) === normalizeFamily(family)).map(({ face }) => face);
145
+ return fonts.length ? { fonts } : undefined;
146
+ }
147
+ };
148
+
149
+ // packages/fonts/src/providers/bunny.ts
150
+ function bunnyFamilyParam(family, options) {
151
+ const weights = new Set;
152
+ for (const weight of options.weights) {
153
+ const [low, high] = weightRange(weight);
154
+ if (low === high)
155
+ weights.add(low);
156
+ else
157
+ for (let at = Math.ceil(low / 100) * 100;at <= high; at += 100)
158
+ weights.add(at);
159
+ }
160
+ const tokens = [];
161
+ for (const weight of [...weights].sort((a, b) => a - b)) {
162
+ if (options.styles.some((style) => style !== "italic"))
163
+ tokens.push(String(weight));
164
+ if (options.styles.includes("italic"))
165
+ tokens.push(`${weight}i`);
166
+ }
167
+ return `${family.toLowerCase().trim().replace(/\s+/g, "-")}:${tokens.join(",")}`;
168
+ }
169
+ var bunny = {
170
+ name: "bunny",
171
+ async resolveFont(family, options) {
172
+ const css = await requestText(options.fetch, `https://fonts.bunny.net/css?family=${bunnyFamilyParam(family, options)}`, { missing: [404] });
173
+ if (!css)
174
+ return;
175
+ const fonts = keepRequested(parseFontFaces(css).map(({ face }) => face), options);
176
+ return fonts.length ? { fonts } : undefined;
177
+ }
178
+ };
179
+
180
+ // packages/fonts/src/providers/fontshare.ts
181
+ function fontshareParam(family, options) {
182
+ const slug = family.toLowerCase().trim().replace(/\s+/g, "-");
183
+ const tokens = [];
184
+ for (const weight of options.weights) {
185
+ const base = isRange(weight) ? weight.replace(" ", "..") : weight;
186
+ if (options.styles.some((style) => style !== "italic"))
187
+ tokens.push(base);
188
+ if (options.styles.includes("italic"))
189
+ tokens.push(`${base}i`);
190
+ }
191
+ return `${slug}@${tokens.join(";")}`;
192
+ }
193
+ var fontshare = {
194
+ name: "fontshare",
195
+ async resolveFont(family, options) {
196
+ const css = await requestText(options.fetch, `https://api.fontshare.com/v2/css?f[]=${fontshareParam(family, options)}&display=swap`, { missing: [404] });
197
+ if (!css)
198
+ return;
199
+ const wanted = options.weights.map(weightRange);
200
+ const fonts = keepRequested(parseFontFaces(css).map(({ face }) => face), options, { subsets: false }).filter(({ weight }) => {
201
+ if (!weight)
202
+ return true;
203
+ const [low, high] = weightRange(weight);
204
+ return wanted.some(([from, to]) => low >= from && high <= to);
205
+ });
206
+ return fonts.length ? { fonts } : undefined;
207
+ }
208
+ };
209
+
210
+ // packages/fonts/src/providers/fontsource.ts
211
+ var fontsourceId = (family) => family.toLowerCase().trim().replace(/\s+/g, "-");
212
+ function parseFontsource(answer, options) {
213
+ const wanted = options.weights.map(weightRange);
214
+ const out = [];
215
+ for (const weight of Object.keys(answer.variants ?? {}).sort((a, b) => Number(a) - Number(b))) {
216
+ if (!wanted.some(([low, high]) => Number(weight) >= low && Number(weight) <= high))
217
+ continue;
218
+ for (const style of options.styles) {
219
+ for (const subset of options.subsets) {
220
+ const urls = answer.variants[weight][style]?.[subset]?.url;
221
+ if (!urls)
222
+ continue;
223
+ const src = options.formats.filter((format) => urls[format]).map((format) => ({ url: urls[format], format }));
224
+ if (!src.length)
225
+ continue;
226
+ const unicodeRange = answer.unicodeRange?.[subset];
227
+ out.push({ src, weight, style, subset, ...unicodeRange ? { unicodeRange } : {} });
228
+ }
229
+ }
230
+ }
231
+ return out;
232
+ }
233
+ var fontsource = {
234
+ name: "fontsource",
235
+ async resolveFont(family, options) {
236
+ const text = await requestText(options.fetch, `https://api.fontsource.org/v1/fonts/${encodeURIComponent(fontsourceId(family))}`, { missing: [404], headers: { accept: "application/json" } });
237
+ if (!text)
238
+ return;
239
+ let answer;
240
+ try {
241
+ answer = JSON.parse(text);
242
+ } catch {
243
+ throw new Error("api.fontsource.org answered something that is not JSON");
244
+ }
245
+ const fonts = parseFontsource(answer, options);
246
+ return fonts.length ? { fonts } : undefined;
247
+ }
248
+ };
249
+
250
+ // packages/fonts/src/providers/google.ts
251
+ var unique = (values) => [...new Set(values)];
252
+ function googleFamilyParam(family, options) {
253
+ const name = encodeURIComponent(family).replace(/%20/g, "+");
254
+ const weights = unique(options.weights.map((weight) => isRange(weight) ? weight.replace(" ", "..") : weight)).sort((a, b) => parseInt(a) - parseInt(b));
255
+ const italic = options.styles.includes("italic");
256
+ const upright = options.styles.some((style) => style !== "italic");
257
+ if (!italic)
258
+ return `${name}:wght@${weights.join(";")}`;
259
+ const tuples = [...upright ? weights.map((weight) => `0,${weight}`) : [], ...weights.map((weight) => `1,${weight}`)];
260
+ return `${name}:ital,wght@${tuples.join(";")}`;
261
+ }
262
+ var google = {
263
+ name: "google",
264
+ async resolveFont(family, options) {
265
+ const url = `https://fonts.googleapis.com/css2?family=${googleFamilyParam(family, options)}&display=swap${glyphsParam(options.glyphs)}`;
266
+ const css = await requestText(options.fetch, url, { missing: [400, 404] });
267
+ if (!css)
268
+ return;
269
+ const fonts = keepRequested(parseFontFaces(css).map(({ face }) => face), options);
270
+ return fonts.length ? { fonts } : undefined;
271
+ }
272
+ };
273
+
274
+ // packages/fonts/src/providers/googleicons.ts
275
+ var FAMILIES = ["Material Symbols Outlined", "Material Symbols Rounded", "Material Symbols Sharp", "Material Icons"];
276
+ var googleicons = {
277
+ name: "googleicons",
278
+ async resolveFont(family, options) {
279
+ const known = FAMILIES.find((name) => normalizeFamily(name) === normalizeFamily(family));
280
+ if (!known)
281
+ return;
282
+ const css = await requestText(options.fetch, `https://fonts.googleapis.com/css2?family=${known.replace(/ /g, "+")}&display=swap${glyphsParam(options.glyphs)}`, { missing: [400, 404] });
283
+ if (!css)
284
+ return;
285
+ const fonts = parseFontFaces(css).map(({ face }) => withoutSubset(face));
286
+ return fonts.length ? { fonts } : undefined;
287
+ }
288
+ };
289
+
290
+ // packages/fonts/src/providers/npm.ts
291
+ import { existsSync } from "fs";
292
+ import { readFile, readdir } from "fs/promises";
293
+ import { dirname, join } from "path";
294
+ var escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
295
+ var FORMATS2 = ["woff2", "woff"];
296
+ async function packageDir(rootDir, scope, id) {
297
+ for (let dir = rootDir;; dir = dirname(dir)) {
298
+ const found = join(dir, "node_modules", scope, id);
299
+ if (existsSync(join(found, "files")))
300
+ return found;
301
+ if (dirname(dir) === dir)
302
+ return;
303
+ }
304
+ }
305
+ async function readJson(file) {
306
+ try {
307
+ return JSON.parse(await readFile(file, "utf8"));
308
+ } catch {
309
+ return;
310
+ }
311
+ }
312
+ function createNpmProvider(scope) {
313
+ return {
314
+ name: "npm",
315
+ async resolveFont(family, options) {
316
+ const id = family.toLowerCase().trim().replace(/\s+/g, "-");
317
+ const [staticDir, variableDir] = await Promise.all([
318
+ packageDir(scope.rootDir, "@fontsource", id),
319
+ packageDir(scope.rootDir, "@fontsource-variable", id)
320
+ ]);
321
+ if (!staticDir && !variableDir)
322
+ return;
323
+ const wanted = options.weights.map(weightRange);
324
+ const useVariable = variableDir !== undefined && (staticDir === undefined || options.weights.some((weight) => weight.includes(" ")));
325
+ const dir = useVariable ? variableDir : staticDir;
326
+ const [files, unicode, metadata] = await Promise.all([
327
+ readdir(join(dir, "files")),
328
+ readJson(join(dir, "unicode.json")),
329
+ readJson(join(dir, "metadata.json"))
330
+ ]);
331
+ const pattern = new RegExp(`^${escape(id)}-(.+)-(${useVariable ? "wght" : "\\d+"})-(normal|italic)\\.(woff2|woff)$`);
332
+ const range = metadata?.variable?.wght;
333
+ const groups = new Map;
334
+ for (const file of files) {
335
+ const match = pattern.exec(file);
336
+ if (!match)
337
+ continue;
338
+ const [, subset, axis, style, extension] = match;
339
+ if (!options.subsets.includes(subset) || !options.styles.includes(style) || !options.formats.includes(extension))
340
+ continue;
341
+ if (!useVariable && !wanted.some(([low, high]) => Number(axis) >= low && Number(axis) <= high))
342
+ continue;
343
+ if (useVariable && extension !== "woff2")
344
+ continue;
345
+ const weight = useVariable ? range ? `${range.min} ${range.max}` : undefined : axis;
346
+ const key = `${weight ?? ""}\x00${style}\x00${subset}`;
347
+ const face = groups.get(key) ?? {
348
+ src: [],
349
+ style,
350
+ subset,
351
+ ...weight ? { weight } : {},
352
+ ...unicode?.[subset] ? { unicodeRange: unicode[subset] } : {}
353
+ };
354
+ face.src.push({ url: join(dir, "files", file), format: extension });
355
+ groups.set(key, face);
356
+ }
357
+ const order = (face) => [
358
+ Number(weightRange(face.weight ?? "400")[0]),
359
+ face.style === "italic" ? 1 : 0,
360
+ options.subsets.indexOf(face.subset)
361
+ ];
362
+ const fonts = [...groups.values()].map((face) => ({
363
+ ...face,
364
+ src: [...face.src].sort((a, b) => FORMATS2.indexOf(a.format) - FORMATS2.indexOf(b.format))
365
+ })).sort((a, b) => {
366
+ const [x, y] = [order(a), order(b)];
367
+ return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
368
+ });
369
+ return fonts.length ? { fonts } : undefined;
370
+ }
371
+ };
372
+ }
373
+
374
+ // packages/fonts/src/providers/index.ts
375
+ var remoteProviders = {
376
+ google,
377
+ googleicons,
378
+ bunny,
379
+ fontshare,
380
+ fontsource,
381
+ adobe
382
+ };
383
+ export {
384
+ createNpmProvider,
385
+ remoteProviders
386
+ };
@@ -0,0 +1,22 @@
1
+ // @bun
2
+ // packages/fonts/src/server/index.ts
3
+ import"hamur/server-only";
4
+ import table from "#hamur/fonts/data";
5
+
6
+ // packages/fonts/src/server/data.ts
7
+ function createFontData(table) {
8
+ return (family) => {
9
+ const faces = Object.hasOwn(table, family) ? table[family] : undefined;
10
+ if (!faces)
11
+ throw new Error(`fonts: "${family}" is not a resolved family (${Object.keys(table).join(", ") || "none"})`);
12
+ return faces.map((face) => ({ ...face }));
13
+ };
14
+ }
15
+
16
+ // packages/fonts/src/server/index.ts
17
+ var fonts = table;
18
+ var getFontData = createFontData(table);
19
+ export {
20
+ fonts,
21
+ getFontData
22
+ };
@@ -0,0 +1,17 @@
1
+ import type { FontResolution } from "../types.ts";
2
+ export interface MetaCache {
3
+ get(key: string): Promise<FontResolution | undefined>;
4
+ set(key: string, value: FontResolution): Promise<void>;
5
+ }
6
+ export declare const sha256: (data: string | Uint8Array) => string;
7
+ /** `meta/<SHA-256 of provider, family, options>.json`. */
8
+ export declare const metaKey: (provider: string, family: string, options: unknown) => string;
9
+ export declare function writeAtomic(target: string, data: string | Uint8Array): Promise<void>;
10
+ export declare function createMetaCache(dir: string): MetaCache;
11
+ /** The directory of the font cache; with `fonts.cache: false` it is the build directory, which the asset pipeline needs. */
12
+ export declare const fontsDirOf: (cache: boolean, hamur: {
13
+ options: {
14
+ cacheDir: string;
15
+ buildDir: string;
16
+ };
17
+ }) => string;
@@ -0,0 +1,19 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import type { FontData } from "../server/data.ts";
3
+ import type { FontFaceData } from "../types.ts";
4
+ /** The families a build resolved and the faces they were written with, as `fonts:resolved` sees them. */
5
+ export interface FontRegistry {
6
+ record(family: string, faces: FontFaceData[]): void;
7
+ /** Writes the names of the families recorded so far, once, for the typegen of the next run. */
8
+ flush(): Promise<void>;
9
+ }
10
+ interface Registered {
11
+ names: Map<string, string>;
12
+ faces: Map<string, FontFaceData[]>;
13
+ }
14
+ export declare function createFontRegistry(dir: string): FontRegistry & Registered;
15
+ /** The `src` of each face a build wrote for the registered families, read from the CSS of the client manifest, where the asset pipeline has put the final URLs. */
16
+ export declare function builtFontData(hamur: HamurContext, names: Map<string, string>): Promise<Record<string, FontData[]>>;
17
+ /** The template `fonts/data` (read at the server build, after the client build wrote the URLs; in `hamur dev` the paths of the files) and the family names in `.hamur/types/fonts.d.ts`, which are those of the last build. */
18
+ export declare function setupData(hamur: HamurContext, dir: string): FontRegistry;
19
+ export {};
@@ -0,0 +1,49 @@
1
+ import type { FontFaceData } from "../types.ts";
2
+ export interface FontMetrics {
3
+ unitsPerEm: number;
4
+ ascender: number;
5
+ descender: number;
6
+ lineGap: number;
7
+ /** The advance of `a`–`z` and the space, weighted by English frequency, in font units. */
8
+ meanWidth: number;
9
+ }
10
+ export interface SystemMetrics {
11
+ unitsPerEm: number;
12
+ meanWidth: number;
13
+ }
14
+ /** Ratios: `1.074` is written `107.4%`. */
15
+ export interface FallbackOverrides {
16
+ sizeAdjust: number;
17
+ ascent: number;
18
+ descent: number;
19
+ lineGap: number;
20
+ }
21
+ export declare const LETTER_FREQUENCY: Readonly<Record<string, number>>;
22
+ export declare const SYSTEM_METRICS: Readonly<Record<string, SystemMetrics>>;
23
+ export interface Table {
24
+ data: DataView;
25
+ /** WOFF2 transform version 1 of `hmtx`. */
26
+ transformed: boolean;
27
+ }
28
+ export declare const WOFF2_TAGS: string[];
29
+ export declare function readTables(bytes: Uint8Array): Map<string, Table>;
30
+ type GlyphOf = (codePoint: number) => number;
31
+ export declare function readCmap(cmap: Table | undefined): GlyphOf;
32
+ /**
33
+ * The metrics a fallback face needs, from a TTF, OTF, WOFF or WOFF2 file. Throws when the file, its cmap, `head`,
34
+ * `hhea` or `hmtx` cannot be read; `undefined` when the cmap maps none of `a`–`z` and the space.
35
+ */
36
+ export declare function readFontMetrics(bytes: Uint8Array): FontMetrics | undefined;
37
+ /** The `size-adjust` and metric overrides that make the system font take the width of `font`. */
38
+ export declare function fallbackOverrides(font: FontMetrics, system: SystemMetrics): FallbackOverrides;
39
+ export declare const fallbackFamily: (family: string, system: string) => string;
40
+ /** The files to read metrics from, best first: the upright face nearest weight 400, of the `latin` subset when there is one. */
41
+ export declare function metricSources(faces: FontFaceData[]): string[];
42
+ export interface MetricsScope {
43
+ /** The bytes of a face's `src` URL, or `undefined` when it is not a file the build can read (a remote URL kept after a failed download). */
44
+ read(url: string): Promise<Uint8Array | undefined>;
45
+ report(message: string): void;
46
+ }
47
+ /** The metrics of a family's first readable file; a file whose tables cannot be read is reported once and gives none. */
48
+ export declare function familyMetrics(family: string, faces: FontFaceData[], scope: MetricsScope): Promise<FontMetrics | undefined>;
49
+ export {};
@@ -0,0 +1,7 @@
1
+ import type { FontFaceData } from "../types.ts";
2
+ export interface FontFiles {
3
+ /** The faces with every remote `src` URL replaced by the absolute path of its downloaded file; a failed download keeps the URL. */
4
+ localize(family: string, faces: FontFaceData[], glyphs?: string): Promise<FontFaceData[]>;
5
+ }
6
+ /** Each remote font URL is downloaded once to `<dir>/<family>-<weight>-<style>-<subset>.<ext>`; with `cache`, a file whose `.json` names the same URL and SHA-256 is kept between builds. */
7
+ export declare function createFontFiles(dir: string, report: (message: string) => void, cache?: boolean): FontFiles;
@@ -0,0 +1,3 @@
1
+ import type { ResolvedFontsOptions } from "../options.ts";
2
+ /** `fonts/global.css` names each `global` family once, so the `fonts:css` transform writes its faces; an app plugin imports it, which makes it global CSS. */
3
+ export declare function setupGlobal(options: ResolvedFontsOptions): void;
@@ -0,0 +1,25 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import type { ResolvedFontsOptions } from "../options.ts";
3
+ import type { FontFaceData } from "../types.ts";
4
+ /** The file names of the faces a document should preload, collected while the CSS is transformed. */
5
+ export interface PreloadNames {
6
+ add(faces: FontFaceData[], subsets: string[]): void;
7
+ has(file: string): boolean;
8
+ }
9
+ export declare const FONT_FACE: RegExp;
10
+ export declare const URL_OF: RegExp;
11
+ export declare const ORIGIN = "http://hamur.invalid";
12
+ export declare const fileName: (url: string) => string;
13
+ /** Of one family's faces, those of the `latin` subset, else of the first of `subsets`; a face with no subset always. */
14
+ export declare function preloadedFaces(faces: FontFaceData[], subsets: string[]): FontFaceData[];
15
+ export declare function createPreloadNames(): PreloadNames;
16
+ export declare function cssURLs(manifest: unknown, into?: Set<string>): Set<string>;
17
+ /** The text of each stylesheet of the client manifest, by its URL; an inlined one is read from the manifest, the others from the output directory. */
18
+ export declare function manifestSheets(hamur: HamurContext): Promise<Array<{
19
+ url: string;
20
+ text: string;
21
+ }>>;
22
+ /** The font files each stylesheet of the manifest uses and `names` lists, by the stylesheet's URL; a `data:` URL is never listed. */
23
+ export declare function preloadTable(hamur: HamurContext, names: PreloadNames): Promise<Record<string, string[]>>;
24
+ /** The template `fonts/preloads` and the door whose server plugin writes the preload links; `hamur dev` has an empty table. */
25
+ export declare function setupPreload(options: ResolvedFontsOptions, hamur: HamurContext, names: PreloadNames): void;
@@ -0,0 +1,5 @@
1
+ import type { HamurContext } from "hamur/kit";
2
+ import { type ResolvedFontsOptions } from "../options.ts";
3
+ import type { FontProvider } from "../types.ts";
4
+ /** The files of `fonts.providers` replace built-ins, then `fonts:providers` runs once in `modules:done`; `providers` is what the resolver reads, so it is changed in place. */
5
+ export declare function setupProviders(options: ResolvedFontsOptions, hamur: HamurContext, providers: Record<string, FontProvider>): void;
@@ -0,0 +1,2 @@
1
+ /** Whether Bun's CSS bundler writes a root-absolute `url(/x.woff2)` as it is, asked once per process; Bun may resolve it as a file or fail on it. */
2
+ export declare function publicUrlsKept(): Promise<boolean>;
@@ -0,0 +1,6 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import type { ResolvedFontsOptions } from "../options.ts";
3
+ import type { FontRegistry } from "./data.ts";
4
+ import type { PreloadNames } from "./preload.ts";
5
+ /** The `fonts:css` transform, which writes the `@font-face` rules of the families a stylesheet names. */
6
+ export declare function setupScan(options: ResolvedFontsOptions, hamur: HamurContext, preload: PreloadNames, registry: FontRegistry): void;
@@ -0,0 +1,7 @@
1
+ import type { FontFaceData } from "../types.ts";
2
+ export interface FontSubsetter {
3
+ /** Each face's first readable TrueType file cut to `glyphs` and written as WOFF2; a CFF or `gvar` font, and a face with no readable file, is kept whole. */
4
+ subset(family: string, faces: FontFaceData[], glyphs: string): Promise<FontFaceData[]>;
5
+ }
6
+ /** Subsets of `local`, `src` and downloaded files, written to `<dir>/<file>-<hash>.woff2`. */
7
+ export declare function createSubsetter(dir: string, read: (url: string) => Promise<Uint8Array | undefined>, report: (message: string) => void): FontSubsetter;
@@ -0,0 +1,18 @@
1
+ import type { FontFaceData, FontProvider, FontsOptions } from "./types.ts";
2
+ export { default } from "./module.ts";
3
+ export type { FontDefaults, FontFaceData, FontFamilyOptions, FontFormat, FontProvider, FontResolution, FontsOptions, ResolveFontOptions, } from "./types.ts";
4
+ declare module "hamur" {
5
+ interface HamurModuleOptions {
6
+ fonts?: FontsOptions;
7
+ }
8
+ interface HamurHooks {
9
+ /** Once in `modules:done`; add a provider or replace one by name. */
10
+ "fonts:providers": (providers: Record<string, FontProvider>) => void | Promise<void>;
11
+ /** A family's faces as written and the absolute paths of their files, once per family. */
12
+ "fonts:resolved": (resolved: {
13
+ family: string;
14
+ faces: FontFaceData[];
15
+ files: string[];
16
+ }) => void | Promise<void>;
17
+ }
18
+ }
@@ -0,0 +1,21 @@
1
+ import { type FallbackOverrides } from "./build/fallbacks.ts";
2
+ import type { FontFaceData } from "./types.ts";
3
+ export interface FaceDescriptors {
4
+ display: string;
5
+ unicodeRange?: string;
6
+ stretch?: string;
7
+ featureSettings?: string;
8
+ variationSettings?: string;
9
+ }
10
+ export declare const quote: (text: string) => string;
11
+ /** One `@font-face` rule. A descriptor the family sets (`descriptors`) wins over the provider's. */
12
+ export declare function fontFaceRule(family: string, face: FontFaceData, descriptors: FaceDescriptors): string;
13
+ /** The face `"<Family> Fallback: <System>"`, the installed system font scaled to the web font's metrics. */
14
+ export declare function fallbackFaceRule(family: string, system: string, overrides: FallbackOverrides): string;
15
+ /** Puts each `text` into `css` at its `at`, an offset of the original text. */
16
+ export declare function insertEdits(css: string, edits: Array<{
17
+ at: number;
18
+ text: string;
19
+ }>): string;
20
+ /** Puts `rules` into `css` at `at`, each on its own line. */
21
+ export declare function insertRules(css: string, at: number, rules: string[]): string;
@@ -0,0 +1,3 @@
1
+ import type { FontsOptions } from "./types.ts";
2
+ declare const _default: import("hamur/kit").HamurModule<FontsOptions>;
3
+ export default _default;
@@ -0,0 +1,46 @@
1
+ import type { FontDefaults, FontProvider } from "./types.ts";
2
+ export declare const BUILT_IN_PROVIDERS: string[];
3
+ export declare const FALLBACK_SYSTEM_FONTS: string[];
4
+ export interface ResolvedFamily extends FontDefaults {
5
+ name: string;
6
+ provider?: string;
7
+ /** Absolute paths. */
8
+ src?: string[];
9
+ /** The family lists its own `weights`, not the defaults'. */
10
+ ownWeights: boolean;
11
+ unicodeRange?: string;
12
+ stretch?: string;
13
+ featureSettings?: string;
14
+ variationSettings?: string;
15
+ glyphs?: string;
16
+ global: boolean;
17
+ }
18
+ export interface ResolvedFontsOptions {
19
+ enabled: boolean;
20
+ priority: string[];
21
+ /** Built-in providers set to `false`. */
22
+ disabled: Set<string>;
23
+ /** `providers.<name>.options`. */
24
+ providerOptions: Record<string, Record<string, unknown>>;
25
+ /** The default export of each file of `providers`, by key. */
26
+ custom: Record<string, FontProvider>;
27
+ defaults: FontDefaults;
28
+ families: ResolvedFamily[];
29
+ processCSSVariables: boolean | "font-prefixed-only";
30
+ fallbacks: false | Record<string, string[]>;
31
+ localSources: boolean;
32
+ cache: boolean;
33
+ throwOnError: boolean;
34
+ }
35
+ export interface OptionsContext {
36
+ rootDir: string;
37
+ exists(path: string): boolean;
38
+ /** The default export of the file. */
39
+ load(file: string): Promise<unknown>;
40
+ }
41
+ /** A path of the config: a `package.json` `imports` key, an absolute path or a path from the app root. */
42
+ export declare function resolveConfigPath(ctx: Pick<OptionsContext, "rootDir">, path: string): string;
43
+ /** Run after `fonts:providers`, which may add the names `priority` lists. */
44
+ export declare function checkPriority(priority: readonly string[], providers: Iterable<string>): void;
45
+ /** Checks the `fonts` config key and fills in its defaults; the first wrong value throws a message naming its key. */
46
+ export declare function resolveOptions(input: unknown, ctx: OptionsContext): Promise<ResolvedFontsOptions>;
@@ -0,0 +1,2 @@
1
+ import type { FontProvider } from "../types.ts";
2
+ export declare const adobe: FontProvider;
@@ -0,0 +1,4 @@
1
+ import type { FontProvider, ResolveFontOptions } from "../types.ts";
2
+ /** `inter:400,400i,700`; a range asks every hundred inside it, because Bunny serves static weights. */
3
+ export declare function bunnyFamilyParam(family: string, options: Pick<ResolveFontOptions, "weights" | "styles">): string;
4
+ export declare const bunny: FontProvider;