@openpresentation/opf-render 0.33.0 → 0.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ // Same deterministic file/directory loading for PDF and raster outline compatibility.
2
+ // No static Node dependency: SVG/edge/browser module graphs remain safe.
3
+ export async function loadFontFiles(library,files,directories,diagnostic=()=>{},onFace) {
4
+ // Font files are Node-only. A browser host passes no paths: its faces come from the SVG's @font-face data or `fontData`.
5
+ if (!files.length && !directories.length) return;
6
+ const { readdir, readFile, stat: fsStat, path } = await nodeFileSystem();
7
+ const seen = new Set();
8
+ const read = async (file) => {
9
+ const resolved = path.resolve(file);
10
+ if (seen.has(resolved)) return;
11
+ seen.add(resolved);
12
+ try {
13
+ const stat = await fsStat(resolved);
14
+ const face=await library.addFile(resolved, stat, () => readFile(resolved));
15
+ if(face)onFace?.(face);
16
+ } catch (error) {
17
+ diagnostic({ code: "pdf-font-unreadable", message: `Font file ${resolved} could not be read: ${error.code ?? error.message}.`, origin: resolved });
18
+ }
19
+ };
20
+ for (const directory of directories) {
21
+ for (const file of await listFonts(directory, { readdir, path })) await read(file);
22
+ }
23
+ for (const file of files) await read(file);
24
+ }
25
+
26
+ async function listFonts(directory, { readdir, path }) {
27
+ const found = [];
28
+ let entries;
29
+ try { entries = await readdir(directory, { withFileTypes: true }); } catch { return found; }
30
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
31
+ for (const entry of entries) {
32
+ const full = path.join(directory, entry.name);
33
+ if (entry.isDirectory()) found.push(...await listFonts(full, { readdir, path }));
34
+ else if (/\.(ttf|otf)$/i.test(entry.name)) found.push(full);
35
+ }
36
+ return found;
37
+ }
38
+
39
+ async function nodeFileSystem() {
40
+ const fsName="node:fs/promises",pathName="node:path";
41
+ const [fs,path]=await Promise.all([import(/* webpackIgnore: true */ /* @vite-ignore */ fsName),import(/* webpackIgnore: true */ /* @vite-ignore */ pathName)]);
42
+ return {readdir:fs.readdir,readFile:fs.readFile,stat:fs.stat,path:path.default??path};
43
+ }
@@ -1,3 +1,4 @@
1
+ import { selectionFamilyGroup } from "./font-selection.js";
1
2
  import { sha256Bytes } from "./sha256.js";
2
3
  import bidiFactory from "bidi-js";
3
4
  import { create } from "fontkit";
@@ -26,7 +27,8 @@ function validFamily(family) {
26
27
  }
27
28
  // The open families load with the office pack (loadFonts({pack:"office"})).
28
29
 
29
- const packFor = family => { const pack = BUNDLED_FONT_MANIFEST.packages.find(pkg=>pkg.renamedFrom?.toLowerCase()===family.toLowerCase() || pkg.faces.some(face=>face.family.toLowerCase()===family.toLowerCase()))?.pack; return pack==="open" ? "office" : pack; };
30
+ const packageFor = family => BUNDLED_FONT_MANIFEST.packages.find(pkg=>pkg.renamedFrom?.toLowerCase()===family.toLowerCase() || pkg.faces.some(face=>face.family.toLowerCase()===family.toLowerCase()));
31
+ const packFor = family => { const pack = packageFor(family)?.pack; return pack==="open" ? "office" : pack; };
30
32
  const percent = value => `${(value*100).toFixed(1)}%`;
31
33
  /** FF-31: say why a family has no face and what the caller can do, from the OPF font policy. */
