@hamur/fonts 0.0.0-stage → 0.0.2
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 +41 -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,2472 @@
|
|
|
1
|
+
// packages/fonts/src/module.ts
|
|
2
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { defineModule } from "hamur/kit";
|
|
5
|
+
|
|
6
|
+
// packages/fonts/src/build/cache.ts
|
|
7
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
var sha256 = (data) => new Bun.CryptoHasher("sha256").update(data).digest("hex");
|
|
10
|
+
var sorted = (_key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : 1)) : value;
|
|
11
|
+
var metaKey = (provider, family, options) => sha256(JSON.stringify([provider, family, options], sorted));
|
|
12
|
+
var writes = 0;
|
|
13
|
+
async function writeAtomic(target, data) {
|
|
14
|
+
await mkdir(join(target, ".."), { recursive: true });
|
|
15
|
+
const part = `${target}.${process.pid}.${++writes}.part`;
|
|
16
|
+
await writeFile(part, data);
|
|
17
|
+
await rename(part, target);
|
|
18
|
+
}
|
|
19
|
+
function createMetaCache(dir) {
|
|
20
|
+
return {
|
|
21
|
+
async get(key) {
|
|
22
|
+
try {
|
|
23
|
+
const value = JSON.parse(await readFile(join(dir, `${key}.json`), "utf8"));
|
|
24
|
+
return typeof value === "object" && value !== null && Array.isArray(value.fonts) ? value : undefined;
|
|
25
|
+
} catch {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
async set(key, value) {
|
|
30
|
+
await writeAtomic(join(dir, `${key}.json`), JSON.stringify(value));
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
var fontsDirOf = (cache, hamur) => join(cache ? hamur.options.cacheDir : hamur.options.buildDir, "fonts");
|
|
35
|
+
|
|
36
|
+
// packages/fonts/src/build/data.ts
|
|
37
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
38
|
+
import { join as join3 } from "node:path";
|
|
39
|
+
import { addTemplate as addTemplate2, addTypeTemplate } from "hamur/kit";
|
|
40
|
+
|
|
41
|
+
// packages/fonts/src/scan.ts
|
|
42
|
+
var GENERIC = new Set([
|
|
43
|
+
"serif",
|
|
44
|
+
"sans-serif",
|
|
45
|
+
"monospace",
|
|
46
|
+
"cursive",
|
|
47
|
+
"fantasy",
|
|
48
|
+
"system-ui",
|
|
49
|
+
"ui-serif",
|
|
50
|
+
"ui-sans-serif",
|
|
51
|
+
"ui-monospace",
|
|
52
|
+
"ui-rounded",
|
|
53
|
+
"emoji",
|
|
54
|
+
"math",
|
|
55
|
+
"fangsong"
|
|
56
|
+
]);
|
|
57
|
+
var CSS_WIDE = new Set(["inherit", "initial", "unset", "revert", "revert-layer", "default"]);
|
|
58
|
+
var SYSTEM_FAMILIES = [
|
|
59
|
+
"-apple-system",
|
|
60
|
+
"BlinkMacSystemFont",
|
|
61
|
+
"Arial",
|
|
62
|
+
"Helvetica",
|
|
63
|
+
"Helvetica Neue",
|
|
64
|
+
"Times New Roman",
|
|
65
|
+
"Georgia",
|
|
66
|
+
"Courier New",
|
|
67
|
+
"Verdana",
|
|
68
|
+
"Tahoma",
|
|
69
|
+
"Trebuchet MS",
|
|
70
|
+
"Menlo",
|
|
71
|
+
"Monaco",
|
|
72
|
+
"Consolas",
|
|
73
|
+
"Segoe UI",
|
|
74
|
+
"Roboto",
|
|
75
|
+
"SF Pro",
|
|
76
|
+
"Noto Sans",
|
|
77
|
+
"Ubuntu",
|
|
78
|
+
"Cantarell",
|
|
79
|
+
"Apple Color Emoji",
|
|
80
|
+
"Segoe UI Emoji",
|
|
81
|
+
"Segoe UI Symbol",
|
|
82
|
+
"Noto Color Emoji",
|
|
83
|
+
"SFMono-Regular",
|
|
84
|
+
"Liberation Mono",
|
|
85
|
+
"Courier",
|
|
86
|
+
"Cambria",
|
|
87
|
+
"Times"
|
|
88
|
+
];
|
|
89
|
+
var SYSTEM = new Set(SYSTEM_FAMILIES.map((name) => name.toLowerCase()));
|
|
90
|
+
var familyKey = (name) => name.trim().replace(/\s+/g, " ").toLowerCase();
|
|
91
|
+
var isSystemFamily = (name) => SYSTEM.has(familyKey(name));
|
|
92
|
+
var lineOf = (text, index) => text.slice(0, index).split(`
|
|
93
|
+
`).length;
|
|
94
|
+
var blank = (length, char) => char.repeat(length);
|
|
95
|
+
function mask(css) {
|
|
96
|
+
let plain = "";
|
|
97
|
+
let shell = "";
|
|
98
|
+
let i = 0;
|
|
99
|
+
while (i < css.length) {
|
|
100
|
+
const char = css[i];
|
|
101
|
+
if (char === "/" && css[i + 1] === "*") {
|
|
102
|
+
const close = css.indexOf("*/", i + 2);
|
|
103
|
+
const end = close === -1 ? css.length : close + 2;
|
|
104
|
+
const gap = css.slice(i, end).replace(/[^\n]/g, " ");
|
|
105
|
+
plain += gap;
|
|
106
|
+
shell += gap;
|
|
107
|
+
i = end;
|
|
108
|
+
} else if (char === '"' || char === "'") {
|
|
109
|
+
let j = i + 1;
|
|
110
|
+
for (;j < css.length && css[j] !== char; j++) {
|
|
111
|
+
if (css[j] === "\\")
|
|
112
|
+
j++;
|
|
113
|
+
else if (css[j] === `
|
|
114
|
+
`)
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
if (css[j] !== char)
|
|
118
|
+
throw new Error(`unterminated string on line ${lineOf(css, i)}`);
|
|
119
|
+
plain += css.slice(i, j + 1);
|
|
120
|
+
shell += char + blank(j - i - 1, "_") + char;
|
|
121
|
+
i = j + 1;
|
|
122
|
+
} else if ((char === "u" || char === "U") && /^url\(\s*[^\s"')]/i.test(css.slice(i, i + 40))) {
|
|
123
|
+
const open = css.indexOf("(", i) + 1;
|
|
124
|
+
let j = open;
|
|
125
|
+
while (j < css.length && css[j] !== ")")
|
|
126
|
+
j += css[j] === "\\" ? 2 : 1;
|
|
127
|
+
j = Math.min(j, css.length);
|
|
128
|
+
plain += css.slice(i, j);
|
|
129
|
+
shell += css.slice(i, open) + blank(j - open, "_");
|
|
130
|
+
i = j;
|
|
131
|
+
} else {
|
|
132
|
+
plain += char;
|
|
133
|
+
shell += char;
|
|
134
|
+
i++;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return { plain, shell };
|
|
138
|
+
}
|
|
139
|
+
var LEADING = /^@(?:charset|import|layer)(?![\w-])/i;
|
|
140
|
+
function leadingEnd(shell) {
|
|
141
|
+
let at = 0;
|
|
142
|
+
let end = 0;
|
|
143
|
+
for (;; ) {
|
|
144
|
+
while (at < shell.length && /\s/.test(shell[at]))
|
|
145
|
+
at++;
|
|
146
|
+
if (!LEADING.test(shell.slice(at, at + 9)))
|
|
147
|
+
return end;
|
|
148
|
+
const semicolon = shell.indexOf(";", at);
|
|
149
|
+
const brace = shell.indexOf("{", at);
|
|
150
|
+
if (semicolon === -1 || brace !== -1 && brace < semicolon)
|
|
151
|
+
return end;
|
|
152
|
+
at = end = semicolon + 1;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
var IDENT = /^-{0,2}[A-Za-z_\u0080-][\w\u0080--]*$/;
|
|
156
|
+
function familyList(plain, shell, from, to) {
|
|
157
|
+
const names = [];
|
|
158
|
+
let generic;
|
|
159
|
+
let itemStart = from;
|
|
160
|
+
let depth = 0;
|
|
161
|
+
const item = (start, end) => {
|
|
162
|
+
while (start < end && /\s/.test(plain[start]))
|
|
163
|
+
start++;
|
|
164
|
+
while (end > start && /\s/.test(plain[end - 1]))
|
|
165
|
+
end--;
|
|
166
|
+
if (start >= end)
|
|
167
|
+
return;
|
|
168
|
+
generic = undefined;
|
|
169
|
+
const text = plain.slice(start, end);
|
|
170
|
+
let name;
|
|
171
|
+
if (text[0] === '"' || text[0] === "'") {
|
|
172
|
+
if (text.length > 1 && text.at(-1) === text[0])
|
|
173
|
+
name = text.slice(1, -1).replace(/\\(.)/g, "$1");
|
|
174
|
+
} else if (!text.includes("(")) {
|
|
175
|
+
const tokens = text.split(/(?<!\\)\s+/);
|
|
176
|
+
if (tokens.every((token) => IDENT.test(token.replace(/\\./g, "_"))))
|
|
177
|
+
name = tokens.map((token) => token.replace(/\\(.)/g, "$1")).join(" ");
|
|
178
|
+
}
|
|
179
|
+
if (name === undefined || name === "")
|
|
180
|
+
return;
|
|
181
|
+
const key = familyKey(name);
|
|
182
|
+
if (text[0] !== '"' && text[0] !== "'" && (GENERIC.has(key) || CSS_WIDE.has(key))) {
|
|
183
|
+
if (GENERIC.has(key))
|
|
184
|
+
generic = key;
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
names.push({ name, start, end });
|
|
188
|
+
};
|
|
189
|
+
for (let i = from;i < to; i++) {
|
|
190
|
+
const char = shell[i];
|
|
191
|
+
if (char === "(" || char === "[")
|
|
192
|
+
depth++;
|
|
193
|
+
else if (char === ")" || char === "]")
|
|
194
|
+
depth--;
|
|
195
|
+
else if (char === "," && depth === 0) {
|
|
196
|
+
item(itemStart, i);
|
|
197
|
+
itemStart = i + 1;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
item(itemStart, to);
|
|
201
|
+
return generic ? { names, generic } : { names };
|
|
202
|
+
}
|
|
203
|
+
var LENGTH = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:px|r?em|ex|ch|cap|ic|r?lh|v[wh]|vmin|vmax|[sld]v(?:w|h|i|b|min|max)|cq(?:w|h|i|b|min|max)|cm|mm|q|in|pt|pc|%)$/i;
|
|
204
|
+
var SIZE_KEYWORD = /^(?:xx-small|x-small|small|medium|large|x-large|xx-large|xxx-large|larger|smaller)$/i;
|
|
205
|
+
var SIZE_FUNCTION = /^(?:calc|clamp|min|max)\(/i;
|
|
206
|
+
var isSize = (token) => {
|
|
207
|
+
const size = token.split("/")[0];
|
|
208
|
+
return LENGTH.test(size) || SIZE_KEYWORD.test(size) || SIZE_FUNCTION.test(size);
|
|
209
|
+
};
|
|
210
|
+
function shorthandFamilies(plain, shell, from, to) {
|
|
211
|
+
const tokens = [];
|
|
212
|
+
let depth = 0;
|
|
213
|
+
let start = -1;
|
|
214
|
+
for (let i = from;i <= to; i++) {
|
|
215
|
+
const char = i < to ? shell[i] : " ";
|
|
216
|
+
if (start === -1 && !/\s/.test(char))
|
|
217
|
+
start = i;
|
|
218
|
+
if (char === "(")
|
|
219
|
+
depth++;
|
|
220
|
+
else if (char === ")")
|
|
221
|
+
depth--;
|
|
222
|
+
if (start !== -1 && depth === 0 && /\s/.test(char)) {
|
|
223
|
+
tokens.push({ text: shell.slice(start, i), start });
|
|
224
|
+
start = -1;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const size = tokens.findIndex((token) => isSize(token.text));
|
|
228
|
+
if (size === -1)
|
|
229
|
+
return;
|
|
230
|
+
let next = size + 1;
|
|
231
|
+
const withLineHeight = tokens[size].text.includes("/") && !tokens[size].text.endsWith("/");
|
|
232
|
+
if (!withLineHeight && tokens[next]?.text.startsWith("/"))
|
|
233
|
+
next += tokens[next].text === "/" ? 2 : 1;
|
|
234
|
+
else if (tokens[size].text.endsWith("/"))
|
|
235
|
+
next += 1;
|
|
236
|
+
const first = tokens[next];
|
|
237
|
+
return first ? familyList(plain, shell, first.start, to) : undefined;
|
|
238
|
+
}
|
|
239
|
+
var PROPERTY = /^\s*([\w\\-]+)\s*:/;
|
|
240
|
+
var IMPORTANT = /\s*!\s*important\s*$/i;
|
|
241
|
+
function scanCss(css, options = {}) {
|
|
242
|
+
const { plain, shell } = mask(css);
|
|
243
|
+
const custom = options.customProperties ?? "font-prefixed-only";
|
|
244
|
+
const uses = [];
|
|
245
|
+
const declared = [];
|
|
246
|
+
const blocks = [];
|
|
247
|
+
const declaration = (from, to) => {
|
|
248
|
+
if (blocks.length === 0)
|
|
249
|
+
return;
|
|
250
|
+
const match = PROPERTY.exec(shell.slice(from, to));
|
|
251
|
+
if (!match)
|
|
252
|
+
return;
|
|
253
|
+
const property = match[1];
|
|
254
|
+
const lower = property.toLowerCase();
|
|
255
|
+
const valueFrom = from + match[0].length;
|
|
256
|
+
const valueTo = to - (IMPORTANT.exec(shell.slice(valueFrom, to))?.[0].length ?? 0);
|
|
257
|
+
if (blocks.at(-1)) {
|
|
258
|
+
if (lower === "font-family")
|
|
259
|
+
for (const name of familyList(plain, shell, valueFrom, valueTo).names)
|
|
260
|
+
declared.push(familyKey(name.name));
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
let use;
|
|
264
|
+
if (lower === "font-family")
|
|
265
|
+
use = familyList(plain, shell, valueFrom, valueTo);
|
|
266
|
+
else if (lower === "font")
|
|
267
|
+
use = shorthandFamilies(plain, shell, valueFrom, valueTo);
|
|
268
|
+
else if (property.startsWith("--") && (custom === true || custom === "font-prefixed-only" && lower.startsWith("--font-")))
|
|
269
|
+
use = familyList(plain, shell, valueFrom, valueTo);
|
|
270
|
+
if (use?.names.length)
|
|
271
|
+
uses.push(use);
|
|
272
|
+
};
|
|
273
|
+
let statement = 0;
|
|
274
|
+
let depth = 0;
|
|
275
|
+
for (let i = 0;i < shell.length; i++) {
|
|
276
|
+
const char = shell[i];
|
|
277
|
+
if (char === "(" || char === "[")
|
|
278
|
+
depth++;
|
|
279
|
+
else if (char === ")" || char === "]")
|
|
280
|
+
depth = Math.max(0, depth - 1);
|
|
281
|
+
else if (depth > 0)
|
|
282
|
+
continue;
|
|
283
|
+
else if (char === "{") {
|
|
284
|
+
blocks.push(/^\s*@font-face(?![\w-])/i.test(shell.slice(statement, i)));
|
|
285
|
+
statement = i + 1;
|
|
286
|
+
} else if (char === ";") {
|
|
287
|
+
declaration(statement, i);
|
|
288
|
+
statement = i + 1;
|
|
289
|
+
} else if (char === "}") {
|
|
290
|
+
declaration(statement, i);
|
|
291
|
+
blocks.pop();
|
|
292
|
+
statement = i + 1;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return { uses, declared, insertAt: leadingEnd(shell) };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// packages/fonts/src/build/preload.ts
|
|
299
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
300
|
+
import { join as join2 } from "node:path";
|
|
301
|
+
import { addServer, addTemplate, createResolver } from "hamur/kit";
|
|
302
|
+
var HASH = /-[0-9a-zA-Z]{8}(\.[^.]+)$/;
|
|
303
|
+
var FONT_FACE = /@font-face\s*\{[^}]*\}/gi;
|
|
304
|
+
var URL_OF = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\)/gi;
|
|
305
|
+
var ORIGIN = "http://hamur.invalid";
|
|
306
|
+
var fileName = (url) => {
|
|
307
|
+
const name = url.split(/[?#]/)[0].split(/[\\/]/).pop();
|
|
308
|
+
try {
|
|
309
|
+
return decodeURIComponent(name);
|
|
310
|
+
} catch {
|
|
311
|
+
return name;
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
function preloadedFaces(faces, subsets) {
|
|
315
|
+
const wanted = faces.some((face) => face.subset === "latin") ? "latin" : subsets[0];
|
|
316
|
+
return faces.filter((face) => face.subset === undefined || face.subset === wanted);
|
|
317
|
+
}
|
|
318
|
+
function createPreloadNames() {
|
|
319
|
+
const names = new Set;
|
|
320
|
+
return {
|
|
321
|
+
add(faces, subsets) {
|
|
322
|
+
for (const face of preloadedFaces(faces, subsets)) {
|
|
323
|
+
const first = face.src.find((entry) => ("url" in entry));
|
|
324
|
+
if (first)
|
|
325
|
+
names.add(fileName(first.url));
|
|
326
|
+
}
|
|
327
|
+
},
|
|
328
|
+
has: (file) => names.has(file) || names.has(file.replace(HASH, "$1"))
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
function cssURLs(manifest, into = new Set) {
|
|
332
|
+
if (typeof manifest === "string") {
|
|
333
|
+
if (manifest.endsWith(".css"))
|
|
334
|
+
into.add(manifest);
|
|
335
|
+
} else if (Array.isArray(manifest)) {
|
|
336
|
+
for (const item of manifest)
|
|
337
|
+
cssURLs(item, into);
|
|
338
|
+
} else if (typeof manifest === "object" && manifest !== null) {
|
|
339
|
+
for (const [key, value] of Object.entries(manifest))
|
|
340
|
+
if (key !== "inline" && key !== "integrity")
|
|
341
|
+
cssURLs(value, into);
|
|
342
|
+
}
|
|
343
|
+
return into;
|
|
344
|
+
}
|
|
345
|
+
async function manifestSheets(hamur) {
|
|
346
|
+
const { manifest, options } = hamur;
|
|
347
|
+
const dir = join2(options.outputDir, "public", options.app.buildAssetsDir.replace(/^\/+|\/+$/g, ""));
|
|
348
|
+
const sheets = [];
|
|
349
|
+
for (const url of cssURLs(manifest)) {
|
|
350
|
+
const text = manifest.inline?.[url] ?? await readFile2(join2(dir, fileName(url)), "utf8").catch(() => {
|
|
351
|
+
return;
|
|
352
|
+
});
|
|
353
|
+
if (text !== undefined)
|
|
354
|
+
sheets.push({ url, text });
|
|
355
|
+
}
|
|
356
|
+
return sheets;
|
|
357
|
+
}
|
|
358
|
+
async function preloadTable(hamur, names) {
|
|
359
|
+
const table = {};
|
|
360
|
+
for (const { url: sheet, text } of await manifestSheets(hamur)) {
|
|
361
|
+
const base = new URL(sheet, `${ORIGIN}/`);
|
|
362
|
+
const fonts = new Set;
|
|
363
|
+
for (const rule of text.match(FONT_FACE) ?? []) {
|
|
364
|
+
for (const match of rule.matchAll(URL_OF)) {
|
|
365
|
+
const href = match[1] ?? match[2] ?? match[3] ?? "";
|
|
366
|
+
if (!href || /^data:/i.test(href))
|
|
367
|
+
continue;
|
|
368
|
+
let resolved;
|
|
369
|
+
try {
|
|
370
|
+
resolved = new URL(href, base);
|
|
371
|
+
} catch {
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if (names.has(fileName(resolved.pathname)))
|
|
375
|
+
fonts.add(resolved.origin === ORIGIN ? resolved.pathname + resolved.search : resolved.href);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (fonts.size)
|
|
379
|
+
table[sheet] = [...fonts];
|
|
380
|
+
}
|
|
381
|
+
return table;
|
|
382
|
+
}
|
|
383
|
+
function setupPreload(options, hamur, names) {
|
|
384
|
+
if (!options.defaults.preload && !options.families.some((family) => family.preload))
|
|
385
|
+
return;
|
|
386
|
+
addTemplate({
|
|
387
|
+
filename: "fonts/preloads",
|
|
388
|
+
getContents: async () => `export default ${JSON.stringify(hamur.options.dev ? {} : await preloadTable(hamur, names))};
|
|
389
|
+
`
|
|
390
|
+
});
|
|
391
|
+
addServer(createResolver(new URL("../../src/build/preload.ts", import.meta.url).href).resolve("../server/door.ts"));
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// packages/fonts/src/build/data.ts
|
|
395
|
+
var FORMATS = {
|
|
396
|
+
woff2: "woff2",
|
|
397
|
+
woff: "woff",
|
|
398
|
+
ttf: "ttf",
|
|
399
|
+
otf: "otf",
|
|
400
|
+
truetype: "ttf",
|
|
401
|
+
opentype: "otf"
|
|
402
|
+
};
|
|
403
|
+
var unquote = (value) => value.trim().replace(/^(["'])(.*)\1$/s, "$2");
|
|
404
|
+
var extensionOf = (url) => FORMATS[/\.([a-z0-9]+)$/i.exec(url.split(/[?#]/)[0])?.[1]?.toLowerCase() ?? ""] ?? "";
|
|
405
|
+
function createFontRegistry(dir) {
|
|
406
|
+
const registered = { names: new Map, faces: new Map };
|
|
407
|
+
return {
|
|
408
|
+
...registered,
|
|
409
|
+
record(family, faces) {
|
|
410
|
+
const key = familyKey(family);
|
|
411
|
+
registered.names.set(key, family);
|
|
412
|
+
registered.faces.set(key, faces);
|
|
413
|
+
},
|
|
414
|
+
async flush() {
|
|
415
|
+
await writeAtomic(join3(dir, "families.json"), JSON.stringify([...registered.names.values()].sort()));
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
function declaration(rule, property) {
|
|
420
|
+
const found = new RegExp(`(?:^|[;{\\s])${property}\\s*:\\s*([^;}]*)`, "i").exec(rule);
|
|
421
|
+
return found?.[1]?.trim();
|
|
422
|
+
}
|
|
423
|
+
async function builtFontData(hamur, names) {
|
|
424
|
+
const table = {};
|
|
425
|
+
const seen = new Set;
|
|
426
|
+
for (const { url: sheet, text } of await manifestSheets(hamur)) {
|
|
427
|
+
const base = new URL(sheet, `${ORIGIN}/`);
|
|
428
|
+
for (const rule of text.match(FONT_FACE) ?? []) {
|
|
429
|
+
const family = names.get(familyKey(unquote(declaration(rule, "font-family") ?? "")));
|
|
430
|
+
const source = declaration(rule, "src");
|
|
431
|
+
if (!family || !source)
|
|
432
|
+
continue;
|
|
433
|
+
for (const match of source.matchAll(URL_OF)) {
|
|
434
|
+
const href = match[1] ?? match[2] ?? match[3] ?? "";
|
|
435
|
+
if (!href || /^data:/i.test(href))
|
|
436
|
+
continue;
|
|
437
|
+
let resolved;
|
|
438
|
+
try {
|
|
439
|
+
resolved = new URL(href, base);
|
|
440
|
+
} catch {
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
const src = resolved.origin === ORIGIN ? resolved.pathname + resolved.search : resolved.href;
|
|
444
|
+
const format = /^\s*format\(\s*(.*?)\s*\)/i.exec(source.slice(match.index + match[0].length).replace(/^\s*/, ""));
|
|
445
|
+
const entry = {
|
|
446
|
+
src,
|
|
447
|
+
weight: declaration(rule, "font-weight") ?? "400",
|
|
448
|
+
style: declaration(rule, "font-style") ?? "normal",
|
|
449
|
+
format: format && FORMATS[unquote(format[1]).toLowerCase()] || extensionOf(fileName(src))
|
|
450
|
+
};
|
|
451
|
+
const id = `${family}\x00${entry.src}\x00${entry.weight}\x00${entry.style}`;
|
|
452
|
+
if (seen.has(id))
|
|
453
|
+
continue;
|
|
454
|
+
seen.add(id);
|
|
455
|
+
(table[family] ??= []).push(entry);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
return table;
|
|
460
|
+
}
|
|
461
|
+
function devFontData(registered) {
|
|
462
|
+
const table = {};
|
|
463
|
+
for (const [key, faces] of registered.faces) {
|
|
464
|
+
const entries = [];
|
|
465
|
+
for (const face of faces) {
|
|
466
|
+
for (const entry of face.src) {
|
|
467
|
+
if (!("url" in entry))
|
|
468
|
+
continue;
|
|
469
|
+
entries.push({
|
|
470
|
+
src: entry.url,
|
|
471
|
+
weight: face.weight ?? "400",
|
|
472
|
+
style: face.style ?? "normal",
|
|
473
|
+
format: entry.format ?? extensionOf(entry.url)
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (entries.length)
|
|
478
|
+
table[registered.names.get(key)] = entries;
|
|
479
|
+
}
|
|
480
|
+
return table;
|
|
481
|
+
}
|
|
482
|
+
async function previousFamilies(dir) {
|
|
483
|
+
try {
|
|
484
|
+
const names = JSON.parse(await readFile3(join3(dir, "families.json"), "utf8"));
|
|
485
|
+
return Array.isArray(names) ? names.filter((name) => typeof name === "string") : [];
|
|
486
|
+
} catch {
|
|
487
|
+
return [];
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function setupData(hamur, dir) {
|
|
491
|
+
const registry = createFontRegistry(dir);
|
|
492
|
+
addTemplate2({
|
|
493
|
+
filename: "fonts/data",
|
|
494
|
+
getContents: async () => {
|
|
495
|
+
await registry.flush();
|
|
496
|
+
return `export default ${JSON.stringify(hamur.options.dev ? devFontData(registry) : await builtFontData(hamur, registry.names))};
|
|
497
|
+
`;
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
addTypeTemplate({
|
|
501
|
+
filename: "fonts.d.ts",
|
|
502
|
+
getContents: async () => {
|
|
503
|
+
const names = (await previousFamilies(dir)).map((name) => ` ${JSON.stringify(name)}: true;`);
|
|
504
|
+
return names.length ? `declare module "@hamur/fonts/server" {
|
|
505
|
+
interface HamurFontFamilies {
|
|
506
|
+
${names.join(`
|
|
507
|
+
`)}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
export {};
|
|
511
|
+
` : `export {};
|
|
512
|
+
`;
|
|
513
|
+
}
|
|
514
|
+
});
|
|
515
|
+
return registry;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// packages/fonts/src/build/global.ts
|
|
519
|
+
import { addAppPlugin, addTemplate as addTemplate3, createResolver as createResolver2 } from "hamur/kit";
|
|
520
|
+
|
|
521
|
+
// packages/fonts/src/build/fallbacks.ts
|
|
522
|
+
import { brotliDecompressSync, inflateSync } from "node:zlib";
|
|
523
|
+
var LETTER_FREQUENCY = {
|
|
524
|
+
" ": 0.154,
|
|
525
|
+
a: 0.0668,
|
|
526
|
+
b: 0.0114,
|
|
527
|
+
c: 0.0232,
|
|
528
|
+
d: 0.0298,
|
|
529
|
+
e: 0.0922,
|
|
530
|
+
f: 0.017,
|
|
531
|
+
g: 0.0155,
|
|
532
|
+
h: 0.0351,
|
|
533
|
+
i: 0.0588,
|
|
534
|
+
j: 0.0009,
|
|
535
|
+
k: 0.0046,
|
|
536
|
+
l: 0.0304,
|
|
537
|
+
m: 0.0181,
|
|
538
|
+
n: 0.0578,
|
|
539
|
+
o: 0.0571,
|
|
540
|
+
p: 0.0163,
|
|
541
|
+
q: 0.0008,
|
|
542
|
+
r: 0.0526,
|
|
543
|
+
s: 0.0469,
|
|
544
|
+
t: 0.0672,
|
|
545
|
+
u: 0.0207,
|
|
546
|
+
v: 0.0076,
|
|
547
|
+
w: 0.011,
|
|
548
|
+
x: 0.0025,
|
|
549
|
+
y: 0.0123,
|
|
550
|
+
z: 0.0011
|
|
551
|
+
};
|
|
552
|
+
var SYSTEM_METRICS = {
|
|
553
|
+
Arial: { unitsPerEm: 2048, meanWidth: 899.0846 },
|
|
554
|
+
Helvetica: { unitsPerEm: 2048, meanWidth: 899.0846 },
|
|
555
|
+
"Times New Roman": { unitsPerEm: 2048, meanWidth: 814.8911 },
|
|
556
|
+
Georgia: { unitsPerEm: 2048, meanWidth: 896.64 },
|
|
557
|
+
"Courier New": { unitsPerEm: 2048, meanWidth: 1229 },
|
|
558
|
+
"Segoe UI": { unitsPerEm: 2048, meanWidth: 901.7859 },
|
|
559
|
+
Roboto: { unitsPerEm: 2048, meanWidth: 902.8188 }
|
|
560
|
+
};
|
|
561
|
+
var view = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
562
|
+
var tagAt = (data, at) => String.fromCharCode(data.getUint8(at), data.getUint8(at + 1), data.getUint8(at + 2), data.getUint8(at + 3));
|
|
563
|
+
function slice(bytes, offset, length) {
|
|
564
|
+
if (offset + length > bytes.byteLength)
|
|
565
|
+
throw new Error("a table runs past the end of the file");
|
|
566
|
+
return bytes.subarray(offset, offset + length);
|
|
567
|
+
}
|
|
568
|
+
function sfntTables(bytes) {
|
|
569
|
+
const data = view(bytes);
|
|
570
|
+
const tables = new Map;
|
|
571
|
+
const count = data.getUint16(4);
|
|
572
|
+
for (let i = 0;i < count; i++) {
|
|
573
|
+
const at = 12 + 16 * i;
|
|
574
|
+
tables.set(tagAt(data, at), {
|
|
575
|
+
data: view(slice(bytes, data.getUint32(at + 8), data.getUint32(at + 12))),
|
|
576
|
+
transformed: false
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
return tables;
|
|
580
|
+
}
|
|
581
|
+
function woffTables(bytes) {
|
|
582
|
+
const data = view(bytes);
|
|
583
|
+
const tables = new Map;
|
|
584
|
+
const count = data.getUint16(12);
|
|
585
|
+
for (let i = 0;i < count; i++) {
|
|
586
|
+
const at = 44 + 20 * i;
|
|
587
|
+
const stored = slice(bytes, data.getUint32(at + 4), data.getUint32(at + 8));
|
|
588
|
+
const length = data.getUint32(at + 12);
|
|
589
|
+
const table = stored.byteLength < length ? new Uint8Array(inflateSync(stored)) : stored;
|
|
590
|
+
tables.set(tagAt(data, at), { data: view(table), transformed: false });
|
|
591
|
+
}
|
|
592
|
+
return tables;
|
|
593
|
+
}
|
|
594
|
+
var WOFF2_TAGS = [
|
|
595
|
+
"cmap",
|
|
596
|
+
"head",
|
|
597
|
+
"hhea",
|
|
598
|
+
"hmtx",
|
|
599
|
+
"maxp",
|
|
600
|
+
"name",
|
|
601
|
+
"OS/2",
|
|
602
|
+
"post",
|
|
603
|
+
"cvt ",
|
|
604
|
+
"fpgm",
|
|
605
|
+
"glyf",
|
|
606
|
+
"loca",
|
|
607
|
+
"prep",
|
|
608
|
+
"CFF ",
|
|
609
|
+
"VORG",
|
|
610
|
+
"EBDT",
|
|
611
|
+
"EBLC",
|
|
612
|
+
"gasp",
|
|
613
|
+
"hdmx",
|
|
614
|
+
"kern",
|
|
615
|
+
"LTSH",
|
|
616
|
+
"PCLT",
|
|
617
|
+
"VDMX",
|
|
618
|
+
"vhea",
|
|
619
|
+
"vmtx",
|
|
620
|
+
"BASE",
|
|
621
|
+
"GDEF",
|
|
622
|
+
"GPOS",
|
|
623
|
+
"GSUB",
|
|
624
|
+
"EBSC",
|
|
625
|
+
"JSTF",
|
|
626
|
+
"MATH",
|
|
627
|
+
"CBDT",
|
|
628
|
+
"CBLC",
|
|
629
|
+
"COLR",
|
|
630
|
+
"CPAL",
|
|
631
|
+
"SVG ",
|
|
632
|
+
"sbix",
|
|
633
|
+
"acnt",
|
|
634
|
+
"avar",
|
|
635
|
+
"bdat",
|
|
636
|
+
"bloc",
|
|
637
|
+
"bsln",
|
|
638
|
+
"cvar",
|
|
639
|
+
"fdsc",
|
|
640
|
+
"feat",
|
|
641
|
+
"fmtx",
|
|
642
|
+
"fvar",
|
|
643
|
+
"gvar",
|
|
644
|
+
"hsty",
|
|
645
|
+
"just",
|
|
646
|
+
"lcar",
|
|
647
|
+
"mort",
|
|
648
|
+
"morx",
|
|
649
|
+
"opbd",
|
|
650
|
+
"prop",
|
|
651
|
+
"trak",
|
|
652
|
+
"Zapf",
|
|
653
|
+
"Silf",
|
|
654
|
+
"Glat",
|
|
655
|
+
"Gloc",
|
|
656
|
+
"Feat",
|
|
657
|
+
"Sill"
|
|
658
|
+
];
|
|
659
|
+
function base128(data, at) {
|
|
660
|
+
let value = 0;
|
|
661
|
+
for (let i = 0;i < 5; i++) {
|
|
662
|
+
const byte = data.getUint8(at.offset++);
|
|
663
|
+
if (i === 0 && byte === 128)
|
|
664
|
+
throw new Error("a UIntBase128 has a leading zero");
|
|
665
|
+
if (value & 4261412864)
|
|
666
|
+
throw new Error("a UIntBase128 overflows");
|
|
667
|
+
value = value << 7 | byte & 127;
|
|
668
|
+
if ((byte & 128) === 0)
|
|
669
|
+
return value >>> 0;
|
|
670
|
+
}
|
|
671
|
+
throw new Error("a UIntBase128 is longer than 5 bytes");
|
|
672
|
+
}
|
|
673
|
+
function woff2Tables(bytes) {
|
|
674
|
+
const data = view(bytes);
|
|
675
|
+
if (tagAt(data, 4) === "ttcf")
|
|
676
|
+
throw new Error("a WOFF2 collection is not read");
|
|
677
|
+
const count = data.getUint16(12);
|
|
678
|
+
const compressed = data.getUint32(20);
|
|
679
|
+
const at = { offset: 48 };
|
|
680
|
+
const entries = [];
|
|
681
|
+
for (let i = 0;i < count; i++) {
|
|
682
|
+
const flags = data.getUint8(at.offset++);
|
|
683
|
+
const known = flags & 63;
|
|
684
|
+
let tag;
|
|
685
|
+
if (known === 63) {
|
|
686
|
+
tag = tagAt(data, at.offset);
|
|
687
|
+
at.offset += 4;
|
|
688
|
+
} else {
|
|
689
|
+
tag = WOFF2_TAGS[known];
|
|
690
|
+
}
|
|
691
|
+
const version = flags >> 6;
|
|
692
|
+
const original = base128(data, at);
|
|
693
|
+
const transformed = tag === "glyf" || tag === "loca" ? version !== 3 : version !== 0;
|
|
694
|
+
entries.push({ tag, length: transformed ? base128(data, at) : original, transformed });
|
|
695
|
+
}
|
|
696
|
+
const stream = new Uint8Array(brotliDecompressSync(slice(bytes, at.offset, compressed)));
|
|
697
|
+
const tables = new Map;
|
|
698
|
+
let offset = 0;
|
|
699
|
+
for (const entry of entries) {
|
|
700
|
+
tables.set(entry.tag, { data: view(slice(stream, offset, entry.length)), transformed: entry.transformed });
|
|
701
|
+
offset += entry.length;
|
|
702
|
+
}
|
|
703
|
+
return tables;
|
|
704
|
+
}
|
|
705
|
+
function readTables(bytes) {
|
|
706
|
+
if (bytes.byteLength < 12)
|
|
707
|
+
throw new Error("the file is not a font");
|
|
708
|
+
const signature = tagAt(view(bytes), 0);
|
|
709
|
+
if (signature === "wOFF")
|
|
710
|
+
return woffTables(bytes);
|
|
711
|
+
if (signature === "wOF2")
|
|
712
|
+
return woff2Tables(bytes);
|
|
713
|
+
if (signature === "\x00\x01\x00\x00" || signature === "OTTO" || signature === "true")
|
|
714
|
+
return sfntTables(bytes);
|
|
715
|
+
throw new Error("the file is not a font");
|
|
716
|
+
}
|
|
717
|
+
function format4(data, base) {
|
|
718
|
+
const segments = data.getUint16(base + 6) / 2;
|
|
719
|
+
const ends = base + 14;
|
|
720
|
+
const starts = ends + 2 * segments + 2;
|
|
721
|
+
const deltas = starts + 2 * segments;
|
|
722
|
+
const ranges = deltas + 2 * segments;
|
|
723
|
+
return (codePoint) => {
|
|
724
|
+
for (let i = 0;i < segments; i++) {
|
|
725
|
+
if (data.getUint16(ends + 2 * i) < codePoint)
|
|
726
|
+
continue;
|
|
727
|
+
const start = data.getUint16(starts + 2 * i);
|
|
728
|
+
if (start > codePoint)
|
|
729
|
+
return 0;
|
|
730
|
+
const delta = data.getInt16(deltas + 2 * i);
|
|
731
|
+
const range = data.getUint16(ranges + 2 * i);
|
|
732
|
+
if (range === 0)
|
|
733
|
+
return codePoint + delta & 65535;
|
|
734
|
+
const glyph = data.getUint16(ranges + 2 * i + range + 2 * (codePoint - start));
|
|
735
|
+
return glyph === 0 ? 0 : glyph + delta & 65535;
|
|
736
|
+
}
|
|
737
|
+
return 0;
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
function format12(data, base) {
|
|
741
|
+
const groups = data.getUint32(base + 12);
|
|
742
|
+
return (codePoint) => {
|
|
743
|
+
for (let i = 0;i < groups; i++) {
|
|
744
|
+
const at = base + 16 + 12 * i;
|
|
745
|
+
const start = data.getUint32(at);
|
|
746
|
+
if (codePoint >= start && codePoint <= data.getUint32(at + 4))
|
|
747
|
+
return data.getUint32(at + 8) + codePoint - start;
|
|
748
|
+
}
|
|
749
|
+
return 0;
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
function readCmap(cmap) {
|
|
753
|
+
if (!cmap)
|
|
754
|
+
throw new Error("no cmap");
|
|
755
|
+
const { data } = cmap;
|
|
756
|
+
let found4;
|
|
757
|
+
let found12;
|
|
758
|
+
for (let i = 0;i < data.getUint16(2); i++) {
|
|
759
|
+
const platform = data.getUint16(4 + 8 * i);
|
|
760
|
+
const encoding = data.getUint16(6 + 8 * i);
|
|
761
|
+
const offset = data.getUint32(8 + 8 * i);
|
|
762
|
+
if (platform !== 0 && !(platform === 3 && (encoding === 1 || encoding === 10)))
|
|
763
|
+
continue;
|
|
764
|
+
const format = data.getUint16(offset);
|
|
765
|
+
if (format === 4)
|
|
766
|
+
found4 ??= offset;
|
|
767
|
+
else if (format === 12)
|
|
768
|
+
found12 ??= offset;
|
|
769
|
+
}
|
|
770
|
+
if (found12 !== undefined)
|
|
771
|
+
return format12(data, found12);
|
|
772
|
+
if (found4 !== undefined)
|
|
773
|
+
return format4(data, found4);
|
|
774
|
+
throw new Error("no cmap of format 4 or 12");
|
|
775
|
+
}
|
|
776
|
+
function need(tables, tag) {
|
|
777
|
+
const table = tables.get(tag);
|
|
778
|
+
if (!table)
|
|
779
|
+
throw new Error(`no ${tag}`);
|
|
780
|
+
return table.data;
|
|
781
|
+
}
|
|
782
|
+
function readFontMetrics(bytes) {
|
|
783
|
+
const tables = readTables(bytes);
|
|
784
|
+
const glyphOf = readCmap(tables.get("cmap"));
|
|
785
|
+
const head = need(tables, "head");
|
|
786
|
+
const hhea = need(tables, "hhea");
|
|
787
|
+
const hmtx = tables.get("hmtx");
|
|
788
|
+
if (!hmtx)
|
|
789
|
+
throw new Error("no hmtx");
|
|
790
|
+
const metrics = hhea.getUint16(34);
|
|
791
|
+
if (metrics === 0)
|
|
792
|
+
throw new Error("hhea.numberOfHMetrics is 0");
|
|
793
|
+
const advance = (glyph) => {
|
|
794
|
+
const index = Math.min(glyph, metrics - 1);
|
|
795
|
+
return hmtx.transformed ? hmtx.data.getUint16(1 + 2 * index) : hmtx.data.getUint16(4 * index);
|
|
796
|
+
};
|
|
797
|
+
let weighted = 0;
|
|
798
|
+
let total = 0;
|
|
799
|
+
for (const [char, weight] of Object.entries(LETTER_FREQUENCY)) {
|
|
800
|
+
const glyph = glyphOf(char.charCodeAt(0));
|
|
801
|
+
if (glyph === 0)
|
|
802
|
+
continue;
|
|
803
|
+
weighted += advance(glyph) * weight;
|
|
804
|
+
total += weight;
|
|
805
|
+
}
|
|
806
|
+
if (total === 0)
|
|
807
|
+
return;
|
|
808
|
+
return {
|
|
809
|
+
unitsPerEm: head.getUint16(18),
|
|
810
|
+
ascender: hhea.getInt16(4),
|
|
811
|
+
descender: hhea.getInt16(6),
|
|
812
|
+
lineGap: hhea.getInt16(8),
|
|
813
|
+
meanWidth: weighted / total
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
function fallbackOverrides(font, system) {
|
|
817
|
+
const sizeAdjust = font.meanWidth / font.unitsPerEm / (system.meanWidth / system.unitsPerEm);
|
|
818
|
+
const scale = font.unitsPerEm * sizeAdjust;
|
|
819
|
+
return {
|
|
820
|
+
sizeAdjust,
|
|
821
|
+
ascent: font.ascender / scale,
|
|
822
|
+
descent: Math.abs(font.descender) / scale,
|
|
823
|
+
lineGap: font.lineGap / scale
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
var fallbackFamily = (family, system) => `${family} Fallback: ${system}`;
|
|
827
|
+
var weightDistance = (weight) => {
|
|
828
|
+
const parts = (weight ?? "400").trim().split(/\s+/).map(Number);
|
|
829
|
+
const low = parts[0];
|
|
830
|
+
const high = parts[1] ?? low;
|
|
831
|
+
return low > 400 ? low - 400 : high < 400 ? 400 - high : 0;
|
|
832
|
+
};
|
|
833
|
+
function metricSources(faces) {
|
|
834
|
+
const ranked = faces.map((face, index) => ({ face, index })).sort((a, b) => Number((a.face.style ?? "normal") !== "normal") - Number((b.face.style ?? "normal") !== "normal") || weightDistance(a.face.weight) - weightDistance(b.face.weight) || Number(a.face.subset !== undefined && a.face.subset !== "latin") - Number(b.face.subset !== undefined && b.face.subset !== "latin") || a.index - b.index);
|
|
835
|
+
return ranked.flatMap(({ face }) => face.src.flatMap((entry) => ("url" in entry) ? [entry.url] : []));
|
|
836
|
+
}
|
|
837
|
+
async function familyMetrics(family, faces, scope) {
|
|
838
|
+
for (const url of metricSources(faces)) {
|
|
839
|
+
const bytes = await scope.read(url);
|
|
840
|
+
if (!bytes)
|
|
841
|
+
continue;
|
|
842
|
+
try {
|
|
843
|
+
return readFontMetrics(bytes);
|
|
844
|
+
} catch {
|
|
845
|
+
scope.report(`[fonts] no fallback metrics for ${JSON.stringify(family)}: its file has no readable cmap`);
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// packages/fonts/src/inject.ts
|
|
853
|
+
var CSS_FORMAT = { woff2: "woff2", woff: "woff", ttf: "truetype", otf: "opentype" };
|
|
854
|
+
var quote = (text) => `"${text.replace(/[\\"]/g, "\\$&").replace(/\n/g, "\\a ")}"`;
|
|
855
|
+
var cssUrl = (url) => /^[\w\-./%~]+$/.test(url) ? `url(${url})` : `url(${quote(url)})`;
|
|
856
|
+
function fontFaceRule(family, face, descriptors) {
|
|
857
|
+
const src = face.src.map((entry) => ("name" in entry) ? `local(${quote(entry.name)})` : `${cssUrl(entry.url)}${entry.format ? ` format(${quote(CSS_FORMAT[entry.format])})` : ""}`);
|
|
858
|
+
const parts = [`font-family: ${quote(family)}`, `src: ${src.join(", ")}`];
|
|
859
|
+
const add = (name, value) => {
|
|
860
|
+
if (value !== undefined && value !== "")
|
|
861
|
+
parts.push(`${name}: ${value}`);
|
|
862
|
+
};
|
|
863
|
+
add("font-weight", face.weight);
|
|
864
|
+
add("font-style", face.style === "normal" ? undefined : face.style);
|
|
865
|
+
add("font-stretch", descriptors.stretch ?? face.stretch);
|
|
866
|
+
add("unicode-range", descriptors.unicodeRange ?? face.unicodeRange);
|
|
867
|
+
add("font-display", descriptors.display);
|
|
868
|
+
add("font-feature-settings", descriptors.featureSettings ?? face.featureSettings);
|
|
869
|
+
add("font-variation-settings", descriptors.variationSettings ?? face.variationSettings);
|
|
870
|
+
return `@font-face { ${parts.join("; ")} }`;
|
|
871
|
+
}
|
|
872
|
+
var percent = (ratio) => `${Number((ratio * 100).toFixed(4))}%`;
|
|
873
|
+
function fallbackFaceRule(family, system, overrides) {
|
|
874
|
+
return `@font-face { font-family: ${quote(fallbackFamily(family, system))}; src: local(${quote(system)}); size-adjust: ${percent(overrides.sizeAdjust)}; ascent-override: ${percent(overrides.ascent)}; descent-override: ${percent(overrides.descent)}; line-gap-override: ${percent(overrides.lineGap)} }`;
|
|
875
|
+
}
|
|
876
|
+
function insertEdits(css, edits) {
|
|
877
|
+
let out = css;
|
|
878
|
+
for (const edit of [...edits].sort((a, b) => b.at - a.at))
|
|
879
|
+
out = `${out.slice(0, edit.at)}${edit.text}${out.slice(edit.at)}`;
|
|
880
|
+
return out;
|
|
881
|
+
}
|
|
882
|
+
function insertRules(css, at, rules) {
|
|
883
|
+
if (rules.length === 0)
|
|
884
|
+
return css;
|
|
885
|
+
const head = css.slice(0, at);
|
|
886
|
+
const tail = css.slice(at).replace(/^\r?\n/, "");
|
|
887
|
+
return `${head}${head === "" || head.endsWith(`
|
|
888
|
+
`) ? "" : `
|
|
889
|
+
`}${rules.join(`
|
|
890
|
+
`)}
|
|
891
|
+
${tail}`;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// packages/fonts/src/build/global.ts
|
|
895
|
+
function setupGlobal(options) {
|
|
896
|
+
const names = options.families.filter((family) => family.global).map((family) => family.name);
|
|
897
|
+
if (names.length === 0)
|
|
898
|
+
return;
|
|
899
|
+
addTemplate3({
|
|
900
|
+
filename: "fonts/global.css",
|
|
901
|
+
getContents: () => `${names.map((name) => `.hamur-fonts-global { font-family: ${quote(name)} }`).join(`
|
|
902
|
+
`)}
|
|
903
|
+
`
|
|
904
|
+
});
|
|
905
|
+
addAppPlugin({ src: createResolver2(new URL("../../src/build/global.ts", import.meta.url).href).resolve("../runtime/global.ts"), mode: "all" });
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// packages/fonts/src/build/public-url.ts
|
|
909
|
+
var kept;
|
|
910
|
+
var PROBE = "@font-face{font-family:probe;src:url(/hamur-probe.woff2)}";
|
|
911
|
+
async function probe() {
|
|
912
|
+
try {
|
|
913
|
+
const result = await Bun.build({ entrypoints: ["./probe.css"], files: { "./probe.css": PROBE }, throw: false });
|
|
914
|
+
if (!result.success)
|
|
915
|
+
return false;
|
|
916
|
+
const css = (await Promise.all(result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => output.text()))).join("");
|
|
917
|
+
return /url\(\s*["']?\/hamur-probe\.woff2["']?\s*\)/.test(css);
|
|
918
|
+
} catch {
|
|
919
|
+
return false;
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
function publicUrlsKept() {
|
|
923
|
+
return kept ??= probe();
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// packages/fonts/src/build/scan.ts
|
|
927
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
928
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
929
|
+
import { isAbsolute as isAbsolute2, join as join8 } from "node:path";
|
|
930
|
+
import { addTransform, diagnostic, useLogger } from "hamur/kit";
|
|
931
|
+
|
|
932
|
+
// packages/fonts/src/providers/local.ts
|
|
933
|
+
import { readdir } from "node:fs/promises";
|
|
934
|
+
import { basename, join as join4, sep } from "node:path";
|
|
935
|
+
var EXTENSION = /\.(woff2|woff|ttf|otf)$/i;
|
|
936
|
+
var FORMAT_ORDER = ["woff2", "woff", "ttf", "otf"];
|
|
937
|
+
var WEIGHT_NAMES = {
|
|
938
|
+
thin: 100,
|
|
939
|
+
hairline: 100,
|
|
940
|
+
extralight: 200,
|
|
941
|
+
ultralight: 200,
|
|
942
|
+
light: 300,
|
|
943
|
+
regular: 400,
|
|
944
|
+
normal: 400,
|
|
945
|
+
book: 400,
|
|
946
|
+
medium: 500,
|
|
947
|
+
semibold: 600,
|
|
948
|
+
demibold: 600,
|
|
949
|
+
bold: 700,
|
|
950
|
+
extrabold: 800,
|
|
951
|
+
ultrabold: 800,
|
|
952
|
+
black: 900,
|
|
953
|
+
heavy: 900
|
|
954
|
+
};
|
|
955
|
+
var normal = (text) => text.toLowerCase().replace(/[\s_-]+/g, "");
|
|
956
|
+
function modifiers(rest) {
|
|
957
|
+
let weight;
|
|
958
|
+
let style = "normal";
|
|
959
|
+
for (const raw of rest.split(/[-_ ]+/).filter(Boolean)) {
|
|
960
|
+
let token = raw.toLowerCase();
|
|
961
|
+
const slanted = /^(.*?)(italic|oblique)$/.exec(token);
|
|
962
|
+
if (slanted) {
|
|
963
|
+
style = slanted[2];
|
|
964
|
+
token = slanted[1];
|
|
965
|
+
if (token === "")
|
|
966
|
+
continue;
|
|
967
|
+
}
|
|
968
|
+
if (/^\d{1,4}$/.test(token) && Number(token) >= 1 && Number(token) <= 1000)
|
|
969
|
+
weight = String(Number(token));
|
|
970
|
+
else if (token in WEIGHT_NAMES)
|
|
971
|
+
weight = String(WEIGHT_NAMES[token]);
|
|
972
|
+
else
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
return { ...weight ? { weight } : {}, style };
|
|
976
|
+
}
|
|
977
|
+
function parseFontFile(file, family) {
|
|
978
|
+
const extension = EXTENSION.exec(file);
|
|
979
|
+
if (!extension)
|
|
980
|
+
return;
|
|
981
|
+
const stem = basename(file).slice(0, -extension[0].length);
|
|
982
|
+
const target = normal(family);
|
|
983
|
+
for (let at = 0;at <= stem.length; at++) {
|
|
984
|
+
if (at < stem.length && !/[-_ ]/.test(stem[at]))
|
|
985
|
+
continue;
|
|
986
|
+
if (normal(stem.slice(0, at)) !== target)
|
|
987
|
+
continue;
|
|
988
|
+
const parsed = modifiers(stem.slice(at + 1));
|
|
989
|
+
if (parsed)
|
|
990
|
+
return { ...parsed, format: extension[1].toLowerCase() };
|
|
991
|
+
}
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
async function list(dir, pub) {
|
|
995
|
+
const entries = await readdir(dir, { recursive: true, withFileTypes: true }).catch(() => []);
|
|
996
|
+
return entries.filter((entry) => entry.isFile() && EXTENSION.test(entry.name)).map((entry) => {
|
|
997
|
+
const absolute = join4(entry.parentPath, entry.name);
|
|
998
|
+
return {
|
|
999
|
+
absolute,
|
|
1000
|
+
relative: absolute.slice(dir.length + 1).split(sep).join("/"),
|
|
1001
|
+
pub
|
|
1002
|
+
};
|
|
1003
|
+
}).sort((a, b) => a.relative.localeCompare(b.relative));
|
|
1004
|
+
}
|
|
1005
|
+
function createLocalProvider(scope) {
|
|
1006
|
+
let index;
|
|
1007
|
+
const files = () => index ??= Promise.all([
|
|
1008
|
+
...scope.assetDirs.map((dir) => list(dir, false)),
|
|
1009
|
+
...scope.publicDirs.map((dir) => list(dir, true))
|
|
1010
|
+
]).then((lists) => lists.flat());
|
|
1011
|
+
const publicUrl = (relative) => `${scope.baseURL.replace(/\/+$/, "")}/${encodeURI(relative)}`;
|
|
1012
|
+
return {
|
|
1013
|
+
name: "local",
|
|
1014
|
+
async resolveFont(family) {
|
|
1015
|
+
const faces = new Map;
|
|
1016
|
+
let kept;
|
|
1017
|
+
for (const file of await files()) {
|
|
1018
|
+
const parsed = parseFontFile(file.relative, family);
|
|
1019
|
+
if (!parsed)
|
|
1020
|
+
continue;
|
|
1021
|
+
const key = `${parsed.weight ?? ""}\x00${parsed.style}`;
|
|
1022
|
+
const face = faces.get(key) ?? {
|
|
1023
|
+
...parsed.weight ? { weight: parsed.weight } : {},
|
|
1024
|
+
style: parsed.style,
|
|
1025
|
+
src: new Map
|
|
1026
|
+
};
|
|
1027
|
+
faces.set(key, face);
|
|
1028
|
+
if (face.src.has(parsed.format))
|
|
1029
|
+
continue;
|
|
1030
|
+
if (file.pub)
|
|
1031
|
+
kept ??= await scope.publicUrlsKept();
|
|
1032
|
+
face.src.set(parsed.format, file.pub && kept ? publicUrl(file.relative) : file.absolute);
|
|
1033
|
+
}
|
|
1034
|
+
if (faces.size === 0)
|
|
1035
|
+
return;
|
|
1036
|
+
const fonts = [...faces.values()].sort((a, b) => Number(a.weight ?? 400) - Number(b.weight ?? 400) || a.style.localeCompare(b.style)).map((face) => ({
|
|
1037
|
+
src: FORMAT_ORDER.filter((format) => face.src.has(format)).map((format) => ({
|
|
1038
|
+
url: face.src.get(format),
|
|
1039
|
+
format
|
|
1040
|
+
})),
|
|
1041
|
+
...face.weight ? { weight: face.weight } : {},
|
|
1042
|
+
style: face.style
|
|
1043
|
+
}));
|
|
1044
|
+
return { fonts };
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
// packages/fonts/src/providers/css.ts
|
|
1050
|
+
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";
|
|
1051
|
+
var FORMATS2 = {
|
|
1052
|
+
woff2: "woff2",
|
|
1053
|
+
"woff2-variations": "woff2",
|
|
1054
|
+
woff: "woff",
|
|
1055
|
+
truetype: "ttf",
|
|
1056
|
+
"truetype-variations": "ttf",
|
|
1057
|
+
opentype: "otf",
|
|
1058
|
+
"opentype-variations": "otf"
|
|
1059
|
+
};
|
|
1060
|
+
var normalizeFamily = (name) => name.toLowerCase().replace(/[\s_-]+/g, "");
|
|
1061
|
+
function splitTop(text, separator) {
|
|
1062
|
+
const parts = [];
|
|
1063
|
+
let depth = 0;
|
|
1064
|
+
let quote = "";
|
|
1065
|
+
let start = 0;
|
|
1066
|
+
for (let at = 0;at < text.length; at++) {
|
|
1067
|
+
const char = text[at];
|
|
1068
|
+
if (quote) {
|
|
1069
|
+
if (char === "\\")
|
|
1070
|
+
at++;
|
|
1071
|
+
else if (char === quote)
|
|
1072
|
+
quote = "";
|
|
1073
|
+
} else if (char === '"' || char === "'")
|
|
1074
|
+
quote = char;
|
|
1075
|
+
else if (char === "(")
|
|
1076
|
+
depth++;
|
|
1077
|
+
else if (char === ")")
|
|
1078
|
+
depth--;
|
|
1079
|
+
else if (char === separator && depth === 0) {
|
|
1080
|
+
parts.push(text.slice(start, at));
|
|
1081
|
+
start = at + 1;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
parts.push(text.slice(start));
|
|
1085
|
+
return parts.map((part) => part.trim()).filter(Boolean);
|
|
1086
|
+
}
|
|
1087
|
+
var unquote2 = (value) => value.trim().replace(/^(["'])(.*)\1$/s, "$2");
|
|
1088
|
+
function absoluteUrl(url) {
|
|
1089
|
+
return url.startsWith("//") ? `https:${url}` : url;
|
|
1090
|
+
}
|
|
1091
|
+
function parseSrc(value) {
|
|
1092
|
+
const out = [];
|
|
1093
|
+
for (const item of splitTop(value, ",")) {
|
|
1094
|
+
const local = /^local\(\s*(.*?)\s*\)$/s.exec(item);
|
|
1095
|
+
if (local) {
|
|
1096
|
+
out.push({ name: unquote2(local[1]) });
|
|
1097
|
+
continue;
|
|
1098
|
+
}
|
|
1099
|
+
const url = /^url\(\s*(.*?)\s*\)\s*(?:format\(\s*(.*?)\s*\))?$/s.exec(item);
|
|
1100
|
+
if (!url)
|
|
1101
|
+
continue;
|
|
1102
|
+
const format = url[2] ? FORMATS2[unquote2(url[2]).toLowerCase()] : undefined;
|
|
1103
|
+
out.push({ url: absoluteUrl(unquote2(url[1])), ...format ? { format } : {} });
|
|
1104
|
+
}
|
|
1105
|
+
return out;
|
|
1106
|
+
}
|
|
1107
|
+
var uniqueGlyphs = (glyphs) => [...new Set(Array.from(glyphs))].join("");
|
|
1108
|
+
var glyphsParam = (glyphs) => {
|
|
1109
|
+
const text = uniqueGlyphs(glyphs ?? "");
|
|
1110
|
+
return text ? `&text=${encodeURIComponent(text)}` : "";
|
|
1111
|
+
};
|
|
1112
|
+
function parseFontFaces(css) {
|
|
1113
|
+
const out = [];
|
|
1114
|
+
const rule = /(?:\/\*\s*([^*]*?)\s*\*\/\s*)?@font-face\s*\{([^}]*)\}/g;
|
|
1115
|
+
for (let match = rule.exec(css);match; match = rule.exec(css)) {
|
|
1116
|
+
const declarations = new Map;
|
|
1117
|
+
for (const declaration of splitTop(match[2], ";")) {
|
|
1118
|
+
const colon = declaration.indexOf(":");
|
|
1119
|
+
if (colon > 0)
|
|
1120
|
+
declarations.set(declaration.slice(0, colon).trim().toLowerCase(), declaration.slice(colon + 1).trim());
|
|
1121
|
+
}
|
|
1122
|
+
const family = declarations.get("font-family");
|
|
1123
|
+
const src = parseSrc(declarations.get("src") ?? "");
|
|
1124
|
+
if (!family || !src.length)
|
|
1125
|
+
continue;
|
|
1126
|
+
const field = (key, name) => {
|
|
1127
|
+
const value = declarations.get(key);
|
|
1128
|
+
return value ? { [name]: value } : {};
|
|
1129
|
+
};
|
|
1130
|
+
const subset = match[1];
|
|
1131
|
+
out.push({
|
|
1132
|
+
family: unquote2(family),
|
|
1133
|
+
face: {
|
|
1134
|
+
src,
|
|
1135
|
+
...field("font-weight", "weight"),
|
|
1136
|
+
...field("font-style", "style"),
|
|
1137
|
+
...field("font-stretch", "stretch"),
|
|
1138
|
+
...field("unicode-range", "unicodeRange"),
|
|
1139
|
+
...field("font-display", "display"),
|
|
1140
|
+
...field("font-feature-settings", "featureSettings"),
|
|
1141
|
+
...field("font-variation-settings", "variationSettings"),
|
|
1142
|
+
...subset ? { subset } : {}
|
|
1143
|
+
}
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
return out;
|
|
1147
|
+
}
|
|
1148
|
+
function withoutSubset({ subset: _subset, ...face }) {
|
|
1149
|
+
return face;
|
|
1150
|
+
}
|
|
1151
|
+
async function requestText(fetchFn, url, options = {}) {
|
|
1152
|
+
const response = await fetchFn(url, { headers: options.headers ?? { "user-agent": CHROME_UA } });
|
|
1153
|
+
if (options.missing?.includes(response.status))
|
|
1154
|
+
return;
|
|
1155
|
+
if (!response.ok)
|
|
1156
|
+
throw new Error(`${new URL(url).host} answered ${response.status}`);
|
|
1157
|
+
return response.text();
|
|
1158
|
+
}
|
|
1159
|
+
var weightRange = (weight) => {
|
|
1160
|
+
const [low, high] = weight.split(" ").map(Number);
|
|
1161
|
+
return [low, high ?? low];
|
|
1162
|
+
};
|
|
1163
|
+
var isRange = (weight) => weight.includes(" ");
|
|
1164
|
+
function keepRequested(faces, options, only = { subsets: true }) {
|
|
1165
|
+
const out = [];
|
|
1166
|
+
for (const face of faces) {
|
|
1167
|
+
if (!options.styles.includes(face.style ?? "normal"))
|
|
1168
|
+
continue;
|
|
1169
|
+
if (only.subsets && face.subset && !/^\[\d+\]$/.test(face.subset) && !options.subsets.includes(face.subset))
|
|
1170
|
+
continue;
|
|
1171
|
+
const src = face.src.filter((entry) => !("url" in entry) || !entry.format || options.formats.includes(entry.format));
|
|
1172
|
+
if (!src.some((entry) => ("url" in entry)))
|
|
1173
|
+
continue;
|
|
1174
|
+
out.push(only.subsets ? { ...face, src } : { ...withoutSubset(face), src });
|
|
1175
|
+
}
|
|
1176
|
+
return out;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// packages/fonts/src/providers/adobe.ts
|
|
1180
|
+
var adobe = {
|
|
1181
|
+
name: "adobe",
|
|
1182
|
+
async resolveFont(family, options) {
|
|
1183
|
+
const id = options.options?.id;
|
|
1184
|
+
if (typeof id !== "string" || id === "")
|
|
1185
|
+
return;
|
|
1186
|
+
const css = await requestText(options.fetch, `https://use.typekit.net/${encodeURIComponent(id)}.css`, {
|
|
1187
|
+
missing: [404]
|
|
1188
|
+
});
|
|
1189
|
+
if (!css)
|
|
1190
|
+
return;
|
|
1191
|
+
const fonts = parseFontFaces(css).filter((parsed) => normalizeFamily(parsed.family) === normalizeFamily(family)).map(({ face }) => face);
|
|
1192
|
+
return fonts.length ? { fonts } : undefined;
|
|
1193
|
+
}
|
|
1194
|
+
};
|
|
1195
|
+
|
|
1196
|
+
// packages/fonts/src/providers/bunny.ts
|
|
1197
|
+
function bunnyFamilyParam(family, options) {
|
|
1198
|
+
const weights = new Set;
|
|
1199
|
+
for (const weight of options.weights) {
|
|
1200
|
+
const [low, high] = weightRange(weight);
|
|
1201
|
+
if (low === high)
|
|
1202
|
+
weights.add(low);
|
|
1203
|
+
else
|
|
1204
|
+
for (let at = Math.ceil(low / 100) * 100;at <= high; at += 100)
|
|
1205
|
+
weights.add(at);
|
|
1206
|
+
}
|
|
1207
|
+
const tokens = [];
|
|
1208
|
+
for (const weight of [...weights].sort((a, b) => a - b)) {
|
|
1209
|
+
if (options.styles.some((style) => style !== "italic"))
|
|
1210
|
+
tokens.push(String(weight));
|
|
1211
|
+
if (options.styles.includes("italic"))
|
|
1212
|
+
tokens.push(`${weight}i`);
|
|
1213
|
+
}
|
|
1214
|
+
return `${family.toLowerCase().trim().replace(/\s+/g, "-")}:${tokens.join(",")}`;
|
|
1215
|
+
}
|
|
1216
|
+
var bunny = {
|
|
1217
|
+
name: "bunny",
|
|
1218
|
+
async resolveFont(family, options) {
|
|
1219
|
+
const css = await requestText(options.fetch, `https://fonts.bunny.net/css?family=${bunnyFamilyParam(family, options)}`, { missing: [404] });
|
|
1220
|
+
if (!css)
|
|
1221
|
+
return;
|
|
1222
|
+
const fonts = keepRequested(parseFontFaces(css).map(({ face }) => face), options);
|
|
1223
|
+
return fonts.length ? { fonts } : undefined;
|
|
1224
|
+
}
|
|
1225
|
+
};
|
|
1226
|
+
|
|
1227
|
+
// packages/fonts/src/providers/fontshare.ts
|
|
1228
|
+
function fontshareParam(family, options) {
|
|
1229
|
+
const slug = family.toLowerCase().trim().replace(/\s+/g, "-");
|
|
1230
|
+
const tokens = [];
|
|
1231
|
+
for (const weight of options.weights) {
|
|
1232
|
+
const base = isRange(weight) ? weight.replace(" ", "..") : weight;
|
|
1233
|
+
if (options.styles.some((style) => style !== "italic"))
|
|
1234
|
+
tokens.push(base);
|
|
1235
|
+
if (options.styles.includes("italic"))
|
|
1236
|
+
tokens.push(`${base}i`);
|
|
1237
|
+
}
|
|
1238
|
+
return `${slug}@${tokens.join(";")}`;
|
|
1239
|
+
}
|
|
1240
|
+
var fontshare = {
|
|
1241
|
+
name: "fontshare",
|
|
1242
|
+
async resolveFont(family, options) {
|
|
1243
|
+
const css = await requestText(options.fetch, `https://api.fontshare.com/v2/css?f[]=${fontshareParam(family, options)}&display=swap`, { missing: [404] });
|
|
1244
|
+
if (!css)
|
|
1245
|
+
return;
|
|
1246
|
+
const wanted = options.weights.map(weightRange);
|
|
1247
|
+
const fonts = keepRequested(parseFontFaces(css).map(({ face }) => face), options, { subsets: false }).filter(({ weight }) => {
|
|
1248
|
+
if (!weight)
|
|
1249
|
+
return true;
|
|
1250
|
+
const [low, high] = weightRange(weight);
|
|
1251
|
+
return wanted.some(([from, to]) => low >= from && high <= to);
|
|
1252
|
+
});
|
|
1253
|
+
return fonts.length ? { fonts } : undefined;
|
|
1254
|
+
}
|
|
1255
|
+
};
|
|
1256
|
+
|
|
1257
|
+
// packages/fonts/src/providers/fontsource.ts
|
|
1258
|
+
var fontsourceId = (family) => family.toLowerCase().trim().replace(/\s+/g, "-");
|
|
1259
|
+
function parseFontsource(answer, options) {
|
|
1260
|
+
const wanted = options.weights.map(weightRange);
|
|
1261
|
+
const out = [];
|
|
1262
|
+
for (const weight of Object.keys(answer.variants ?? {}).sort((a, b) => Number(a) - Number(b))) {
|
|
1263
|
+
if (!wanted.some(([low, high]) => Number(weight) >= low && Number(weight) <= high))
|
|
1264
|
+
continue;
|
|
1265
|
+
for (const style of options.styles) {
|
|
1266
|
+
for (const subset of options.subsets) {
|
|
1267
|
+
const urls = answer.variants[weight][style]?.[subset]?.url;
|
|
1268
|
+
if (!urls)
|
|
1269
|
+
continue;
|
|
1270
|
+
const src = options.formats.filter((format) => urls[format]).map((format) => ({ url: urls[format], format }));
|
|
1271
|
+
if (!src.length)
|
|
1272
|
+
continue;
|
|
1273
|
+
const unicodeRange = answer.unicodeRange?.[subset];
|
|
1274
|
+
out.push({ src, weight, style, subset, ...unicodeRange ? { unicodeRange } : {} });
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
return out;
|
|
1279
|
+
}
|
|
1280
|
+
var fontsource = {
|
|
1281
|
+
name: "fontsource",
|
|
1282
|
+
async resolveFont(family, options) {
|
|
1283
|
+
const text = await requestText(options.fetch, `https://api.fontsource.org/v1/fonts/${encodeURIComponent(fontsourceId(family))}`, { missing: [404], headers: { accept: "application/json" } });
|
|
1284
|
+
if (!text)
|
|
1285
|
+
return;
|
|
1286
|
+
let answer;
|
|
1287
|
+
try {
|
|
1288
|
+
answer = JSON.parse(text);
|
|
1289
|
+
} catch {
|
|
1290
|
+
throw new Error("api.fontsource.org answered something that is not JSON");
|
|
1291
|
+
}
|
|
1292
|
+
const fonts = parseFontsource(answer, options);
|
|
1293
|
+
return fonts.length ? { fonts } : undefined;
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
|
|
1297
|
+
// packages/fonts/src/providers/google.ts
|
|
1298
|
+
var unique = (values) => [...new Set(values)];
|
|
1299
|
+
function googleFamilyParam(family, options) {
|
|
1300
|
+
const name = encodeURIComponent(family).replace(/%20/g, "+");
|
|
1301
|
+
const weights = unique(options.weights.map((weight) => isRange(weight) ? weight.replace(" ", "..") : weight)).sort((a, b) => parseInt(a) - parseInt(b));
|
|
1302
|
+
const italic = options.styles.includes("italic");
|
|
1303
|
+
const upright = options.styles.some((style) => style !== "italic");
|
|
1304
|
+
if (!italic)
|
|
1305
|
+
return `${name}:wght@${weights.join(";")}`;
|
|
1306
|
+
const tuples = [...upright ? weights.map((weight) => `0,${weight}`) : [], ...weights.map((weight) => `1,${weight}`)];
|
|
1307
|
+
return `${name}:ital,wght@${tuples.join(";")}`;
|
|
1308
|
+
}
|
|
1309
|
+
var google = {
|
|
1310
|
+
name: "google",
|
|
1311
|
+
async resolveFont(family, options) {
|
|
1312
|
+
const url = `https://fonts.googleapis.com/css2?family=${googleFamilyParam(family, options)}&display=swap${glyphsParam(options.glyphs)}`;
|
|
1313
|
+
const css = await requestText(options.fetch, url, { missing: [400, 404] });
|
|
1314
|
+
if (!css)
|
|
1315
|
+
return;
|
|
1316
|
+
const fonts = keepRequested(parseFontFaces(css).map(({ face }) => face), options);
|
|
1317
|
+
return fonts.length ? { fonts } : undefined;
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
|
|
1321
|
+
// packages/fonts/src/providers/googleicons.ts
|
|
1322
|
+
var FAMILIES = ["Material Symbols Outlined", "Material Symbols Rounded", "Material Symbols Sharp", "Material Icons"];
|
|
1323
|
+
var googleicons = {
|
|
1324
|
+
name: "googleicons",
|
|
1325
|
+
async resolveFont(family, options) {
|
|
1326
|
+
const known = FAMILIES.find((name) => normalizeFamily(name) === normalizeFamily(family));
|
|
1327
|
+
if (!known)
|
|
1328
|
+
return;
|
|
1329
|
+
const css = await requestText(options.fetch, `https://fonts.googleapis.com/css2?family=${known.replace(/ /g, "+")}&display=swap${glyphsParam(options.glyphs)}`, { missing: [400, 404] });
|
|
1330
|
+
if (!css)
|
|
1331
|
+
return;
|
|
1332
|
+
const fonts = parseFontFaces(css).map(({ face }) => withoutSubset(face));
|
|
1333
|
+
return fonts.length ? { fonts } : undefined;
|
|
1334
|
+
}
|
|
1335
|
+
};
|
|
1336
|
+
|
|
1337
|
+
// packages/fonts/src/providers/npm.ts
|
|
1338
|
+
import { existsSync } from "node:fs";
|
|
1339
|
+
import { readFile as readFile4, readdir as readdir2 } from "node:fs/promises";
|
|
1340
|
+
import { dirname, join as join5 } from "node:path";
|
|
1341
|
+
var escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1342
|
+
var FORMATS3 = ["woff2", "woff"];
|
|
1343
|
+
async function packageDir(rootDir, scope, id) {
|
|
1344
|
+
for (let dir = rootDir;; dir = dirname(dir)) {
|
|
1345
|
+
const found = join5(dir, "node_modules", scope, id);
|
|
1346
|
+
if (existsSync(join5(found, "files")))
|
|
1347
|
+
return found;
|
|
1348
|
+
if (dirname(dir) === dir)
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
async function readJson(file) {
|
|
1353
|
+
try {
|
|
1354
|
+
return JSON.parse(await readFile4(file, "utf8"));
|
|
1355
|
+
} catch {
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
function createNpmProvider(scope) {
|
|
1360
|
+
return {
|
|
1361
|
+
name: "npm",
|
|
1362
|
+
async resolveFont(family, options) {
|
|
1363
|
+
const id = family.toLowerCase().trim().replace(/\s+/g, "-");
|
|
1364
|
+
const [staticDir, variableDir] = await Promise.all([
|
|
1365
|
+
packageDir(scope.rootDir, "@fontsource", id),
|
|
1366
|
+
packageDir(scope.rootDir, "@fontsource-variable", id)
|
|
1367
|
+
]);
|
|
1368
|
+
if (!staticDir && !variableDir)
|
|
1369
|
+
return;
|
|
1370
|
+
const wanted = options.weights.map(weightRange);
|
|
1371
|
+
const useVariable = variableDir !== undefined && (staticDir === undefined || options.weights.some((weight) => weight.includes(" ")));
|
|
1372
|
+
const dir = useVariable ? variableDir : staticDir;
|
|
1373
|
+
const [files, unicode, metadata] = await Promise.all([
|
|
1374
|
+
readdir2(join5(dir, "files")),
|
|
1375
|
+
readJson(join5(dir, "unicode.json")),
|
|
1376
|
+
readJson(join5(dir, "metadata.json"))
|
|
1377
|
+
]);
|
|
1378
|
+
const pattern = new RegExp(`^${escape(id)}-(.+)-(${useVariable ? "wght" : "\\d+"})-(normal|italic)\\.(woff2|woff)$`);
|
|
1379
|
+
const range = metadata?.variable?.wght;
|
|
1380
|
+
const groups = new Map;
|
|
1381
|
+
for (const file of files) {
|
|
1382
|
+
const match = pattern.exec(file);
|
|
1383
|
+
if (!match)
|
|
1384
|
+
continue;
|
|
1385
|
+
const [, subset, axis, style, extension] = match;
|
|
1386
|
+
if (!options.subsets.includes(subset) || !options.styles.includes(style) || !options.formats.includes(extension))
|
|
1387
|
+
continue;
|
|
1388
|
+
if (!useVariable && !wanted.some(([low, high]) => Number(axis) >= low && Number(axis) <= high))
|
|
1389
|
+
continue;
|
|
1390
|
+
if (useVariable && extension !== "woff2")
|
|
1391
|
+
continue;
|
|
1392
|
+
const weight = useVariable ? range ? `${range.min} ${range.max}` : undefined : axis;
|
|
1393
|
+
const key = `${weight ?? ""}\x00${style}\x00${subset}`;
|
|
1394
|
+
const face = groups.get(key) ?? {
|
|
1395
|
+
src: [],
|
|
1396
|
+
style,
|
|
1397
|
+
subset,
|
|
1398
|
+
...weight ? { weight } : {},
|
|
1399
|
+
...unicode?.[subset] ? { unicodeRange: unicode[subset] } : {}
|
|
1400
|
+
};
|
|
1401
|
+
face.src.push({ url: join5(dir, "files", file), format: extension });
|
|
1402
|
+
groups.set(key, face);
|
|
1403
|
+
}
|
|
1404
|
+
const order = (face) => [
|
|
1405
|
+
Number(weightRange(face.weight ?? "400")[0]),
|
|
1406
|
+
face.style === "italic" ? 1 : 0,
|
|
1407
|
+
options.subsets.indexOf(face.subset)
|
|
1408
|
+
];
|
|
1409
|
+
const fonts = [...groups.values()].map((face) => ({
|
|
1410
|
+
...face,
|
|
1411
|
+
src: [...face.src].sort((a, b) => FORMATS3.indexOf(a.format) - FORMATS3.indexOf(b.format))
|
|
1412
|
+
})).sort((a, b) => {
|
|
1413
|
+
const [x, y] = [order(a), order(b)];
|
|
1414
|
+
return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
|
|
1415
|
+
});
|
|
1416
|
+
return fonts.length ? { fonts } : undefined;
|
|
1417
|
+
}
|
|
1418
|
+
};
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
// packages/fonts/src/providers/index.ts
|
|
1422
|
+
var remoteProviders = {
|
|
1423
|
+
google,
|
|
1424
|
+
googleicons,
|
|
1425
|
+
bunny,
|
|
1426
|
+
fontshare,
|
|
1427
|
+
fontsource,
|
|
1428
|
+
adobe
|
|
1429
|
+
};
|
|
1430
|
+
|
|
1431
|
+
// packages/fonts/src/resolve.ts
|
|
1432
|
+
import { extname } from "node:path";
|
|
1433
|
+
import { DiagnosticError } from "hamur/kit";
|
|
1434
|
+
|
|
1435
|
+
class Unreachable extends Error {
|
|
1436
|
+
host;
|
|
1437
|
+
constructor(host) {
|
|
1438
|
+
super(`cannot reach ${host}`);
|
|
1439
|
+
this.host = host;
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
var FORMATS4 = { ".woff2": "woff2", ".woff": "woff", ".ttf": "ttf", ".otf": "otf" };
|
|
1443
|
+
function sourceFaces(entry) {
|
|
1444
|
+
return entry.src.map((file, index) => {
|
|
1445
|
+
const format = FORMATS4[extname(file).toLowerCase()];
|
|
1446
|
+
const weight = entry.ownWeights ? entry.weights[index] : undefined;
|
|
1447
|
+
return {
|
|
1448
|
+
src: [{ url: file, ...format ? { format } : {} }],
|
|
1449
|
+
...weight !== undefined ? { weight: String(weight) } : {},
|
|
1450
|
+
style: entry.styles[index] ?? entry.styles[0] ?? "normal"
|
|
1451
|
+
};
|
|
1452
|
+
});
|
|
1453
|
+
}
|
|
1454
|
+
function createResolver3({
|
|
1455
|
+
options,
|
|
1456
|
+
builtIn,
|
|
1457
|
+
report,
|
|
1458
|
+
fetch: given = globalThis.fetch,
|
|
1459
|
+
cache
|
|
1460
|
+
}) {
|
|
1461
|
+
const entries = new Map(options.families.map((family) => [familyKey(family.name), family]));
|
|
1462
|
+
const answers = new Map;
|
|
1463
|
+
let version = 0;
|
|
1464
|
+
const fetchFn = async (input, init) => {
|
|
1465
|
+
try {
|
|
1466
|
+
return await given(input, init);
|
|
1467
|
+
} catch (error) {
|
|
1468
|
+
throw new Unreachable(new URL(input instanceof Request ? input.url : String(input)).host);
|
|
1469
|
+
}
|
|
1470
|
+
};
|
|
1471
|
+
const ask = async (name) => {
|
|
1472
|
+
const entry = entries.get(familyKey(name));
|
|
1473
|
+
const written = entry?.name ?? name;
|
|
1474
|
+
if (entry?.src)
|
|
1475
|
+
return { name: written, faces: sourceFaces(entry), entry };
|
|
1476
|
+
if (entry?.provider === "none")
|
|
1477
|
+
return;
|
|
1478
|
+
const defaults = entry ?? options.defaults;
|
|
1479
|
+
const names = entry?.provider ? [entry.provider] : options.priority.filter((provider) => !options.disabled.has(provider));
|
|
1480
|
+
for (const provider of names) {
|
|
1481
|
+
const found = options.custom[provider] ?? builtIn[provider];
|
|
1482
|
+
if (!found)
|
|
1483
|
+
continue;
|
|
1484
|
+
try {
|
|
1485
|
+
const request = {
|
|
1486
|
+
weights: defaults.weights.map(String),
|
|
1487
|
+
styles: defaults.styles,
|
|
1488
|
+
subsets: defaults.subsets,
|
|
1489
|
+
formats: defaults.formats,
|
|
1490
|
+
...entry?.glyphs !== undefined ? { glyphs: entry.glyphs } : {},
|
|
1491
|
+
...options.providerOptions[provider] ? { options: options.providerOptions[provider] } : {}
|
|
1492
|
+
};
|
|
1493
|
+
const stored = cache?.providers.has(provider) ? cache.store : undefined;
|
|
1494
|
+
const key = stored ? metaKey(provider, written, request) : "";
|
|
1495
|
+
const hit = await stored?.get(key);
|
|
1496
|
+
if (hit)
|
|
1497
|
+
return { name: written, faces: hit.fonts, provider, ...entry ? { entry } : {} };
|
|
1498
|
+
const resolution = await found.resolveFont(written, { ...request, fetch: fetchFn });
|
|
1499
|
+
if (resolution && stored)
|
|
1500
|
+
await stored.set(key, resolution).catch(() => {});
|
|
1501
|
+
if (resolution)
|
|
1502
|
+
return { name: written, faces: resolution.fonts, provider, ...entry ? { entry } : {} };
|
|
1503
|
+
} catch (error) {
|
|
1504
|
+
if (error instanceof Unreachable)
|
|
1505
|
+
throw new DiagnosticError("HAMUR_E5702", `[fonts] cannot reach ${error.host} and no cached copy of ${JSON.stringify(written)} exists`);
|
|
1506
|
+
report(`[fonts] ${provider} failed for ${JSON.stringify(written)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
report(`[fonts] no provider found for ${JSON.stringify(written)}`);
|
|
1510
|
+
return;
|
|
1511
|
+
};
|
|
1512
|
+
return {
|
|
1513
|
+
resolve(name) {
|
|
1514
|
+
const key = familyKey(name);
|
|
1515
|
+
let answer = answers.get(key);
|
|
1516
|
+
if (!answer) {
|
|
1517
|
+
answer = ask(name);
|
|
1518
|
+
answers.set(key, answer);
|
|
1519
|
+
answer.then(() => void version++, () => {});
|
|
1520
|
+
}
|
|
1521
|
+
return answer;
|
|
1522
|
+
},
|
|
1523
|
+
listed: (name) => entries.get(familyKey(name)),
|
|
1524
|
+
version: () => version
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
// packages/fonts/src/build/files.ts
|
|
1529
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
1530
|
+
import { extname as extname2, join as join6 } from "node:path";
|
|
1531
|
+
var slugPart = (text) => text.toLowerCase().replace(/[^a-z0-9.]+/g, "-").replace(/^-+|-+$/g, "");
|
|
1532
|
+
var glyphsSlug = (glyphs) => {
|
|
1533
|
+
const set = [...new Set(Array.from(glyphs ?? ""))].sort().join("");
|
|
1534
|
+
return set ? `g${new Bun.CryptoHasher("sha256").update(set).digest("hex").slice(0, 8)}` : undefined;
|
|
1535
|
+
};
|
|
1536
|
+
var REMOTE = /^https?:\/\//i;
|
|
1537
|
+
function extension(url, format) {
|
|
1538
|
+
const ext = extname2(new URL(url).pathname).slice(1).toLowerCase();
|
|
1539
|
+
return /^(?:woff2|woff|ttf|otf)$/.test(ext) ? ext : format ?? "woff2";
|
|
1540
|
+
}
|
|
1541
|
+
function createFontFiles(dir, report, cache = true) {
|
|
1542
|
+
const downloads = new Map;
|
|
1543
|
+
const owners = new Map;
|
|
1544
|
+
const cached = async (target, url) => {
|
|
1545
|
+
try {
|
|
1546
|
+
const entry = JSON.parse(await readFile5(`${target}.json`, "utf8"));
|
|
1547
|
+
return entry.url === url && entry.sha256 === sha256(await readFile5(target));
|
|
1548
|
+
} catch {
|
|
1549
|
+
return false;
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
1552
|
+
const download = async (url, name) => {
|
|
1553
|
+
const target = join6(dir, name);
|
|
1554
|
+
try {
|
|
1555
|
+
if (cache && await cached(target, url))
|
|
1556
|
+
return target;
|
|
1557
|
+
const response = await globalThis.fetch(url);
|
|
1558
|
+
if (!response.ok) {
|
|
1559
|
+
report(`[fonts] could not download ${url}: ${response.status}`);
|
|
1560
|
+
return;
|
|
1561
|
+
}
|
|
1562
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
1563
|
+
await writeAtomic(target, bytes);
|
|
1564
|
+
await writeAtomic(`${target}.json`, JSON.stringify({ url, sha256: sha256(bytes) }));
|
|
1565
|
+
return target;
|
|
1566
|
+
} catch (error) {
|
|
1567
|
+
if (error instanceof Error && error.message.startsWith("[fonts] "))
|
|
1568
|
+
throw error;
|
|
1569
|
+
report(`[fonts] could not download ${url}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
};
|
|
1573
|
+
const fileName = (family, face, url, format, glyphs) => {
|
|
1574
|
+
const base = [family, face.weight ?? "400", face.style ?? "normal", face.subset, glyphsSlug(glyphs)].filter((part) => part !== undefined && part !== "").map((part) => slugPart(part)).join("-");
|
|
1575
|
+
const ext = extension(url, format);
|
|
1576
|
+
let name = `${base}.${ext}`;
|
|
1577
|
+
const owner = owners.get(name);
|
|
1578
|
+
if (owner !== undefined && owner !== url)
|
|
1579
|
+
name = `${base}-${new Bun.CryptoHasher("sha256").update(url).digest("hex").slice(0, 8)}.${ext}`;
|
|
1580
|
+
owners.set(name, url);
|
|
1581
|
+
return name;
|
|
1582
|
+
};
|
|
1583
|
+
return {
|
|
1584
|
+
async localize(family, faces, glyphs) {
|
|
1585
|
+
return Promise.all(faces.map(async (face) => ({
|
|
1586
|
+
...face,
|
|
1587
|
+
src: await Promise.all(face.src.map(async (entry) => {
|
|
1588
|
+
if (!("url" in entry) || !REMOTE.test(entry.url))
|
|
1589
|
+
return entry;
|
|
1590
|
+
let pending = downloads.get(entry.url);
|
|
1591
|
+
if (!pending) {
|
|
1592
|
+
pending = download(entry.url, fileName(family, face, entry.url, entry.format, glyphs));
|
|
1593
|
+
downloads.set(entry.url, pending);
|
|
1594
|
+
}
|
|
1595
|
+
const path = await pending;
|
|
1596
|
+
return path ? { ...entry, url: path } : entry;
|
|
1597
|
+
}))
|
|
1598
|
+
})));
|
|
1599
|
+
}
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
// packages/fonts/src/build/subset.ts
|
|
1604
|
+
import { basename as basename2, extname as extname3, join as join7 } from "node:path";
|
|
1605
|
+
|
|
1606
|
+
// packages/fonts/src/subset/cmap.ts
|
|
1607
|
+
function runs(entries) {
|
|
1608
|
+
const found = [];
|
|
1609
|
+
for (const [codePoint, glyph] of entries) {
|
|
1610
|
+
const last = found[found.length - 1];
|
|
1611
|
+
if (last && codePoint === last.end + 1 && glyph === last.glyph + codePoint - last.start)
|
|
1612
|
+
last.end = codePoint;
|
|
1613
|
+
else
|
|
1614
|
+
found.push({ start: codePoint, end: codePoint, glyph });
|
|
1615
|
+
}
|
|
1616
|
+
return found;
|
|
1617
|
+
}
|
|
1618
|
+
function format42(entries) {
|
|
1619
|
+
const segments = [
|
|
1620
|
+
...runs(entries.filter(([codePoint]) => codePoint < 65535)).map((run) => ({
|
|
1621
|
+
...run,
|
|
1622
|
+
delta: run.glyph - run.start & 65535
|
|
1623
|
+
})),
|
|
1624
|
+
{ start: 65535, end: 65535, delta: 1 }
|
|
1625
|
+
];
|
|
1626
|
+
const count = segments.length;
|
|
1627
|
+
const length = 16 + 8 * count;
|
|
1628
|
+
const data = new DataView(new ArrayBuffer(length));
|
|
1629
|
+
const power = 2 ** Math.floor(Math.log2(count));
|
|
1630
|
+
data.setUint16(0, 4);
|
|
1631
|
+
data.setUint16(2, length);
|
|
1632
|
+
data.setUint16(6, 2 * count);
|
|
1633
|
+
data.setUint16(8, 2 * power);
|
|
1634
|
+
data.setUint16(10, Math.log2(power));
|
|
1635
|
+
data.setUint16(12, 2 * count - 2 * power);
|
|
1636
|
+
const ends = 14;
|
|
1637
|
+
const starts = ends + 2 * count + 2;
|
|
1638
|
+
const deltas = starts + 2 * count;
|
|
1639
|
+
segments.forEach((segment, i) => {
|
|
1640
|
+
data.setUint16(ends + 2 * i, segment.end);
|
|
1641
|
+
data.setUint16(starts + 2 * i, segment.start);
|
|
1642
|
+
data.setUint16(deltas + 2 * i, segment.delta);
|
|
1643
|
+
});
|
|
1644
|
+
return new Uint8Array(data.buffer);
|
|
1645
|
+
}
|
|
1646
|
+
function format122(entries) {
|
|
1647
|
+
const groups = runs(entries);
|
|
1648
|
+
const length = 16 + 12 * groups.length;
|
|
1649
|
+
const data = new DataView(new ArrayBuffer(length));
|
|
1650
|
+
data.setUint16(0, 12);
|
|
1651
|
+
data.setUint32(4, length);
|
|
1652
|
+
data.setUint32(12, groups.length);
|
|
1653
|
+
groups.forEach((group, i) => {
|
|
1654
|
+
data.setUint32(16 + 12 * i, group.start);
|
|
1655
|
+
data.setUint32(20 + 12 * i, group.end);
|
|
1656
|
+
data.setUint32(24 + 12 * i, group.glyph);
|
|
1657
|
+
});
|
|
1658
|
+
return new Uint8Array(data.buffer);
|
|
1659
|
+
}
|
|
1660
|
+
function writeCmap(entries) {
|
|
1661
|
+
const subtables = [[1, format42(entries)]];
|
|
1662
|
+
if (entries.some(([codePoint]) => codePoint > 65535))
|
|
1663
|
+
subtables.push([10, format122(entries)]);
|
|
1664
|
+
const header = 4 + 8 * subtables.length;
|
|
1665
|
+
const out = new Uint8Array(header + subtables.reduce((sum, [, table]) => sum + table.byteLength, 0));
|
|
1666
|
+
const data = new DataView(out.buffer);
|
|
1667
|
+
data.setUint16(2, subtables.length);
|
|
1668
|
+
let offset = header;
|
|
1669
|
+
subtables.forEach(([encoding, table], i) => {
|
|
1670
|
+
data.setUint16(4 + 8 * i, 3);
|
|
1671
|
+
data.setUint16(6 + 8 * i, encoding);
|
|
1672
|
+
data.setUint32(8 + 8 * i, offset);
|
|
1673
|
+
out.set(table, offset);
|
|
1674
|
+
offset += table.byteLength;
|
|
1675
|
+
});
|
|
1676
|
+
return out;
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
// packages/fonts/src/subset/glyf.ts
|
|
1680
|
+
var view2 = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1681
|
+
var pad4 = (length) => length + 3 & ~3;
|
|
1682
|
+
var ARG_1_AND_2_ARE_WORDS = 1;
|
|
1683
|
+
var WE_HAVE_A_SCALE = 8;
|
|
1684
|
+
var MORE_COMPONENTS = 32;
|
|
1685
|
+
var WE_HAVE_AN_X_AND_Y_SCALE = 64;
|
|
1686
|
+
var WE_HAVE_A_TWO_BY_TWO = 128;
|
|
1687
|
+
function glyphOffsets(loca, indexToLocFormat, numGlyphs, glyfLength) {
|
|
1688
|
+
const data = view2(loca);
|
|
1689
|
+
const width = indexToLocFormat === 0 ? 2 : 4;
|
|
1690
|
+
if (loca.byteLength < width * (numGlyphs + 1))
|
|
1691
|
+
throw new Error("loca is shorter than maxp.numGlyphs");
|
|
1692
|
+
const offsets = [];
|
|
1693
|
+
for (let i = 0;i <= numGlyphs; i++) {
|
|
1694
|
+
const offset = width === 2 ? 2 * data.getUint16(2 * i) : data.getUint32(4 * i);
|
|
1695
|
+
if (offset > glyfLength || i > 0 && offset < offsets[i - 1])
|
|
1696
|
+
throw new Error(`loca entry ${i} is out of order or past glyf`);
|
|
1697
|
+
offsets.push(offset);
|
|
1698
|
+
}
|
|
1699
|
+
return offsets;
|
|
1700
|
+
}
|
|
1701
|
+
function components(glyph) {
|
|
1702
|
+
if (glyph.byteLength < 10)
|
|
1703
|
+
return [];
|
|
1704
|
+
const data = view2(glyph);
|
|
1705
|
+
if (data.getInt16(0) >= 0)
|
|
1706
|
+
return [];
|
|
1707
|
+
const found = [];
|
|
1708
|
+
let at = 10;
|
|
1709
|
+
for (;; ) {
|
|
1710
|
+
const flags = data.getUint16(at);
|
|
1711
|
+
found.push({ at: at + 2, glyph: data.getUint16(at + 2) });
|
|
1712
|
+
at += 4 + (flags & ARG_1_AND_2_ARE_WORDS ? 4 : 2) + (flags & WE_HAVE_A_SCALE ? 2 : flags & WE_HAVE_AN_X_AND_Y_SCALE ? 4 : flags & WE_HAVE_A_TWO_BY_TWO ? 8 : 0);
|
|
1713
|
+
if (!(flags & MORE_COMPONENTS))
|
|
1714
|
+
return found;
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
var glyphAt = (glyf, offsets, glyph) => glyf.subarray(offsets[glyph], offsets[glyph + 1]);
|
|
1718
|
+
function glyphClosure(glyf, offsets, roots) {
|
|
1719
|
+
const numGlyphs = offsets.length - 1;
|
|
1720
|
+
const kept = new Set;
|
|
1721
|
+
const pending = [0, ...roots];
|
|
1722
|
+
while (pending.length > 0) {
|
|
1723
|
+
const glyph = pending.pop();
|
|
1724
|
+
if (glyph >= numGlyphs)
|
|
1725
|
+
throw new Error(`glyph ${glyph} is past maxp.numGlyphs`);
|
|
1726
|
+
if (kept.has(glyph))
|
|
1727
|
+
continue;
|
|
1728
|
+
kept.add(glyph);
|
|
1729
|
+
for (const part of components(glyphAt(glyf, offsets, glyph)))
|
|
1730
|
+
pending.push(part.glyph);
|
|
1731
|
+
}
|
|
1732
|
+
return [...kept].sort((a, b) => a - b);
|
|
1733
|
+
}
|
|
1734
|
+
function subsetGlyf(glyf, offsets, kept) {
|
|
1735
|
+
const id = new Map(kept.map((glyph, index) => [glyph, index]));
|
|
1736
|
+
const parts = kept.map((glyph) => {
|
|
1737
|
+
const copy = glyphAt(glyf, offsets, glyph).slice();
|
|
1738
|
+
for (const part of components(copy))
|
|
1739
|
+
view2(copy).setUint16(part.at, id.get(part.glyph));
|
|
1740
|
+
return copy;
|
|
1741
|
+
});
|
|
1742
|
+
const total = parts.reduce((sum, part) => sum + pad4(part.byteLength), 0);
|
|
1743
|
+
const indexToLocFormat = total <= 131070 ? 0 : 1;
|
|
1744
|
+
const out = new Uint8Array(total);
|
|
1745
|
+
const loca = new Uint8Array((kept.length + 1) * (indexToLocFormat === 0 ? 2 : 4));
|
|
1746
|
+
const locaView = view2(loca);
|
|
1747
|
+
const setOffset = (index, offset) => indexToLocFormat === 0 ? locaView.setUint16(2 * index, offset / 2) : locaView.setUint32(4 * index, offset);
|
|
1748
|
+
let at = 0;
|
|
1749
|
+
parts.forEach((part, index) => {
|
|
1750
|
+
setOffset(index, at);
|
|
1751
|
+
out.set(part, at);
|
|
1752
|
+
at += pad4(part.byteLength);
|
|
1753
|
+
});
|
|
1754
|
+
setOffset(kept.length, at);
|
|
1755
|
+
return { glyf: out, loca, indexToLocFormat };
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
// packages/fonts/src/subset/sfnt.ts
|
|
1759
|
+
var KEPT = new Set(["name", "OS/2", "cvt ", "fpgm", "prep", "gasp"]);
|
|
1760
|
+
var AUTOHINT_LATIN = ["THEZOCQS", "HEZLOCUS", "fijkdbh", "xzroesc", "pqgjy", "oO0"].join("");
|
|
1761
|
+
var view3 = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1762
|
+
var bytesOf = (table) => new Uint8Array(table.data.buffer, table.data.byteOffset, table.data.byteLength);
|
|
1763
|
+
function subsetKern(kern, id) {
|
|
1764
|
+
const data = view3(kern);
|
|
1765
|
+
if (kern.byteLength < 4 || data.getUint16(0) !== 0)
|
|
1766
|
+
return;
|
|
1767
|
+
const subtables = [];
|
|
1768
|
+
let at = 4;
|
|
1769
|
+
for (let i = 0;i < data.getUint16(2) && at + 14 <= kern.byteLength; i++) {
|
|
1770
|
+
const coverage = data.getUint16(at + 4);
|
|
1771
|
+
const length = coverage >> 8 === 0 ? 14 + 6 * data.getUint16(at + 6) : data.getUint16(at + 2);
|
|
1772
|
+
if (coverage >> 8 === 0) {
|
|
1773
|
+
const pairs = [];
|
|
1774
|
+
for (let p = 0;p < data.getUint16(at + 6); p++) {
|
|
1775
|
+
const pair = at + 14 + 6 * p;
|
|
1776
|
+
const left = id.get(data.getUint16(pair));
|
|
1777
|
+
const right = id.get(data.getUint16(pair + 2));
|
|
1778
|
+
if (left !== undefined && right !== undefined)
|
|
1779
|
+
pairs.push([left, right, data.getInt16(pair + 4)]);
|
|
1780
|
+
}
|
|
1781
|
+
if (pairs.length > 0) {
|
|
1782
|
+
pairs.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
1783
|
+
const out = new Uint8Array(14 + 6 * pairs.length);
|
|
1784
|
+
const write = view3(out);
|
|
1785
|
+
const power = 2 ** Math.floor(Math.log2(pairs.length));
|
|
1786
|
+
write.setUint16(2, out.byteLength);
|
|
1787
|
+
write.setUint16(4, coverage);
|
|
1788
|
+
write.setUint16(6, pairs.length);
|
|
1789
|
+
write.setUint16(8, 6 * power);
|
|
1790
|
+
write.setUint16(10, Math.log2(power));
|
|
1791
|
+
write.setUint16(12, 6 * pairs.length - 6 * power);
|
|
1792
|
+
pairs.forEach(([left, right, value], p) => {
|
|
1793
|
+
write.setUint16(14 + 6 * p, left);
|
|
1794
|
+
write.setUint16(16 + 6 * p, right);
|
|
1795
|
+
write.setInt16(18 + 6 * p, value);
|
|
1796
|
+
});
|
|
1797
|
+
subtables.push(out);
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
at += length;
|
|
1801
|
+
}
|
|
1802
|
+
if (subtables.length === 0)
|
|
1803
|
+
return;
|
|
1804
|
+
const out = new Uint8Array(4 + subtables.reduce((sum, table) => sum + table.byteLength, 0));
|
|
1805
|
+
view3(out).setUint16(2, subtables.length);
|
|
1806
|
+
let offset = 4;
|
|
1807
|
+
for (const table of subtables) {
|
|
1808
|
+
out.set(table, offset);
|
|
1809
|
+
offset += table.byteLength;
|
|
1810
|
+
}
|
|
1811
|
+
return out;
|
|
1812
|
+
}
|
|
1813
|
+
function subsetFont(bytes, text) {
|
|
1814
|
+
const source = readTables(bytes);
|
|
1815
|
+
if (source.has("CFF ") || source.has("CFF2"))
|
|
1816
|
+
return { outlines: "cff" };
|
|
1817
|
+
if (source.has("gvar"))
|
|
1818
|
+
return { outlines: "gvar" };
|
|
1819
|
+
const table = (tag) => {
|
|
1820
|
+
const found = source.get(tag);
|
|
1821
|
+
if (!found)
|
|
1822
|
+
throw new Error(`no ${tag}`);
|
|
1823
|
+
if (found.transformed)
|
|
1824
|
+
throw new Error(`a transformed ${tag} is not read`);
|
|
1825
|
+
return bytesOf(found);
|
|
1826
|
+
};
|
|
1827
|
+
const head = table("head").slice();
|
|
1828
|
+
const hhea = table("hhea").slice();
|
|
1829
|
+
const maxp = table("maxp").slice();
|
|
1830
|
+
const hmtx = view3(table("hmtx"));
|
|
1831
|
+
const glyf = table("glyf");
|
|
1832
|
+
const numGlyphs = view3(maxp).getUint16(4);
|
|
1833
|
+
const offsets = glyphOffsets(table("loca"), view3(head).getInt16(50), numGlyphs, glyf.byteLength);
|
|
1834
|
+
const glyphOf = readCmap(source.get("cmap"));
|
|
1835
|
+
const wanted = /\p{Script=Latin}/u.test(text) ? text + AUTOHINT_LATIN : text;
|
|
1836
|
+
const mapped = [...new Set(Array.from(wanted, (char) => char.codePointAt(0)))].sort((a, b) => a - b).map((codePoint) => [codePoint, glyphOf(codePoint)]).filter(([, glyph]) => glyph > 0 && glyph < numGlyphs);
|
|
1837
|
+
const kept = glyphClosure(glyf, offsets, mapped.map(([, glyph]) => glyph));
|
|
1838
|
+
const id = new Map(kept.map((glyph, index) => [glyph, index]));
|
|
1839
|
+
const outlines = subsetGlyf(glyf, offsets, kept);
|
|
1840
|
+
const longMetrics = view3(hhea).getUint16(34);
|
|
1841
|
+
if (longMetrics === 0)
|
|
1842
|
+
throw new Error("hhea.numberOfHMetrics is 0");
|
|
1843
|
+
const advance = (glyph) => hmtx.getUint16(4 * Math.min(glyph, longMetrics - 1));
|
|
1844
|
+
const bearing = (glyph) => glyph < longMetrics ? hmtx.getInt16(4 * glyph + 2) : hmtx.getInt16(4 * longMetrics + 2 * (glyph - longMetrics));
|
|
1845
|
+
let metrics = kept.length;
|
|
1846
|
+
while (metrics > 1 && advance(kept[metrics - 1]) === advance(kept[metrics - 2]))
|
|
1847
|
+
metrics--;
|
|
1848
|
+
const newHmtx = new Uint8Array(4 * metrics + 2 * (kept.length - metrics));
|
|
1849
|
+
const hmtxOut = view3(newHmtx);
|
|
1850
|
+
kept.forEach((glyph, index) => {
|
|
1851
|
+
if (index < metrics) {
|
|
1852
|
+
hmtxOut.setUint16(4 * index, advance(glyph));
|
|
1853
|
+
hmtxOut.setInt16(4 * index + 2, bearing(glyph));
|
|
1854
|
+
} else {
|
|
1855
|
+
hmtxOut.setInt16(4 * metrics + 2 * (index - metrics), bearing(glyph));
|
|
1856
|
+
}
|
|
1857
|
+
});
|
|
1858
|
+
view3(head).setUint32(8, 0);
|
|
1859
|
+
view3(head).setInt16(50, outlines.indexToLocFormat);
|
|
1860
|
+
view3(hhea).setUint16(34, metrics);
|
|
1861
|
+
view3(maxp).setUint16(4, kept.length);
|
|
1862
|
+
const tables = new Map;
|
|
1863
|
+
for (const [tag, found] of source)
|
|
1864
|
+
if (KEPT.has(tag) && !found.transformed)
|
|
1865
|
+
tables.set(tag, bytesOf(found));
|
|
1866
|
+
tables.set("head", head);
|
|
1867
|
+
tables.set("hhea", hhea);
|
|
1868
|
+
tables.set("maxp", maxp);
|
|
1869
|
+
tables.set("hmtx", newHmtx);
|
|
1870
|
+
tables.set("glyf", outlines.glyf);
|
|
1871
|
+
tables.set("loca", outlines.loca);
|
|
1872
|
+
tables.set("cmap", writeCmap(mapped.map(([codePoint, glyph]) => [codePoint, id.get(glyph)])));
|
|
1873
|
+
const post = source.get("post");
|
|
1874
|
+
if (post && post.data.byteLength >= 32 && !post.transformed) {
|
|
1875
|
+
const names = new Uint8Array(32);
|
|
1876
|
+
names.set(bytesOf(post).subarray(4, 32), 4);
|
|
1877
|
+
view3(names).setUint32(0, 196608);
|
|
1878
|
+
tables.set("post", names);
|
|
1879
|
+
}
|
|
1880
|
+
const kern = source.get("kern");
|
|
1881
|
+
const pairs = kern && !kern.transformed ? subsetKern(bytesOf(kern), id) : undefined;
|
|
1882
|
+
if (pairs)
|
|
1883
|
+
tables.set("kern", pairs);
|
|
1884
|
+
return { outlines: "glyf", tables };
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
// packages/fonts/src/subset/woff2.ts
|
|
1888
|
+
import { brotliCompressSync, constants } from "node:zlib";
|
|
1889
|
+
var pad42 = (length) => length + 3 & ~3;
|
|
1890
|
+
function base1282(value) {
|
|
1891
|
+
const bytes = [];
|
|
1892
|
+
do {
|
|
1893
|
+
bytes.unshift(value & 127);
|
|
1894
|
+
value = Math.floor(value / 128);
|
|
1895
|
+
} while (value > 0);
|
|
1896
|
+
return bytes.map((byte, i) => i < bytes.length - 1 ? byte | 128 : byte);
|
|
1897
|
+
}
|
|
1898
|
+
function writeWoff2(tables) {
|
|
1899
|
+
const tags = [...tables.keys()].sort();
|
|
1900
|
+
const directory = [];
|
|
1901
|
+
const data = [];
|
|
1902
|
+
let sfntSize = 12 + 16 * tags.length;
|
|
1903
|
+
for (const tag of tags) {
|
|
1904
|
+
let table = tables.get(tag);
|
|
1905
|
+
if (tag === "head") {
|
|
1906
|
+
table = table.slice();
|
|
1907
|
+
const head = new DataView(table.buffer);
|
|
1908
|
+
head.setUint16(16, head.getUint16(16) | 2048);
|
|
1909
|
+
}
|
|
1910
|
+
const known = WOFF2_TAGS.indexOf(tag);
|
|
1911
|
+
const version = tag === "glyf" || tag === "loca" ? 3 : 0;
|
|
1912
|
+
directory.push((known === -1 ? 63 : known) | version << 6);
|
|
1913
|
+
if (known === -1)
|
|
1914
|
+
for (let k = 0;k < 4; k++)
|
|
1915
|
+
directory.push(tag.charCodeAt(k));
|
|
1916
|
+
directory.push(...base1282(table.byteLength));
|
|
1917
|
+
data.push(table);
|
|
1918
|
+
sfntSize += pad42(table.byteLength);
|
|
1919
|
+
}
|
|
1920
|
+
const stream = new Uint8Array(data.reduce((sum, table) => sum + table.byteLength, 0));
|
|
1921
|
+
let at = 0;
|
|
1922
|
+
for (const table of data) {
|
|
1923
|
+
stream.set(table, at);
|
|
1924
|
+
at += table.byteLength;
|
|
1925
|
+
}
|
|
1926
|
+
const compressed = brotliCompressSync(stream, {
|
|
1927
|
+
params: {
|
|
1928
|
+
[constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_FONT,
|
|
1929
|
+
[constants.BROTLI_PARAM_QUALITY]: 11,
|
|
1930
|
+
[constants.BROTLI_PARAM_SIZE_HINT]: stream.byteLength
|
|
1931
|
+
}
|
|
1932
|
+
});
|
|
1933
|
+
const headerSize = 48 + directory.length;
|
|
1934
|
+
const length = pad42(headerSize + compressed.byteLength);
|
|
1935
|
+
const out = new Uint8Array(length);
|
|
1936
|
+
const header = new DataView(out.buffer);
|
|
1937
|
+
out.set([119, 79, 70, 50], 0);
|
|
1938
|
+
header.setUint32(4, 65536);
|
|
1939
|
+
header.setUint32(8, length);
|
|
1940
|
+
header.setUint16(12, tags.length);
|
|
1941
|
+
header.setUint32(16, sfntSize);
|
|
1942
|
+
header.setUint32(20, compressed.byteLength);
|
|
1943
|
+
header.setUint16(24, 1);
|
|
1944
|
+
out.set(directory, 48);
|
|
1945
|
+
out.set(compressed, headerSize);
|
|
1946
|
+
return out;
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
// packages/fonts/src/build/subset.ts
|
|
1950
|
+
function createSubsetter(dir, read, report) {
|
|
1951
|
+
const cuts = new Map;
|
|
1952
|
+
const reported = new Set;
|
|
1953
|
+
const cut = async (url, glyphs) => {
|
|
1954
|
+
const bytes = await read(url);
|
|
1955
|
+
if (!bytes)
|
|
1956
|
+
return;
|
|
1957
|
+
let result;
|
|
1958
|
+
try {
|
|
1959
|
+
result = subsetFont(bytes, glyphs);
|
|
1960
|
+
} catch {
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1963
|
+
if (result.outlines !== "glyf")
|
|
1964
|
+
return { skipped: result.outlines };
|
|
1965
|
+
const target = join7(dir, `${basename2(url, extname3(url))}-${sha256(`${sha256(bytes)}
|
|
1966
|
+
${glyphs}`).slice(0, 8)}.woff2`);
|
|
1967
|
+
await writeAtomic(target, writeWoff2(result.tables));
|
|
1968
|
+
return { path: target };
|
|
1969
|
+
};
|
|
1970
|
+
return {
|
|
1971
|
+
subset(family, faces, glyphs) {
|
|
1972
|
+
const set = [...new Set(Array.from(glyphs))].sort().join("");
|
|
1973
|
+
return Promise.all(faces.map(async (face) => {
|
|
1974
|
+
for (const entry of face.src) {
|
|
1975
|
+
if (!("url" in entry))
|
|
1976
|
+
continue;
|
|
1977
|
+
const key = `${entry.url}
|
|
1978
|
+
${set}`;
|
|
1979
|
+
let pending = cuts.get(key);
|
|
1980
|
+
if (!pending)
|
|
1981
|
+
cuts.set(key, pending = cut(entry.url, set));
|
|
1982
|
+
const result = await pending;
|
|
1983
|
+
if (!result)
|
|
1984
|
+
continue;
|
|
1985
|
+
if ("skipped" in result) {
|
|
1986
|
+
const message = result.skipped === "cff" ? `[fonts] ${family} is CFF; glyphs applies to TrueType outlines only` : `[fonts] ${family} is a variable font with gvar; glyphs does not subset it`;
|
|
1987
|
+
if (!reported.has(message)) {
|
|
1988
|
+
reported.add(message);
|
|
1989
|
+
report(message);
|
|
1990
|
+
}
|
|
1991
|
+
return face;
|
|
1992
|
+
}
|
|
1993
|
+
return {
|
|
1994
|
+
...face,
|
|
1995
|
+
src: [...face.src.filter((source) => !("url" in source)), { url: result.path, format: "woff2" }]
|
|
1996
|
+
};
|
|
1997
|
+
}
|
|
1998
|
+
return face;
|
|
1999
|
+
}));
|
|
2000
|
+
}
|
|
2001
|
+
};
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
// packages/fonts/src/options.ts
|
|
2005
|
+
import { isAbsolute, resolve } from "node:path";
|
|
2006
|
+
import { DiagnosticError as DiagnosticError2 } from "hamur/kit";
|
|
2007
|
+
var BUILT_IN_PROVIDERS = ["local", "npm", "google", "bunny", "fontshare", "fontsource", "googleicons", "adobe"];
|
|
2008
|
+
var FALLBACK_SYSTEM_FONTS = Object.keys(SYSTEM_METRICS);
|
|
2009
|
+
var OPTION_KEYS = [
|
|
2010
|
+
"enabled",
|
|
2011
|
+
"priority",
|
|
2012
|
+
"providers",
|
|
2013
|
+
"defaults",
|
|
2014
|
+
"families",
|
|
2015
|
+
"processCSSVariables",
|
|
2016
|
+
"fallbacks",
|
|
2017
|
+
"localSources",
|
|
2018
|
+
"cache",
|
|
2019
|
+
"throwOnError"
|
|
2020
|
+
];
|
|
2021
|
+
var DEFAULT_KEYS = ["weights", "styles", "subsets", "display", "formats", "preload"];
|
|
2022
|
+
var FAMILY_KEYS = [
|
|
2023
|
+
"name",
|
|
2024
|
+
"provider",
|
|
2025
|
+
"src",
|
|
2026
|
+
...DEFAULT_KEYS,
|
|
2027
|
+
"unicodeRange",
|
|
2028
|
+
"stretch",
|
|
2029
|
+
"featureSettings",
|
|
2030
|
+
"variationSettings",
|
|
2031
|
+
"glyphs",
|
|
2032
|
+
"global"
|
|
2033
|
+
];
|
|
2034
|
+
var STYLES = ["normal", "italic", "oblique"];
|
|
2035
|
+
var DISPLAYS = ["auto", "block", "swap", "fallback", "optional"];
|
|
2036
|
+
var FORMATS5 = ["woff2", "woff", "ttf", "otf"];
|
|
2037
|
+
var DEFAULTS = {
|
|
2038
|
+
weights: [400],
|
|
2039
|
+
styles: ["normal"],
|
|
2040
|
+
subsets: ["latin", "latin-ext"],
|
|
2041
|
+
display: "swap",
|
|
2042
|
+
formats: ["woff2"],
|
|
2043
|
+
preload: true
|
|
2044
|
+
};
|
|
2045
|
+
var FALLBACKS = {
|
|
2046
|
+
"sans-serif": ["Arial"],
|
|
2047
|
+
serif: ["Times New Roman"],
|
|
2048
|
+
monospace: ["Courier New"]
|
|
2049
|
+
};
|
|
2050
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2051
|
+
var shown = (value) => typeof value === "function" ? "a function" : JSON.stringify(value) ?? String(value);
|
|
2052
|
+
var list2 = (values) => values.join(", ");
|
|
2053
|
+
function fail(message) {
|
|
2054
|
+
throw new DiagnosticError2("HAMUR_E5701", message);
|
|
2055
|
+
}
|
|
2056
|
+
function resolveConfigPath(ctx, path) {
|
|
2057
|
+
if (path.startsWith("#")) {
|
|
2058
|
+
try {
|
|
2059
|
+
return Bun.resolveSync(path, ctx.rootDir);
|
|
2060
|
+
} catch {
|
|
2061
|
+
return path;
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
return isAbsolute(path) ? path : resolve(ctx.rootDir, path);
|
|
2065
|
+
}
|
|
2066
|
+
var isCssWeight = (value) => {
|
|
2067
|
+
const inRange = (n) => Number.isFinite(n) && n >= 1 && n <= 1000;
|
|
2068
|
+
if (typeof value === "number")
|
|
2069
|
+
return inRange(value);
|
|
2070
|
+
if (typeof value !== "string")
|
|
2071
|
+
return false;
|
|
2072
|
+
const parts = value.split(" ");
|
|
2073
|
+
if (parts.length > 2 || !parts.every((part) => /^\d+(?:\.\d+)?$/.test(part)))
|
|
2074
|
+
return false;
|
|
2075
|
+
return parts.every((part) => inRange(Number(part)));
|
|
2076
|
+
};
|
|
2077
|
+
function oneOf(value, allowed, at, what) {
|
|
2078
|
+
if (typeof value !== "string" || !allowed.includes(value))
|
|
2079
|
+
fail(`${at} ${shown(value)} is not ${what} (${list2(allowed)})`);
|
|
2080
|
+
return value;
|
|
2081
|
+
}
|
|
2082
|
+
function checkBoolean(value, at) {
|
|
2083
|
+
if (typeof value !== "boolean")
|
|
2084
|
+
fail(`${at} must be a boolean (got ${shown(value)})`);
|
|
2085
|
+
return value;
|
|
2086
|
+
}
|
|
2087
|
+
function resolveDefaultKeys(input, at) {
|
|
2088
|
+
const out = {};
|
|
2089
|
+
if (input.weights !== undefined) {
|
|
2090
|
+
if (!Array.isArray(input.weights))
|
|
2091
|
+
fail(`${at}.weights must be an array of CSS weights (got ${shown(input.weights)})`);
|
|
2092
|
+
input.weights.forEach((weight, i) => {
|
|
2093
|
+
if (!isCssWeight(weight))
|
|
2094
|
+
fail(`${at}.weights[${i}] must be a CSS weight, 1 to 1000, or a range such as "100 900" (got ${shown(weight)})`);
|
|
2095
|
+
});
|
|
2096
|
+
out.weights = [...input.weights];
|
|
2097
|
+
}
|
|
2098
|
+
if (input.styles !== undefined) {
|
|
2099
|
+
if (!Array.isArray(input.styles))
|
|
2100
|
+
fail(`${at}.styles must be an array of styles (got ${shown(input.styles)})`);
|
|
2101
|
+
out.styles = input.styles.map((style, i) => oneOf(style, STYLES, `${at}.styles[${i}]`, "a style"));
|
|
2102
|
+
}
|
|
2103
|
+
if (input.subsets !== undefined) {
|
|
2104
|
+
if (!Array.isArray(input.subsets))
|
|
2105
|
+
fail(`${at}.subsets must be an array of subset names (got ${shown(input.subsets)})`);
|
|
2106
|
+
if (!input.subsets.length)
|
|
2107
|
+
fail(`${at}.subsets must list at least one subset`);
|
|
2108
|
+
input.subsets.forEach((subset, i) => {
|
|
2109
|
+
if (typeof subset !== "string" || subset === "")
|
|
2110
|
+
fail(`${at}.subsets[${i}] must be a subset name (got ${shown(subset)})`);
|
|
2111
|
+
});
|
|
2112
|
+
out.subsets = [...input.subsets];
|
|
2113
|
+
}
|
|
2114
|
+
if (input.display !== undefined)
|
|
2115
|
+
out.display = oneOf(input.display, DISPLAYS, `${at}.display`, "a font-display value");
|
|
2116
|
+
if (input.formats !== undefined) {
|
|
2117
|
+
if (!Array.isArray(input.formats))
|
|
2118
|
+
fail(`${at}.formats must be an array of font formats (got ${shown(input.formats)})`);
|
|
2119
|
+
out.formats = input.formats.map((format, i) => oneOf(format, FORMATS5, `${at}.formats[${i}]`, "a font format"));
|
|
2120
|
+
}
|
|
2121
|
+
if (input.preload !== undefined)
|
|
2122
|
+
out.preload = checkBoolean(input.preload, `${at}.preload`);
|
|
2123
|
+
return out;
|
|
2124
|
+
}
|
|
2125
|
+
async function resolveProviders(input, ctx) {
|
|
2126
|
+
const out = {
|
|
2127
|
+
disabled: new Set,
|
|
2128
|
+
providerOptions: {},
|
|
2129
|
+
custom: {}
|
|
2130
|
+
};
|
|
2131
|
+
if (input === undefined)
|
|
2132
|
+
return out;
|
|
2133
|
+
if (!isObject(input))
|
|
2134
|
+
return fail(`fonts.providers must be an object (got ${shown(input)})`);
|
|
2135
|
+
for (const [name, value] of Object.entries(input)) {
|
|
2136
|
+
const at = `fonts.providers.${name}`;
|
|
2137
|
+
if (value === false) {
|
|
2138
|
+
out.disabled.add(name);
|
|
2139
|
+
} else if (typeof value === "string") {
|
|
2140
|
+
const file = resolveConfigPath(ctx, value);
|
|
2141
|
+
if (!ctx.exists(file))
|
|
2142
|
+
fail(`${at} ${JSON.stringify(value)} does not exist`);
|
|
2143
|
+
let exported;
|
|
2144
|
+
try {
|
|
2145
|
+
exported = await ctx.load(file);
|
|
2146
|
+
} catch (error) {
|
|
2147
|
+
fail(`${at} ${JSON.stringify(value)} could not be loaded: ${error instanceof Error ? error.message : String(error)}`);
|
|
2148
|
+
}
|
|
2149
|
+
if (!isObject(exported) || typeof exported.name !== "string" || typeof exported.resolveFont !== "function") {
|
|
2150
|
+
fail(`${at} ${JSON.stringify(value)} must default-export { name, resolveFont } (got ${shown(exported)})`);
|
|
2151
|
+
}
|
|
2152
|
+
if (exported.name !== name)
|
|
2153
|
+
fail(`${at} ${JSON.stringify(value)} exports name ${JSON.stringify(exported.name)}; the key and the name must match`);
|
|
2154
|
+
out.custom[name] = exported;
|
|
2155
|
+
} else if (isObject(value) && Object.keys(value).every((key) => key === "options")) {
|
|
2156
|
+
const options = value.options;
|
|
2157
|
+
if (options !== undefined && !isObject(options))
|
|
2158
|
+
fail(`${at}.options must be an object (got ${shown(options)})`);
|
|
2159
|
+
if (options)
|
|
2160
|
+
out.providerOptions[name] = options;
|
|
2161
|
+
if (name === "adobe" && (typeof options?.id !== "string" || options.id === ""))
|
|
2162
|
+
fail("fonts.providers.adobe.options.id is required (the Adobe Fonts kit id)");
|
|
2163
|
+
} else {
|
|
2164
|
+
fail(`${at} must be false, a file path or { options } (got ${shown(value)})`);
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
return out;
|
|
2168
|
+
}
|
|
2169
|
+
function resolveFallbacks(input) {
|
|
2170
|
+
if (input === undefined)
|
|
2171
|
+
return { ...FALLBACKS };
|
|
2172
|
+
if (input === false)
|
|
2173
|
+
return false;
|
|
2174
|
+
if (!isObject(input))
|
|
2175
|
+
return fail(`fonts.fallbacks must be false or an object of system font lists (got ${shown(input)})`);
|
|
2176
|
+
const out = { ...FALLBACKS };
|
|
2177
|
+
for (const [generic, fonts] of Object.entries(input)) {
|
|
2178
|
+
if (!Array.isArray(fonts))
|
|
2179
|
+
fail(`fonts.fallbacks.${generic} must be an array of system fonts (got ${shown(fonts)})`);
|
|
2180
|
+
fonts.forEach((font, i) => {
|
|
2181
|
+
if (typeof font !== "string" || !FALLBACK_SYSTEM_FONTS.includes(font))
|
|
2182
|
+
fail(`fonts.fallbacks.${generic}[${i}] ${shown(font)} has no metrics here (${list2(FALLBACK_SYSTEM_FONTS)})`);
|
|
2183
|
+
});
|
|
2184
|
+
out[generic] = [...fonts];
|
|
2185
|
+
}
|
|
2186
|
+
return out;
|
|
2187
|
+
}
|
|
2188
|
+
function resolveFamilies(input, defaults, providerNames, ctx, adobeId) {
|
|
2189
|
+
if (input === undefined)
|
|
2190
|
+
return [];
|
|
2191
|
+
if (!Array.isArray(input))
|
|
2192
|
+
return fail(`fonts.families must be an array (got ${shown(input)})`);
|
|
2193
|
+
const seen = new Set;
|
|
2194
|
+
return input.map((entry, index) => {
|
|
2195
|
+
const at = `fonts.families[${index}]`;
|
|
2196
|
+
if (!isObject(entry))
|
|
2197
|
+
return fail(`${at} must be an object (got ${shown(entry)})`);
|
|
2198
|
+
for (const key of Object.keys(entry))
|
|
2199
|
+
if (!FAMILY_KEYS.includes(key))
|
|
2200
|
+
fail(`${at}.${key} is not an option; use ${list2(FAMILY_KEYS)}`);
|
|
2201
|
+
const { name } = entry;
|
|
2202
|
+
if (typeof name !== "string" || name.trim() === "")
|
|
2203
|
+
fail(`${at}.name must be a non-empty string (got ${shown(name)})`);
|
|
2204
|
+
const key = name.trim().toLowerCase();
|
|
2205
|
+
if (seen.has(key))
|
|
2206
|
+
fail(`${at} ${JSON.stringify(name)} is listed twice; merge the entries`);
|
|
2207
|
+
seen.add(key);
|
|
2208
|
+
if (entry.provider !== undefined && (typeof entry.provider !== "string" || entry.provider !== "none" && !providerNames.has(entry.provider))) {
|
|
2209
|
+
fail(`${at}.provider ${shown(entry.provider)} is not "none", a built-in provider or a key of fonts.providers`);
|
|
2210
|
+
}
|
|
2211
|
+
if (entry.provider === "adobe" && !adobeId)
|
|
2212
|
+
fail("fonts.providers.adobe.options.id is required (the Adobe Fonts kit id)");
|
|
2213
|
+
if (entry.src !== undefined && entry.provider !== undefined)
|
|
2214
|
+
fail(`${at} sets src and provider; src means no provider is asked`);
|
|
2215
|
+
let src;
|
|
2216
|
+
if (entry.src !== undefined) {
|
|
2217
|
+
const given = typeof entry.src === "string" ? [entry.src] : entry.src;
|
|
2218
|
+
if (!Array.isArray(given) || !given.length || given.some((file) => typeof file !== "string" || file === "")) {
|
|
2219
|
+
fail(`${at}.src must be a file path or a list of file paths (got ${shown(entry.src)})`);
|
|
2220
|
+
}
|
|
2221
|
+
src = given.map((file) => {
|
|
2222
|
+
const path = resolveConfigPath(ctx, file);
|
|
2223
|
+
if (!ctx.exists(path))
|
|
2224
|
+
fail(`${at}.src ${JSON.stringify(file)} does not exist`);
|
|
2225
|
+
return path;
|
|
2226
|
+
});
|
|
2227
|
+
}
|
|
2228
|
+
if (entry.glyphs !== undefined && typeof entry.glyphs !== "string")
|
|
2229
|
+
fail(`${at}.glyphs must be a string (got ${shown(entry.glyphs)})`);
|
|
2230
|
+
if (entry.global !== undefined)
|
|
2231
|
+
checkBoolean(entry.global, `${at}.global`);
|
|
2232
|
+
for (const descriptor of ["unicodeRange", "stretch", "featureSettings", "variationSettings"]) {
|
|
2233
|
+
if (entry[descriptor] !== undefined && typeof entry[descriptor] !== "string")
|
|
2234
|
+
fail(`${at}.${descriptor} must be a string (got ${shown(entry[descriptor])})`);
|
|
2235
|
+
}
|
|
2236
|
+
const own = resolveDefaultKeys(entry, at);
|
|
2237
|
+
if (src && own.weights && own.weights.length > src.length)
|
|
2238
|
+
fail(`${at}.weights lists ${own.weights.length} weights for ${src.length} src file${src.length === 1 ? "" : "s"}; list one weight per file`);
|
|
2239
|
+
const text = (key) => typeof entry[key] === "string" ? entry[key] : undefined;
|
|
2240
|
+
const optional = {
|
|
2241
|
+
provider: text("provider"),
|
|
2242
|
+
glyphs: text("glyphs"),
|
|
2243
|
+
unicodeRange: text("unicodeRange"),
|
|
2244
|
+
stretch: text("stretch"),
|
|
2245
|
+
featureSettings: text("featureSettings"),
|
|
2246
|
+
variationSettings: text("variationSettings")
|
|
2247
|
+
};
|
|
2248
|
+
return {
|
|
2249
|
+
...defaults,
|
|
2250
|
+
...own,
|
|
2251
|
+
name,
|
|
2252
|
+
ownWeights: own.weights !== undefined,
|
|
2253
|
+
global: entry.global === true,
|
|
2254
|
+
...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)),
|
|
2255
|
+
...src ? { src } : {}
|
|
2256
|
+
};
|
|
2257
|
+
});
|
|
2258
|
+
}
|
|
2259
|
+
function checkPriority(priority, providers) {
|
|
2260
|
+
const known = new Set([...BUILT_IN_PROVIDERS, ...providers]);
|
|
2261
|
+
priority.forEach((name, i) => {
|
|
2262
|
+
if (!known.has(name))
|
|
2263
|
+
fail(`fonts.priority[${i}] ${shown(name)} is not a provider (${list2(BUILT_IN_PROVIDERS)}, or a key of fonts.providers)`);
|
|
2264
|
+
});
|
|
2265
|
+
}
|
|
2266
|
+
async function resolveOptions(input, ctx) {
|
|
2267
|
+
const given = input ?? {};
|
|
2268
|
+
if (!isObject(given))
|
|
2269
|
+
return fail(`fonts must be an object (got ${shown(given)})`);
|
|
2270
|
+
for (const key of Object.keys(given))
|
|
2271
|
+
if (!OPTION_KEYS.includes(key))
|
|
2272
|
+
fail(`fonts.${key} is not an option; use ${list2(OPTION_KEYS)}`);
|
|
2273
|
+
const enabled = given.enabled === undefined ? true : checkBoolean(given.enabled, "fonts.enabled");
|
|
2274
|
+
const providers = await resolveProviders(given.providers, ctx);
|
|
2275
|
+
const providerNames = new Set([
|
|
2276
|
+
...BUILT_IN_PROVIDERS,
|
|
2277
|
+
...Object.keys(isObject(given.providers) ? given.providers : {})
|
|
2278
|
+
]);
|
|
2279
|
+
let priority = [...BUILT_IN_PROVIDERS];
|
|
2280
|
+
if (given.priority !== undefined) {
|
|
2281
|
+
if (!Array.isArray(given.priority))
|
|
2282
|
+
fail(`fonts.priority must be an array of provider names (got ${shown(given.priority)})`);
|
|
2283
|
+
given.priority.forEach((name, i) => {
|
|
2284
|
+
if (typeof name !== "string")
|
|
2285
|
+
fail(`fonts.priority[${i}] ${shown(name)} is not a provider name`);
|
|
2286
|
+
});
|
|
2287
|
+
priority = [...given.priority];
|
|
2288
|
+
}
|
|
2289
|
+
let defaults = DEFAULTS;
|
|
2290
|
+
if (given.defaults !== undefined) {
|
|
2291
|
+
if (!isObject(given.defaults))
|
|
2292
|
+
fail(`fonts.defaults must be an object (got ${shown(given.defaults)})`);
|
|
2293
|
+
for (const key of Object.keys(given.defaults))
|
|
2294
|
+
if (!DEFAULT_KEYS.includes(key))
|
|
2295
|
+
fail(`fonts.defaults.${key} is not an option; use ${list2(DEFAULT_KEYS)}`);
|
|
2296
|
+
defaults = { ...DEFAULTS, ...resolveDefaultKeys(given.defaults, "fonts.defaults") };
|
|
2297
|
+
}
|
|
2298
|
+
const families = resolveFamilies(given.families, defaults, providerNames, ctx, providers.providerOptions.adobe?.id !== undefined);
|
|
2299
|
+
const css = given.processCSSVariables;
|
|
2300
|
+
if (css !== undefined && css !== true && css !== false && css !== "font-prefixed-only")
|
|
2301
|
+
fail(`fonts.processCSSVariables must be true, false or "font-prefixed-only" (got ${shown(css)})`);
|
|
2302
|
+
return {
|
|
2303
|
+
enabled,
|
|
2304
|
+
priority,
|
|
2305
|
+
...providers,
|
|
2306
|
+
defaults,
|
|
2307
|
+
families,
|
|
2308
|
+
processCSSVariables: css ?? "font-prefixed-only",
|
|
2309
|
+
fallbacks: resolveFallbacks(given.fallbacks),
|
|
2310
|
+
localSources: given.localSources === undefined ? true : checkBoolean(given.localSources, "fonts.localSources"),
|
|
2311
|
+
cache: given.cache === undefined ? true : checkBoolean(given.cache, "fonts.cache"),
|
|
2312
|
+
throwOnError: given.throwOnError === undefined ? false : checkBoolean(given.throwOnError, "fonts.throwOnError")
|
|
2313
|
+
};
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2316
|
+
// packages/fonts/src/build/providers.ts
|
|
2317
|
+
function setupProviders(options, hamur, providers) {
|
|
2318
|
+
hamur.hooks.hook("modules:done", async () => {
|
|
2319
|
+
const all = { ...providers, ...options.custom };
|
|
2320
|
+
await hamur.hooks.callHook("fonts:providers", all);
|
|
2321
|
+
for (const name of Object.keys(providers))
|
|
2322
|
+
delete providers[name];
|
|
2323
|
+
Object.assign(providers, all);
|
|
2324
|
+
options.custom = {};
|
|
2325
|
+
checkPriority(options.priority, Object.keys(providers));
|
|
2326
|
+
});
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
// packages/fonts/src/build/scan.ts
|
|
2330
|
+
import { DiagnosticError as DiagnosticError3 } from "hamur/kit";
|
|
2331
|
+
function setupScan(options, hamur, preload, registry) {
|
|
2332
|
+
const log = useLogger("fonts");
|
|
2333
|
+
const { srcDir, publicDir, layers, app } = hamur.options;
|
|
2334
|
+
const roots = [{ srcDir, publicDir }, ...layers];
|
|
2335
|
+
const report = (message) => {
|
|
2336
|
+
if (options.throwOnError)
|
|
2337
|
+
throw new DiagnosticError3("HAMUR_E5703", message);
|
|
2338
|
+
log.warn(diagnostic("HAMUR_W5704", message.replace(/^\[fonts\] /, "")));
|
|
2339
|
+
};
|
|
2340
|
+
const fontsDir = fontsDirOf(options.cache, hamur);
|
|
2341
|
+
const files = createFontFiles(join8(fontsDir, "files"), report, options.cache);
|
|
2342
|
+
const providers = {
|
|
2343
|
+
...remoteProviders,
|
|
2344
|
+
npm: createNpmProvider({ rootDir: hamur.options.rootDir }),
|
|
2345
|
+
local: createLocalProvider({
|
|
2346
|
+
assetDirs: roots.map((root) => `${root.srcDir}/assets/fonts`),
|
|
2347
|
+
publicDirs: roots.map((root) => root.publicDir),
|
|
2348
|
+
baseURL: app.baseURL,
|
|
2349
|
+
publicUrlsKept
|
|
2350
|
+
})
|
|
2351
|
+
};
|
|
2352
|
+
setupProviders(options, hamur, providers);
|
|
2353
|
+
const resolver = createResolver3({
|
|
2354
|
+
options,
|
|
2355
|
+
builtIn: providers,
|
|
2356
|
+
report,
|
|
2357
|
+
...options.cache ? { cache: { store: createMetaCache(join8(fontsDir, "meta")), providers: new Set(Object.keys(remoteProviders)) } } : {}
|
|
2358
|
+
});
|
|
2359
|
+
const fallbacks = options.fallbacks;
|
|
2360
|
+
const systemsFor = (generic) => fallbacks ? fallbacks[generic ?? "sans-serif"] ?? [] : [];
|
|
2361
|
+
const publicPrefix = `${app.baseURL.replace(/\/+$/, "")}/`;
|
|
2362
|
+
const read = async (url) => {
|
|
2363
|
+
const candidates = isAbsolute2(url) && existsSync2(url) ? [url] : url.startsWith(publicPrefix) ? roots.map((root) => join8(root.publicDir, decodeURI(url.slice(publicPrefix.length)))) : [];
|
|
2364
|
+
const file = candidates.find((path) => existsSync2(path));
|
|
2365
|
+
return file ? new Uint8Array(await readFile6(file)) : undefined;
|
|
2366
|
+
};
|
|
2367
|
+
const subsetter = createSubsetter(join8(fontsDir, "subset"), read, report);
|
|
2368
|
+
const notified = new Set;
|
|
2369
|
+
const withoutLocal = (faces) => faces.map((face) => ({ ...face, src: face.src.filter((entry) => ("url" in entry)) })).filter((face) => face.src.length > 0);
|
|
2370
|
+
const metrics = new Map;
|
|
2371
|
+
const metricsOf = (family, faces) => {
|
|
2372
|
+
const key = familyKey(family);
|
|
2373
|
+
let found = metrics.get(key);
|
|
2374
|
+
if (!found)
|
|
2375
|
+
metrics.set(key, found = familyMetrics(family, faces, { read, report }));
|
|
2376
|
+
return found;
|
|
2377
|
+
};
|
|
2378
|
+
addTransform({
|
|
2379
|
+
name: "fonts:css",
|
|
2380
|
+
filter: { id: /\.(?:css|s[ac]ss|less|styl)$/ },
|
|
2381
|
+
target: "client",
|
|
2382
|
+
version: () => resolver.version(),
|
|
2383
|
+
async transform(code, { loader }) {
|
|
2384
|
+
if (loader !== "css" || !/font/i.test(code))
|
|
2385
|
+
return null;
|
|
2386
|
+
const scan = scanCss(code, { customProperties: options.processCSSVariables });
|
|
2387
|
+
const declared = new Set(scan.declared);
|
|
2388
|
+
const wanted = new Map;
|
|
2389
|
+
for (const use of scan.uses) {
|
|
2390
|
+
for (const { name } of use.names) {
|
|
2391
|
+
const key = familyKey(name);
|
|
2392
|
+
if (declared.has(key) || wanted.has(key) || isSystemFamily(name) && !resolver.listed(name))
|
|
2393
|
+
continue;
|
|
2394
|
+
wanted.set(key, name);
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2397
|
+
const rules = [];
|
|
2398
|
+
const fallbackOf = new Map;
|
|
2399
|
+
for (const [key, name] of wanted) {
|
|
2400
|
+
const resolved = await resolver.resolve(name);
|
|
2401
|
+
if (!resolved)
|
|
2402
|
+
continue;
|
|
2403
|
+
const descriptors = {
|
|
2404
|
+
display: resolved.entry?.display ?? options.defaults.display,
|
|
2405
|
+
...resolved.entry?.unicodeRange !== undefined ? { unicodeRange: resolved.entry.unicodeRange } : {},
|
|
2406
|
+
...resolved.entry?.stretch !== undefined ? { stretch: resolved.entry.stretch } : {},
|
|
2407
|
+
...resolved.entry?.featureSettings !== undefined ? { featureSettings: resolved.entry.featureSettings } : {},
|
|
2408
|
+
...resolved.entry?.variationSettings !== undefined ? { variationSettings: resolved.entry.variationSettings } : {}
|
|
2409
|
+
};
|
|
2410
|
+
const glyphs = resolved.entry?.glyphs;
|
|
2411
|
+
const whole = await files.localize(resolved.name, options.localSources ? resolved.faces : withoutLocal(resolved.faces), glyphs);
|
|
2412
|
+
const faces = glyphs && resolved.provider !== "google" && resolved.provider !== "googleicons" ? await subsetter.subset(resolved.name, whole, glyphs) : whole;
|
|
2413
|
+
if (!notified.has(key)) {
|
|
2414
|
+
notified.add(key);
|
|
2415
|
+
const paths = faces.flatMap((face) => face.src.flatMap((entry) => ("url" in entry) && !/^https?:\/\//i.test(entry.url) && existsSync2(entry.url) ? [entry.url] : []));
|
|
2416
|
+
registry.record(resolved.name, faces);
|
|
2417
|
+
await hamur.hooks.callHook("fonts:resolved", { family: resolved.name, faces, files: [...new Set(paths)] });
|
|
2418
|
+
}
|
|
2419
|
+
if (resolved.entry?.preload ?? options.defaults.preload)
|
|
2420
|
+
preload.add(faces, (resolved.entry ?? options.defaults).subsets);
|
|
2421
|
+
for (const face of faces)
|
|
2422
|
+
rules.push(fontFaceRule(resolved.name, face, descriptors));
|
|
2423
|
+
const systems = [
|
|
2424
|
+
...new Set(scan.uses.filter((use) => use.names.some((family) => familyKey(family.name) === key)).flatMap((use) => systemsFor(use.generic)))
|
|
2425
|
+
];
|
|
2426
|
+
if (systems.length === 0)
|
|
2427
|
+
continue;
|
|
2428
|
+
const font = await metricsOf(resolved.name, whole);
|
|
2429
|
+
if (!font)
|
|
2430
|
+
continue;
|
|
2431
|
+
for (const system of systems)
|
|
2432
|
+
rules.push(fallbackFaceRule(resolved.name, system, fallbackOverrides(font, SYSTEM_METRICS[system])));
|
|
2433
|
+
fallbackOf.set(key, resolved.name);
|
|
2434
|
+
}
|
|
2435
|
+
if (rules.length === 0)
|
|
2436
|
+
return null;
|
|
2437
|
+
const edits = scan.uses.flatMap((use) => use.names.flatMap((family) => {
|
|
2438
|
+
const resolvedName = fallbackOf.get(familyKey(family.name));
|
|
2439
|
+
const systems = systemsFor(use.generic);
|
|
2440
|
+
return resolvedName && systems.length ? [
|
|
2441
|
+
{
|
|
2442
|
+
at: family.end,
|
|
2443
|
+
text: systems.map((system) => `, ${quote(fallbackFamily(resolvedName, system))}`).join("")
|
|
2444
|
+
}
|
|
2445
|
+
] : [];
|
|
2446
|
+
}));
|
|
2447
|
+
return insertRules(insertEdits(code, edits), scan.insertAt, rules);
|
|
2448
|
+
}
|
|
2449
|
+
});
|
|
2450
|
+
}
|
|
2451
|
+
|
|
2452
|
+
// packages/fonts/src/module.ts
|
|
2453
|
+
var module_default = defineModule({
|
|
2454
|
+
meta: { name: "fonts", configKey: "fonts", hooks: ["fonts:providers", "fonts:resolved"] },
|
|
2455
|
+
async setup(input, hamur) {
|
|
2456
|
+
const options = await resolveOptions(input, {
|
|
2457
|
+
rootDir: hamur.options.rootDir,
|
|
2458
|
+
exists: existsSync3,
|
|
2459
|
+
load: async (file) => (await import(pathToFileURL(file).href)).default
|
|
2460
|
+
});
|
|
2461
|
+
if (!options.enabled)
|
|
2462
|
+
return;
|
|
2463
|
+
await publicUrlsKept();
|
|
2464
|
+
const preload = createPreloadNames();
|
|
2465
|
+
setupScan(options, hamur, preload, setupData(hamur, fontsDirOf(options.cache, hamur)));
|
|
2466
|
+
setupPreload(options, hamur, preload);
|
|
2467
|
+
setupGlobal(options);
|
|
2468
|
+
}
|
|
2469
|
+
});
|
|
2470
|
+
export {
|
|
2471
|
+
module_default as default
|
|
2472
|
+
};
|