@openartifactsai/export-kit 0.0.0-stage → 0.23.0-rc.0

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.
@@ -0,0 +1,65 @@
1
+ /**
2
+ * A TrueType font cut down to the glyphs a document can draw, for inlining
3
+ * into pictures of it.
4
+ *
5
+ * The browser parses an inlined font again for every picture, about 30 ms of
6
+ * main thread a megabyte, and a CJK font runs to tens of megabytes, almost
7
+ * all of it ideographs and Hangul syllables the document never shows.
8
+ * {@link subsetFont} drops the outlines of those glyphs and nothing else:
9
+ *
10
+ * - only code points in the bulk ranges ({@link isBulkCodePoint}) ever lose
11
+ * their glyphs. Latin, kana, punctuation, symbols and private use stay, so
12
+ * the characters CSS makes up on its own (`text-transform`, hyphens,
13
+ * ellipses, quotes, list markers) never need to be known; only counter
14
+ * styles make ideographs, and {@link COUNTER_IDEOGRAPHS} keeps those;
15
+ * - the shaper normalizes text before it looks glyphs up: conjoining jamo
16
+ * become Hangul syllables, a compatibility ideograph the font lacks
17
+ * becomes its unified ideograph, a syllable the font lacks may be drawn as
18
+ * a shorter one plus a jamo. {@link addBulkCodePoints} counts those forms
19
+ * as used too, or they would be drawn blank;
20
+ * - glyph ids are kept. Only `glyf` and `loca` are written again (a dropped
21
+ * glyph becomes an empty one); `cmap`, `GSUB`, `GPOS`, metrics and every
22
+ * other table are copied byte for byte, so shaping and layout are those
23
+ * of the whole font;
24
+ * - every glyph that GSUB (any lookup, any feature, any context) or a
25
+ * composite glyph can reach from a kept glyph is kept as well. A glyph
26
+ * cmap does not map is decided by that reach when GSUB or a composite
27
+ * leads to it (the regional and alternate forms of ideographs, most of
28
+ * what is left of a big CJK font), and kept when nothing does.
29
+ *
30
+ * A dropped glyph that is drawn anyway would be blank, so whatever is not
31
+ * fully understood is left whole: CFF outlines, variable fonts (`gvar`),
32
+ * AAT fonts (`morx`), color and math fonts, collections, WOFF and WOFF2
33
+ * files, unknown cmap or GSUB formats, anything malformed.
34
+ *
35
+ * Pure: no DOM, loads in `node --test`.
36
+ */
37
+ /** Code points whose glyphs a subset may drop when the document does not use them. */
38
+ export declare function isBulkCodePoint(codePoint: number): boolean;
39
+ /**
40
+ * Adds to `into` the bulk code points `text` may be drawn with: its own, those
41
+ * of its NFC form (decomposed Hangul composes to syllables, compatibility
42
+ * ideographs decompose to unified ones; the shaper does the same before it
43
+ * looks glyphs up), and for each Hangul syllable with a trailing consonant
44
+ * the syllable without it (drawn with a trailing jamo when the font lacks
45
+ * the whole syllable).
46
+ */
47
+ export declare function addBulkCodePoints(text: string, into: Set<number>): void;
48
+ /**
49
+ * Ideographs list counters generate (`list-style-type: cjk-ideographic` …):
50
+ * never in the DOM text, always kept. Every Han and Hangul character of the
51
+ * CSS counter styles cjk-decimal, cjk-ideographic, simp-/trad-chinese-
52
+ * informal and formal, japanese-informal and formal, korean-hangul-formal,
53
+ * korean-hanja-informal and formal, cjk-heavenly-stem and cjk-earthly-branch,
54
+ * their negative signs, and the large-number words around them.
55
+ */
56
+ export declare const COUNTER_IDEOGRAPHS: string;
57
+ /** Options of {@link subsetFont}. */
58
+ export interface SubsetOptions {
59
+ /** Fewest glyphs mapped only from bulk code points for a subset to be worth it (default 512). */
60
+ minBulkGlyphs?: number;
61
+ /** Least share of the file the dropped outlines must make up (default 0.2). */
62
+ minSaving?: number;
63
+ }
64
+ /** The font with the outlines of unused bulk glyphs removed, or null when it is left whole. */
65
+ export declare function subsetFont(font: Uint8Array, used: ReadonlySet<number>, options?: SubsetOptions): Uint8Array<ArrayBuffer> | null;
@@ -0,0 +1,627 @@
1
+ /**
2
+ * A TrueType font cut down to the glyphs a document can draw, for inlining
3
+ * into pictures of it.
4
+ *
5
+ * The browser parses an inlined font again for every picture, about 30 ms of
6
+ * main thread a megabyte, and a CJK font runs to tens of megabytes, almost
7
+ * all of it ideographs and Hangul syllables the document never shows.
8
+ * {@link subsetFont} drops the outlines of those glyphs and nothing else:
9
+ *
10
+ * - only code points in the bulk ranges ({@link isBulkCodePoint}) ever lose
11
+ * their glyphs. Latin, kana, punctuation, symbols and private use stay, so
12
+ * the characters CSS makes up on its own (`text-transform`, hyphens,
13
+ * ellipses, quotes, list markers) never need to be known; only counter
14
+ * styles make ideographs, and {@link COUNTER_IDEOGRAPHS} keeps those;
15
+ * - the shaper normalizes text before it looks glyphs up: conjoining jamo
16
+ * become Hangul syllables, a compatibility ideograph the font lacks
17
+ * becomes its unified ideograph, a syllable the font lacks may be drawn as
18
+ * a shorter one plus a jamo. {@link addBulkCodePoints} counts those forms
19
+ * as used too, or they would be drawn blank;
20
+ * - glyph ids are kept. Only `glyf` and `loca` are written again (a dropped
21
+ * glyph becomes an empty one); `cmap`, `GSUB`, `GPOS`, metrics and every
22
+ * other table are copied byte for byte, so shaping and layout are those
23
+ * of the whole font;
24
+ * - every glyph that GSUB (any lookup, any feature, any context) or a
25
+ * composite glyph can reach from a kept glyph is kept as well. A glyph
26
+ * cmap does not map is decided by that reach when GSUB or a composite
27
+ * leads to it (the regional and alternate forms of ideographs, most of
28
+ * what is left of a big CJK font), and kept when nothing does.
29
+ *
30
+ * A dropped glyph that is drawn anyway would be blank, so whatever is not
31
+ * fully understood is left whole: CFF outlines, variable fonts (`gvar`),
32
+ * AAT fonts (`morx`), color and math fonts, collections, WOFF and WOFF2
33
+ * files, unknown cmap or GSUB formats, anything malformed.
34
+ *
35
+ * Pure: no DOM, loads in `node --test`.
36
+ */
37
+ /** Code points whose glyphs a subset may drop when the document does not use them. */
38
+ export function isBulkCodePoint(codePoint) {
39
+ if (codePoint < 0x3400)
40
+ return false;
41
+ if (codePoint < 0xac00)
42
+ return codePoint <= 0x4dbf || (codePoint >= 0x4e00 && codePoint <= 0x9fff);
43
+ if (codePoint < 0x10000)
44
+ return codePoint <= 0xd7a3 || (codePoint >= 0xf900 && codePoint <= 0xfaff);
45
+ return (codePoint >= 0x20000 && codePoint <= 0x323af) || (codePoint >= 0x2f800 && codePoint <= 0x2fa1f);
46
+ }
47
+ /**
48
+ * Adds to `into` the bulk code points `text` may be drawn with: its own, those
49
+ * of its NFC form (decomposed Hangul composes to syllables, compatibility
50
+ * ideographs decompose to unified ones; the shaper does the same before it
51
+ * looks glyphs up), and for each Hangul syllable with a trailing consonant
52
+ * the syllable without it (drawn with a trailing jamo when the font lacks
53
+ * the whole syllable).
54
+ */
55
+ export function addBulkCodePoints(text, into) {
56
+ // Nothing below U+1100 (Hangul jamo) normalizes into a bulk code point: plain text is read once and never normalized.
57
+ if (addOwn(text, into)) {
58
+ const normalized = text.normalize('NFC');
59
+ if (normalized !== text)
60
+ addOwn(normalized, into);
61
+ }
62
+ }
63
+ /** Adds the bulk code points of `text` (and the LV syllable of each LVT one); true when it holds anything from U+1100 on. */
64
+ function addOwn(text, into) {
65
+ let high = false;
66
+ for (let i = 0; i < text.length; i++) {
67
+ const unit = text.charCodeAt(i);
68
+ if (unit < 0x1100)
69
+ continue;
70
+ high = true;
71
+ if (unit < 0x3400)
72
+ continue;
73
+ let point = unit;
74
+ if (unit >= 0xd800 && unit <= 0xdbff && i + 1 < text.length) {
75
+ const low = text.charCodeAt(i + 1);
76
+ if (low >= 0xdc00 && low <= 0xdfff) {
77
+ point = (unit - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000;
78
+ i++;
79
+ }
80
+ }
81
+ if (!isBulkCodePoint(point))
82
+ continue;
83
+ into.add(point);
84
+ if (point >= 0xac00 && point <= 0xd7a3) {
85
+ const trailing = (point - 0xac00) % 28;
86
+ if (trailing)
87
+ into.add(point - trailing);
88
+ }
89
+ }
90
+ return high;
91
+ }
92
+ /**
93
+ * Ideographs list counters generate (`list-style-type: cjk-ideographic` …):
94
+ * never in the DOM text, always kept. Every Han and Hangul character of the
95
+ * CSS counter styles cjk-decimal, cjk-ideographic, simp-/trad-chinese-
96
+ * informal and formal, japanese-informal and formal, korean-hangul-formal,
97
+ * korean-hanja-informal and formal, cjk-heavenly-stem and cjk-earthly-branch,
98
+ * their negative signs, and the large-number words around them.
99
+ */
100
+ export const COUNTER_IDEOGRAPHS = '〇零一二三四五六七八九十百千万萬億亿兆负負' +
101
+ '壹贰叁肆伍陆柒捌玖拾佰仟' +
102
+ '貳參陸' +
103
+ '壱弐参阡' +
104
+ '영일이삼사오육칠팔구십백천만억조마이너스' +
105
+ '甲乙丙丁戊己庚辛壬癸' +
106
+ '子丑寅卯辰巳午未申酉戌亥';
107
+ /** Tables whose reach over glyphs is not followed: a font with one is left whole. */
108
+ const UNFOLLOWED = new Set(['morx', 'mort', 'gvar', 'CFF ', 'CFF2', 'COLR', 'MATH']);
109
+ /** Per-glyph facts, as bits of one byte. */
110
+ const BULK = 1;
111
+ const OTHER = 2;
112
+ const USED = 4;
113
+ const KEEP = 8;
114
+ /** Made by some GSUB lookup, or a component of a composite glyph. */
115
+ const REACHED = 16;
116
+ /** Thrown on anything out of bounds or not understood; turned into null by {@link subsetFont}. */
117
+ class Unfit extends Error {
118
+ }
119
+ class Reader {
120
+ view;
121
+ length;
122
+ bytes;
123
+ constructor(bytes) {
124
+ this.bytes = bytes;
125
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
126
+ this.length = bytes.byteLength;
127
+ }
128
+ check(offset, size) {
129
+ if (!(offset >= 0 && offset + size <= this.length))
130
+ throw new Unfit('out of bounds');
131
+ }
132
+ u16(offset) {
133
+ this.check(offset, 2);
134
+ return this.view.getUint16(offset);
135
+ }
136
+ i16(offset) {
137
+ this.check(offset, 2);
138
+ return this.view.getInt16(offset);
139
+ }
140
+ u24(offset) {
141
+ this.check(offset, 3);
142
+ return (this.view.getUint16(offset) << 8) | this.view.getUint8(offset + 2);
143
+ }
144
+ u32(offset) {
145
+ this.check(offset, 4);
146
+ return this.view.getUint32(offset);
147
+ }
148
+ tag(offset) {
149
+ this.check(offset, 4);
150
+ return String.fromCharCode(this.bytes[offset], this.bytes[offset + 1], this.bytes[offset + 2], this.bytes[offset + 3]);
151
+ }
152
+ }
153
+ /** The font with the outlines of unused bulk glyphs removed, or null when it is left whole. */
154
+ export function subsetFont(font, used, options = {}) {
155
+ try {
156
+ return subset(new Reader(font), used, options.minBulkGlyphs ?? 512, options.minSaving ?? 0.2);
157
+ }
158
+ catch {
159
+ return null;
160
+ }
161
+ }
162
+ function subset(r, used, minBulkGlyphs, minSaving) {
163
+ const version = r.u32(0);
164
+ if (version !== 0x00010000 && version !== 0x74727565)
165
+ return null;
166
+ const count = r.u16(4);
167
+ const tables = new Map();
168
+ for (let i = 0; i < count; i++) {
169
+ const at = 12 + i * 16;
170
+ const table = { tag: r.tag(at), offset: r.u32(at + 8), length: r.u32(at + 12) };
171
+ r.check(table.offset, table.length);
172
+ if (tables.has(table.tag))
173
+ return null;
174
+ tables.set(table.tag, table);
175
+ }
176
+ for (const tag of UNFOLLOWED)
177
+ if (tables.has(tag))
178
+ return null;
179
+ const head = tables.get('head');
180
+ const maxp = tables.get('maxp');
181
+ const loca = tables.get('loca');
182
+ const glyf = tables.get('glyf');
183
+ const cmap = tables.get('cmap');
184
+ if (!head || !maxp || !loca || !glyf || !cmap)
185
+ return null;
186
+ if (head.length < 54 || maxp.length < 6)
187
+ return null;
188
+ const longOffsets = r.i16(head.offset + 50);
189
+ if (longOffsets !== 0 && longOffsets !== 1)
190
+ return null;
191
+ const glyphs = r.u16(maxp.offset + 4);
192
+ if (!glyphs)
193
+ return null;
194
+ // Where each glyph's outline lies within glyf.
195
+ if (loca.length < (glyphs + 1) * (longOffsets ? 4 : 2))
196
+ return null;
197
+ const starts = new Uint32Array(glyphs + 1);
198
+ for (let g = 0; g <= glyphs; g++) {
199
+ const at = longOffsets ? r.u32(loca.offset + g * 4) : r.u16(loca.offset + g * 2) * 2;
200
+ if (at > glyf.length || (g && at < starts[g - 1]))
201
+ return null;
202
+ starts[g] = at;
203
+ }
204
+ const flags = new Uint8Array(glyphs);
205
+ readCmap(r, cmap, flags, used);
206
+ // Every glyph a substitution or a composite glyph can lead to; the closures below decide those that cmap does not map.
207
+ const gsub = tables.get('GSUB');
208
+ const rules = gsub ? readGsub(r, gsub, flags) : null;
209
+ const parts = readComposites(r, glyf.offset, starts, flags);
210
+ // Kept to begin with: .notdef, every glyph cmap maps from a non-bulk code point, bulk glyphs in use, and unmapped
211
+ // glyphs nothing followed here leads to (only some way not followed could draw them).
212
+ let bulkOnly = 0;
213
+ flags[0] |= KEEP;
214
+ for (let g = 0; g < glyphs; g++) {
215
+ const f = flags[g];
216
+ if (f & OTHER || f & USED || (!(f & BULK) && !(f & REACHED)))
217
+ flags[g] = f | KEEP;
218
+ if (f & BULK && !(f & OTHER))
219
+ bulkOnly++;
220
+ }
221
+ if (bulkOnly < minBulkGlyphs)
222
+ return null;
223
+ if (rules)
224
+ closeOverGsub(rules, flags);
225
+ closeOverComposites(parts, flags);
226
+ let kept = 0;
227
+ for (let g = 0; g < glyphs; g++)
228
+ if (flags[g] & KEEP)
229
+ kept += starts[g + 1] - starts[g];
230
+ const dropped = starts[glyphs] - kept;
231
+ if (dropped <= 0 || dropped < minSaving * r.length)
232
+ return null;
233
+ // The new glyf and loca: kept outlines in glyph order, dropped ones empty.
234
+ const newGlyf = new Uint8Array(kept);
235
+ const newLoca = new Uint8Array((glyphs + 1) * (longOffsets ? 4 : 2));
236
+ const locaView = new DataView(newLoca.buffer);
237
+ let at = 0;
238
+ for (let g = 0; g <= glyphs; g++) {
239
+ if (longOffsets)
240
+ locaView.setUint32(g * 4, at);
241
+ else
242
+ locaView.setUint16(g * 2, at / 2);
243
+ if (g === glyphs || !(flags[g] & KEEP))
244
+ continue;
245
+ const from = glyf.offset + starts[g];
246
+ const size = starts[g + 1] - starts[g];
247
+ newGlyf.set(r.bytes.subarray(from, from + size), at);
248
+ at += size;
249
+ }
250
+ return writeFont(r, version, [...tables.values()], new Map([['glyf', newGlyf], ['loca', newLoca]]));
251
+ }
252
+ /** Marks each glyph mapped from a bulk, a non-bulk and a used code point; keeps the variation glyphs of used ones. */
253
+ function readCmap(r, cmap, flags, used) {
254
+ const base = cmap.offset;
255
+ const glyphs = flags.length;
256
+ const map = (codePoint, glyph) => {
257
+ if (glyph <= 0 || glyph >= glyphs)
258
+ return;
259
+ if (!isBulkCodePoint(codePoint))
260
+ flags[glyph] |= OTHER;
261
+ else
262
+ flags[glyph] |= used.has(codePoint) ? BULK | USED : BULK;
263
+ };
264
+ const read = new Set();
265
+ const subtables = r.u16(base + 2);
266
+ for (let i = 0; i < subtables; i++) {
267
+ const platform = r.u16(base + 4 + i * 8);
268
+ const encoding = r.u16(base + 6 + i * 8);
269
+ if (!(platform === 0 || (platform === 3 && (encoding === 1 || encoding === 10))))
270
+ continue;
271
+ const at = base + r.u32(base + 8 + i * 8);
272
+ if (at + 2 > base + cmap.length)
273
+ throw new Unfit('cmap subtable');
274
+ // Subtables may share their data.
275
+ if (read.has(at))
276
+ continue;
277
+ read.add(at);
278
+ const format = r.u16(at);
279
+ if (format === 4) {
280
+ const segments = r.u16(at + 6) / 2;
281
+ const ends = at + 14;
282
+ const startCodes = ends + segments * 2 + 2;
283
+ const deltas = startCodes + segments * 2;
284
+ const rangeOffsets = deltas + segments * 2;
285
+ for (let s = 0; s < segments; s++) {
286
+ const end = r.u16(ends + s * 2);
287
+ const start = r.u16(startCodes + s * 2);
288
+ const delta = r.u16(deltas + s * 2);
289
+ const rangeOffset = r.u16(rangeOffsets + s * 2);
290
+ if (start > end)
291
+ throw new Unfit('cmap segment');
292
+ for (let c = start; c <= end && c !== 0xffff; c++) {
293
+ if (!rangeOffset)
294
+ map(c, (c + delta) & 0xffff);
295
+ else {
296
+ const glyph = r.u16(rangeOffsets + s * 2 + rangeOffset + (c - start) * 2);
297
+ if (glyph)
298
+ map(c, (glyph + delta) & 0xffff);
299
+ }
300
+ }
301
+ }
302
+ }
303
+ else if (format === 6) {
304
+ const first = r.u16(at + 6);
305
+ const entries = r.u16(at + 8);
306
+ for (let e = 0; e < entries; e++)
307
+ map(first + e, r.u16(at + 10 + e * 2));
308
+ }
309
+ else if (format === 12) {
310
+ const groups = r.u32(at + 12);
311
+ r.check(at + 16, groups * 12);
312
+ for (let n = 0; n < groups; n++) {
313
+ const start = r.u32(at + 16 + n * 12);
314
+ const end = r.u32(at + 20 + n * 12);
315
+ const glyph = r.u32(at + 24 + n * 12);
316
+ if (start > end || end > 0x10ffff)
317
+ throw new Unfit('cmap group');
318
+ for (let c = start; c <= end; c++)
319
+ map(c, glyph + c - start);
320
+ }
321
+ }
322
+ else if (format === 14) {
323
+ const records = r.u32(at + 6);
324
+ r.check(at + 10, records * 11);
325
+ for (let n = 0; n < records; n++) {
326
+ const nonDefault = r.u32(at + 10 + n * 11 + 7);
327
+ if (!nonDefault)
328
+ continue;
329
+ const list = at + nonDefault;
330
+ const mappings = r.u32(list);
331
+ r.check(list + 4, mappings * 5);
332
+ for (let m = 0; m < mappings; m++) {
333
+ const codePoint = r.u24(list + 4 + m * 5);
334
+ const glyph = r.u16(list + 7 + m * 5);
335
+ // Non-bulk bases are always taken as used.
336
+ if (glyph < glyphs && (!isBulkCodePoint(codePoint) || used.has(codePoint)))
337
+ flags[glyph] |= KEEP;
338
+ }
339
+ }
340
+ }
341
+ else
342
+ throw new Unfit(`cmap format ${format}`);
343
+ }
344
+ }
345
+ /** Glyph ids of a coverage table, in coverage index order. */
346
+ function coverage(r, at) {
347
+ const format = r.u16(at);
348
+ const out = [];
349
+ if (format === 1) {
350
+ const count = r.u16(at + 2);
351
+ r.check(at + 4, count * 2);
352
+ for (let i = 0; i < count; i++)
353
+ out.push(r.u16(at + 4 + i * 2));
354
+ }
355
+ else if (format === 2) {
356
+ const ranges = r.u16(at + 2);
357
+ r.check(at + 4, ranges * 6);
358
+ for (let i = 0; i < ranges; i++) {
359
+ const start = r.u16(at + 4 + i * 6);
360
+ const end = r.u16(at + 6 + i * 6);
361
+ const index = r.u16(at + 8 + i * 6);
362
+ if (start > end)
363
+ throw new Unfit('coverage range');
364
+ for (let g = start; g <= end; g++)
365
+ out[index + g - start] = g;
366
+ }
367
+ for (let i = 0; i < out.length; i++)
368
+ if (out[i] === undefined)
369
+ throw new Unfit('coverage index');
370
+ }
371
+ else
372
+ throw new Unfit(`coverage format ${format}`);
373
+ return out;
374
+ }
375
+ /**
376
+ * Every substitution of every GSUB lookup, whatever its feature, script or
377
+ * context: a superset of what shaping can produce. Marks what they make as
378
+ * reached.
379
+ */
380
+ function readGsub(r, gsub, flags) {
381
+ const from = [];
382
+ const to = [];
383
+ const ligatures = [];
384
+ const rules = { from, to, ligatures };
385
+ const base = gsub.offset;
386
+ if (r.u16(base) !== 1)
387
+ throw new Unfit('GSUB version');
388
+ if (!r.u16(base + 8))
389
+ return rules;
390
+ const lookupList = base + r.u16(base + 8);
391
+ const pairs = (input, outputs) => {
392
+ input.forEach((glyph, index) => {
393
+ for (const out of outputs(index)) {
394
+ from.push(glyph);
395
+ to.push(out);
396
+ }
397
+ });
398
+ };
399
+ const glyphList = (at) => {
400
+ const count = r.u16(at);
401
+ r.check(at + 2, count * 2);
402
+ return Array.from({ length: count }, (_, i) => r.u16(at + 2 + i * 2));
403
+ };
404
+ const subtable = (type, at, extended) => {
405
+ const format = r.u16(at);
406
+ switch (type) {
407
+ case 1: {
408
+ const covered = coverage(r, at + r.u16(at + 2));
409
+ if (format === 1) {
410
+ const delta = r.u16(at + 4);
411
+ pairs(covered, (i) => [(covered[i] + delta) & 0xffff]);
412
+ }
413
+ else if (format === 2) {
414
+ const substitutes = glyphList(at + 4);
415
+ if (substitutes.length !== covered.length)
416
+ throw new Unfit('single substitution');
417
+ pairs(covered, (i) => [substitutes[i]]);
418
+ }
419
+ else
420
+ throw new Unfit('single format');
421
+ return;
422
+ }
423
+ case 2:
424
+ case 3: {
425
+ if (format !== 1)
426
+ throw new Unfit('multiple format');
427
+ const covered = coverage(r, at + r.u16(at + 2));
428
+ const sets = r.u16(at + 4);
429
+ if (sets !== covered.length)
430
+ throw new Unfit('multiple count');
431
+ pairs(covered, (i) => glyphList(at + r.u16(at + 6 + i * 2)));
432
+ return;
433
+ }
434
+ case 4: {
435
+ if (format !== 1)
436
+ throw new Unfit('ligature format');
437
+ const covered = coverage(r, at + r.u16(at + 2));
438
+ const sets = r.u16(at + 4);
439
+ if (sets !== covered.length)
440
+ throw new Unfit('ligature count');
441
+ for (let i = 0; i < sets; i++) {
442
+ const set = at + r.u16(at + 6 + i * 2);
443
+ const count = r.u16(set);
444
+ for (let l = 0; l < count; l++) {
445
+ const ligature = set + r.u16(set + 2 + l * 2);
446
+ const glyph = r.u16(ligature);
447
+ const components = r.u16(ligature + 2);
448
+ if (!components)
449
+ throw new Unfit('ligature components');
450
+ const parts = [covered[i]];
451
+ for (let c = 1; c < components; c++)
452
+ parts.push(r.u16(ligature + 2 + c * 2));
453
+ ligatures.push({ glyph, parts });
454
+ }
455
+ }
456
+ return;
457
+ }
458
+ case 5:
459
+ case 6:
460
+ // The lookups they call are followed on their own, unconditionally.
461
+ if (format < 1 || format > 3)
462
+ throw new Unfit('context format');
463
+ return;
464
+ case 7: {
465
+ if (format !== 1 || extended)
466
+ throw new Unfit('extension');
467
+ const inner = r.u16(at + 2);
468
+ if (inner === 7)
469
+ throw new Unfit('nested extension');
470
+ subtable(inner, at + r.u32(at + 4), true);
471
+ return;
472
+ }
473
+ case 8: {
474
+ if (format !== 1)
475
+ throw new Unfit('reverse chaining format');
476
+ const covered = coverage(r, at + r.u16(at + 2));
477
+ const backtrack = r.u16(at + 4);
478
+ const lookahead = r.u16(at + 6 + backtrack * 2);
479
+ const substitutes = glyphList(at + 8 + (backtrack + lookahead) * 2);
480
+ if (substitutes.length !== covered.length)
481
+ throw new Unfit('reverse chaining count');
482
+ pairs(covered, (i) => [substitutes[i]]);
483
+ return;
484
+ }
485
+ default:
486
+ throw new Unfit(`GSUB lookup type ${type}`);
487
+ }
488
+ };
489
+ const lookups = r.u16(lookupList);
490
+ for (let l = 0; l < lookups; l++) {
491
+ const lookup = lookupList + r.u16(lookupList + 2 + l * 2);
492
+ const type = r.u16(lookup);
493
+ const count = r.u16(lookup + 4);
494
+ for (let s = 0; s < count; s++)
495
+ subtable(type, lookup + r.u16(lookup + 6 + s * 2), false);
496
+ }
497
+ const glyphs = flags.length;
498
+ for (const glyph of to)
499
+ if (glyph < glyphs)
500
+ flags[glyph] |= REACHED;
501
+ for (const { glyph } of ligatures)
502
+ if (glyph < glyphs)
503
+ flags[glyph] |= REACHED;
504
+ return rules;
505
+ }
506
+ /** Keeps every glyph GSUB can make from kept glyphs, until a pass adds none. */
507
+ function closeOverGsub({ from, to, ligatures }, flags) {
508
+ const glyphs = flags.length;
509
+ const keptGlyph = (glyph) => glyph < glyphs && (flags[glyph] & KEEP) !== 0;
510
+ for (let changed = true; changed;) {
511
+ changed = false;
512
+ for (let i = 0; i < from.length; i++) {
513
+ const out = to[i];
514
+ if (out < glyphs && !(flags[out] & KEEP) && keptGlyph(from[i])) {
515
+ flags[out] |= KEEP;
516
+ changed = true;
517
+ }
518
+ }
519
+ for (const { glyph, parts } of ligatures) {
520
+ if (glyph < glyphs && !(flags[glyph] & KEEP) && parts.every(keptGlyph)) {
521
+ flags[glyph] |= KEEP;
522
+ changed = true;
523
+ }
524
+ }
525
+ }
526
+ }
527
+ /** The components of every composite glyph (glyph g's are `list[first[g]]` up to `list[first[g + 1]]`), marked as reached. */
528
+ function readComposites(r, glyf, starts, flags) {
529
+ const glyphs = flags.length;
530
+ const first = new Uint32Array(glyphs + 1);
531
+ const list = [];
532
+ for (let g = 0; g < glyphs; g++) {
533
+ first[g] = list.length;
534
+ const start = starts[g];
535
+ const end = starts[g + 1];
536
+ if (end === start)
537
+ continue;
538
+ if (end - start < 10)
539
+ throw new Unfit('glyph header');
540
+ if (r.i16(glyf + start) >= 0)
541
+ continue;
542
+ let at = glyf + start + 10;
543
+ for (let more = true; more;) {
544
+ if (at + 4 > glyf + end)
545
+ throw new Unfit('composite glyph');
546
+ const flag = r.u16(at);
547
+ const component = r.u16(at + 2);
548
+ at += 4 + (flag & 0x1 ? 4 : 2) + (flag & 0x8 ? 2 : flag & 0x40 ? 4 : flag & 0x80 ? 8 : 0);
549
+ if (component >= glyphs)
550
+ throw new Unfit('composite component');
551
+ flags[component] |= REACHED;
552
+ list.push(component);
553
+ more = (flag & 0x20) !== 0;
554
+ }
555
+ }
556
+ first[glyphs] = list.length;
557
+ return { first, list };
558
+ }
559
+ /** Keeps the components of every kept composite glyph, and theirs. */
560
+ function closeOverComposites({ first, list }, flags) {
561
+ const work = [];
562
+ for (let g = 0; g < flags.length; g++)
563
+ if (flags[g] & KEEP && first[g + 1] > first[g])
564
+ work.push(g);
565
+ while (work.length) {
566
+ const g = work.pop();
567
+ for (let i = first[g]; i < first[g + 1]; i++) {
568
+ const component = list[i];
569
+ if (!(flags[component] & KEEP)) {
570
+ flags[component] |= KEEP;
571
+ work.push(component);
572
+ }
573
+ }
574
+ }
575
+ }
576
+ function checksum(bytes, offset, length) {
577
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
578
+ let sum = 0;
579
+ const whole = length & ~3;
580
+ for (let i = 0; i < whole; i += 4)
581
+ sum = (sum + view.getUint32(offset + i)) >>> 0;
582
+ if (whole < length) {
583
+ let last = 0;
584
+ for (let i = 0; i < 4; i++)
585
+ last = (last << 8) | (whole + i < length ? bytes[offset + whole + i] : 0);
586
+ sum = (sum + (last >>> 0)) >>> 0;
587
+ }
588
+ return sum;
589
+ }
590
+ /** A new sfnt: tables in tag order, each on a 4-byte boundary, checksums and `head.checkSumAdjustment` worked out again. */
591
+ function writeFont(r, version, tables, replaced) {
592
+ const sorted = tables
593
+ .map((table) => ({ tag: table.tag, data: replaced.get(table.tag) ?? r.bytes.subarray(table.offset, table.offset + table.length) }))
594
+ .sort((a, b) => (a.tag < b.tag ? -1 : a.tag > b.tag ? 1 : 0));
595
+ const count = sorted.length;
596
+ let size = 12 + count * 16;
597
+ const offsets = sorted.map((table) => {
598
+ const at = size;
599
+ size += (table.data.length + 3) & ~3;
600
+ return at;
601
+ });
602
+ const out = new Uint8Array(size);
603
+ const view = new DataView(out.buffer);
604
+ const selector = Math.floor(Math.log2(count));
605
+ view.setUint32(0, version);
606
+ view.setUint16(4, count);
607
+ view.setUint16(6, 16 << selector);
608
+ view.setUint16(8, selector);
609
+ view.setUint16(10, count * 16 - (16 << selector));
610
+ let headAt = -1;
611
+ sorted.forEach((table, i) => {
612
+ const at = offsets[i];
613
+ out.set(table.data, at);
614
+ if (table.tag === 'head') {
615
+ headAt = at;
616
+ view.setUint32(at + 8, 0);
617
+ }
618
+ const entry = 12 + i * 16;
619
+ for (let c = 0; c < 4; c++)
620
+ out[entry + c] = table.tag.charCodeAt(c);
621
+ view.setUint32(entry + 4, checksum(out, at, table.data.length));
622
+ view.setUint32(entry + 8, at);
623
+ view.setUint32(entry + 12, table.data.length);
624
+ });
625
+ view.setUint32(headAt + 8, (0xb1b0afba - checksum(out, 0, size)) >>> 0);
626
+ return out;
627
+ }