32
34
  function unavailableFontError(family, style, policy) {
@@ -35,8 +37,9 @@ function unavailableFontError(family, style, policy) {
35
37
  if (!row) return new OPFFontError("font-unavailable", `No local font face for '${family}'. '${family}' is not in the OPF font policy table, so there is no declared replacement: ${hook}, add an alias, or set fallbackFamily.`, {...details, licenseClass:"unknown"});
36
38
  Object.assign(details, {licenseClass:row.licenseClass});
37
39
  if (!row.replacement) {
38
- const pack = packFor(family);
39
- return new OPFFontError("font-unavailable", `No local font face for '${family}'. '${family}' is ${row.licenseClass === "open" ? `openly licensed (${row.license})` : row.license}${pack ? `; load the '${pack}' font pack` : `; no pinned renderer pack ships it yet, so supply its font files (for example from @expo-google-fonts/${family.toLowerCase().replace(/ +/g,"-")})`}.`, {...details, ...(pack?{pack}:{})});
40
+ const pack = packFor(family), npm = pack === "scripts" ? packageFor(family) : undefined;
41
+ const how = npm ? `; install ${npm.name}@${npm.version} (an optional npm package of the 'scripts' font pack)` : pack ? `; load the '${pack}' font pack` : undefined;
42
+ return new OPFFontError("font-unavailable", `No local font face for '${family}'. '${family}' is ${row.licenseClass === "open" ? `openly licensed (${row.license})` : row.license}${how ?? `; no pinned renderer pack ships it yet, so supply its font files (for example from @expo-google-fonts/${family.toLowerCase().replace(/ +/g,"-")})`}.`, {...details, ...(pack?{pack}:{}), ...(npm?{package:npm.name, version:npm.version}:{})});
40
43
  }
41
44
  const {family:replacement, compatibility, measured} = row.replacement;
42
45
  const candidates = [replacement, ...(row.alternates ?? [])], packs = [...new Set(candidates.map(packFor).filter(Boolean))];
@@ -130,9 +133,9 @@ export function pickFace(faces, family, style, {policy = "none", aliases = new M
130
133
  const metricFallback = policy!=="visual" && candidate?.metricModeFallback===true && [400,700].includes(weight);
131
134
  const allowVisual = policy==="visual" || metricFallback;
132
135
  if (candidate && (allowVisual || tier==="metric")) {
133
- // A family that names its weight (Segoe UI Semibold, Arial Black) selects that weight in
134
- // the replacement; its bold style link still selects bold (FF-31).
135
- const wanted = candidate.weight ? (weight>=600 ? Math.max(candidate.weight,700) : candidate.weight) : weight;
136
+ // A weight-named family keeps its lighter base weight. Native bold on Light/Semilight
137
+ // is a modest emphasis, not the Bold face of the parent family (LH-177).
138
+ const wanted = candidate.weight ? (weight>=600 ? candidate.weight<400 ? 400 : Math.max(candidate.weight,700) : candidate.weight) : weight;
136
139
  for (const [index, substitute] of candidate.substitutes.entries()) {
137
140
  // Only the declared replacement can carry the row's metric claim; an alternate is visual.
138
141
  const substituteTier = index===0 ? tier : "visual";
@@ -164,11 +167,11 @@ export function pickFace(faces, family, style, {policy = "none", aliases = new M
164
167
  return {face, compatibility, rule, styleFallback, via, ...(encoding ? {encoding} : {})};
165
168
  }
166
169
 
167
- export function createFontRegistry(entries, options = {}) {
168
- if (!Array.isArray(entries) || !entries.length) throw new OPFFontError("empty-font-registry", "Supply at least one font file.");
170
+ export function createFontRegistry(entries, options = {}, {allowEmpty = false, controls} = {}) {
171
+ if (!Array.isArray(entries) || !entries.length && !allowEmpty) throw new OPFFontError("empty-font-registry", "Supply at least one font file.");
169
172
  const makeFace = entry => {
170
173
  if (!(entry.data instanceof Uint8Array)) throw new OPFFontError("invalid-font-data", "Font data must be a Uint8Array.");
171
- const data = entry.data.slice();
174
+ const data = new Uint8Array(entry.data);
172
175
  let font;
173
176
  try { font = create(data, entry.postscriptName); } catch (error) { throw new OPFFontError("invalid-font-data", error.message); }
174
177
  if (!font?.layout || !font.unitsPerEm) throw new OPFFontError("font-collection", "Select one font from a collection with postscriptName.");
@@ -177,8 +180,7 @@ export function createFontRegistry(entries, options = {}) {
177
180
  // OpenType groups Medium/SemiBold/ExtraBold under a preferred family, while
178
181
  // retaining separate legacy families for four-style native font selectors.
179
182
  // An explicit caller rename owns its namespace and must not add this alias.
180
- const familyGroup = entry.family && entry.family.toLowerCase() !== font.familyName?.toLowerCase()
181
- ? family : validFamily(font.getName?.('preferredFamily', 'en') ?? family);
183
+ const familyGroup = validFamily(selectionFamilyGroup(font, entry.family ?? family));
182
184
  const linking = font['OS/2']?.fsSelection ?? font.head?.macStyle;
183
185
  const fontFace = linking && typeof linking.bold === 'boolean' && typeof linking.italic === 'boolean'
184
186
  ? {family:validFamily(font.getName?.('fontFamily', 'en') ?? font.familyName ?? family),bold:linking.bold,italic:linking.italic} : undefined;
@@ -201,8 +203,11 @@ export function createFontRegistry(entries, options = {}) {
201
203
  return hash;
202
204
  },license:entry.license,embed:entry.embed,scripts,fallbackOnly:entry.fallbackOnly===true,cache:new Map()};
203
205
  };
204
- let shaper;
206
+ let shaper, ownedShaper, ownedBackend = true;
205
207
  const faces = [], duplicates = new Set(), familySlots = new Map();
208
+ // Bumped whenever the held faces or what selection reads of them (their scripts, fallbackOnly) change: addFaces, activateScriptFamilies.
209
+ // A cache of selection results (lazyFontNames) compares this number instead of describing every face on every call.
210
+ let generation = 0;
206
211
  // Adds faces atomically: every check runs before any face is registered.
207
212
  const register = added => {
208
213
  const ids = new Set(duplicates), slots = new Map(familySlots);
@@ -217,6 +222,7 @@ export function createFontRegistry(entries, options = {}) {
217
222
  slots.set(id,face);
218
223
  }
219
224
  faces.push(...added);
225
+ generation++;
220
226
  for (const id of ids) duplicates.add(id);
221
227
  for (const [id,face] of slots) familySlots.set(id,face);
222
228
  };
@@ -230,6 +236,14 @@ export function createFontRegistry(entries, options = {}) {
230
236
  aliases = new Map(Object.entries({...scriptAliases,...options.aliases}).map(([from,to])=>[validFamily(from).toLowerCase(),validFamily(to)]));
231
237
  };
232
238
  buildAliases();
239
+ // Private loader control: a fallback first loaded for coverage may later be explicitly selected by a script font scheme.
240
+ if (controls) controls.activateScriptFamilies = families => {
241
+ const named = new Set(families.map(family=>family.toLowerCase()));
242
+ let changed = false;
243
+ for (const face of faces) if (face.fallbackOnly && named.has(face.family.toLowerCase())) { face.fallbackOnly = false; changed = true; }
244
+ if (changed) { buildAliases(); substitutions.clear(); generation++; }
245
+ return changed;
246
+ };
233
247
  const policy = options.substitutionPolicy ?? "none";
234
248
  if (!["none","metric","visual"].includes(policy)) throw new OPFFontError("invalid-font-policy", "substitutionPolicy must be none, metric, or visual.");
235
249
  if (options.fallbackFamily) validFamily(options.fallbackFamily);
@@ -258,6 +272,11 @@ export function createFontRegistry(entries, options = {}) {
258
272
  const resolveFace = style => resolve(style).face;
259
273
  const resolveStyle = style => {
260
274
  const {face,resolution}=resolve(style),resolved={...style,fontFamily:face.family,fontWeight:face.weight,italic:face.italic};
275
+ // A rich run's explicit bold flag must link from the named lightweight family, not its parent replacement.
276
+ const sourceWeight = fontPolicyFor(resolution.sourceFamily)?.replacement?.weight;
277
+ if (resolution.substitute && sourceWeight && sourceWeight<400) resolved.sourceFontFamily=resolution.sourceFamily;
278
+ else if (style.sourceFontFamily && fontPolicyFor(style.sourceFontFamily)?.replacement?.family===face.family) resolved.sourceFontFamily=style.sourceFontFamily;
279
+ else delete resolved.sourceFontFamily;
261
280
  // Never carry a stale selection from a previously resolved style.
262
281
  delete resolved.fontFace;
263
282
  delete resolved.symbolEncoding;
@@ -270,16 +289,10 @@ export function createFontRegistry(entries, options = {}) {
270
289
  else if(style.symbolEncoding && symbolPreviewFaces(style.symbolEncoding).some(name=>name.toLowerCase()===face.family.toLowerCase())) resolved.symbolEncoding=symbolEncodingFamily(style.symbolEncoding);
271
290
  return resolved;
272
291
  };
273
- const metrics = (text,size,style,includeOutline=false) => {
292
+ const validateMeasurementInput = (text,size) => {
274
293
  if (typeof text!=='string'||!Number.isFinite(size)||size<=0) throw new OPFFontError('invalid-text-measurement','Text measurement requires a string and a positive finite font size.');
275
- const {face,resolution}=resolve(style);
276
- // A BCP-47 `lang` selects the font's OpenType language system, as a browser
277
- // does for an element's lang (FF-19). Without it, shaping is unchanged.
278
- const language=openTypeLanguage(style.lang);
279
- const direction = style.direction ?? (bidi.getEmbeddingLevels(text).paragraphs[0]?.level % 2 ? "rtl" : "ltr");
280
- const key = `${direction}\u0000${style.lang ?? ""}\u0000${text}`;
281
- let value=face.cache.get(key);
282
- if (value===undefined) {
294
+ };
295
+ const checkGlyphCoverage = (face,text,style) => {
283
296
  if (options.strictGlyphs!==false) for(const character of text) {
284
297
  if (/\p{Default_Ignorable_Code_Point}/u.test(character)) continue;
285
298
  const code=character.codePointAt(0);
@@ -289,8 +302,29 @@ export function createFontRegistry(entries, options = {}) {
289
302
  throw new OPFFontError("missing-glyph", `Font '${face.family}' cannot display U+${code.toString(16).toUpperCase()}.${loadedElsewhere?"":" No loaded font has it, so glyph fallback has no face to fall back to; if it is a script character, load that script's font (loadFonts with scripts: 'auto' and the presentation, or fonts.ensure(presentation))."}`, {path:style.path,fontFamily:face.family,character,...(loadedElsewhere?{}:{loadedFaceHasGlyph:false})});
290
303
  }
291
304
  }
305
+ };
306
+ if (controls) {
307
+ // Node-only preparation control. It never supplies geometry or populates metric caches.
308
+ controls.probeGlyphs = (text,size,style) => { validateMeasurementInput(text,size); const {face}=resolve(style); checkGlyphCoverage(face,text,style); };
309
+ controls.canProbeGlyphs = () => ownedBackend && shaper === ownedShaper;
310
+ // Called only by the local fonts-node handoff after it attaches its own default outline adapter.
311
+ controls.acceptOwnedShaper = () => { ownedShaper=shaper; ownedBackend=true; };
312
+ }
313
+ const metrics = (text,size,style,includeOutline=false) => {
314
+ validateMeasurementInput(text,size);
315
+ const {face,resolution}=resolve(style);
316
+ // Automatic and explicit direction requests have separate keys. A cache hit
317
+ // needs neither Unicode direction analysis nor OpenType language lookup.
318
+ const directionKey = style.direction == null ? "auto" : `explicit:${style.direction}`;
319
+ const key = `${directionKey}\u0000${style.lang ?? ""}\u0000${text}`;
320
+ let value=face.cache.get(key);
321
+ if (value===undefined) {
322
+ checkGlyphCoverage(face,text,style);
292
323
  }
293
324
  if(value===undefined||includeOutline&&!Object.hasOwn(value,'outline')) {
325
+ // A width-only entry is shaped again when its outline is first requested.
326
+ const language = openTypeLanguage(style.lang);
327
+ const direction = style.direction ?? (bidi.getEmbeddingLevels(text).paragraphs[0]?.level % 2 ? "rtl" : "ltr");
294
328
  // FF-31: features a policy row turns off in its replacement (Gelasio for Georgia: liga, clig), the
295
329
  // same ones the SVG output turns off, so measured and drawn advances agree.
296
330
  const off=disabledFeaturesFor(face.family),policyFeatures=off&&Object.fromEntries(off.map(tag=>[tag,false]));
@@ -356,11 +390,13 @@ export function createFontRegistry(entries, options = {}) {
356
390
  // validate asks for each slide's measurement, so its layout checks measure script runs in the faces this renderer draws.
357
391
  const textMeasurement={measure,resolveStyle,outlineBounds,resolveFont:style=>resolve(style).resolution};
358
392
  textMeasurement.forScripts=profile=>createScriptFonts(profile,textMeasurement).textMeasurement;
359
- return {
393
+ const registry = {
360
394
  textMeasurement,
361
395
  // Attach the handle's outline shaper after its WASM loads. Earlier measurements must not survive the engine switch.
362
396
  setShaper(engine) {
363
397
  shaper = engine;
398
+ // A public setter call is never a trusted Node-owned attachment.
399
+ ownedBackend = false;
364
400
  for (const face of faces) face.cache.clear();
365
401
  },
366
402
  resolveFont(style) { return resolve(style).resolution; },
@@ -370,7 +406,7 @@ export function createFontRegistry(entries, options = {}) {
370
406
  // `loadFonts` handle's embeddedFonts). Whichever list it is given, the SVG writer embeds a face only where its text draws it (RR-61).
371
407
  get embeddedFonts() { return embedded(face=>face.embed!=="used"); },
372
408
  /** Parsed face metadata in entry order, without encoding font bytes. */
373
- describeFaces: ()=>faces.map(face=>({family:face.family,weight:face.weight,italic:face.italic,...(face.scripts?{scripts:[...face.scripts]}:{}),...(face.fallbackOnly?{fallbackOnly:true}:{})})),
409
+ describeFaces: ({selection = false} = {})=>faces.map(face=>({family:face.family,weight:face.weight,italic:face.italic,...(selection?{familyGroup:face.familyGroup}:{}),...(face.scripts?{scripts:[...face.scripts]}:{}),...(face.fallbackOnly?{fallbackOnly:true}:{})})),
374
410
  /** Embedded faces for which `predicate({family,weight,italic,scripts})` holds; large script faces can be left to raster fontFiles. */
375
411
  selectEmbeddedFonts: predicate=>embedded(predicate),
376
412
  /** Every face as `{family, data}` (the bytes the registry measures with), for the browser PDF export to embed. */
@@ -391,5 +427,8 @@ export function createFontRegistry(entries, options = {}) {
391
427
  return made.map(face=>({family:face.family,weight:face.weight,italic:face.italic,...(face.scripts?{scripts:[...face.scripts]}:{})}));
392
428
  },
393
429
  };
430
+ // Not part of the public registry (like fontNames): the number lazyFontNames compares to know the face pool changed.
431
+ Object.defineProperty(registry, "facesGeneration", { get: () => generation });
432
+ return registry;
394
433
  function embedded(predicate) { return faces.filter(face=>predicate({family:face.family,weight:face.weight,italic:face.italic,scripts:face.scripts,embed:face.embed,fallbackOnly:face.fallbackOnly})).map(face=>({family:face.family,weight:face.weight,italic:face.italic,...(face.license ? {license:face.license} : {}),...(face.embed ? {embed:face.embed} : {}),dataUrl:`data:font/${face.format};base64,${base64(face.data)}`})); }
395
434
  }
@@ -0,0 +1,21 @@
1
+ // Generated by scripts/update-font-manifest.mjs from verified pinned font files; do not edit.
2
+ export const FONT_SELECTION_METADATA = Object.freeze([
3
+ {
4
+ "package": "@expo-google-fonts/roboto",
5
+ "file": "500Medium/Roboto_500Medium.ttf",
6
+ "sha256": "79343dc641a2e8d48a703a4667b71fc8dc6565cc8ce47dfc34fc52c12aadbf38",
7
+ "familyGroup": "Roboto"
8
+ },
9
+ {
10
+ "package": "@expo-google-fonts/roboto",
11
+ "file": "600SemiBold/Roboto_600SemiBold.ttf",
12
+ "sha256": "32fe2086b0e54eca85a68eb74e3d89bb16a7ffe59085d6dc7d079f5b3c26d6ab",
13
+ "familyGroup": "Roboto"
14
+ },
15
+ {
16
+ "package": "@expo-google-fonts/roboto",
17
+ "file": "800ExtraBold/Roboto_800ExtraBold.ttf",
18
+ "sha256": "43d5ce98c58336045220fa1dac2bd22281b1aab3eca66785cb34eb3ad1dfe1a5",
19
+ "familyGroup": "Roboto"
20
+ }
21
+ ].map(Object.freeze));
@@ -0,0 +1,6 @@
1
+ // Shared with the maintained manifest generator: match the registry's preferred-family namespace exactly.
2
+ export function selectionFamilyGroup(font, family) {
3
+ return family && family.toLowerCase() !== font.familyName?.toLowerCase()
4
+ ? family
5
+ : (font.getName?.('preferredFamily', 'en') ?? family);
6
+ }
@@ -4,6 +4,7 @@ import type {
4
4
  FontRegistry,
5
5
  FontRegistryOptions,
6
6
  FontsHandle,
7
+ FontPreparationOptions,
7
8
  } from "./fonts.js";
8
9
  import type { AutoScriptSelection, BundledFontPackage, LazyFont, ScriptSelection } from "./fonts-node.js";
9
10
  import type { ToSvgOptions } from "./svg.js";
@@ -30,13 +31,13 @@ export interface BrowserFontRegistry extends FontRegistry {
30
31
  * with (`catalogs`, ...) over the loader's `renderOptions`. A document that does not resolve rejects with the error
31
32
  * `toSvg` throws for it. After `dispose()` it rejects with `font-registry-disposed`.
32
33
  */
33
- ensureLazyFonts(presentation: unknown, options?: { signal?: AbortSignal } & Partial<ToSvgOptions>): Promise<LazyFont[]>;
34
+ ensureLazyFonts(presentation: unknown, options?: { signal?: AbortSignal } & FontPreparationOptions): Promise<LazyFont[]>;
34
35
  /**
35
36
  * Synchronous: the vendored faces the presentation draws under the registry's policy that are not loaded yet. Empty means
36
37
  * `ensureLazyFonts` fetches nothing. `renderOptions` are the `toSvg` options the document resolves with (`catalogs`, ...)
37
38
  * over the loader's `renderOptions`. Throws what `toSvg` throws for a document that does not resolve.
38
39
  */
39
- pendingLazyFonts(presentation: unknown, renderOptions?: Partial<ToSvgOptions>): LazyFont[];
40
+ pendingLazyFonts(presentation: unknown, renderOptions?: FontPreparationOptions): LazyFont[];
40
41
 
41
42
  /** Load script faces for ISO 15924 codes (or "all") from `scriptBaseUrl`. Resolves with the newly loaded package names. */
42
43
  loadScripts(scripts: ScriptSelection, options?: { signal?: AbortSignal }): Promise<string[]>;
@@ -70,7 +71,7 @@ export interface BrowserFontsHandle extends FontsHandle {
70
71
  * (`catalogs`, ...) over the loader's `renderOptions`. A document that does not resolve rejects with what `toSvg` throws for it; after
71
72
  * `dispose()` it rejects with `font-registry-disposed`.
72
73
  */
73
- ensure(presentation: unknown, options?: { signal?: AbortSignal } & Partial<ToSvgOptions>): Promise<EnsureResult>;
74
+ ensure(presentation: unknown, options?: { signal?: AbortSignal } & FontPreparationOptions): Promise<EnsureResult>;
74
75
  /** Synchronous: the vendored files and script packages `ensure` would fetch. Empty means a render can start now. Throws what `toSvg` throws for a document that does not resolve. */
75
76
  pending(presentation: unknown, renderOptions?: Partial<ToSvgOptions>): string[];
76
77
  /**
@@ -1,7 +1,7 @@
1
1
  import { diagramsPending, ensureDiagrams, ensureIcons, ensureShapes, iconsPending, shapesPending } from "@openpresentation/opf/composition";
2
2
  import { createFontRegistry, OPFFontError } from "./font-registry.js";
3
3
  import { lazyFontEntries, lazyFontList, normalizeExtraLazyFonts } from "./lazy-font-list.js";
4
- import { createFontAnalysis, lazyFacesNeeded } from "./lazy-fonts.js";
4
+ import { createFontAnalysis, lazyFacesNeeded, lazyFontNames, fontMeasurementRequests } from "./lazy-fonts.js";
5
5
  import { BUNDLED_FONT_MANIFEST } from "./font-manifest.js";
6
6
  import { textOutlines } from "./text-paths.js";
7
7
  import { createSubsetter, fontSubsets } from "./font-subset.js";
@@ -112,7 +112,7 @@ async function loadRegistry(entries, options = {}, startup = {}) {
112
112
  let queue = Promise.resolve();
113
113
  // FF-41: the `toSvg` options a document resolves with (`catalogs`, ...). `options.renderOptions` are the defaults; a call's own
114
114
  // options (everything but `signal`) are added over them, so a host that passes its canvas options gets the same resolution here.
115
- const renderOptionsFor = (callOptions) => { const { signal: _signal, ...own } = callOptions ?? {}; return { ...options.renderOptions, ...own }; };
115
+ const renderOptionsFor = (callOptions) => { const {signal: _signal,renderOptions,mapFamily,preserveChosenFamilies,measurementRequests,...own}=callOptions??{};return {...options.renderOptions,...own,...renderOptions}; };
116
116
  const gone = () => new OPFFontError("font-registry-disposed", "The font registry was disposed.");
117
117
  const baseUrl = () => {
118
118
  if (typeof options.scriptBaseUrl !== "string" || !options.scriptBaseUrl)
@@ -208,7 +208,10 @@ async function loadRegistry(entries, options = {}, startup = {}) {
208
208
  const aliasTargets = new Map(Object.entries(options.aliases ?? {}).map(([from, to]) => [from.toLowerCase(), to]));
209
209
  // Face level (FF-41): the faces the document draws, resolved as the registry resolves them with every vendored face loaded.
210
210
  // A document that does not resolve throws what `toSvg` throws for it.
211
- const neededLazy = (presentation, callOptions) => lazyFacesNeeded(presentation, renderOptionsFor(callOptions), { lazy, held: registry.describeFaces(), loaded: lazyLoaded, policy, aliases: aliasTargets, fallbackFamily: options.fallbackFamily, analysis: fontAnalysis });
211
+ const neededLazy = (presentation, callOptions) => lazyFacesNeeded(presentation, renderOptionsFor(callOptions), { lazy, held: registry.describeFaces(callOptions?.preserveChosenFamilies||callOptions?.measurementRequests?.length?{selection:true}:undefined), loaded: lazyLoaded, policy, aliases: aliasTargets, fallbackFamily: options.fallbackFamily, analysis: fontAnalysis,
212
+ metrics: registry.textMeasurement,
213
+ mapFamily:callOptions?.mapFamily,preserveChosenFamilies:callOptions?.preserveChosenFamilies,measurementRequests:callOptions?.measurementRequests });
214
+ Object.defineProperty(registry,'fontNames',{value:lazyFontNames({lazy,describeFaces:registry.describeFaces,generation:()=>registry.facesGeneration,policy,aliases:aliasTargets,fallbackFamily:options.fallbackFamily})});
212
215
  const lazyBaseUrl = () => {
213
216
  if (typeof options.lazyFontsBaseUrl !== "string" || !options.lazyFontsBaseUrl)
214
217
  throw new OPFFontError("invalid-font-source", "Loading vendored fonts requires lazyFontsBaseUrl, where the host serves the package's fonts directory.");
@@ -280,7 +283,8 @@ async function loadRegistry(entries, options = {}, startup = {}) {
280
283
  return Object.assign(registry, { dispose });
281
284
  }
282
285
 
283
- const MAX_ENSURE_ROUNDS = 4;
286
+ // Lazy faces, script packages and the analysis's real-metrics passes (RR-105) each take a round; a deck settles in a few.
287
+ const MAX_ENSURE_ROUNDS = 16, SCRIPT_ROUNDS = 4;
284
288
 
285
289
  /**
286
290
  * The fonts handle for a browser: the faces you list (`faces`, each `{ url | data, family, weight, italic, sha256 }`, fetched and
@@ -359,19 +363,26 @@ export async function loadFonts({ faces = [], subsetWasm, shapeWasm, ...options
359
363
  * does not resolve rejects with what `toSvg` throws for it. After `dispose()` it rejects with `font-registry-disposed`.
360
364
  */
361
365
  async ensure(presentation, callOptions = {}) {
366
+ const measurements=fontMeasurementRequests(callOptions.measurementRequests);
362
367
  const diagrams = await ensureDiagrams(presentation);
363
368
  // SH-02: the preset geometry, the first time the deck has a shape (core loads it on demand in a browser).
364
369
  await ensureShapes(presentation);
365
370
  await ensureIcons(presentation, { catalogs: callOptions.catalogs ?? options.renderOptions?.catalogs });
366
371
  const lazy = [], scripts = [];
367
372
  let uncovered = [];
368
- for (let round = 0; round < MAX_ENSURE_ROUNDS; round++) {
369
- const needLazy = registry.pendingLazyFonts(presentation, callOptions).length > 0, needScripts = registry.pendingScripts(presentation, callOptions).length > 0;
370
- if (!needLazy && !needScripts) break;
373
+ for (let round = 0; ; round++) {
374
+ const needLazy = registry.pendingLazyFonts(presentation, callOptions), needScripts = registry.pendingScripts(presentation, callOptions).length > 0;
375
+ if (!needLazy.length && !needScripts) break;
376
+ // Script packages that cannot settle keep the earlier bound of four rounds; a vendored face real metrics still ask for is an error.
377
+ if (!needLazy.length && round >= SCRIPT_ROUNDS) break;
378
+ if (round >= MAX_ENSURE_ROUNDS) {
379
+ throw new OPFFontError("font-preparation-unsettled", "Preparing the fonts of this presentation did not settle: each pass measured faces the one before had not prepared.", { faces: needLazy.map(({ family, weight, italic, file }) => ({ family, weight, italic, file })) });
380
+ }
371
381
  callOptions.signal?.throwIfAborted?.();
372
- if (needLazy) lazy.push(...(await registry.ensureLazyFonts(presentation, callOptions)));
382
+ if (needLazy.length) lazy.push(...(await registry.ensureLazyFonts(presentation, callOptions)));
373
383
  if (needScripts) { const result = await registry.ensureScripts(presentation, callOptions); scripts.push(...result.loaded); uncovered = result.uncovered; }
374
384
  }
385
+ for(const request of measurements)if(request.text!=='')registry.textMeasurement.measure(request.text,request.size,request.style);
375
386
  return { scripts, lazy, uncovered, ...(diagrams.length ? { diagrams } : {}) };
376
387
  },
377
388
  /** Synchronous: the files and script packages `ensure` would fetch. Empty means a render can start now. Throws what `toSvg` throws for a document that does not resolve. */
@@ -1,3 +1,4 @@
1
+ import type {TextStyle} from "@openpresentation/opf/composition";
1
2
  import type {FontRegistry,FontRegistryOptions,FontFaceInput,FontsHandle,EnsureResult,ScriptFontProfile} from "./fonts.js";
2
3
  import type {ToSvgOptions} from "./svg.js";
3
4
  /** A caller-supplied face (FF-31), for example a licensed copy of the real font. Node callers may pass a file path. */
@@ -28,7 +29,7 @@ export interface ScriptPackOptions {
28
29
  * is reported through `onDiagnostic` instead of failing.
29
30
  */
30
31
  scripts?: ScriptSelection | "auto";
31
- /** The presentation whose text decides `scripts: "auto"`. */
32
+ /** With a presentation, load only the faces its actual styles/glyphs need; omission preserves whole-pack loading. Also decides scripts: "auto". */
32
33
  presentation?: unknown;
33
34
  /** The `toSvg` options the presentation resolves with (`catalogs`, ...), for the font schemes `scripts: "auto"` reads (FF-41). */
34
35
  renderOptions?: Partial<ToSvgOptions>;
@@ -37,7 +38,7 @@ export interface ScriptPackOptions {
37
38
  * `harfbuzz-unavailable` when a harfbuzzjs .wasm (`file`) cannot be loaded, for example in a bundled server that did not ship it:
38
39
  * the handle then has no `subsets`, or shapes outlines with fontkit.
39
40
  */
40
- onDiagnostic?: (diagnostic: {code: string; message: string; script?: string; package?: string; scripts?: string[]; file?: string}) => void;
41
+ onDiagnostic?: (diagnostic: {code: string; message: string; script?: string; package?: string; version?: string; scripts?: string[]; file?: string}) => void;
41
42
  }
42
43
  /** A vendored face that an SVG embeds only when its text names the family (the open families and Intos), and that browser hosts load on demand from a separate hash-pinned file. */
43
44
  export interface LazyFont { readonly package: string; readonly family: string; readonly weight: number; readonly italic: boolean; /** Path relative to the package root, for example fonts/intos/Intos-Regular.ttf. */ readonly file: string; readonly sha256: string; readonly license: string; readonly renamedFrom?: string; /** Set on a host's extra lazy face (`extraLazyFonts`, `package: "host"`): where the host serves the file from. */ readonly url?: string }
@@ -85,13 +86,13 @@ export interface NodeFontsHandle extends FontsHandle {
85
86
  /** System fonts never load: the output does not depend on the machine. */
86
87
  readonly loadSystemFonts: false;
87
88
  /**
88
- * Load the script faces the presentation's text needs that this handle does not hold (what `scripts: "auto"` does at load, for another
89
+ * Load the ordinary and script faces the presentation's text needs that this handle does not hold (what `scripts: "auto"` does at load, for another
89
90
  * presentation), including the CJK face a glyph fallback needs. Cheap when nothing is missing; `embeddedFonts` and `fontFiles` then include
90
91
  * the new faces. A package that is not installed or a script no pinned font serves is reported once through `onDiagnostic`.
91
- * Resolves with the packages this call added (`scripts`; `lazy` is empty: Node loads every vendored face with its pack).
92
+ * Resolves with the script packages and exact face descriptors this call added (`scripts` and `lazy`).
92
93
  */
93
- ensure(presentation: unknown, options?: { onDiagnostic?: ScriptPackOptions["onDiagnostic"]; renderOptions?: Partial<ToSvgOptions> }): Promise<EnsureResult>;
94
- /** Synchronous: the script packages the presentation needs that are not loaded yet. */
94
+ ensure(presentation: unknown, options?: Partial<ToSvgOptions> & { onDiagnostic?: ScriptPackOptions["onDiagnostic"]; renderOptions?: Partial<ToSvgOptions>; /** Additional preparation for an exporter that maps source families, such as safe PPTX typefaces. Does not rewrite the document. Pass the same function on every call: the analysis cache is keyed by the function's identity, so a fresh closure each call starts cold. */ mapFamily?: (family: string) => string; /** Prepare native PPTX chosen-family roles/weights as well as physical preview faces. Does not alter ordinary rendering. */ preserveChosenFamilies?: boolean; /** Actual exporter-only measurement dependencies, separate from SVG demand analysis. Families are already mapped by the exporter. */ measurementRequests?: readonly {text: string; size: number; style: TextStyle}[] }): Promise<EnsureResult>;
95
+ /** Synchronous: the missing face resources and script packages the presentation needs. */
95
96
  pending(presentation: unknown, renderOptions?: Partial<ToSvgOptions>): string[];
96
97
  }
97
98
  export interface LoadFontsOptions extends FontRegistryOptions, ScriptPackOptions {
@@ -1,6 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { createHash } from "node:crypto";
4
+ import { createNodeDemand } from "./font-demand.js";
4
5
  import { createFontRegistry, OPFFontError } from "./font-registry.js";
5
6
  import { BUNDLED_FONT_MANIFEST } from "./font-manifest.js";
6
7
  import { lazyFontList } from "./lazy-font-list.js";
@@ -77,7 +78,7 @@ async function loadPackages(packages, skipped, {fallbackOnly = false, what = "Th
77
78
  const file = path.join(directory, face.file);
78
79
  const data = await verifiedFile(file, face.sha256, {package:pkg.name, file:face.file});
79
80
  fontFiles.push(file);
80
- entries.push({data:new Uint8Array(data), family:face.family, weight:face.weight, italic:face.italic, license, ...(pkg.scripts ? {scripts:[...pkg.scripts]} : {}), ...(fallbackOnly ? {fallbackOnly:true, embed:"used"} : {})});
81
+ entries.push({data:new Uint8Array(data), family:face.family, weight:face.weight, italic:face.italic, license, ...(pkg.scripts ? {scripts:[...pkg.scripts]} : {}), ...(fallbackOnly || face.fallbackOnly ? {fallbackOnly:true, embed:"used"} : {})});
81
82
  }
82
83
  }
83
84
  return {entries, fontFiles, packages:packages.map(pkg => pkg.name)};
@@ -108,7 +109,7 @@ async function withScripts(loaded, scripts, {presentation, onDiagnostic, renderO
108
109
  const selection = scriptSelectionOf(analyzePresentationScripts(presentation, undefined, renderOptions)), skipped = [];
109
110
  const extra = await loadPackages(notLoaded(scriptFontPackages(selection.scripts)), skipped);
110
111
  for (const script of selection.unavailable) onDiagnostic?.({code: "script-font-unavailable", script, message: `No pinned open font serves script '${script}'; that text uses the design font.`});
111
- for (const item of skipped) onDiagnostic?.({code: "script-font-not-installed", package: item.package, scripts: item.scripts, message: `Install ${item.package}@${item.version} to preview ${item.scripts.join(", ")} text with its designated open font.`});
112
+ for (const item of skipped) onDiagnostic?.({code: "script-font-not-installed", package: item.package, version: item.version, scripts: item.scripts, message: `Install ${item.package}@${item.version} to preview ${item.scripts.join(", ")} text with its designated open font.`});
112
113
  return {entries:[...loaded.entries, ...embedUsed(extra.entries)], fontFiles:[...loaded.fontFiles, ...extra.fontFiles], packages:[...(loaded.packages ?? []), ...extra.packages],
113
114
  selection:{...selection, packages: scriptFontPackages(selection.scripts).map(item => item.name).filter(name => !skipped.some(item => item.package === name)), notInstalled: skipped.map(item => item.package)}};
114
115
  }
@@ -134,7 +135,7 @@ async function completeFallback(registry, presentation, loaded, onDiagnostic, re
134
135
  const skipped = [], extra = await loadPackages([next], skipped);
135
136
  if (skipped.length) {
136
137
  selection.notInstalled.push(next.name);
137
- onDiagnostic?.({code: "script-font-not-installed", package: next.name, scripts: [...next.scripts], message: `Install ${next.name}@${next.version} for glyphs the loaded CJK faces lack.`});
138
+ onDiagnostic?.({code: "script-font-not-installed", package: next.name, version: next.version, scripts: [...next.scripts], message: `Install ${next.name}@${next.version} for glyphs the loaded CJK faces lack.`});
138
139
  continue;
139
140
  }
140
141
  registry.addFaces(embedUsed(extra.entries));
@@ -237,7 +238,7 @@ async function ensureFonts(registry, loaded, presentation, {onDiagnostic, render
237
238
  selection.packages.push(...extra.packages);
238
239
  for (const item of skipped) {
239
240
  selection.notInstalled.push(item.package);
240
- onDiagnostic?.({code: "script-font-not-installed", package: item.package, scripts: item.scripts, message: `Install ${item.package}@${item.version} to preview ${item.scripts.join(", ")} text with its designated open font.`});
241
+ onDiagnostic?.({code: "script-font-not-installed", package: item.package, version: item.version, scripts: item.scripts, message: `Install ${item.package}@${item.version} to preview ${item.scripts.join(", ")} text with its designated open font.`});
241
242
  }
242
243
  for (const script of wanted.unavailable) if (!selection.unavailable.includes(script)) {
243
244
  selection.unavailable.push(script);
@@ -277,10 +278,12 @@ function nodeHarfbuzz(kind) {
277
278
  */
278
279
  export async function loadFonts({pack = "base", embedScriptFonts = false, ...options} = {}) {
279
280
  if (pack !== "base" && pack !== "office" && pack !== "none") throw new OPFFontError("invalid-font-pack", "Choose the base, office or none font pack.", {pack});
280
- const {registry, loaded} = await buildRegistry(pack, options);
281
+ const demand = options.presentation !== undefined ? await createNodeDemand(pack, options, {loadPackages, callerFaces, renamedAliases}) : undefined;
282
+ const {registry, loaded} = demand ?? await buildRegistry(pack, options);
283
+ if(demand)registry.lazyFonts=lazyOf(registry);
281
284
  // Script faces are large (CJK faces are 5-10 MB each). Raster output reads them from fontFiles; embed them in standalone SVG only
282
285
  // on request. The default Noto Sans fallback is always offered (embed "used"), so an SVG carries it exactly when its text draws it.
283
- const selectEmbedded = () => registry.selectEmbeddedFonts(face => embedScriptFonts || !face.scripts || face.fallbackOnly);
286
+ const selectEmbedded = () => { const selected=registry.selectEmbeddedFonts(face => embedScriptFonts || !face.scripts || face.fallbackOnly); return demand?demand.orderFaces(selected):selected; };
284
287
  // The embedded list is base64 of every face: computed on first use, and again after `ensure` added faces.
285
288
  let embeddedFonts, fontFiles = [...registry.fontFiles];
286
289
  // Calls mutate one registry: serialize their reads/additions, while returning each
@@ -288,12 +291,16 @@ export async function loadFonts({pack = "base", embedScriptFonts = false, ...opt
288
291
  let ensureQueue = Promise.resolve();
289
292
  // `pending` is asked before every render: each string is scanned once and each slide's families resolved once (see createScriptAnalysis).
290
293
  const scriptMemory = createScriptAnalysis();
294
+ const renderOptionsFor = callOptions => {const {renderOptions,onDiagnostic,mapFamily,preserveChosenFamilies,measurementRequests,signal,...inline}=callOptions??{};return {...options.renderOptions,...inline,...renderOptions};};
291
295
  const refresh = () => { embeddedFonts = undefined; fontFiles = [...registry.fontFiles]; };
292
296
  const [subsetter, shaper] = await Promise.all([nodeHarfbuzz("subsets"), nodeHarfbuzz("shaper")]);
293
297
  for (const [kind, engine] of [["subsets", subsetter], ["shaper", shaper]]) if (!engine) {
294
298
  const {file, without} = HARFBUZZ[kind];
295
299
  options.onDiagnostic?.({code: "harfbuzz-unavailable", package: "harfbuzzjs", file, message: `${file} could not be loaded, so ${without}. Ship the harfbuzzjs package with the server.`});
296
300
  }
301
+ const outlines = textOutlines({ registry, shaper });
302
+ // Private local handoff only: later public setShaper calls remain conservative full-measure coverage.
303
+ demand?.acceptOwnedShaper();
297
304
  return {
298
305
  textMeasurement: registry.textMeasurement,
299
306
  get embeddedFonts() { return (embeddedFonts ??= selectEmbedded()); },
@@ -302,7 +309,7 @@ export async function loadFonts({pack = "base", embedScriptFonts = false, ...opt
302
309
  loadSystemFonts: false,
303
310
  registry,
304
311
  // RR-64: the outline engine `toSvg(deck, { fonts, text: "paths" })` draws text with, over this registry's faces.
305
- outlines: textOutlines({ registry, shaper }),
312
+ outlines,
306
313
  // RR-65: the subset engine that cuts each face an SVG embeds to the characters the slide draws.
307
314
  ...(subsetter ? { subsets: fontSubsets(registry, subsetter) } : {}),
308
315
  manifest: BUNDLED_FONT_MANIFEST,
@@ -310,15 +317,28 @@ export async function loadFonts({pack = "base", embedScriptFonts = false, ...opt
310
317
  /** Load the script faces the presentation's text needs (see `ensureFonts`); `embeddedFonts` and `fontFiles` then include them. */
311
318
  ensure(presentation, callOptions = {}) {
312
319
  const result = ensureQueue.then(async () => {
313
- const prepared = await ensureFonts(registry, loaded, presentation, {onDiagnostic: callOptions.onDiagnostic ?? options.onDiagnostic, renderOptions: {...options.renderOptions, ...callOptions.renderOptions}});
314
- refresh();
315
- return prepared;
320
+ const prepare = demand ? (_registry,_loaded,presentation,opts)=>demand.ensure(presentation,opts) : ensureFonts;
321
+ let rejected = false;
322
+ try {
323
+ return await prepare(registry, loaded, presentation, {onDiagnostic: callOptions.onDiagnostic ?? options.onDiagnostic, renderOptions: renderOptionsFor(callOptions), ...(callOptions.mapFamily ? {mapFamily:callOptions.mapFamily} : {}), ...(callOptions.preserveChosenFamilies ? {preserveChosenFamilies:true} : {}), ...(callOptions.measurementRequests ? {measurementRequests:callOptions.measurementRequests} : {})});
324
+ } catch (error) {
325
+ rejected = true;
326
+ throw error;
327
+ } finally {
328
+ // A later resource can fail after verified faces or fallback-only metadata already changed.
329
+ // Derived views must reflect those committed registry changes while the original rejection propagates.
330
+ try {
331
+ refresh();
332
+ if(demand)registry.lazyFonts=lazyOf(registry);
333
+ } catch(error) { if(!rejected)throw error; } // Never replace the original preparation rejection.
334
+ }
316
335
  });
317
336
  ensureQueue = result.catch(() => {});
318
337
  return result;
319
338
  },
320
339
  /** Synchronous: the script packages the presentation needs that are not loaded yet. Empty means `ensure` loads nothing. */
321
340
  pending(presentation, renderOptions) {
341
+ if(demand)return demand.pending(presentation,renderOptionsFor(renderOptions));
322
342
  const held = new Set([...loaded.packages, ...(loaded.selection?.notInstalled ?? [])]);
323
343
  const analysis = analyzePresentationScripts(presentation, undefined, {...options.renderOptions, ...renderOptions}, scriptMemory);
324
344
  const primary = scriptFontPackages(scriptSelectionOf(analysis).scripts).map(pkg => pkg.name).filter(name => !held.has(name));
package/dist/fonts.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { TextMeasurement, TextStyle, ScriptRole } from "@openpresentation/opf/composition";
2
2
  import type { FontPolicyEntry } from "@openpresentation/opf/font-policy";
3
3
  import type { LazyFont } from "./fonts-node.js";
4
+ import type {ToSvgOptions} from "./svg.js";
4
5
  // Core owns these: the font policy table and lookup, the symbol-font code rules and the script slot of a script. They are core's own
5
6
  // exports (the same objects), not copies.
6
7
  export { FONT_POLICY, fontPolicyFor } from "@openpresentation/opf/font-policy";
@@ -69,6 +70,15 @@ export interface TextOutlines {
69
70
  /** What `fonts.ensure(presentation)` loaded: the script packages and vendored faces that were missing, and drawn CJK characters no face covers. */
70
71
  /** What `ensure` loaded. `diagrams`: the diagram types it loaded (in a browser, core loads each type on demand; Node has them all). */
71
72
  export interface EnsureResult { scripts: string[]; lazy: LazyFont[]; uncovered: string[]; diagrams?: string[] }
73
+ /** An exporter's actual additional measurement, separate from the text SVG draws. Family names have already been mapped by the exporter. */
74
+ export interface FontMeasurementRequest { text: string; size: number; style: TextStyle }
75
+ export type FontPreparationOptions = Partial<ToSvgOptions> & {
76
+ renderOptions?: Partial<ToSvgOptions>;
77
+ /** Additional exporter mapping; never rewrites the document or ordinary SVG demand. Pass the same function on every call: the handle keeps its font analysis per mapping function (by identity), so a fresh closure each call starts from a cold cache. */
78
+ mapFamily?: (family: string) => string;
79
+ preserveChosenFamilies?: boolean;
80
+ measurementRequests?: readonly FontMeasurementRequest[];
81
+ };
72
82
  /** The fonts handle `loadFonts()` returns from `/fonts-node` and `/fonts-browser`: pass it as `{ fonts }` to every deck-level function. */
73
83
  export interface FontsHandle extends RenderFonts {
74
84
  readonly textMeasurement: FontRegistry["textMeasurement"];
@@ -82,13 +92,13 @@ export interface FontsHandle extends RenderFonts {
82
92
  /** The substitutions made so far (a requested family drawn with another face), as `registry.substitutions`. */
83
93
  readonly substitutions: FontResolution[];
84
94
  /** Load the script (and, in a browser, vendored) faces the presentation's text needs. Cheap when nothing is missing. */
85
- ensure(presentation: unknown, options?: object): Promise<EnsureResult>;
95
+ ensure(presentation: unknown, options?: FontPreparationOptions): Promise<EnsureResult>;
86
96
  /** Synchronous: the files and script packages `ensure` would load, and in a browser the diagram types (`diagram:<type>`). Empty means a render can start now. */
87
97
  pending(presentation: unknown, renderOptions?: object): string[];
88
98
  /** Remove the faces this handle added to the document (a browser handle). */
89
99
  dispose?(): void;
90
100
  }
91
- export interface FaceDescription { family:string; weight:number; italic:boolean; scripts?:string[] }
101
+ export interface FaceDescription { family:string; weight:number; italic:boolean; scripts?:string[]; /** Present when selection metadata is requested. */ familyGroup?:string }
92
102
  export interface FontRegistry {
93
103
  textMeasurement: TextMeasurement & {outlineBounds: NonNullable<TextMeasurement['outlineBounds']>; resolveFont(style: TextStyle): FontResolution};
94
104
  clearSubstitutions(): void;
@@ -97,7 +107,7 @@ export interface FontRegistry {
97
107
  /** Embedded faces matching `predicate`; large script faces can stay with raster fontFiles. */
98
108
  selectEmbeddedFonts(predicate: (face: FaceDescription) => boolean): EmbeddedFont[];
99
109
  /** Parsed face metadata in entry order, without encoding font bytes. */
100
- describeFaces(): FaceDescription[];
110
+ describeFaces(options?: {selection?: boolean}): FaceDescription[];
101
111
  /** Every face as `{ family, data }`, the bytes the registry measures with. */
102
112
  exportFaces(): { family: string; data: Uint8Array }[];
103
113
  readonly substitutions: FontResolution[];
package/dist/hb-shape.js CHANGED
@@ -116,10 +116,10 @@ function shaperOver(instance, state) {
116
116
  const carrier = carriers.get(glyph.cluster);
117
117
  if (!carrier || (carrier.advance === 0 && glyph.advance !== 0)) carriers.set(glyph.cluster, glyph);
118
118
  }
119
- for (const glyph of glyphs) {
120
- if (carriers.get(glyph.cluster) !== glyph) { glyph.codePoints = []; continue; }
121
- const end = starts[starts.indexOf(glyph.cluster) + 1] ?? units;
122
- glyph.codePoints = [...text.slice(glyph.cluster, end)].map((character) => character.codePointAt(0));
119
+ for (const glyph of glyphs) glyph.codePoints = [];
120
+ for (let index = 0; index < starts.length; index++) {
121
+ const start = starts[index], end = starts[index + 1] ?? units;
122
+ carriers.get(start).codePoints = [...text.slice(start, end)].map((character) => character.codePointAt(0));
123
123
  }
124
124
  return glyphs.map(({ gid, codePoints, advance, xOffset, yOffset }) => ({ gid, codePoints, advance, xOffset, yOffset }));
125
125
  } finally {
package/dist/index.d.ts CHANGED
@@ -28,6 +28,12 @@ export declare const engineDefaults: Readonly<{
28
28
  }>;
29
29
 
30
30
  export type RenderDiagnostic = LayoutDiagnostic | {
31
+ /** A generated RTL numbered marker stayed text; this PNG/raster-PDF marker is not direction-qualified. */
32
+ code: "raster-marker-unavailable";
33
+ reason: "unresolved" | "restricted" | "colour-font" | "shaping" | "system-fonts";
34
+ fontFamily?: string;
35
+ message: string;
36
+ } | {
31
37
  /** LH-145: a picture background could not be read or decoded by `measurePictures`; its scrim is sized for any picture. */
32
38
  code: "picture-not-measured";
33
39
  path: string;