@deepseek-ai/libreoffice-kit 0.0.1 → 0.0.2-rc4
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/NOTICE +2 -0
- package/README.md +43 -47
- package/README.zh.md +35 -50
- package/assets/font-subset.json +70 -0
- package/assets/font-subset.wasm +0 -0
- package/lib/browser/assets.json +10 -0
- package/lib/browser/index.js +435 -0
- package/lib/browser/types/connection.d.ts +20 -0
- package/lib/browser/types/editor-engine.d.ts +50 -0
- package/lib/browser/types/editor-types.d.ts +141 -0
- package/lib/browser/types/editor.d.ts +9 -0
- package/lib/browser/types/engine-rendering.d.ts +3 -0
- package/lib/browser/types/engine-types.d.ts +17 -0
- package/lib/browser/types/font-channel.d.ts +20 -0
- package/lib/browser/types/index.d.ts +13 -0
- package/lib/browser/types/protocol.d.ts +117 -0
- package/lib/browser/types/rendering.d.ts +4 -0
- package/lib/browser/types/types.d.ts +90 -0
- package/lib/browser/types/worker.d.ts +2 -0
- package/lib/browser/worker.js +3711 -0
- package/lib/browser-assets.js +119 -0
- package/lib/cli.js +1303 -0
- package/lib/document.js +178 -0
- package/lib/engine-rendering.js +120 -0
- package/lib/font-config.js +46 -0
- package/lib/font-source.js +344 -0
- package/lib/font-worker.js +712 -0
- package/lib/index.js +319 -109
- package/lib/rendering.js +99 -0
- package/lib/sheet-geometry.js +111 -0
- package/lib/types/browser-assets.d.ts +15 -0
- package/lib/types/cli.d.ts +3 -0
- package/lib/types/document.d.ts +1 -1
- package/lib/types/engine-rendering.d.ts +15 -0
- package/lib/types/engine.d.ts +5 -5
- package/lib/types/font-config.d.ts +24 -0
- package/lib/types/font-full.d.ts +13 -0
- package/lib/types/font-loader.d.ts +1 -7
- package/lib/types/font-request.d.ts +12 -0
- package/lib/types/font-source-types.d.ts +82 -0
- package/lib/types/font-source.d.ts +10 -0
- package/lib/types/font-subsets.d.ts +35 -0
- package/lib/types/font-worker.d.ts +2 -0
- package/lib/types/fonts.d.ts +9 -29
- package/lib/types/harfbuzz-subset.d.ts +11 -0
- package/lib/types/image-operations.d.ts +58 -0
- package/lib/types/image-renderer.d.ts +6 -0
- package/lib/types/index.d.ts +25 -2
- package/lib/types/native.d.ts +4 -2
- package/lib/types/operations.d.ts +41 -0
- package/lib/types/png.d.ts +2 -0
- package/lib/types/profile.d.ts +8 -0
- package/lib/types/rendering.d.ts +41 -0
- package/lib/types/runtime.d.ts +14 -0
- package/lib/types/sheet-geometry.d.ts +38 -0
- package/lib/types/unicode-scripts.d.ts +18 -0
- package/lib/types/wasm.d.ts +76 -1
- package/lib/types/worker.d.ts +3 -0
- package/lib/worker.js +1012 -237
- package/licenses/font-subset/harfbuzz-COPYING +42 -0
- package/licenses/font-subset/harfbuzzjs-LICENSE +19 -0
- package/licenses/javascript/fflate-LICENSE +21 -0
- package/licenses/javascript/saxes-LICENSE +64 -0
- package/licenses/javascript/xmlchars-LICENSE +18 -0
- package/package.json +59 -12
- package/sources/browser/packages/browser/package.json +22 -0
- package/sources/browser/packages/browser/src/connection.ts +168 -0
- package/sources/browser/packages/browser/src/editor-engine.ts +382 -0
- package/sources/browser/packages/browser/src/editor-types.ts +106 -0
- package/sources/browser/packages/browser/src/editor.ts +55 -0
- package/sources/browser/packages/browser/src/engine-rendering.ts +2 -0
- package/sources/browser/packages/browser/src/engine-types.ts +14 -0
- package/sources/browser/packages/browser/src/font-channel.ts +99 -0
- package/sources/browser/packages/browser/src/index.ts +39 -0
- package/sources/browser/packages/browser/src/protocol.ts +40 -0
- package/sources/browser/packages/browser/src/rendering.ts +3 -0
- package/sources/browser/packages/browser/src/types.ts +92 -0
- package/sources/browser/packages/browser/src/worker.ts +171 -0
- package/sources/browser/packages/browser/tsconfig.json +5 -0
- package/sources/browser/packages/browser/tsdown.config.ts +7 -0
- package/sources/browser/scripts/build-browser.mjs +74 -0
- package/sources/font-subset/engine/font-subset/README.md +23 -0
- package/sources/font-subset/engine/font-subset/README.zh.md +23 -0
- package/sources/font-subset/engine/font-subset/source.json +16 -0
- package/sources/font-subset/harfbuzzjs/config-override-subset.h +7 -0
- package/sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols +34 -0
- package/sources/font-subset/scripts/build-font-subset.mjs +64 -0
- package/sources/font-subset/scripts/pack-utils.mjs +69 -0
- package/sources/font-subset/scripts/platform-matrix.mjs +100 -0
- package/sources/font-subset/scripts/verify-artifacts.mjs +260 -0
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { closeSync, constants, fstatSync, openSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
4
|
+
import { create } from "fontkit";
|
|
5
|
+
import { basename, extname, join } from "node:path";
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import * as publishedProperties from "@unicode/unicode-17.0.0";
|
|
8
|
+
import variationSelectors from "@unicode/unicode-17.0.0/Binary_Property/Variation_Selector/code-points.mjs";
|
|
9
|
+
//#region lib/types/font-config.js
|
|
10
|
+
/** Browser-safe family ordering and Fontconfig XML shared by both WASM adapters. */
|
|
11
|
+
/**
|
|
12
|
+
* Case- and separator-insensitive family key used to compare names across sources.
|
|
13
|
+
* @param value - Family, style, or postscript name as recorded by a document or font.
|
|
14
|
+
* @returns The normalized key.
|
|
15
|
+
*/
|
|
16
|
+
function normalize(value) {
|
|
17
|
+
return value.normalize("NFKC").toLowerCase().replaceAll(/[\s_-]/g, "");
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Order named substitutions and their generic text family without excluding unlisted fonts.
|
|
21
|
+
* @param requested - Original family names, in document order.
|
|
22
|
+
* @param groups - Ordered family groups shared with Fontconfig aliases.
|
|
23
|
+
* @param pitch - VCL pitch; one requests a monospaced fallback.
|
|
24
|
+
* @param symbols - Whether symbol alternatives precede the generic fallback.
|
|
25
|
+
* @returns distinct family names, with original requests first.
|
|
26
|
+
*/
|
|
27
|
+
function fontFamilyPriority(requested, groups, pitch = 0, symbols = false) {
|
|
28
|
+
const original = requested.map(normalize);
|
|
29
|
+
const matched = groups.filter((group) => group.some((family) => original.includes(normalize(family))));
|
|
30
|
+
const generic = original.includes("monospace") || pitch === 1 ? "monospace" : original.includes("serif") ? "serif" : matched.flat().map(normalize).find((family) => family === "serif" || family === "sansserif" || family === "monospace") ?? "sansserif";
|
|
31
|
+
const families = [...requested, ...matched.flat()];
|
|
32
|
+
for (const kind of symbols ? ["symbol", generic] : [generic]) for (const group of groups) if (group.some((family) => normalize(family) === kind)) families.push(...group);
|
|
33
|
+
const priority = /* @__PURE__ */ new Map();
|
|
34
|
+
for (const family of families) {
|
|
35
|
+
const name = normalize(family);
|
|
36
|
+
if (!priority.has(name)) priority.set(name, family);
|
|
37
|
+
}
|
|
38
|
+
return [...priority.values()];
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region lib/types/fonts.js
|
|
42
|
+
/** Host font metadata snapshots and conversion-local glyph matching over original files. */
|
|
43
|
+
const FONT_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
44
|
+
".ttf",
|
|
45
|
+
".otf",
|
|
46
|
+
".ttc",
|
|
47
|
+
".otc",
|
|
48
|
+
".dfont"
|
|
49
|
+
]);
|
|
50
|
+
const VCL_WEIGHTS = [
|
|
51
|
+
400,
|
|
52
|
+
100,
|
|
53
|
+
200,
|
|
54
|
+
300,
|
|
55
|
+
350,
|
|
56
|
+
400,
|
|
57
|
+
500,
|
|
58
|
+
600,
|
|
59
|
+
700,
|
|
60
|
+
800,
|
|
61
|
+
900
|
|
62
|
+
];
|
|
63
|
+
const GENERIC_FAMILIES = /* @__PURE__ */ new Set([
|
|
64
|
+
"serif",
|
|
65
|
+
"sansserif",
|
|
66
|
+
"monospace",
|
|
67
|
+
"cursive",
|
|
68
|
+
"fantasy",
|
|
69
|
+
"systemui",
|
|
70
|
+
"symbol"
|
|
71
|
+
]);
|
|
72
|
+
/** File identity read from the descriptor, before and after, to detect concurrent replacement. */
|
|
73
|
+
const STAT_KEYS$1 = [
|
|
74
|
+
"dev",
|
|
75
|
+
"ino",
|
|
76
|
+
"size",
|
|
77
|
+
"mtimeMs",
|
|
78
|
+
"ctimeMs"
|
|
79
|
+
];
|
|
80
|
+
/**
|
|
81
|
+
* @param error - Thrown filesystem value.
|
|
82
|
+
* @returns whether it means the path is not a usable font source.
|
|
83
|
+
*/
|
|
84
|
+
function absent(error) {
|
|
85
|
+
return error instanceof Error && "code" in error && [
|
|
86
|
+
"ENOENT",
|
|
87
|
+
"EACCES",
|
|
88
|
+
"EPERM",
|
|
89
|
+
"ENOTDIR"
|
|
90
|
+
].includes(String(error.code));
|
|
91
|
+
}
|
|
92
|
+
function fontPaths(directories, maxFiles) {
|
|
93
|
+
const pending = [...directories].reverse();
|
|
94
|
+
const visited = /* @__PURE__ */ new Set();
|
|
95
|
+
const paths = [];
|
|
96
|
+
for (let path = pending.pop(); path !== void 0; path = pending.pop()) {
|
|
97
|
+
let canonical;
|
|
98
|
+
let status;
|
|
99
|
+
try {
|
|
100
|
+
canonical = realpathSync(path);
|
|
101
|
+
status = statSync(canonical);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (absent(error)) continue;
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
if (visited.has(canonical)) continue;
|
|
107
|
+
visited.add(canonical);
|
|
108
|
+
if (status.isDirectory()) {
|
|
109
|
+
let names;
|
|
110
|
+
try {
|
|
111
|
+
names = readdirSync(canonical);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (absent(error)) continue;
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
pending.push(...names.sort().reverse().map((name) => join(canonical, name)));
|
|
117
|
+
} else if (status.isFile() && FONT_EXTENSIONS.has(extname(canonical).toLowerCase())) {
|
|
118
|
+
if (paths.length >= maxFiles) throw new Error("The system font catalog exceeds maxFontFiles.");
|
|
119
|
+
paths.push(canonical);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return paths;
|
|
123
|
+
}
|
|
124
|
+
function ranges(font) {
|
|
125
|
+
const points = font.characterSet.filter((point) => font.hasGlyphForCodePoint(point)).sort((left, right) => left - right);
|
|
126
|
+
const result = [];
|
|
127
|
+
for (const point of points) {
|
|
128
|
+
const last = result.at(-1);
|
|
129
|
+
if (last !== void 0 && point <= last[1] + 1) last[1] = Math.max(last[1], point);
|
|
130
|
+
else result.push([point, point]);
|
|
131
|
+
}
|
|
132
|
+
return result;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Decode glyph coverage for one parsed face.
|
|
136
|
+
* @param font - The parsed physical face.
|
|
137
|
+
* @returns the inclusive ranges the face renders, or none when its glyph tables reject decoding.
|
|
138
|
+
*/
|
|
139
|
+
function faceCoverage(font) {
|
|
140
|
+
try {
|
|
141
|
+
return ranges(font);
|
|
142
|
+
} catch {
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* @param parsed - Parsed font file: one face, or a collection of faces.
|
|
148
|
+
* @param face - Indexed metadata naming the face inside that file.
|
|
149
|
+
* @returns the physical face the index names.
|
|
150
|
+
* @throws when the file no longer provides the indexed face.
|
|
151
|
+
*/
|
|
152
|
+
function indexedFace(parsed, face) {
|
|
153
|
+
const font = "fonts" in parsed ? parsed.fonts[face.faceIndex] : parsed;
|
|
154
|
+
if (font === void 0 || font.postscriptName !== face.postscriptName) throw new Error("The indexed font face is no longer available; recreate the converter.");
|
|
155
|
+
return font;
|
|
156
|
+
}
|
|
157
|
+
function covers(face, points) {
|
|
158
|
+
if (points.length === 0) return [];
|
|
159
|
+
if (face.coverage === void 0) face.coverage = faceCoverage(indexedFace(create(readFont(face)), face));
|
|
160
|
+
const coverage = face.coverage;
|
|
161
|
+
return points.filter((point) => coverage.some(([first, last]) => point >= first && point <= last));
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* VCL weight, width, and fixed-pitch values for one parsed face.
|
|
165
|
+
* @param font - The parsed physical face, whose `OS/2` and `post` tables may be absent.
|
|
166
|
+
* @returns the recorded classes, or the regular defaults for an absent table.
|
|
167
|
+
*/
|
|
168
|
+
function faceMetrics(font) {
|
|
169
|
+
const os2 = font["OS/2"];
|
|
170
|
+
return {
|
|
171
|
+
weight: os2 === void 0 ? 400 : os2.usWeightClass,
|
|
172
|
+
width: os2 === void 0 ? 5 : os2.usWidthClass,
|
|
173
|
+
fixed: Boolean(font.post?.isFixedPitch)
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function inspect(path, maxBytes) {
|
|
177
|
+
let status;
|
|
178
|
+
let bytes;
|
|
179
|
+
try {
|
|
180
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
181
|
+
try {
|
|
182
|
+
status = fstatSync(fd);
|
|
183
|
+
if (!status.isFile() || status.size > maxBytes) return [];
|
|
184
|
+
bytes = Buffer.alloc(status.size);
|
|
185
|
+
let offset = 0;
|
|
186
|
+
while (offset < bytes.length) {
|
|
187
|
+
const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
188
|
+
if (count === 0) throw new Error("A system font was truncated while indexing; reload the font service.");
|
|
189
|
+
offset += count;
|
|
190
|
+
}
|
|
191
|
+
const after = fstatSync(fd);
|
|
192
|
+
if (after.size !== status.size || after.mtimeMs !== status.mtimeMs || after.ctimeMs !== status.ctimeMs) throw new Error("A system font changed while indexing; reload the font service.");
|
|
193
|
+
} finally {
|
|
194
|
+
closeSync(fd);
|
|
195
|
+
}
|
|
196
|
+
} catch (error) {
|
|
197
|
+
if (absent(error)) return [];
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
let faces;
|
|
201
|
+
try {
|
|
202
|
+
const parsed = create(bytes);
|
|
203
|
+
faces = ("fonts" in parsed ? parsed.fonts : [parsed]).map((font, faceIndex) => {
|
|
204
|
+
const names = [
|
|
205
|
+
"fontFamily",
|
|
206
|
+
"preferredFamily",
|
|
207
|
+
"fullName",
|
|
208
|
+
"postscriptName"
|
|
209
|
+
].flatMap((key) => Object.values(font.name?.records[key] ?? {})).filter((name) => typeof name === "string");
|
|
210
|
+
const aliases = [...new Set([
|
|
211
|
+
...names,
|
|
212
|
+
font.familyName,
|
|
213
|
+
font.fullName,
|
|
214
|
+
font.postscriptName
|
|
215
|
+
].filter((name) => Boolean(name)).map(normalize))];
|
|
216
|
+
return {
|
|
217
|
+
path,
|
|
218
|
+
size: status.size,
|
|
219
|
+
mtimeMs: status.mtimeMs,
|
|
220
|
+
ctimeMs: status.ctimeMs,
|
|
221
|
+
dev: status.dev,
|
|
222
|
+
ino: status.ino,
|
|
223
|
+
faceIndex,
|
|
224
|
+
family: font.familyName,
|
|
225
|
+
style: font.subfamilyName,
|
|
226
|
+
aliases,
|
|
227
|
+
...faceMetrics(font),
|
|
228
|
+
italic: font.italicAngle !== 0,
|
|
229
|
+
postscriptName: font.postscriptName
|
|
230
|
+
};
|
|
231
|
+
});
|
|
232
|
+
} catch {
|
|
233
|
+
return [];
|
|
234
|
+
}
|
|
235
|
+
return faces;
|
|
236
|
+
}
|
|
237
|
+
function regionalPriority(face, language) {
|
|
238
|
+
const locale = language.toLowerCase();
|
|
239
|
+
const preferred = locale.startsWith("ja") ? ["jp"] : locale.startsWith("ko") ? ["kr"] : locale.startsWith("zh") ? /hant|tw|hk|mo/.test(locale) ? ["tc", "hk"] : ["sc"] : [];
|
|
240
|
+
if (preferred.length === 0) return 0;
|
|
241
|
+
const region = `${face.family} ${face.postscriptName} ${basename(face.path)}`.toLowerCase().match(/(?:cjk|[\s_-])(sc|tc|jp|kr|hk)(?=[\s_.-]|$)/)?.[1];
|
|
242
|
+
return region === void 0 ? 1 : preferred.includes(region) ? 0 : 2;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Snapshot eligible local font metadata without retaining font bytes or decoding glyph coverage.
|
|
246
|
+
* @param options - Host font roots and physical file limits.
|
|
247
|
+
* @param previous - Optional prior snapshot whose unchanged physical files can reuse parsed metadata.
|
|
248
|
+
* @returns current metadata; changed and newly installed files are decoded again.
|
|
249
|
+
*/
|
|
250
|
+
function indexSystemFonts(options, previous = []) {
|
|
251
|
+
const reusable = /* @__PURE__ */ new Map();
|
|
252
|
+
for (const face of previous) {
|
|
253
|
+
const group = reusable.get(face.path);
|
|
254
|
+
if (group) group.push(face);
|
|
255
|
+
else reusable.set(face.path, [face]);
|
|
256
|
+
}
|
|
257
|
+
return fontPaths(options.directories, options.maxFiles).flatMap((path) => {
|
|
258
|
+
const prior = reusable.get(path);
|
|
259
|
+
if (prior !== void 0) {
|
|
260
|
+
let current;
|
|
261
|
+
try {
|
|
262
|
+
current = statSync(path);
|
|
263
|
+
} catch (error) {
|
|
264
|
+
if (absent(error)) return [];
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
if (current.isFile() && current.size <= options.maxFileBytes && STAT_KEYS$1.every((key) => current[key] === prior[0][key])) return prior;
|
|
268
|
+
}
|
|
269
|
+
return inspect(path, options.maxFileBytes);
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
/** Conversion-local glyph coverage over the converter's first metadata snapshot. */
|
|
273
|
+
var SystemFontCatalog = class {
|
|
274
|
+
options;
|
|
275
|
+
faces;
|
|
276
|
+
/**
|
|
277
|
+
* @param options - Host metadata snapshot and fallback families.
|
|
278
|
+
*/
|
|
279
|
+
constructor(options) {
|
|
280
|
+
this.options = options;
|
|
281
|
+
this.faces = options.faces.map((face) => ({ ...face }));
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Find installed faces covering the requested family or missing characters.
|
|
285
|
+
* Exact families precede configured alternatives, symbol families for missing symbols,
|
|
286
|
+
* generic families, then other glyph-covering faces.
|
|
287
|
+
* @param request - VCL family/style attributes and Unicode scalars missing from its current font.
|
|
288
|
+
* @param signal - cancellation checked between synchronous font reads.
|
|
289
|
+
* @returns selected files or physical faces according to deduplicateBy; absent glyphs remain unresolved.
|
|
290
|
+
* @throws if an indexed font changes or cannot be read during glyph matching.
|
|
291
|
+
*/
|
|
292
|
+
match(request, signal) {
|
|
293
|
+
signal.throwIfAborted();
|
|
294
|
+
const requested = request.family.split(";").map((family) => family.trim()).filter(Boolean);
|
|
295
|
+
const primary = requested[0];
|
|
296
|
+
let missingFamily;
|
|
297
|
+
if (primary !== void 0 && !GENERIC_FAMILIES.has(normalize(primary)) && !this.faces.some((face) => face.aliases.includes(normalize(primary)))) missingFamily = primary;
|
|
298
|
+
const priority = fontFamilyPriority(requested, this.options.fallbackFamilies, request.pitch, request.codePoints.some((point) => /\p{Symbol}/u.test(String.fromCodePoint(point)))).map(normalize);
|
|
299
|
+
const missing = new Set(request.codePoints);
|
|
300
|
+
const ranked = this.faces.map((face) => {
|
|
301
|
+
const rank = priority.findIndex((family) => face.aliases.includes(family));
|
|
302
|
+
const region = regionalPriority(face, request.language);
|
|
303
|
+
const style = (request.style && normalize(request.style) === normalize(face.style) ? -1 : 0) + (request.italic === 3 || request.italic !== 0 === face.italic ? 0 : 100) + (request.pitch === 0 || request.pitch === 1 === face.fixed ? 0 : 50) + Math.abs((VCL_WEIGHTS[request.weight] ?? 400) - face.weight) / 100 + (request.width === 0 ? 0 : Math.abs(request.width - face.width));
|
|
304
|
+
return {
|
|
305
|
+
face,
|
|
306
|
+
rank: rank < 0 ? priority.length : rank,
|
|
307
|
+
region,
|
|
308
|
+
style
|
|
309
|
+
};
|
|
310
|
+
}).sort((left, right) => left.rank - right.rank || left.region - right.region || left.style - right.style || left.face.path.localeCompare(right.face.path, "en") || left.face.faceIndex - right.face.faceIndex);
|
|
311
|
+
const selected = [];
|
|
312
|
+
const files = /* @__PURE__ */ new Set();
|
|
313
|
+
for (const { face } of ranked) {
|
|
314
|
+
signal.throwIfAborted();
|
|
315
|
+
const covered = covers(face, [...missing]);
|
|
316
|
+
if (missing.size > 0 && covered.length === 0) continue;
|
|
317
|
+
const identity = this.options.deduplicateBy === "face" ? `${face.path}#${face.faceIndex}` : face.path;
|
|
318
|
+
if (!files.has(identity)) {
|
|
319
|
+
selected.push(face);
|
|
320
|
+
files.add(identity);
|
|
321
|
+
}
|
|
322
|
+
for (const point of covered) missing.delete(point);
|
|
323
|
+
if (missing.size === 0) break;
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
fonts: selected,
|
|
327
|
+
...missingFamily === void 0 ? {} : { missingFamily }
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
/**
|
|
332
|
+
* Read the unchanged indexed regular file; reject concurrent replacement or truncation.
|
|
333
|
+
* @param face - Indexed face metadata whose identity and timestamps must still match the file.
|
|
334
|
+
* @returns the complete original font bytes.
|
|
335
|
+
* @throws when the file changed, was replaced, or was truncated since indexing.
|
|
336
|
+
*/
|
|
337
|
+
function readFont(face) {
|
|
338
|
+
const fd = openSync(face.path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
339
|
+
try {
|
|
340
|
+
const before = fstatSync(fd);
|
|
341
|
+
if (!before.isFile() || STAT_KEYS$1.some((key) => before[key] !== face[key])) throw new Error("An indexed font changed; recreate the converter.");
|
|
342
|
+
const bytes = Buffer.alloc(face.size);
|
|
343
|
+
for (let offset = 0; offset < bytes.length;) {
|
|
344
|
+
const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
345
|
+
if (!count) throw new Error("An indexed font was truncated.");
|
|
346
|
+
offset += count;
|
|
347
|
+
}
|
|
348
|
+
const after = fstatSync(fd);
|
|
349
|
+
if (STAT_KEYS$1.some((key) => after[key] !== face[key])) throw new Error("An indexed font changed while reading.");
|
|
350
|
+
return bytes;
|
|
351
|
+
} finally {
|
|
352
|
+
closeSync(fd);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
//#endregion
|
|
356
|
+
//#region lib/types/font-full.js
|
|
357
|
+
/** Whole fonts for engines such as PDFium that perform their own glyph mapping. */
|
|
358
|
+
function fontFileFormat(bytes) {
|
|
359
|
+
const magic = new TextDecoder().decode(bytes.subarray(0, 4));
|
|
360
|
+
if (magic === "ttcf") return "ttc";
|
|
361
|
+
if (magic === "OTTO") return "otf";
|
|
362
|
+
if (magic === "true" || bytes[0] === 0 && bytes[1] === 1 && bytes[2] === 0 && bytes[3] === 0) return "ttf";
|
|
363
|
+
throw new Error("The full font asset is not an sfnt font or collection.");
|
|
364
|
+
}
|
|
365
|
+
/** Keep full names, encoding tables and glyphs. Apple dfont containers expose one complete sfnt resource. */
|
|
366
|
+
function fullFontFile(face) {
|
|
367
|
+
const original = readFont(face);
|
|
368
|
+
const sourceHash = createHash("sha256").update(original).digest("hex");
|
|
369
|
+
let bytes = original;
|
|
370
|
+
if (extname(face.path).toLowerCase() === ".dfont") bytes = indexedFace(create(original), face).stream.buffer;
|
|
371
|
+
return {
|
|
372
|
+
bytes,
|
|
373
|
+
sourceHash,
|
|
374
|
+
format: fontFileFormat(bytes)
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
//#endregion
|
|
378
|
+
//#region lib/types/harfbuzz-subset.js
|
|
379
|
+
/** Portable HarfBuzz sfnt subsetting, preserving shaping features and variable axes. */
|
|
380
|
+
/** Exact upstream subset source and heap-growth recipe, included in generated subset identities. */
|
|
381
|
+
const FONT_SUBSET_VERSION = "harfbuzzjs-1.6.1-hb-36cb489-growth-v1";
|
|
382
|
+
let engine;
|
|
383
|
+
function load() {
|
|
384
|
+
return engine ??= (async () => {
|
|
385
|
+
const [bytes, manifest] = await Promise.all([readFile(new URL("../assets/font-subset.wasm", import.meta.url)), readFile(new URL("../assets/font-subset.json", import.meta.url), "utf8")]);
|
|
386
|
+
const receipt = JSON.parse(manifest);
|
|
387
|
+
const entry = receipt.files?.["assets/font-subset.wasm"];
|
|
388
|
+
if (receipt.schemaVersion !== 1 || receipt.source?.algorithm !== "harfbuzzjs-1.6.1-hb-36cb489-growth-v1" || entry?.bytes !== bytes.byteLength || entry.sha256 !== createHash("sha256").update(bytes).digest("hex")) throw new Error("The packaged font subset module does not match its receipt.");
|
|
389
|
+
const { instance } = await WebAssembly.instantiate(bytes, { env: { emscripten_notify_memory_growth: () => {} } });
|
|
390
|
+
const hb = instance.exports;
|
|
391
|
+
hb._initialize();
|
|
392
|
+
return hb;
|
|
393
|
+
})();
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Extract and subset one physical face without renaming it or instancing variable axes.
|
|
397
|
+
* @param original - TTF, OTF, or collection bytes.
|
|
398
|
+
* @param faceIndex - Collection face index; zero for a standalone face.
|
|
399
|
+
* @param points - Unicode scalars, including any required variation selectors.
|
|
400
|
+
* @returns caller-owned sfnt bytes; all layout scripts/features and glyph closure remain enabled.
|
|
401
|
+
*/
|
|
402
|
+
async function subsetFont(original, faceIndex, points) {
|
|
403
|
+
const hb = await load();
|
|
404
|
+
let allocation = 0;
|
|
405
|
+
let blob = 0;
|
|
406
|
+
let face = 0;
|
|
407
|
+
let input = 0;
|
|
408
|
+
let subset = 0;
|
|
409
|
+
let result = 0;
|
|
410
|
+
try {
|
|
411
|
+
allocation = hb.malloc(original.byteLength);
|
|
412
|
+
if (!allocation) throw new Error("The font subsetter could not allocate its input.");
|
|
413
|
+
new Uint8Array(hb.memory.buffer).set(original, allocation);
|
|
414
|
+
blob = hb.hb_blob_create(allocation, original.byteLength, 2, 0, 0);
|
|
415
|
+
face = hb.hb_face_create(blob, faceIndex);
|
|
416
|
+
input = hb.hb_subset_input_create_or_fail();
|
|
417
|
+
if (!input) throw new Error("The font subsetter could not create its input.");
|
|
418
|
+
for (const kind of [
|
|
419
|
+
4,
|
|
420
|
+
5,
|
|
421
|
+
6,
|
|
422
|
+
7
|
|
423
|
+
]) {
|
|
424
|
+
const set = hb.hb_subset_input_set(input, kind);
|
|
425
|
+
hb.hb_set_clear(set);
|
|
426
|
+
hb.hb_set_invert(set);
|
|
427
|
+
}
|
|
428
|
+
hb.hb_subset_input_set_flags(input, 72);
|
|
429
|
+
const unicode = hb.hb_subset_input_unicode_set(input);
|
|
430
|
+
for (const point of points) hb.hb_set_add(unicode, point);
|
|
431
|
+
subset = hb.hb_subset_or_fail(face, input);
|
|
432
|
+
if (!subset) throw new Error("The font subsetter rejected the selected face.");
|
|
433
|
+
result = hb.hb_face_reference_blob(subset);
|
|
434
|
+
const offset = hb.hb_blob_get_data(result, 0);
|
|
435
|
+
const length = hb.hb_blob_get_length(result);
|
|
436
|
+
if (!length) throw new Error("The font subsetter returned no sfnt bytes.");
|
|
437
|
+
return new Uint8Array(hb.memory.buffer).slice(offset, offset + length);
|
|
438
|
+
} finally {
|
|
439
|
+
if (result) hb.hb_blob_destroy(result);
|
|
440
|
+
if (subset) hb.hb_face_destroy(subset);
|
|
441
|
+
if (input) hb.hb_subset_input_destroy(input);
|
|
442
|
+
if (face) hb.hb_face_destroy(face);
|
|
443
|
+
if (blob) hb.hb_blob_destroy(blob);
|
|
444
|
+
if (allocation) hb.free(allocation);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
//#endregion
|
|
448
|
+
//#region lib/types/unicode-scripts.js
|
|
449
|
+
/** Complete Unicode Script partitions with shared punctuation, marks and variation selectors. */
|
|
450
|
+
var __rewriteRelativeImportExtension = function(path, preserveJsx) {
|
|
451
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
|
|
452
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
|
|
453
|
+
});
|
|
454
|
+
return path;
|
|
455
|
+
};
|
|
456
|
+
const properties = publishedProperties.default;
|
|
457
|
+
/** Unicode data and partition generation participate in every subset request identity. */
|
|
458
|
+
const FONT_PARTITION_VERSION = "unicode-17.0.0-data-2.0.7-script-v1";
|
|
459
|
+
/** A shared metadata/punctuation subset used before layout requests any script. */
|
|
460
|
+
const FONT_BASE_SCRIPT = "Common";
|
|
461
|
+
let loaded;
|
|
462
|
+
function scriptData() {
|
|
463
|
+
return loaded ??= (async () => {
|
|
464
|
+
const names = properties.Script;
|
|
465
|
+
const primary = /* @__PURE__ */ new Uint16Array(1114112);
|
|
466
|
+
const extensions = /* @__PURE__ */ new Map();
|
|
467
|
+
await Promise.all(names.map(async (name, index) => {
|
|
468
|
+
const [script, extended] = await Promise.all([import(__rewriteRelativeImportExtension(`@unicode/unicode-17.0.0/Script/${name}/ranges.mjs`)), import(__rewriteRelativeImportExtension(`@unicode/unicode-17.0.0/Script_Extensions/${name}/ranges.mjs`))]);
|
|
469
|
+
for (const range of script.default) primary.fill(index, range.begin, range.end);
|
|
470
|
+
extensions.set(name, extended.default);
|
|
471
|
+
}));
|
|
472
|
+
return {
|
|
473
|
+
names,
|
|
474
|
+
primary,
|
|
475
|
+
extensions
|
|
476
|
+
};
|
|
477
|
+
})();
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Select stable whole-script partitions for a request; shared characters use the base partition.
|
|
481
|
+
* @param points - Unicode scalars requested by layout.
|
|
482
|
+
* @returns deterministic Unicode script names, including Unknown for private-use or unassigned characters.
|
|
483
|
+
*/
|
|
484
|
+
async function requestedFontScripts(points) {
|
|
485
|
+
const data = await scriptData();
|
|
486
|
+
const scripts = new Set(points.map((point) => data.names[data.primary[point]]));
|
|
487
|
+
scripts.delete("Common");
|
|
488
|
+
scripts.delete("Inherited");
|
|
489
|
+
return scripts.size === 0 ? [FONT_BASE_SCRIPT] : [...scripts].sort();
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Retain source characters in a script's Script_Extensions, plus Common/Inherited and variation selectors.
|
|
493
|
+
* @param points - Character repertoire of one physical font face.
|
|
494
|
+
* @param script - Name returned by requestedFontScripts.
|
|
495
|
+
* @returns Unicode set for HarfBuzz's layout and composite-glyph closure.
|
|
496
|
+
*/
|
|
497
|
+
async function fontScriptCodePoints(points, script) {
|
|
498
|
+
const data = await scriptData();
|
|
499
|
+
const ranges = data.extensions.get(script);
|
|
500
|
+
const selected = points.filter((point) => {
|
|
501
|
+
const primary = data.names[data.primary[point]];
|
|
502
|
+
return primary === "Common" || primary === "Inherited" || script !== "Common" && ranges.some((range) => point >= range.begin && point < range.end);
|
|
503
|
+
});
|
|
504
|
+
return [.../* @__PURE__ */ new Set([...selected, ...variationSelectors])].sort((left, right) => left - right);
|
|
505
|
+
}
|
|
506
|
+
//#endregion
|
|
507
|
+
//#region lib/types/font-subsets.js
|
|
508
|
+
/** Refreshable installed-font matching with deterministic, memory-bounded sfnt subsets. */
|
|
509
|
+
const ALGORITHM = `${FONT_SUBSET_VERSION}/${FONT_PARTITION_VERSION}`;
|
|
510
|
+
const STAT_KEYS = [
|
|
511
|
+
"dev",
|
|
512
|
+
"ino",
|
|
513
|
+
"size",
|
|
514
|
+
"mtimeMs",
|
|
515
|
+
"ctimeMs"
|
|
516
|
+
];
|
|
517
|
+
function hash(bytes) {
|
|
518
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
519
|
+
}
|
|
520
|
+
function unchanged(face) {
|
|
521
|
+
const status = statSync(face.path);
|
|
522
|
+
if (!status.isFile() || STAT_KEYS.some((key) => status[key] !== face[key])) throw new Error("The selected font changed; resolve it again.");
|
|
523
|
+
}
|
|
524
|
+
function fileIdentity(face) {
|
|
525
|
+
return JSON.stringify([
|
|
526
|
+
face.path,
|
|
527
|
+
...STAT_KEYS.map((key) => face[key]),
|
|
528
|
+
face.faceIndex
|
|
529
|
+
]);
|
|
530
|
+
}
|
|
531
|
+
/** One Worker-owned font index and LRU whose byte budget excludes transient subsetting input/output. */
|
|
532
|
+
var FontSubsetSource = class {
|
|
533
|
+
options;
|
|
534
|
+
snapshot = [];
|
|
535
|
+
catalog;
|
|
536
|
+
selected = /* @__PURE__ */ new Map();
|
|
537
|
+
partitions = /* @__PURE__ */ new Map();
|
|
538
|
+
cached = /* @__PURE__ */ new Map();
|
|
539
|
+
cachedBytes = 0;
|
|
540
|
+
/** @param options - Resolved discovery, fallback, and retained subset limits. */
|
|
541
|
+
constructor(options) {
|
|
542
|
+
this.options = options;
|
|
543
|
+
}
|
|
544
|
+
retain(key, bytes) {
|
|
545
|
+
const existing = this.cached.get(key);
|
|
546
|
+
if (existing !== void 0) {
|
|
547
|
+
this.cached.delete(key);
|
|
548
|
+
this.cachedBytes -= existing.byteLength;
|
|
549
|
+
}
|
|
550
|
+
if (bytes.byteLength > this.options.maxCachedSubsetBytes) return;
|
|
551
|
+
while (this.cachedBytes + bytes.byteLength > this.options.maxCachedSubsetBytes) {
|
|
552
|
+
const oldest = this.cached.entries().next().value;
|
|
553
|
+
this.cached.delete(oldest[0]);
|
|
554
|
+
this.cachedBytes -= oldest[1].byteLength;
|
|
555
|
+
}
|
|
556
|
+
this.cached.set(key, bytes);
|
|
557
|
+
this.cachedBytes += bytes.byteLength;
|
|
558
|
+
}
|
|
559
|
+
async generate(face, script, expectedHash) {
|
|
560
|
+
if (script === "full") {
|
|
561
|
+
const result = fullFontFile(face);
|
|
562
|
+
if (expectedHash !== void 0 && result.sourceHash !== expectedHash) throw new Error("The selected font content changed.");
|
|
563
|
+
unchanged(face);
|
|
564
|
+
return result;
|
|
565
|
+
}
|
|
566
|
+
const original = readFont(face);
|
|
567
|
+
const sourceHash = hash(original);
|
|
568
|
+
if (expectedHash !== void 0 && sourceHash !== expectedHash) throw new Error("The selected font content changed.");
|
|
569
|
+
const parsed = create(original);
|
|
570
|
+
const physical = indexedFace(parsed, face);
|
|
571
|
+
const points = await fontScriptCodePoints(physical.characterSet, script);
|
|
572
|
+
const resource = "fonts" in parsed && parsed.type === "DFont";
|
|
573
|
+
const bytes = await subsetFont(resource ? physical.stream.buffer : original, resource ? 0 : face.faceIndex, points);
|
|
574
|
+
unchanged(face);
|
|
575
|
+
return {
|
|
576
|
+
bytes,
|
|
577
|
+
sourceHash
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
async describe(face, script) {
|
|
581
|
+
unchanged(face);
|
|
582
|
+
const partition = `${fileIdentity(face)}/${script}`;
|
|
583
|
+
const previous = this.partitions.get(partition);
|
|
584
|
+
if (previous !== void 0) {
|
|
585
|
+
this.selected.set(previous.asset.id, previous);
|
|
586
|
+
return {
|
|
587
|
+
...previous.asset,
|
|
588
|
+
family: face.family
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
const { bytes, sourceHash } = await this.generate(face, script);
|
|
592
|
+
const id = `${script === "full" ? "full_" : ""}${hash(bytes)}`;
|
|
593
|
+
const key = `${sourceHash}/${face.faceIndex}/${ALGORITHM}/${script}`;
|
|
594
|
+
const asset = {
|
|
595
|
+
id,
|
|
596
|
+
bytes: bytes.byteLength,
|
|
597
|
+
family: face.family,
|
|
598
|
+
alias: script === "full" ? face.family : `DSH_${id}`,
|
|
599
|
+
...script === "full" ? {
|
|
600
|
+
mode: "full",
|
|
601
|
+
format: fontFileFormat(bytes)
|
|
602
|
+
} : {}
|
|
603
|
+
};
|
|
604
|
+
const selection = {
|
|
605
|
+
asset,
|
|
606
|
+
face,
|
|
607
|
+
script,
|
|
608
|
+
sourceHash,
|
|
609
|
+
key
|
|
610
|
+
};
|
|
611
|
+
this.selected.set(id, selection);
|
|
612
|
+
this.partitions.set(partition, selection);
|
|
613
|
+
this.retain(key, bytes);
|
|
614
|
+
return asset;
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Refresh installed files and select whole Unicode-script subsets for matching physical faces.
|
|
618
|
+
* @param request - Requested family/style attributes and Unicode scalars.
|
|
619
|
+
* @returns reusable subset identities; unavailable characters remain unresolved.
|
|
620
|
+
*/
|
|
621
|
+
async resolve(request) {
|
|
622
|
+
if (request.mode !== void 0 && request.mode !== "subset" && request.mode !== "full") throw new TypeError("Unknown font asset mode.");
|
|
623
|
+
const snapshot = indexSystemFonts(this.options, this.snapshot);
|
|
624
|
+
if (this.catalog === void 0 || snapshot.length !== this.snapshot.length || snapshot.some((face, index) => face !== this.snapshot[index])) {
|
|
625
|
+
const current = new Set(snapshot.map(fileIdentity));
|
|
626
|
+
for (const [partition, selection] of this.partitions) {
|
|
627
|
+
if (current.has(fileIdentity(selection.face))) continue;
|
|
628
|
+
this.partitions.delete(partition);
|
|
629
|
+
if (this.selected.get(selection.asset.id) === selection) this.selected.delete(selection.asset.id);
|
|
630
|
+
const bytes = this.cached.get(selection.key);
|
|
631
|
+
if (bytes !== void 0) {
|
|
632
|
+
this.cached.delete(selection.key);
|
|
633
|
+
this.cachedBytes -= bytes.byteLength;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
this.snapshot = snapshot;
|
|
637
|
+
this.catalog = new SystemFontCatalog({
|
|
638
|
+
faces: snapshot,
|
|
639
|
+
fallbackFamilies: this.options.fallbackFamilies,
|
|
640
|
+
deduplicateBy: "face"
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
const matched = this.catalog.match(request, new AbortController().signal);
|
|
644
|
+
const fonts = [];
|
|
645
|
+
for (const face of matched.fonts) {
|
|
646
|
+
if (request.mode === "full") {
|
|
647
|
+
fonts.push(await this.describe(face, "full"));
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
const points = request.codePoints.filter((point) => face.coverage?.some(([first, last]) => point >= first && point <= last));
|
|
651
|
+
for (const script of await requestedFontScripts(points)) fonts.push(await this.describe(face, script));
|
|
652
|
+
}
|
|
653
|
+
return {
|
|
654
|
+
fonts,
|
|
655
|
+
...matched.missingFamily === void 0 ? {} : { missingFamily: matched.missingFamily }
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Return caller-owned bytes, regenerating an evicted subset from its unchanged original.
|
|
660
|
+
* @param id - Subset identity previously returned by this source.
|
|
661
|
+
* @returns sfnt bytes copied so a Worker transfer cannot detach the retained cache entry.
|
|
662
|
+
*/
|
|
663
|
+
async read(id) {
|
|
664
|
+
const selected = this.selected.get(id);
|
|
665
|
+
if (selected === void 0) throw new Error("The font identity was not selected by this source.");
|
|
666
|
+
unchanged(selected.face);
|
|
667
|
+
let bytes = this.cached.get(selected.key);
|
|
668
|
+
if (bytes === void 0) {
|
|
669
|
+
bytes = (await this.generate(selected.face, selected.script, selected.sourceHash)).bytes;
|
|
670
|
+
if (`${selected.script === "full" ? "full_" : ""}${hash(bytes)}` !== id) throw new Error("The font subset identity changed during regeneration.");
|
|
671
|
+
}
|
|
672
|
+
this.retain(selected.key, bytes);
|
|
673
|
+
return Uint8Array.from(bytes);
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
//#endregion
|
|
677
|
+
//#region lib/types/font-worker.js
|
|
678
|
+
/** Serialized font matching and portable HarfBuzz subsetting on a private Node Worker. */
|
|
679
|
+
if (parentPort === null) throw new Error("The font service requires a Worker parent.");
|
|
680
|
+
const port = parentPort;
|
|
681
|
+
const source = new FontSubsetSource(workerData);
|
|
682
|
+
let queue = Promise.resolve();
|
|
683
|
+
port.on("message", (command) => {
|
|
684
|
+
if (!Number.isSafeInteger(command?.id) || command.kind !== "resolve" && command.kind !== "read") throw new Error("The font Worker received an invalid operation.");
|
|
685
|
+
queue = queue.then(async () => {
|
|
686
|
+
try {
|
|
687
|
+
if (command.kind === "resolve") {
|
|
688
|
+
const value = await source.resolve(command.request);
|
|
689
|
+
port.postMessage({
|
|
690
|
+
id: command.id,
|
|
691
|
+
kind: "resolved",
|
|
692
|
+
value
|
|
693
|
+
});
|
|
694
|
+
} else {
|
|
695
|
+
const value = await source.read(command.asset);
|
|
696
|
+
port.postMessage({
|
|
697
|
+
id: command.id,
|
|
698
|
+
kind: "bytes",
|
|
699
|
+
value
|
|
700
|
+
}, [value.buffer]);
|
|
701
|
+
}
|
|
702
|
+
} catch (error) {
|
|
703
|
+
port.postMessage({
|
|
704
|
+
id: command.id,
|
|
705
|
+
kind: "failed",
|
|
706
|
+
message: error instanceof Error ? error.message : String(error)
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
});
|
|
710
|
+
});
|
|
711
|
+
//#endregion
|
|
712
|
+
export {};
|