@mark1russell7/typeset 0.1.3 → 0.1.5

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.
@@ -291,26 +291,41 @@ function scriptTags(script) {
291
291
  /** The GPOS features with pair lookups that HarfBuzz applies to horizontal text. */
292
292
  const pairFeatures = /* @__PURE__ */ new Set(["kern", "dist"]);
293
293
  /** The lookup flag that selects a mark filtering set of GDEF. */
294
- const USE_MARK_FILTERING_SET$1 = 16;
295
- /**
296
- * This function gives the pair lookups of the features `kern` and `dist` of GPOS for a script, in the order of the lookup
297
- * list. The store gives the deltas of a variable font at its instance. The filter gives the mark filtering sets of GDEF.
298
- */
299
- function readGposKerning(gpos, script, store, filter) {
300
- const scripts = gpos.part(gpos.u16(4));
301
- const features = gpos.part(gpos.u16(6));
302
- const lookups = gpos.part(gpos.u16(8));
303
- const scriptCount = scripts.u16(0);
304
- let langSys;
305
- for (const wanted of scriptTags(script)) {
306
- for (let i = 0; i < scriptCount && langSys === void 0; i++) {
307
- if (scripts.tag(2 + i * 6) !== wanted) continue;
308
- const table = scripts.part(scripts.u16(2 + i * 6 + 4));
309
- const fallback = table.u16(0);
310
- if (fallback !== 0) langSys = table.part(fallback);
311
- }
312
- if (langSys !== void 0) break;
294
+ const USE_MARK_FILTERING_SET = 16;
295
+ /** This function gives the test of the glyphs that a lookup skips. */
296
+ function lookupSkip(lookup, flags, filter) {
297
+ const markSet = (flags & USE_MARK_FILTERING_SET) !== 0 ? lookup.u16(6 + lookup.u16(4) * 2) : -1;
298
+ return (glyph) => {
299
+ const kind = filter.glyphClass(glyph);
300
+ if ((flags & 2) !== 0 && kind === 1) return true;
301
+ if ((flags & 4) !== 0 && kind === 2) return true;
302
+ if (kind !== 3) return false;
303
+ if ((flags & 8) !== 0) return true;
304
+ if (markSet >= 0) return !filter.inMarkSet(markSet, glyph);
305
+ const attach = flags >> 8;
306
+ return attach !== 0 && filter.markAttachClass(glyph) !== attach;
307
+ };
308
+ }
309
+ /** This function gives the subtables of a lookup with their types, after each extension of the type `extension`. */
310
+ function subtablesOf(lookup, extension) {
311
+ return Array.from({ length: lookup.u16(4) }, (_, s) => {
312
+ const subtable = lookup.part(lookup.u16(6 + s * 2));
313
+ return lookup.u16(0) === extension ? [subtable.u16(2), subtable.part(subtable.u32(4))] : [lookup.u16(0), subtable];
314
+ });
315
+ }
316
+ /** This function gives the default language system of a table for a script. */
317
+ function languageSystem(table, script) {
318
+ const scripts = table.part(table.u16(4));
319
+ for (const wanted of scriptTags(script)) for (let i = 0; i < scripts.u16(0); i++) {
320
+ if (scripts.tag(2 + i * 6) !== wanted) continue;
321
+ const entry = scripts.part(scripts.u16(2 + i * 6 + 4));
322
+ if (entry.u16(0) !== 0) return entry.part(entry.u16(0));
313
323
  }
324
+ }
325
+ /** This function gives the indices of the lookups of `kern` and `dist` for a script, in the order of the lookup list. */
326
+ function pairLookupIndices(gpos, script) {
327
+ const features = gpos.part(gpos.u16(6));
328
+ const langSys = languageSystem(gpos, script);
314
329
  if (langSys === void 0) return [];
315
330
  const indices = /* @__PURE__ */ new Set();
316
331
  const featureCount = langSys.u16(4);
@@ -320,29 +335,21 @@ function readGposKerning(gpos, script, store, filter) {
320
335
  const feature = features.part(features.u16(record + 4));
321
336
  for (let k = 0; k < feature.u16(2); k++) indices.add(feature.u16(4 + k * 2));
322
337
  }
323
- return [...indices].sort((a, b) => a - b).flatMap((index) => {
338
+ return [...indices].sort((a, b) => a - b);
339
+ }
340
+ /**
341
+ * This function gives the pair lookups of the features `kern` and `dist` of GPOS for a script, in the order of the lookup
342
+ * list. The store gives the deltas of a variable font at its instance. The filter gives the mark filtering sets of GDEF.
343
+ */
344
+ function readGposKerning(gpos, script, store, filter) {
345
+ const lookups = gpos.part(gpos.u16(8));
346
+ return pairLookupIndices(gpos, script).flatMap((index) => {
324
347
  const lookup = lookups.part(lookups.u16(2 + index * 2));
325
348
  const subtables = [];
326
- const type = lookup.u16(0);
327
- for (let s = 0; s < lookup.u16(4); s++) {
328
- let subtable = lookup.part(lookup.u16(6 + s * 2));
329
- let subtype = type;
330
- if (type === 9) {
331
- subtype = subtable.u16(2);
332
- subtable = subtable.part(subtable.u32(4));
333
- }
334
- if (subtype === 2) subtables.push(pairSubtable(subtable, store));
335
- }
349
+ for (const [subtype, subtable] of subtablesOf(lookup, 9)) if (subtype === 2) subtables.push(pairSubtable(subtable, store));
336
350
  if (subtables.length === 0) return [];
337
351
  const flags = lookup.u16(2);
338
- const markSet = (flags & USE_MARK_FILTERING_SET$1) !== 0 && filter !== void 0 ? lookup.u16(6 + lookup.u16(4) * 2) : -1;
339
- const skip = markSet < 0 ? void 0 : (glyph) => {
340
- const kind = filter.glyphClass(glyph);
341
- if ((flags & 2) !== 0 && kind === 1) return true;
342
- if ((flags & 4) !== 0 && kind === 2) return true;
343
- if (kind !== 3) return false;
344
- return (flags & 8) !== 0 || !filter.inMarkSet(markSet, glyph);
345
- };
352
+ const skip = (flags & USE_MARK_FILTERING_SET) !== 0 && filter !== void 0 ? lookupSkip(lookup, flags, filter) : void 0;
346
353
  return [{
347
354
  flags,
348
355
  ...skip === void 0 ? {} : { skip },
@@ -401,191 +408,6 @@ function readKernTable(kern) {
401
408
  }
402
409
  }];
403
410
  }
404
- // src/fonts/binary.ts
405
- /** A big-endian reader over a part of a font file. The offsets are relative to the start of the part. */
406
- var Reader = class Reader {
407
- bytes;
408
- view;
409
- constructor(bytes) {
410
- this.bytes = bytes;
411
- this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
412
- }
413
- get length() {
414
- return this.bytes.byteLength;
415
- }
416
- u8(offset) {
417
- return this.view.getUint8(offset);
418
- }
419
- u16(offset) {
420
- return this.view.getUint16(offset);
421
- }
422
- i16(offset) {
423
- return this.view.getInt16(offset);
424
- }
425
- u32(offset) {
426
- return this.view.getUint32(offset);
427
- }
428
- tag(offset) {
429
- return String.fromCharCode(this.u8(offset), this.u8(offset + 1), this.u8(offset + 2), this.u8(offset + 3));
430
- }
431
- /** This method gives a reader over the bytes from `offset`, with the length `length` or to the end. */
432
- part(offset, length) {
433
- const end = length === void 0 ? this.bytes.byteLength : offset + length;
434
- if (offset < 0 || end > this.bytes.byteLength || offset > end) throw new RangeError(`the part ${offset}..${end} is outside ${this.bytes.byteLength} bytes`);
435
- return new Reader(this.bytes.subarray(offset, end));
436
- }
437
- };
438
- // src/fonts/sfnt.ts
439
- /** The tags of the WOFF2 table directory, in the order of the WOFF2 specification. */
440
- const knownTags = [
441
- "cmap",
442
- "head",
443
- "hhea",
444
- "hmtx",
445
- "maxp",
446
- "name",
447
- "OS/2",
448
- "post",
449
- "cvt ",
450
- "fpgm",
451
- "glyf",
452
- "loca",
453
- "prep",
454
- "CFF ",
455
- "VORG",
456
- "EBDT",
457
- "EBLC",
458
- "gasp",
459
- "hdmx",
460
- "kern",
461
- "LTSH",
462
- "PCLT",
463
- "VDMX",
464
- "vhea",
465
- "vmtx",
466
- "BASE",
467
- "GDEF",
468
- "GPOS",
469
- "GSUB",
470
- "EBSC",
471
- "JSTF",
472
- "MATH",
473
- "CBDT",
474
- "CBLC",
475
- "COLR",
476
- "CPAL",
477
- "SVG ",
478
- "sbix",
479
- "acnt",
480
- "avar",
481
- "bdat",
482
- "bloc",
483
- "bsln",
484
- "cvar",
485
- "fdsc",
486
- "feat",
487
- "fmtx",
488
- "fvar",
489
- "gvar",
490
- "hsty",
491
- "just",
492
- "lcar",
493
- "mort",
494
- "morx",
495
- "opbd",
496
- "prop",
497
- "trak",
498
- "Zapf",
499
- "Silf",
500
- "Glat",
501
- "Gloc",
502
- "Feat",
503
- "Sill"
504
- ];
505
- /** This function gives the tables of a TrueType, OpenType or WOFF2 file. */
506
- function readTables(bytes, decompress) {
507
- const file = new Reader(bytes);
508
- if (file.length < 12) throw new RangeError("the file is too short for a font");
509
- const signature = file.tag(0);
510
- if (signature === "wOF2") {
511
- if (decompress === void 0) throw new Error("a WOFF2 file needs a Brotli decompress function");
512
- return readWoff2(file, decompress);
513
- }
514
- if (signature === "wOFF") throw new Error("WOFF 1 files are not supported");
515
- if (signature === "ttcf") throw new Error("font collections are not supported");
516
- if (file.u32(0) !== 65536 && signature !== "OTTO" && signature !== "true") throw new Error(`the signature ${JSON.stringify(signature)} is not a font`);
517
- const tables = /* @__PURE__ */ new Map();
518
- const count = file.u16(4);
519
- for (let i = 0; i < count; i++) {
520
- const record = 12 + i * 16;
521
- tables.set(file.tag(record), file.part(file.u32(record + 8), file.u32(record + 12)));
522
- }
523
- return tables;
524
- }
525
- /** This function reads a UIntBase128 number of WOFF2 and gives the number and the next offset. */
526
- function base128(file, offset) {
527
- let value = 0;
528
- for (let i = 0; i < 5; i++) {
529
- const byte = file.u8(offset + i);
530
- if (i === 0 && byte === 128) throw new RangeError("a UIntBase128 has a leading zero");
531
- value = value * 128 + (byte & 127);
532
- if ((byte & 128) === 0) return [value, offset + i + 1];
533
- }
534
- throw new RangeError("a UIntBase128 is longer than 5 bytes");
535
- }
536
- /**
537
- * This function gives the tables of a WOFF2 file. The `glyf` and `loca` tables stay in their transformed form,
538
- * because the width does not use them. A transformed `hmtx` table becomes a plain table again.
539
- */
540
- function readWoff2(file, decompress) {
541
- if (file.u32(4) === 1953784678) throw new Error("WOFF2 font collections are not supported");
542
- const count = file.u16(12);
543
- const compressedLength = file.u32(20);
544
- let offset = 48;
545
- const entries = [];
546
- for (let i = 0; i < count; i++) {
547
- const flags = file.u8(offset++);
548
- let tag;
549
- if ((flags & 63) === 63) {
550
- tag = file.tag(offset);
551
- offset += 4;
552
- } else {
553
- const known = knownTags[flags & 63];
554
- if (known === void 0) throw new RangeError(`the WOFF2 tag index ${flags & 63} is unknown`);
555
- tag = known;
556
- }
557
- const version = flags >> 6 & 3;
558
- let length;
559
- [length, offset] = base128(file, offset);
560
- const transformed = tag === "glyf" || tag === "loca" ? version === 0 : version !== 0;
561
- if (transformed) [length, offset] = base128(file, offset);
562
- entries.push({
563
- tag,
564
- length,
565
- transformed
566
- });
567
- }
568
- const data = new Reader(decompress(file.bytes.subarray(offset, offset + compressedLength)));
569
- const tables = /* @__PURE__ */ new Map();
570
- let at = 0;
571
- for (const entry of entries) {
572
- tables.set(entry.tag, data.part(at, entry.length));
573
- at += entry.length;
574
- }
575
- if (entries.find((entry) => entry.tag === "hmtx")?.transformed === true) tables.set("hmtx", untransformHmtx(tables));
576
- return tables;
577
- }
578
- /** This function gives a plain `hmtx` table from the transform of WOFF2. Only the advances matter, so each side bearing is 0. */
579
- function untransformHmtx(tables) {
580
- const source = tables.get("hmtx");
581
- const hhea = tables.get("hhea");
582
- if (hhea === void 0) throw new Error("a transformed hmtx needs hhea");
583
- const metrics = hhea.u16(34);
584
- const plain = new Uint8Array(metrics * 4);
585
- const view = new DataView(plain.buffer);
586
- for (let i = 0; i < metrics; i++) view.setUint16(i * 4, source.u16(1 + i * 2));
587
- return new Reader(plain);
588
- }
589
411
  // src/fonts/substitution.ts
590
412
  /**
591
413
  * The GSUB features that the default model applies: the features that HarfBuzz and Chromium apply to horizontal text
@@ -600,8 +422,6 @@ const defaultFeatures = [
600
422
  "calt",
601
423
  "rclt"
602
424
  ];
603
- /** The lookup flag that selects a mark filtering set of GDEF. */
604
- const USE_MARK_FILTERING_SET = 16;
605
425
  /** The largest depth of nested lookups, as in HarfBuzz. */
606
426
  const MAX_NESTING = 64;
607
427
  /** This function reads the glyph classes, the mark attachment classes and the mark filtering sets of GDEF. */
@@ -714,35 +534,14 @@ var Gsub = class {
714
534
  let found = this.cache.get(index);
715
535
  if (found === void 0) {
716
536
  const table = this.lookups.part(this.lookups.u16(2 + index * 2));
717
- const type = table.u16(0);
718
537
  const flags = table.u16(2);
719
- const count = table.u16(4);
720
- const markSet = (flags & USE_MARK_FILTERING_SET) !== 0 ? table.u16(6 + count * 2) : -1;
721
- const subtables = [];
722
- let subtype = type;
723
- for (let s = 0; s < count; s++) {
724
- const subtable = table.part(table.u16(6 + s * 2));
725
- if (type === 7) {
726
- subtype = subtable.u16(2);
727
- subtables.push(subtable.part(subtable.u32(4)));
728
- } else subtables.push(subtable);
729
- }
730
- const { glyphClass, markAttachClass, inMarkSet } = this.filter;
731
- const skip = (glyph) => {
732
- const kind = glyphClass(glyph);
733
- if ((flags & 2) !== 0 && kind === 1) return true;
734
- if ((flags & 4) !== 0 && kind === 2) return true;
735
- if (kind !== 3) return false;
736
- if ((flags & 8) !== 0) return true;
737
- if (markSet >= 0) return !inMarkSet(markSet, glyph);
738
- const attach = flags >> 8;
739
- return attach !== 0 && markAttachClass(glyph) !== attach;
740
- };
538
+ const parts = subtablesOf(table, 7);
539
+ const subtables = parts.map((part) => part[1]);
741
540
  found = {
742
- type: subtype,
541
+ type: parts.at(-1)?.[0] ?? table.u16(0),
743
542
  flags,
744
543
  subtables,
745
- skip
544
+ skip: lookupSkip(table, flags, this.filter)
746
545
  };
747
546
  this.cache.set(index, found);
748
547
  }
@@ -846,8 +645,9 @@ var Gsub = class {
846
645
  for (let j = from; j < glyphs.length; j++) if (!lookup.skip(glyphs[j])) return j;
847
646
  return -1;
848
647
  }
849
- previousOf(lookup, glyphs, from) {
850
- for (let j = from; j >= 0; j--) if (!lookup.skip(glyphs[j])) return j;
648
+ /** This function finds the next glyph of a backtrack or a lookahead. As in HarfBuzz, a joiner does not stop the context. */
649
+ contextOf(lookup, glyphs, from, step) {
650
+ for (let j = from; j >= 0 && j < glyphs.length; j += step) if (!lookup.skip(glyphs[j]) && !this.filter.joiners?.includes(glyphs[j])) return j;
851
651
  return -1;
852
652
  }
853
653
  /**
@@ -867,7 +667,7 @@ var Gsub = class {
867
667
  matchBacktrack(lookup, glyphs, i, count, test) {
868
668
  let at = i;
869
669
  for (let k = 0; k < count; k++) {
870
- at = this.previousOf(lookup, glyphs, at - 1);
670
+ at = this.contextOf(lookup, glyphs, at - 1, -1);
871
671
  if (at < 0 || !this.admits(at, i, false) || !test(k, glyphs[at])) return false;
872
672
  }
873
673
  return true;
@@ -875,7 +675,7 @@ var Gsub = class {
875
675
  matchLookahead(lookup, glyphs, first, last, count, test) {
876
676
  let at = last;
877
677
  for (let k = 0; k < count; k++) {
878
- at = this.nextOf(lookup, glyphs, at + 1);
678
+ at = this.contextOf(lookup, glyphs, at + 1, 1);
879
679
  if (at < 0 || !this.admits(at, first, false) || !test(k, glyphs[at])) return false;
880
680
  }
881
681
  return true;
@@ -1104,61 +904,276 @@ var Gsub = class {
1104
904
  }
1105
905
  return -1;
1106
906
  }
1107
- };
907
+ };
908
+ /**
909
+ * This function gives the lookups of the features `features` of GSUB for a script, in the order of the lookup list, as
910
+ * HarfBuzz applies them. The lookups include the lookups of the necessary feature of the language system.
911
+ */
912
+ function readSubstitutions(gsub, script, features, filter) {
913
+ const featureList = gsub.part(gsub.u16(6));
914
+ const langSys = languageSystem(gsub, script);
915
+ if (langSys === void 0 || features.length === 0) return [];
916
+ const wanted = new Set(features);
917
+ const indices = /* @__PURE__ */ new Map();
918
+ const add = (featureIndex, required) => {
919
+ const record = 2 + featureIndex * 6;
920
+ if (featureIndex >= featureList.u16(0)) return;
921
+ const tag = featureList.tag(record);
922
+ if (!required && !wanted.has(tag)) return;
923
+ const feature = featureList.part(featureList.u16(record + 4));
924
+ for (let k = 0; k < feature.u16(2); k++) {
925
+ const index = feature.u16(4 + k * 2);
926
+ const tags = indices.get(index) ?? [];
927
+ if (!tags.includes(tag)) tags.push(tag);
928
+ indices.set(index, tags);
929
+ }
930
+ };
931
+ const required = langSys.u16(2);
932
+ if (required !== 65535) add(required, true);
933
+ for (let i = 0; i < langSys.u16(4); i++) add(langSys.u16(6 + i * 2), false);
934
+ const table = new Gsub(gsub, filter);
935
+ const result = [];
936
+ for (const [index, tags] of [...indices].sort(([a], [b]) => a - b)) {
937
+ const lookup = table.lookup(index);
938
+ if (lookup === void 0) continue;
939
+ result.push({
940
+ index,
941
+ type: lookup.type,
942
+ flags: lookup.flags,
943
+ features: tags,
944
+ apply: (glyphs, masks, mask) => table.applyAll(index, glyphs, masks, mask),
945
+ applyInfos: (glyphs, infos, mask, perSyllable) => table.applyRun(index, glyphs, infos, mask, perSyllable),
946
+ wouldApply: (glyphs) => table.wouldApply(index, glyphs),
947
+ rules: () => table.rulesOf(index)
948
+ });
949
+ }
950
+ return result;
951
+ }
952
+ // src/fonts/context.ts
953
+ /**
954
+ * This function gives a test for each such lookup that can change an advance. A chained rule of format 3 must match.
955
+ * Another rule needs only its coverage. With `zeroesMarks`, HarfBuzz zeroes a mark after GPOS, so a value on a mark changes no width.
956
+ */
957
+ function readContextKerning(gpos, script, filter, zeroesMarks) {
958
+ const lookups = gpos.part(gpos.u16(8));
959
+ const lookupAt = (index) => lookups.part(lookups.u16(2 + index * 2));
960
+ const changes = (type, t, depth) => {
961
+ if (type === 7 || type === 8) return depth < 8 && (type === 7 ? contextRecords(t) : chainRecords(t)).some((record) => subtablesOf(lookupAt(record.lookupIndex), 9).some(([nested, table]) => changes(nested, table, depth + 1)));
962
+ return type === 3 || (type === 1 || type === 2) && ((t.u16(4) | (type === 2 ? t.u16(6) : 0)) & 68) !== 0;
963
+ };
964
+ const applies = (index, glyphs, at, depth) => {
965
+ const lookup = lookupAt(index);
966
+ const skip = lookupSkip(lookup, lookup.u16(2), filter);
967
+ return !skip(glyphs[at]) && subtablesOf(lookup, 9).some(([type, t]) => {
968
+ if (depth === 0 && type === 2 || !changes(type, t, depth) || type < 7 && zeroesMarks && filter.glyphClass(glyphs[at]) === 3) return false;
969
+ const covers = (offset, glyph) => coverageIndex(t.part(t.u16(offset)), glyph) >= 0;
970
+ if (type !== 8 || t.u16(0) !== 3) return covers(type === 7 && t.u16(0) === 3 ? 6 : 2, glyphs[at]);
971
+ const walk = (from, step, offset, count, seen = []) => {
972
+ let i = from;
973
+ for (let k = 0; k < count; k++) {
974
+ do
975
+ i += step;
976
+ while (i >= 0 && i < glyphs.length && skip(glyphs[i]));
977
+ if (i < 0 || i >= glyphs.length || !covers(offset + k * 2, glyphs[i])) return -1;
978
+ seen.push(i);
979
+ }
980
+ return i;
981
+ };
982
+ const inputAt = 4 + t.u16(2) * 2;
983
+ const aheadAt = inputAt + 2 + t.u16(inputAt) * 2;
984
+ const positions = [at];
985
+ if (!covers(inputAt + 2, glyphs[at]) || walk(at, -1, 4, t.u16(2)) < 0) return false;
986
+ const last = walk(at, 1, inputAt + 4, t.u16(inputAt) - 1, positions);
987
+ if (last < 0 || walk(last, 1, aheadAt + 2, t.u16(aheadAt)) < 0) return false;
988
+ return chainRecords(t).some((record) => record.sequenceIndex < positions.length && applies(record.lookupIndex, glyphs, positions[record.sequenceIndex], depth + 1));
989
+ });
990
+ };
991
+ return pairLookupIndices(gpos, script).filter((index) => subtablesOf(lookupAt(index), 9).some(([type, t]) => type !== 2 && changes(type, t, 0))).map((index) => (glyphs) => glyphs.some((_, at) => applies(index, glyphs, at, 0)));
992
+ }
993
+ // src/fonts/binary.ts
994
+ /** A big-endian reader over a part of a font file. The offsets are relative to the start of the part. */
995
+ var Reader = class Reader {
996
+ bytes;
997
+ view;
998
+ constructor(bytes) {
999
+ this.bytes = bytes;
1000
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1001
+ }
1002
+ get length() {
1003
+ return this.bytes.byteLength;
1004
+ }
1005
+ u8(offset) {
1006
+ return this.view.getUint8(offset);
1007
+ }
1008
+ u16(offset) {
1009
+ return this.view.getUint16(offset);
1010
+ }
1011
+ i16(offset) {
1012
+ return this.view.getInt16(offset);
1013
+ }
1014
+ u32(offset) {
1015
+ return this.view.getUint32(offset);
1016
+ }
1017
+ tag(offset) {
1018
+ return String.fromCharCode(this.u8(offset), this.u8(offset + 1), this.u8(offset + 2), this.u8(offset + 3));
1019
+ }
1020
+ /** This method gives a reader over the bytes from `offset`, with the length `length` or to the end. */
1021
+ part(offset, length) {
1022
+ const end = length === void 0 ? this.bytes.byteLength : offset + length;
1023
+ if (offset < 0 || end > this.bytes.byteLength || offset > end) throw new RangeError(`the part ${offset}..${end} is outside ${this.bytes.byteLength} bytes`);
1024
+ return new Reader(this.bytes.subarray(offset, end));
1025
+ }
1026
+ };
1027
+ // src/fonts/sfnt.ts
1028
+ /** The tags of the WOFF2 table directory, in the order of the WOFF2 specification. */
1029
+ const knownTags = [
1030
+ "cmap",
1031
+ "head",
1032
+ "hhea",
1033
+ "hmtx",
1034
+ "maxp",
1035
+ "name",
1036
+ "OS/2",
1037
+ "post",
1038
+ "cvt ",
1039
+ "fpgm",
1040
+ "glyf",
1041
+ "loca",
1042
+ "prep",
1043
+ "CFF ",
1044
+ "VORG",
1045
+ "EBDT",
1046
+ "EBLC",
1047
+ "gasp",
1048
+ "hdmx",
1049
+ "kern",
1050
+ "LTSH",
1051
+ "PCLT",
1052
+ "VDMX",
1053
+ "vhea",
1054
+ "vmtx",
1055
+ "BASE",
1056
+ "GDEF",
1057
+ "GPOS",
1058
+ "GSUB",
1059
+ "EBSC",
1060
+ "JSTF",
1061
+ "MATH",
1062
+ "CBDT",
1063
+ "CBLC",
1064
+ "COLR",
1065
+ "CPAL",
1066
+ "SVG ",
1067
+ "sbix",
1068
+ "acnt",
1069
+ "avar",
1070
+ "bdat",
1071
+ "bloc",
1072
+ "bsln",
1073
+ "cvar",
1074
+ "fdsc",
1075
+ "feat",
1076
+ "fmtx",
1077
+ "fvar",
1078
+ "gvar",
1079
+ "hsty",
1080
+ "just",
1081
+ "lcar",
1082
+ "mort",
1083
+ "morx",
1084
+ "opbd",
1085
+ "prop",
1086
+ "trak",
1087
+ "Zapf",
1088
+ "Silf",
1089
+ "Glat",
1090
+ "Gloc",
1091
+ "Feat",
1092
+ "Sill"
1093
+ ];
1094
+ /** This function gives the tables of a TrueType, OpenType or WOFF2 file. */
1095
+ function readTables(bytes, decompress) {
1096
+ const file = new Reader(bytes);
1097
+ if (file.length < 12) throw new RangeError("the file is too short for a font");
1098
+ const signature = file.tag(0);
1099
+ if (signature === "wOF2") {
1100
+ if (decompress === void 0) throw new Error("a WOFF2 file needs a Brotli decompress function");
1101
+ return readWoff2(file, decompress);
1102
+ }
1103
+ if (signature === "wOFF") throw new Error("WOFF 1 files are not supported");
1104
+ if (signature === "ttcf") throw new Error("font collections are not supported");
1105
+ if (file.u32(0) !== 65536 && signature !== "OTTO" && signature !== "true") throw new Error(`the signature ${JSON.stringify(signature)} is not a font`);
1106
+ const tables = /* @__PURE__ */ new Map();
1107
+ const count = file.u16(4);
1108
+ for (let i = 0; i < count; i++) {
1109
+ const record = 12 + i * 16;
1110
+ tables.set(file.tag(record), file.part(file.u32(record + 8), file.u32(record + 12)));
1111
+ }
1112
+ return tables;
1113
+ }
1114
+ /** This function reads a UIntBase128 number of WOFF2 and gives the number and the next offset. */
1115
+ function base128(file, offset) {
1116
+ let value = 0;
1117
+ for (let i = 0; i < 5; i++) {
1118
+ const byte = file.u8(offset + i);
1119
+ if (i === 0 && byte === 128) throw new RangeError("a UIntBase128 has a leading zero");
1120
+ value = value * 128 + (byte & 127);
1121
+ if ((byte & 128) === 0) return [value, offset + i + 1];
1122
+ }
1123
+ throw new RangeError("a UIntBase128 is longer than 5 bytes");
1124
+ }
1108
1125
  /**
1109
- * This function gives the lookups of the features `features` of GSUB for a script, in the order of the lookup list, as
1110
- * HarfBuzz applies them. The lookups include the lookups of the necessary feature of the language system.
1126
+ * This function gives the tables of a WOFF2 file. The `glyf` and `loca` tables stay in their transformed form,
1127
+ * because the width does not use them. A transformed `hmtx` table becomes a plain table again.
1111
1128
  */
1112
- function readSubstitutions(gsub, script, features, filter) {
1113
- const scripts = gsub.part(gsub.u16(4));
1114
- const featureList = gsub.part(gsub.u16(6));
1115
- const scriptCount = scripts.u16(0);
1116
- let langSys;
1117
- for (const wanted of scriptTags(script)) {
1118
- for (let i = 0; i < scriptCount && langSys === void 0; i++) {
1119
- if (scripts.tag(2 + i * 6) !== wanted) continue;
1120
- const table = scripts.part(scripts.u16(2 + i * 6 + 4));
1121
- const fallback = table.u16(0);
1122
- if (fallback !== 0) langSys = table.part(fallback);
1123
- }
1124
- if (langSys !== void 0) break;
1125
- }
1126
- if (langSys === void 0 || features.length === 0) return [];
1127
- const wanted = new Set(features);
1128
- const indices = /* @__PURE__ */ new Map();
1129
- const add = (featureIndex, required) => {
1130
- const record = 2 + featureIndex * 6;
1131
- if (featureIndex >= featureList.u16(0)) return;
1132
- const tag = featureList.tag(record);
1133
- if (!required && !wanted.has(tag)) return;
1134
- const feature = featureList.part(featureList.u16(record + 4));
1135
- for (let k = 0; k < feature.u16(2); k++) {
1136
- const index = feature.u16(4 + k * 2);
1137
- const tags = indices.get(index) ?? [];
1138
- if (!tags.includes(tag)) tags.push(tag);
1139
- indices.set(index, tags);
1129
+ function readWoff2(file, decompress) {
1130
+ if (file.u32(4) === 1953784678) throw new Error("WOFF2 font collections are not supported");
1131
+ const count = file.u16(12);
1132
+ const compressedLength = file.u32(20);
1133
+ let offset = 48;
1134
+ const entries = [];
1135
+ for (let i = 0; i < count; i++) {
1136
+ const flags = file.u8(offset++);
1137
+ let tag;
1138
+ if ((flags & 63) === 63) {
1139
+ tag = file.tag(offset);
1140
+ offset += 4;
1141
+ } else {
1142
+ const known = knownTags[flags & 63];
1143
+ if (known === void 0) throw new RangeError(`the WOFF2 tag index ${flags & 63} is unknown`);
1144
+ tag = known;
1140
1145
  }
1141
- };
1142
- const required = langSys.u16(2);
1143
- if (required !== 65535) add(required, true);
1144
- for (let i = 0; i < langSys.u16(4); i++) add(langSys.u16(6 + i * 2), false);
1145
- const table = new Gsub(gsub, filter);
1146
- const result = [];
1147
- for (const [index, tags] of [...indices].sort(([a], [b]) => a - b)) {
1148
- const lookup = table.lookup(index);
1149
- if (lookup === void 0) continue;
1150
- result.push({
1151
- index,
1152
- type: lookup.type,
1153
- flags: lookup.flags,
1154
- features: tags,
1155
- apply: (glyphs, masks, mask) => table.applyAll(index, glyphs, masks, mask),
1156
- applyInfos: (glyphs, infos, mask, perSyllable) => table.applyRun(index, glyphs, infos, mask, perSyllable),
1157
- wouldApply: (glyphs) => table.wouldApply(index, glyphs),
1158
- rules: () => table.rulesOf(index)
1146
+ const version = flags >> 6 & 3;
1147
+ let length;
1148
+ [length, offset] = base128(file, offset);
1149
+ const transformed = tag === "glyf" || tag === "loca" ? version === 0 : version !== 0;
1150
+ if (transformed) [length, offset] = base128(file, offset);
1151
+ entries.push({
1152
+ tag,
1153
+ length,
1154
+ transformed
1159
1155
  });
1160
1156
  }
1161
- return result;
1157
+ const data = new Reader(decompress(file.bytes.subarray(offset, offset + compressedLength)));
1158
+ const tables = /* @__PURE__ */ new Map();
1159
+ let at = 0;
1160
+ for (const entry of entries) {
1161
+ tables.set(entry.tag, data.part(at, entry.length));
1162
+ at += entry.length;
1163
+ }
1164
+ if (entries.find((entry) => entry.tag === "hmtx")?.transformed === true) tables.set("hmtx", untransformHmtx(tables));
1165
+ return tables;
1166
+ }
1167
+ /** This function gives a plain `hmtx` table from the transform of WOFF2. Only the advances matter, so each side bearing is 0. */
1168
+ function untransformHmtx(tables) {
1169
+ const source = tables.get("hmtx");
1170
+ const hhea = tables.get("hhea");
1171
+ if (hhea === void 0) throw new Error("a transformed hmtx needs hhea");
1172
+ const metrics = hhea.u16(34);
1173
+ const plain = new Uint8Array(metrics * 4);
1174
+ const view = new DataView(plain.buffer);
1175
+ for (let i = 0; i < metrics; i++) view.setUint16(i * 4, source.u16(1 + i * 2));
1176
+ return new Reader(plain);
1162
1177
  }
1163
1178
  // src/fonts/variations.ts
1164
1179
  /** This function reads a 16.16 fixed number. */
@@ -1194,7 +1209,7 @@ function readAxes(fvar) {
1194
1209
  * This function gives the normalized coordinates of an instance. Each coordinate is in -1 to 1, on the 2.14 grid. The
1195
1210
  * segment maps of `avar` change it when the font has them. A value outside the range of an axis is clamped to the range.
1196
1211
  */
1197
- function normalize$1(axes, avar, instance) {
1212
+ function normalize(axes, avar, instance) {
1198
1213
  const coordinates = axes.map((axis) => {
1199
1214
  const value = Math.min(axis.max, Math.max(axis.min, instance[axis.tag] ?? axis.default));
1200
1215
  if (value < axis.default) return toF2dot14(axis.default === axis.min ? 0 : (value - axis.default) / (axis.default - axis.min));
@@ -1521,6 +1536,167 @@ function gvarAdvanceDeltas(gvar, pointCounts, coordinates, deltas) {
1521
1536
  }
1522
1537
  return result;
1523
1538
  }
1539
+ // src/fonts/normalize.ts
1540
+ /**
1541
+ * The Unicode normalization of HarfBuzz, from `hb-ot-shape-normalize.cc`. HarfBuzz decomposes each cluster of a base and its marks.
1542
+ * It then sorts the marks, and composes each mark with its base when the font has the glyph of the composite.
1543
+ */
1544
+ const unicodeMark = /\p{M}/u;
1545
+ const nonspacingMark = /\p{Mn}/u;
1546
+ /**
1547
+ * The classes of HarfBuzz for the marks of Hebrew and Arabic, from `hb-unicode.hh`. Their order is not the canonical order:
1548
+ * for example the shadda comes first. Each other pair of marks uses the canonical order.
1549
+ */
1550
+ const sortClasses = /* @__PURE__ */ new Map([
1551
+ [1456, 22],
1552
+ [1457, 15],
1553
+ [1458, 16],
1554
+ [1459, 17],
1555
+ [1460, 23],
1556
+ [1461, 18],
1557
+ [1462, 19],
1558
+ [1463, 20],
1559
+ [1464, 21],
1560
+ [1465, 14],
1561
+ [1466, 14],
1562
+ [1467, 24],
1563
+ [1468, 12],
1564
+ [1469, 25],
1565
+ [1471, 13],
1566
+ [1473, 10],
1567
+ [1474, 11],
1568
+ [1479, 21],
1569
+ [64286, 26],
1570
+ [1560, 31],
1571
+ [1561, 32],
1572
+ [1562, 33],
1573
+ [1611, 28],
1574
+ [1612, 29],
1575
+ [1613, 30],
1576
+ [1614, 31],
1577
+ [1615, 32],
1578
+ [1616, 33],
1579
+ [1617, 27],
1580
+ [1618, 34],
1581
+ [1648, 35],
1582
+ [2288, 28],
1583
+ [2289, 29],
1584
+ [2290, 30]
1585
+ ]);
1586
+ /** The default ignorables of `hb-unicode.hh`. This set is not the Unicode property: it does not have the Hangul fillers. */
1587
+ const defaultIgnorable = /[\u00ad\u034f\u061c\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufe00-\ufe0f\ufeff\ufff0-\ufff8\u{1d173}-\u{1d17a}\u{e0000}-\u{e0fff}]/u;
1588
+ /** This function tells if a text has a default ignorable. */
1589
+ function hasDefaultIgnorable(text) {
1590
+ return defaultIgnorable.test(text);
1591
+ }
1592
+ /** This function tells if the model hides a code point. A hidden code point takes no advance, and the kerning skips it. */
1593
+ function isHidden(codePoint) {
1594
+ return hasDefaultIgnorable(String.fromCodePoint(codePoint));
1595
+ }
1596
+ /** This function tells if a code point is a mark of Unicode. The first mark of Unicode is U+0300. */
1597
+ function isMark(codePoint) {
1598
+ return codePoint >= 768 && unicodeMark.test(String.fromCodePoint(codePoint));
1599
+ }
1600
+ /** This function tells if a text has a mark of Unicode. */
1601
+ function hasMark(text) {
1602
+ return unicodeMark.test(text);
1603
+ }
1604
+ /** This function tells which code points take no advance: nonspacing marks with `classes`, marks with a class after a base with `fallback`. */
1605
+ function zeroedMarks(codePoints, classes, fallback) {
1606
+ let base = false;
1607
+ return codePoints.map((codePoint) => {
1608
+ const character = String.fromCodePoint(codePoint);
1609
+ if (!isMark(codePoint)) {
1610
+ base = true;
1611
+ return false;
1612
+ }
1613
+ return classes && nonspacingMark.test(character) && !hasDefaultIgnorable(character) || fallback && base && !isStarter(codePoint);
1614
+ });
1615
+ }
1616
+ function decomposed(codePoint) {
1617
+ return String.fromCodePoint(codePoint).normalize("NFD");
1618
+ }
1619
+ /**
1620
+ * This function tells if the mark `second` sorts before the mark `first`. That is true when the class of `first` is larger
1621
+ * than the class of `second`, and neither class is 0. The form NFD of JavaScript gives the canonical order, so no table is needed.
1622
+ */
1623
+ function reorders(first, second) {
1624
+ const firstClass = sortClasses.get(first);
1625
+ const secondClass = sortClasses.get(second);
1626
+ if (firstClass !== void 0 && secondClass !== void 0) return firstClass > secondClass;
1627
+ const text = decomposed(first) + decomposed(second);
1628
+ return text.normalize("NFD") !== text;
1629
+ }
1630
+ /** This function tells if a code point has the combining class 0. U+0345 has the largest class of Unicode. */
1631
+ function isStarter(codePoint) {
1632
+ return !isMark(codePoint) || codePoint !== 837 && !reorders(837, codePoint);
1633
+ }
1634
+ /** This function gives the canonical composite of two code points, or `undefined`. A mark does not compose with a mark. */
1635
+ function compose(first, second) {
1636
+ if (isMark(first)) return void 0;
1637
+ const [single, ...rest] = [...String.fromCodePoint(first, second).normalize("NFC")];
1638
+ return rest.length === 0 && single !== void 0 ? single.codePointAt(0) : void 0;
1639
+ }
1640
+ /**
1641
+ * This function gives the code points of a character after the decomposition. A character keeps its form when the font has
1642
+ * no glyph for one of its parts, or when the set `kept` has the character.
1643
+ */
1644
+ function decomposition(codePoint, hasGlyph, kept) {
1645
+ const parts = kept.has(codePoint) ? [codePoint] : Array.from(decomposed(codePoint), (part) => part.codePointAt(0));
1646
+ return (parts.length > 1 || parts[0] !== codePoint) && parts.every(hasGlyph) ? parts : [codePoint];
1647
+ }
1648
+ /**
1649
+ * This function normalizes code points as HarfBuzz does. It decomposes the characters by `rules`. A text with a mark after
1650
+ * its first character then gets more steps. The function sorts the marks, and composes each mark with its starter again
1651
+ * when the font has the glyph of the composite. A mark between them with the same class or a larger class blocks this.
1652
+ */
1653
+ function normalizeCodePoints(codePoints, rules) {
1654
+ const { hasGlyph, shortCircuit, kept = /* @__PURE__ */ new Set() } = rules;
1655
+ const marked = codePoints.map(isMark);
1656
+ const parts = codePoints.flatMap((codePoint, i) => {
1657
+ const simple = marked[i + 1] !== true && !(i > 0 && marked[i]);
1658
+ return shortCircuit && simple && hasGlyph(codePoint) ? [codePoint] : decomposition(codePoint, hasGlyph, kept);
1659
+ });
1660
+ if (!marked.slice(1).includes(true)) return parts;
1661
+ for (let i = 1; i < parts.length; i++) for (let j = i; j > 0 && isMark(parts[j - 1]) && isMark(parts[j]) && reorders(parts[j - 1], parts[j]); j--) [parts[j - 1], parts[j]] = [parts[j], parts[j - 1]];
1662
+ const out = parts.slice(0, 1);
1663
+ let starter = 0;
1664
+ for (let i = 1; i < parts.length; i++) {
1665
+ const codePoint = parts[i];
1666
+ if (isMark(codePoint) && (starter === out.length - 1 || reorders(codePoint, out[out.length - 1]))) {
1667
+ const composed = compose(out[starter], codePoint);
1668
+ if (composed !== void 0 && hasGlyph(composed)) {
1669
+ out[starter] = composed;
1670
+ continue;
1671
+ }
1672
+ }
1673
+ out.push(codePoint);
1674
+ if (isStarter(codePoint)) starter = out.length - 1;
1675
+ }
1676
+ return out;
1677
+ }
1678
+ /** This function gives the forms of a set of characters. It repeats the compositions until the set of code points is stable. */
1679
+ function normalForms(characters, hasGlyph, kept = /* @__PURE__ */ new Set()) {
1680
+ const parts = new Map([...characters].map((codePoint) => [codePoint, decomposition(codePoint, hasGlyph, kept)]));
1681
+ const codePoints = /* @__PURE__ */ new Set([...characters, ...[...parts.values()].flat()]);
1682
+ const composites = /* @__PURE__ */ new Map();
1683
+ for (let size = 0; size !== codePoints.size;) {
1684
+ size = codePoints.size;
1685
+ const marks = [...codePoints].filter(isMark);
1686
+ for (const starter of codePoints) for (const mark of marks) {
1687
+ const composed = compose(starter, mark);
1688
+ if (composed === void 0 || !hasGlyph(composed)) continue;
1689
+ const known = composites.get(starter) ?? [];
1690
+ if (!known.includes(composed)) composites.set(starter, [...known, composed]);
1691
+ codePoints.add(composed);
1692
+ }
1693
+ }
1694
+ return {
1695
+ parts,
1696
+ composites,
1697
+ codePoints
1698
+ };
1699
+ }
1524
1700
  // src/fonts/indic.ts
1525
1701
  /** The OpenType script tags that use the Indic shaper in this model. */
1526
1702
  const indicScripts = ["deva"];
@@ -1775,70 +1951,8 @@ function indicProperties(codePoint) {
1775
1951
  }
1776
1952
  return [X, END];
1777
1953
  }
1778
- /**
1779
- * The canonical combining classes of the marks of the Devanagari blocks that are not 0. The normalization uses them to
1780
- * sort the marks and to block a composition. A mark of another block has the class 0 in this model.
1781
- */
1782
- const combiningClasses = [
1783
- 2364,
1784
- 2364,
1785
- 7,
1786
- 2381,
1787
- 2381,
1788
- 9,
1789
- 2385,
1790
- 2385,
1791
- 230,
1792
- 2386,
1793
- 2386,
1794
- 220,
1795
- 2387,
1796
- 2388,
1797
- 230,
1798
- 7376,
1799
- 7378,
1800
- 230,
1801
- 7380,
1802
- 7380,
1803
- 1,
1804
- 7381,
1805
- 7385,
1806
- 220,
1807
- 7386,
1808
- 7387,
1809
- 230,
1810
- 7388,
1811
- 7391,
1812
- 220,
1813
- 7392,
1814
- 7392,
1815
- 230,
1816
- 7394,
1817
- 7400,
1818
- 1,
1819
- 7405,
1820
- 7405,
1821
- 220,
1822
- 7412,
1823
- 7412,
1824
- 230,
1825
- 7416,
1826
- 7417,
1827
- 230,
1828
- 43232,
1829
- 43249,
1830
- 230
1831
- ];
1832
- function combiningClass(codePoint) {
1833
- for (let i = 0; i < combiningClasses.length; i += 3) if (codePoint >= combiningClasses[i] && codePoint <= combiningClasses[i + 1]) return combiningClasses[i + 2];
1834
- return 0;
1835
- }
1836
- const unicodeMark = /\p{M}/u;
1837
1954
  /** The general categories from `FORMAT` to `NON_SPACING_MARK` of HarfBuzz: a letter, a mark, or a format or other code point. */
1838
1955
  const letterOrMark = /[\p{L}\p{M}\p{Cf}\p{Cn}\p{Co}\p{Cs}]/u;
1839
- function isMark(codePoint) {
1840
- return unicodeMark.test(String.fromCodePoint(codePoint));
1841
- }
1842
1956
  /**
1843
1957
  * This function inserts a dotted circle in each vowel sequence of Devanagari that looks like another vowel, as
1844
1958
  * `_hb_preprocess_text_vowel_constraints` does.
@@ -1887,75 +2001,11 @@ function vowelConstraints(codePoints) {
1887
2001
  while (i < codePoints.length) out.push(codePoints[i++]);
1888
2002
  return out;
1889
2003
  }
1890
- /**
1891
- * This function normalizes the code points as HarfBuzz does in the mode `COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT`. It
1892
- * decomposes each character that has a canonical decomposition when the font has the glyphs of its parts. The letter
1893
- * U+0931 does not decompose. A text with a mark after its first character then gets more steps. The function sorts the
1894
- * marks, and composes each mark with its starter again when the font has the glyph of the composite.
1895
- */
1896
- function normalize(codePoints, hasGlyph) {
1897
- const allSimple = !codePoints.some((codePoint, i) => i > 0 && isMark(codePoint));
1898
- const decomposed = codePoints.flatMap((codePoint) => decomposition(codePoint, hasGlyph));
1899
- if (allSimple) return decomposed;
1900
- for (let i = 1; i < decomposed.length; i++) for (let j = i; j > 0; j--) {
1901
- const before = combiningClass(decomposed[j - 1]);
1902
- const after = combiningClass(decomposed[j]);
1903
- if (after === 0 || before <= after) break;
1904
- [decomposed[j - 1], decomposed[j]] = [decomposed[j], decomposed[j - 1]];
1905
- }
1906
- const out = decomposed.slice(0, 1);
1907
- let starter = 0;
1908
- for (let i = 1; i < decomposed.length; i++) {
1909
- const codePoint = decomposed[i];
1910
- if (isMark(codePoint) && (starter === out.length - 1 || combiningClass(out[out.length - 1]) < combiningClass(codePoint))) {
1911
- const composed = compose(out[starter], codePoint);
1912
- if (composed !== void 0 && hasGlyph(composed)) {
1913
- out[starter] = composed;
1914
- continue;
1915
- }
1916
- }
1917
- out.push(codePoint);
1918
- if (combiningClass(codePoint) === 0) starter = out.length - 1;
1919
- }
1920
- return out;
1921
- }
1922
- /** This function gives the code points of a character after the decomposition of `normalize`. */
1923
- function decomposition(codePoint, hasGlyph) {
1924
- const parts = codePoint === 2353 ? [codePoint] : [...String.fromCodePoint(codePoint).normalize("NFD")].map((part) => part.codePointAt(0));
1925
- return (parts.length > 1 || parts[0] !== codePoint) && parts.every(hasGlyph) ? parts : [codePoint];
1926
- }
1927
- /**
1928
- * This function gives the code points that the normalization can give for the characters `characters`. A composite is
1929
- * not always in the set: a nukta that follows U+0928 gives U+0929. The function repeats until no new composite appears.
1930
- */
2004
+ /** The code points of Devanagari that do not decompose. */
2005
+ const kept = /* @__PURE__ */ new Set([2353]);
2006
+ /** This function gives the code points that `normalizeCodePoints` and `vowelConstraints` can give for a set of characters. */
1931
2007
  function indicForms(characters, hasGlyph) {
1932
- const parts = new Map([...characters].map((codePoint) => [codePoint, decomposition(codePoint, hasGlyph)]));
1933
- const codePoints = new Set([...parts.values()].flat());
1934
- for (const codePoint of characters) codePoints.add(codePoint);
1935
- codePoints.add(9676);
1936
- const composites = /* @__PURE__ */ new Map();
1937
- for (let size = 0; size !== codePoints.size;) {
1938
- size = codePoints.size;
1939
- const marks = [...codePoints].filter(isMark);
1940
- for (const starter of codePoints) for (const mark of marks) {
1941
- const composed = compose(starter, mark);
1942
- if (composed === void 0 || !hasGlyph(composed)) continue;
1943
- const known = composites.get(starter) ?? [];
1944
- if (!known.includes(composed)) composites.set(starter, [...known, composed]);
1945
- codePoints.add(composed);
1946
- }
1947
- }
1948
- return {
1949
- parts,
1950
- composites,
1951
- codePoints
1952
- };
1953
- }
1954
- /** This function gives the canonical composite of two code points, or `undefined`. A mark does not compose with a mark. */
1955
- function compose(first, second) {
1956
- if (isMark(first)) return void 0;
1957
- const [single, ...rest] = [...[(String.fromCodePoint(first) + String.fromCodePoint(second)).normalize("NFC")][0]];
1958
- return rest.length === 0 && single !== void 0 ? single.codePointAt(0) : void 0;
2008
+ return normalForms(/* @__PURE__ */ new Set([...characters, 9676]), hasGlyph, kept);
1959
2009
  }
1960
2010
  const letters = /* @__PURE__ */ new Map([
1961
2011
  [X, "x"],
@@ -2349,7 +2399,11 @@ function indicShaper(font, script, features) {
2349
2399
  if (infos[start].position === PRE_M && (start === 0 || !letterOrMark.test(String.fromCodePoint(infos[start - 1].codePoint)))) infos[start].mask |= initMask;
2350
2400
  };
2351
2401
  return (word) => {
2352
- const codePoints = normalize(vowelConstraints([...word].map((character) => character.codePointAt(0))), (codePoint) => font.glyph(codePoint) !== 0);
2402
+ const codePoints = normalizeCodePoints(vowelConstraints([...word].map((character) => character.codePointAt(0))), {
2403
+ hasGlyph: (codePoint) => font.glyph(codePoint) !== 0,
2404
+ shortCircuit: false,
2405
+ kept
2406
+ });
2353
2407
  const run = {
2354
2408
  glyphs: codePoints.map((codePoint) => font.glyph(codePoint)),
2355
2409
  infos: []
@@ -2390,7 +2444,7 @@ function indicShaper(font, script, features) {
2390
2444
  for (const { lookups, mask } of basic) for (const lookup of lookups) lookup.applyInfos(run.glyphs, run.infos, mask, true);
2391
2445
  for (const [start, end] of syllables(run.infos)) finalReordering(run, start, end);
2392
2446
  for (const { lookup, mask, perSyllable } of last) lookup.applyInfos(run.glyphs, run.infos, mask, perSyllable);
2393
- return run.glyphs;
2447
+ return run.glyphs.map((glyph, i) => (run.infos[i].props & 16) === 0 && isHidden(run.infos[i].codePoint) ? ~glyph : glyph);
2394
2448
  };
2395
2449
  }
2396
2450
  // src/fonts/joining.ts
@@ -2722,12 +2776,18 @@ const joiningTable = [
2722
2776
  2274,
2723
2777
  2274,
2724
2778
  U,
2779
+ 6158,
2780
+ 6158,
2781
+ U,
2725
2782
  8204,
2726
2783
  8204,
2727
2784
  U,
2728
2785
  8205,
2729
2786
  8205,
2730
- D
2787
+ D,
2788
+ 8294,
2789
+ 8297,
2790
+ U
2731
2791
  ];
2732
2792
  const transparent = /[\p{Mn}\p{Me}\p{Cf}]/u;
2733
2793
  /** This function gives the joining type of a code point: a column of the state machine, or `T`. */
@@ -3502,7 +3562,7 @@ function build(parsed, requested, modes) {
3502
3562
  const { tables, header, characters, glyphClass, axes } = parsed;
3503
3563
  const { deltas } = modes;
3504
3564
  const instance = Object.fromEntries(axes.map((axis) => [axis.tag, Math.min(axis.max, Math.max(axis.min, requested[axis.tag] ?? axis.default))]));
3505
- const coordinates = normalize$1(axes, tables.get("avar"), instance);
3565
+ const coordinates = normalize(axes, tables.get("avar"), instance);
3506
3566
  const variable = coordinates.some((value) => value !== 0);
3507
3567
  const hvar = tables.get("HVAR");
3508
3568
  const gvar = tables.get("gvar");
@@ -3518,6 +3578,7 @@ function build(parsed, requested, modes) {
3518
3578
  const kern = tables.get("kern");
3519
3579
  const gsub = tables.get("GSUB");
3520
3580
  const lookups = /* @__PURE__ */ new Map();
3581
+ const contexts = /* @__PURE__ */ new Map();
3521
3582
  const substitutions = /* @__PURE__ */ new Map();
3522
3583
  const hashed = [
3523
3584
  tables.get("cmap"),
@@ -3533,6 +3594,8 @@ function build(parsed, requested, modes) {
3533
3594
  epoch: `${header.revision.toString(16).padStart(8, "0")}-${widthHash(header.unitsPerEm, coordinates, advances, hashed)}${deltas === "exact" ? "-exact" : ""}${advanceSource === "gvar" && hvar !== void 0 ? "-gvar" : ""}${metrics !== void 0 ? "-metrics" : ""}`,
3534
3595
  unitsPerEm: header.unitsPerEm,
3535
3596
  numGlyphs: header.numGlyphs,
3597
+ hasPositioning: gpos !== void 0,
3598
+ hasGlyphClasses: gdef !== void 0 && gdef.u16(4) !== 0,
3536
3599
  axes,
3537
3600
  instance,
3538
3601
  coordinates,
@@ -3548,11 +3611,19 @@ function build(parsed, requested, modes) {
3548
3611
  }
3549
3612
  return found;
3550
3613
  },
3614
+ contextKerning(script) {
3615
+ if (!contexts.has(script)) contexts.set(script, gpos === void 0 ? [] : readContextKerning(gpos, script, parsed.filter, !noMarkZero.includes(script)));
3616
+ return contexts.get(script);
3617
+ },
3551
3618
  substitutions(script, features) {
3552
3619
  const key = `${script} ${features.join(",")}`;
3553
3620
  let found = substitutions.get(key);
3554
3621
  if (found === void 0) {
3555
- found = gsub === void 0 ? [] : readSubstitutions(gsub, script, features, parsed.filter);
3622
+ const joiners = script === "deva" ? [] : [characters.get(8204) ?? 0, characters.get(8205) ?? 0].filter((glyph) => glyph !== 0);
3623
+ found = gsub === void 0 ? [] : readSubstitutions(gsub, script, features, {
3624
+ ...parsed.filter,
3625
+ joiners
3626
+ });
3556
3627
  substitutions.set(key, found);
3557
3628
  }
3558
3629
  return found;
@@ -3632,6 +3703,25 @@ function shapingOf(font, options) {
3632
3703
  kerning
3633
3704
  };
3634
3705
  }
3706
+ /** The bits of a mask: all the glyphs, a default ignorable, a mark with no advance. */
3707
+ const GLOBAL_MASK = 128;
3708
+ const IGNORABLE_MASK = 256;
3709
+ const ZEROED_MASK = 512;
3710
+ /** The scripts whose shaper in HarfBuzz has no fallback mark position. */
3711
+ const noFallbackPosition = [
3712
+ "thai",
3713
+ "lao ",
3714
+ "khmr",
3715
+ "mymr",
3716
+ "mym2",
3717
+ ...indicScripts
3718
+ ];
3719
+ /** The scripts whose shaper in HarfBuzz does not zero the marks. */
3720
+ const noMarkZero = [
3721
+ "hang",
3722
+ "khmr",
3723
+ ...indicScripts
3724
+ ];
3635
3725
  /** The GSUB pass of one set of options: a function that gives the glyphs of one word, and the kerning lookups. */
3636
3726
  function shaperOf(font, options) {
3637
3727
  const { script, features, shaper, kerning } = shapingOf(font, options);
@@ -3639,24 +3729,40 @@ function shaperOf(font, options) {
3639
3729
  substitute: indicShaper(font, script, features),
3640
3730
  kerning
3641
3731
  };
3732
+ const classes = font.hasGlyphClasses === false && !noMarkZero.includes(script);
3733
+ const fallback = font.hasPositioning === false && !noFallbackPosition.includes(script);
3642
3734
  const joins = shaper === "joining";
3643
3735
  const lookups = joins ? [] : font.substitutions(script, features);
3644
3736
  const stages = joins ? joiningStages(features, features.includes("rclt") && font.substitutions(script, ["rclt"]).length > 0).map((stage) => ({
3645
3737
  stage,
3646
3738
  lookups: font.substitutions(script, stage.features)
3647
3739
  })) : [];
3740
+ const normalizes = script !== "hang";
3741
+ const rules = {
3742
+ hasGlyph: (codePoint) => font.glyph(codePoint) !== 0,
3743
+ shortCircuit: true
3744
+ };
3648
3745
  const substitute = (word) => {
3649
- const codePoints = [...word].map((character) => character.codePointAt(0));
3650
- const wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
3651
- for (const lookup of lookups) lookup.apply(wordGlyphs);
3652
- if (joins) {
3653
- const masks = joiningForms(codePoints).map((form) => 128 | (form === void 0 ? 0 : 1 << joiningFeatures.indexOf(form)));
3654
- for (const { stage, lookups: stageLookups } of stages) {
3655
- const mask = stage.form === void 0 ? 128 : 1 << joiningFeatures.indexOf(stage.form);
3656
- for (const lookup of stageLookups) lookup.apply(wordGlyphs, masks, mask);
3657
- }
3658
- }
3659
- return wordGlyphs;
3746
+ let codePoints = [...word].map((character) => character.codePointAt(0));
3747
+ let wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
3748
+ if (normalizes && (hasMark(word) || wordGlyphs.includes(0))) {
3749
+ codePoints = normalizeCodePoints(codePoints, rules);
3750
+ wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
3751
+ }
3752
+ const hides = hasDefaultIgnorable(word);
3753
+ const zeroed = (classes || fallback) && hasMark(word) ? zeroedMarks(codePoints, classes, fallback) : [];
3754
+ const forms = joins ? joiningForms(codePoints) : [];
3755
+ const masks = joins || hides || zeroed.length > 0 ? codePoints.map((codePoint, i) => GLOBAL_MASK | (forms[i] === void 0 ? 0 : 1 << joiningFeatures.indexOf(forms[i])) | (hides && isHidden(codePoint) ? IGNORABLE_MASK : 0) | (zeroed[i] === true ? ZEROED_MASK : 0)) : void 0;
3756
+ const before = hides ? [...wordGlyphs] : [];
3757
+ for (const lookup of lookups) lookup.apply(wordGlyphs, masks, GLOBAL_MASK);
3758
+ for (const { stage, lookups: stageLookups } of stages) {
3759
+ const mask = stage.form === void 0 ? GLOBAL_MASK : 1 << joiningFeatures.indexOf(stage.form);
3760
+ for (const lookup of stageLookups) lookup.apply(wordGlyphs, masks, mask);
3761
+ }
3762
+ return masks === void 0 ? wordGlyphs : wordGlyphs.map((glyph, i) => {
3763
+ const mask = masks[i] ?? 0;
3764
+ return (mask & ZEROED_MASK) !== 0 || (mask & IGNORABLE_MASK) !== 0 && before.includes(glyph) ? ~glyph : glyph;
3765
+ });
3660
3766
  };
3661
3767
  return {
3662
3768
  substitute,
@@ -3670,6 +3776,14 @@ function shaperOf(font, options) {
3670
3776
  * the joining forms of each word, in the stages of `joiningStages`. A script of `indicScripts` uses `indicShaper`.
3671
3777
  */
3672
3778
  function glyphAdvances(font, text, options = {}) {
3779
+ const { glyphs, advances } = shapedAdvances(font, text, options);
3780
+ return {
3781
+ glyphs: glyphs.map((glyph) => glyph < 0 ? ~glyph : glyph),
3782
+ advances
3783
+ };
3784
+ }
3785
+ /** This function is `glyphAdvances`, with `~glyph` for a hidden glyph. It has no advance, and the kerning skips it. */
3786
+ function shapedAdvances(font, text, options) {
3673
3787
  const { substitute, kerning } = shaperOf(font, options);
3674
3788
  const canvas = options.shaping === "canvas";
3675
3789
  const glyphs = [];
@@ -3707,7 +3821,7 @@ function kerningPosition(value, delta, scale) {
3707
3821
  function kern(font, lookups, glyphs, advances, positions, scale) {
3708
3822
  for (const lookup of lookups) {
3709
3823
  const next = (from) => {
3710
- for (let j = from; j < glyphs.length; j++) if (!(lookup.skip?.(glyphs[j]) ?? skips(lookup.flags, font.glyphClass(glyphs[j])))) return j;
3824
+ for (let j = from; j < glyphs.length; j++) if (glyphs[j] >= 0 && !(lookup.skip?.(glyphs[j]) ?? skips(lookup.flags, font.glyphClass(glyphs[j])))) return j;
3711
3825
  return -1;
3712
3826
  };
3713
3827
  let i = next(0);
@@ -3760,7 +3874,7 @@ function float32Width(font, text, size, options) {
3760
3874
  */
3761
3875
  function measureWidth(font, text, size, options = {}) {
3762
3876
  if (options.sum === "float32" && options.rounding !== "pixel") return float32Width(font, text, size, options);
3763
- const { glyphs, advances } = glyphAdvances(font, text, options);
3877
+ const { glyphs, advances } = shapedAdvances(font, text, options);
3764
3878
  if (options.rounding === "pixel") {
3765
3879
  const scale = size / font.unitsPerEm;
3766
3880
  let px = 0;
@@ -3774,6 +3888,6 @@ function measureWidth(font, text, size, options = {}) {
3774
3888
  for (const advance of advances) units += advance;
3775
3889
  return units * size / font.unitsPerEm;
3776
3890
  }
3777
- export { shapingWords as a, indicFeatures as c, readTables as d, shapingOf as i, indicForms as l, measureWidth as n, canvasWords as o, readFont as r, joiningStages as s, glyphAdvances as t, defaultFeatures as u };
3891
+ export { shapingWords as a, joiningStages as c, hasDefaultIgnorable as d, normalForms as f, defaultFeatures as h, shapingOf as i, indicFeatures as l, readTables as m, measureWidth as n, canvasSegments as o, normalizeCodePoints as p, readFont as r, canvasWords as s, glyphAdvances as t, indicForms as u };
3778
3892
 
3779
3893
  //# sourceMappingURL=font.js.map