@openpresentation/opf-render 0.32.1 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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";
@@ -130,9 +131,9 @@ export function pickFace(faces, family, style, {policy = "none", aliases = new M
130
131
  const metricFallback = policy!=="visual" && candidate?.metricModeFallback===true && [400,700].includes(weight);
131
132
  const allowVisual = policy==="visual" || metricFallback;
132
133
  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;
134
+ // A weight-named family keeps its lighter base weight. Native bold on Light/Semilight
135
+ // is a modest emphasis, not the Bold face of the parent family (LH-177).
136
+ const wanted = candidate.weight ? (weight>=600 ? candidate.weight<400 ? 400 : Math.max(candidate.weight,700) : candidate.weight) : weight;
136
137
  for (const [index, substitute] of candidate.substitutes.entries()) {
137
138
  // Only the declared replacement can carry the row's metric claim; an alternate is visual.
138
139
  const substituteTier = index===0 ? tier : "visual";
@@ -164,11 +165,11 @@ export function pickFace(faces, family, style, {policy = "none", aliases = new M
164
165
  return {face, compatibility, rule, styleFallback, via, ...(encoding ? {encoding} : {})};
165
166
  }
166
167
 
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.");
168
+ export function createFontRegistry(entries, options = {}, {allowEmpty = false, controls} = {}) {
169
+ if (!Array.isArray(entries) || !entries.length && !allowEmpty) throw new OPFFontError("empty-font-registry", "Supply at least one font file.");
169
170
  const makeFace = entry => {
170
171
  if (!(entry.data instanceof Uint8Array)) throw new OPFFontError("invalid-font-data", "Font data must be a Uint8Array.");
171
- const data = entry.data.slice();
172
+ const data = new Uint8Array(entry.data);
172
173
  let font;
173
174
  try { font = create(data, entry.postscriptName); } catch (error) { throw new OPFFontError("invalid-font-data", error.message); }
174
175
  if (!font?.layout || !font.unitsPerEm) throw new OPFFontError("font-collection", "Select one font from a collection with postscriptName.");
@@ -177,8 +178,7 @@ export function createFontRegistry(entries, options = {}) {
177
178
  // OpenType groups Medium/SemiBold/ExtraBold under a preferred family, while
178
179
  // retaining separate legacy families for four-style native font selectors.
179
180
  // 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);
181
+ const familyGroup = validFamily(selectionFamilyGroup(font, entry.family ?? family));
182
182
  const linking = font['OS/2']?.fsSelection ?? font.head?.macStyle;
183
183
  const fontFace = linking && typeof linking.bold === 'boolean' && typeof linking.italic === 'boolean'
184
184
  ? {family:validFamily(font.getName?.('fontFamily', 'en') ?? font.familyName ?? family),bold:linking.bold,italic:linking.italic} : undefined;
@@ -201,8 +201,11 @@ export function createFontRegistry(entries, options = {}) {
201
201
  return hash;
202
202
  },license:entry.license,embed:entry.embed,scripts,fallbackOnly:entry.fallbackOnly===true,cache:new Map()};
203
203
  };
204
- let shaper;
204
+ let shaper, ownedShaper, ownedBackend = true;
205
205
  const faces = [], duplicates = new Set(), familySlots = new Map();
206
+ // Bumped whenever the held faces or what selection reads of them (their scripts, fallbackOnly) change: addFaces, activateScriptFamilies.
207
+ // A cache of selection results (lazyFontNames) compares this number instead of describing every face on every call.
208
+ let generation = 0;
206
209
  // Adds faces atomically: every check runs before any face is registered.
207
210
  const register = added => {
208
211
  const ids = new Set(duplicates), slots = new Map(familySlots);
@@ -217,6 +220,7 @@ export function createFontRegistry(entries, options = {}) {
217
220
  slots.set(id,face);
218
221
  }
219
222
  faces.push(...added);
223
+ generation++;
220
224
  for (const id of ids) duplicates.add(id);
221
225
  for (const [id,face] of slots) familySlots.set(id,face);
222
226
  };
@@ -230,6 +234,14 @@ export function createFontRegistry(entries, options = {}) {
230
234
  aliases = new Map(Object.entries({...scriptAliases,...options.aliases}).map(([from,to])=>[validFamily(from).toLowerCase(),validFamily(to)]));
231
235
  };
232
236
  buildAliases();
237
+ // Private loader control: a fallback first loaded for coverage may later be explicitly selected by a script font scheme.
238
+ if (controls) controls.activateScriptFamilies = families => {
239
+ const named = new Set(families.map(family=>family.toLowerCase()));
240
+ let changed = false;
241
+ for (const face of faces) if (face.fallbackOnly && named.has(face.family.toLowerCase())) { face.fallbackOnly = false; changed = true; }
242
+ if (changed) { buildAliases(); substitutions.clear(); generation++; }
243
+ return changed;
244
+ };
233
245
  const policy = options.substitutionPolicy ?? "none";
234
246
  if (!["none","metric","visual"].includes(policy)) throw new OPFFontError("invalid-font-policy", "substitutionPolicy must be none, metric, or visual.");
235
247
  if (options.fallbackFamily) validFamily(options.fallbackFamily);
@@ -258,6 +270,11 @@ export function createFontRegistry(entries, options = {}) {
258
270
  const resolveFace = style => resolve(style).face;
259
271
  const resolveStyle = style => {
260
272
  const {face,resolution}=resolve(style),resolved={...style,fontFamily:face.family,fontWeight:face.weight,italic:face.italic};
273
+ // A rich run's explicit bold flag must link from the named lightweight family, not its parent replacement.
274
+ const sourceWeight = fontPolicyFor(resolution.sourceFamily)?.replacement?.weight;
275
+ if (resolution.substitute && sourceWeight && sourceWeight<400) resolved.sourceFontFamily=resolution.sourceFamily;
276
+ else if (style.sourceFontFamily && fontPolicyFor(style.sourceFontFamily)?.replacement?.family===face.family) resolved.sourceFontFamily=style.sourceFontFamily;
277
+ else delete resolved.sourceFontFamily;
261
278
  // Never carry a stale selection from a previously resolved style.
262
279
  delete resolved.fontFace;
263
280
  delete resolved.symbolEncoding;
@@ -270,16 +287,10 @@ export function createFontRegistry(entries, options = {}) {
270
287
  else if(style.symbolEncoding && symbolPreviewFaces(style.symbolEncoding).some(name=>name.toLowerCase()===face.family.toLowerCase())) resolved.symbolEncoding=symbolEncodingFamily(style.symbolEncoding);
271
288
  return resolved;
272
289
  };
273
- const metrics = (text,size,style,includeOutline=false) => {
290
+ const validateMeasurementInput = (text,size) => {
274
291
  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) {
292
+ };
293
+ const checkGlyphCoverage = (face,text,style) => {
283
294
  if (options.strictGlyphs!==false) for(const character of text) {
284
295
  if (/\p{Default_Ignorable_Code_Point}/u.test(character)) continue;
285
296
  const code=character.codePointAt(0);
@@ -289,8 +300,29 @@ export function createFontRegistry(entries, options = {}) {
289
300
  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
301
  }
291
302
  }
303
+ };
304
+ if (controls) {
305
+ // Node-only preparation control. It never supplies geometry or populates metric caches.
306
+ controls.probeGlyphs = (text,size,style) => { validateMeasurementInput(text,size); const {face}=resolve(style); checkGlyphCoverage(face,text,style); };
307
+ controls.canProbeGlyphs = () => ownedBackend && shaper === ownedShaper;
308
+ // Called only by the local fonts-node handoff after it attaches its own default outline adapter.
309
+ controls.acceptOwnedShaper = () => { ownedShaper=shaper; ownedBackend=true; };
310
+ }
311
+ const metrics = (text,size,style,includeOutline=false) => {
312
+ validateMeasurementInput(text,size);
313
+ const {face,resolution}=resolve(style);
314
+ // Automatic and explicit direction requests have separate keys. A cache hit
315
+ // needs neither Unicode direction analysis nor OpenType language lookup.
316
+ const directionKey = style.direction == null ? "auto" : `explicit:${style.direction}`;
317
+ const key = `${directionKey}\u0000${style.lang ?? ""}\u0000${text}`;
318
+ let value=face.cache.get(key);
319
+ if (value===undefined) {
320
+ checkGlyphCoverage(face,text,style);
292
321
  }
293
322
  if(value===undefined||includeOutline&&!Object.hasOwn(value,'outline')) {
323
+ // A width-only entry is shaped again when its outline is first requested.
324
+ const language = openTypeLanguage(style.lang);
325
+ const direction = style.direction ?? (bidi.getEmbeddingLevels(text).paragraphs[0]?.level % 2 ? "rtl" : "ltr");
294
326
  // FF-31: features a policy row turns off in its replacement (Gelasio for Georgia: liga, clig), the
295
327
  // same ones the SVG output turns off, so measured and drawn advances agree.
296
328
  const off=disabledFeaturesFor(face.family),policyFeatures=off&&Object.fromEntries(off.map(tag=>[tag,false]));
@@ -356,11 +388,13 @@ export function createFontRegistry(entries, options = {}) {
356
388
  // validate asks for each slide's measurement, so its layout checks measure script runs in the faces this renderer draws.
357
389
  const textMeasurement={measure,resolveStyle,outlineBounds,resolveFont:style=>resolve(style).resolution};
358
390
  textMeasurement.forScripts=profile=>createScriptFonts(profile,textMeasurement).textMeasurement;
359
- return {
391
+ const registry = {
360
392
  textMeasurement,
361
393
  // Attach the handle's outline shaper after its WASM loads. Earlier measurements must not survive the engine switch.
362
394
  setShaper(engine) {
363
395
  shaper = engine;
396
+ // A public setter call is never a trusted Node-owned attachment.
397
+ ownedBackend = false;
364
398
  for (const face of faces) face.cache.clear();
365
399
  },
366
400
  resolveFont(style) { return resolve(style).resolution; },
@@ -370,7 +404,7 @@ export function createFontRegistry(entries, options = {}) {
370
404
  // `loadFonts` handle's embeddedFonts). Whichever list it is given, the SVG writer embeds a face only where its text draws it (RR-61).
371
405
  get embeddedFonts() { return embedded(face=>face.embed!=="used"); },
372
406
  /** 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}:{})})),
407
+ 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
408
  /** Embedded faces for which `predicate({family,weight,italic,scripts})` holds; large script faces can be left to raster fontFiles. */
375
409
  selectEmbeddedFonts: predicate=>embedded(predicate),
376
410
  /** Every face as `{family, data}` (the bytes the registry measures with), for the browser PDF export to embed. */
@@ -391,5 +425,8 @@ export function createFontRegistry(entries, options = {}) {
391
425
  return made.map(face=>({family:face.family,weight:face.weight,italic:face.italic,...(face.scripts?{scripts:[...face.scripts]}:{})}));
392
426
  },
393
427
  };
428
+ // Not part of the public registry (like fontNames): the number lazyFontNames compares to know the face pool changed.
429
+ Object.defineProperty(registry, "facesGeneration", { get: () => generation });
430
+ return registry;
394
431
  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
432
  }
@@ -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
- import { diagramsPending, ensureDiagrams } from "@openpresentation/opf/composition";
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
@@ -335,6 +339,9 @@ export async function loadFonts({ faces = [], subsetWasm, shapeWasm, ...options
335
339
  // `ensure` loads it first, since the font analysis measures a diagram's labels only once its type is loaded.
336
340
  const pending = (presentation, renderOptions) => [
337
341
  ...diagramsPending(presentation).map((type) => `diagram:${type}`),
342
+ ...shapesPending(presentation),
343
+ // LH-14: an icon set the presentation names that is not loaded yet (a registered loader, such as the gallery's) is pending as `icons:<set>`.
344
+ ...iconsPending(presentation, { catalogs: renderOptions?.catalogs ?? options.renderOptions?.catalogs }).sets.map((set) => `icons:${set}`),
338
345
  ...registry.pendingLazyFonts(presentation, renderOptions).map((face) => face.file),
339
346
  ...registry.pendingScripts(presentation, renderOptions),
340
347
  ];
@@ -349,23 +356,33 @@ export async function loadFonts({ faces = [], subsetWasm, shapeWasm, ...options
349
356
  manifest: BUNDLED_FONT_MANIFEST,
350
357
  get substitutions() { return registry.substitutions; },
351
358
  /**
352
- * Load the diagram types the presentation draws (core loads each on demand in a browser), then the vendored and script faces
359
+ * Load the diagram types and the icon sets the presentation draws (core loads each on demand: the sets from `catalogs`, LH-14), then the vendored and script faces
353
360
  * it draws, each hash-verified, all or nothing, and repeat while loading
354
361
  * changes what is needed (a script face can need a vendored one). Cheap when nothing is needed. Besides `signal`, the call
355
362
  * takes the `toSvg` options the document resolves with (`catalogs`, ...) over the loader's `renderOptions`. A document that
356
363
  * does not resolve rejects with what `toSvg` throws for it. After `dispose()` it rejects with `font-registry-disposed`.
357
364
  */
358
365
  async ensure(presentation, callOptions = {}) {
366
+ const measurements=fontMeasurementRequests(callOptions.measurementRequests);
359
367
  const diagrams = await ensureDiagrams(presentation);
368
+ // SH-02: the preset geometry, the first time the deck has a shape (core loads it on demand in a browser).
369
+ await ensureShapes(presentation);
370
+ await ensureIcons(presentation, { catalogs: callOptions.catalogs ?? options.renderOptions?.catalogs });
360
371
  const lazy = [], scripts = [];
361
372
  let uncovered = [];
362
- for (let round = 0; round < MAX_ENSURE_ROUNDS; round++) {
363
- const needLazy = registry.pendingLazyFonts(presentation, callOptions).length > 0, needScripts = registry.pendingScripts(presentation, callOptions).length > 0;
364
- 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
+ }
365
381
  callOptions.signal?.throwIfAborted?.();
366
- if (needLazy) lazy.push(...(await registry.ensureLazyFonts(presentation, callOptions)));
382
+ if (needLazy.length) lazy.push(...(await registry.ensureLazyFonts(presentation, callOptions)));
367
383
  if (needScripts) { const result = await registry.ensureScripts(presentation, callOptions); scripts.push(...result.loaded); uncovered = result.uncovered; }
368
384
  }
385
+ for(const request of measurements)if(request.text!=='')registry.textMeasurement.measure(request.text,request.size,request.style);
369
386
  return { scripts, lazy, uncovered, ...(diagrams.length ? { diagrams } : {}) };
370
387
  },
371
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>;
@@ -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)};
@@ -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;