@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,673 @@
1
+ // RR-114: Node face-level preparation. The complete allowed metadata decides selection; only selected bytes are read.
2
+ import { BUNDLED_FONT_MANIFEST } from './font-manifest.js';
3
+ import { FONT_SELECTION_METADATA } from './font-selection-metadata.js';
4
+ import { createFontRegistry, pickFace, OPFFontError } from './font-registry.js';
5
+ import { createFontAnalysis } from './lazy-fonts.js';
6
+ import { scriptFontAliases } from './script-fonts.js';
7
+ import {
8
+ analyzePresentationScripts,
9
+ createScriptAnalysis,
10
+ nextFallbackPackage,
11
+ scriptFontPackages,
12
+ scriptSelectionOf,
13
+ uncoveredCjkCharacters,
14
+ } from './script-font-pack.js';
15
+
16
+ // Font loading, script fallback packages and real-metrics passes each take a round; a deck settles in a few.
17
+ const MAX_ENSURE_ROUNDS = 64;
18
+ const key = (face) =>
19
+ String(face.family).toLowerCase() + '\0' + face.weight + '\0' + !!face.italic;
20
+ const packageKey = (pkg, face) => pkg.name + '\0' + face.file;
21
+ const groups = new Map(
22
+ FONT_SELECTION_METADATA.map((face) => [
23
+ face.package + '\0' + face.file,
24
+ face,
25
+ ]),
26
+ );
27
+ function candidate(pkg, face, fallbackOnly = false) {
28
+ const group = groups.get(packageKey(pkg, face));
29
+ if (group && group.sha256 !== face.sha256)
30
+ throw new OPFFontError(
31
+ 'font-selection-metadata-mismatch',
32
+ 'Regenerate selection metadata for the reviewed font manifest.',
33
+ { package: pkg.name, file: face.file },
34
+ );
35
+ return {
36
+ ...face,
37
+ familyGroup: group?.familyGroup ?? face.family,
38
+ package: pkg.name,
39
+ pkg,
40
+ id: packageKey(pkg, face),
41
+ file: pkg.vendored ? pkg.vendored + '/' + face.file : face.file,
42
+ sourceFile: face.file,
43
+ license: pkg.license,
44
+ ...(pkg.scripts ? { scripts: [...pkg.scripts] } : {}),
45
+ ...(fallbackOnly ? { fallbackOnly: true } : {}),
46
+ };
47
+ }
48
+ const publicFace = (face) => ({
49
+ package: face.package,
50
+ family: face.family,
51
+ weight: face.weight,
52
+ italic: face.italic,
53
+ file: face.file,
54
+ sha256: face.sha256,
55
+ license: face.license,
56
+ });
57
+
58
+ export async function createNodeDemand(
59
+ pack,
60
+ options,
61
+ { loadPackages, callerFaces, renamedAliases },
62
+ ) {
63
+ const registryOptions =
64
+ pack === 'office'
65
+ ? {
66
+ substitutionPolicy: 'metric',
67
+ ...options,
68
+ ...(options.includeOpenFonts === false
69
+ ? {}
70
+ : { aliases: { ...renamedAliases(), ...options.aliases } }),
71
+ }
72
+ : options;
73
+ const own = await callerFaces(options.faces),
74
+ controls = {};
75
+ const registry = createFontRegistry(own.entries, registryOptions, {
76
+ allowEmpty: true,
77
+ controls,
78
+ });
79
+ const loaded = {
80
+ fontFiles: [...own.fontFiles],
81
+ packages: [],
82
+ selection: undefined,
83
+ };
84
+ registry.fontFiles = loaded.fontFiles;
85
+ const callerFaceKeys = new Set(registry.describeFaces().map(key));
86
+ const ownedMeasurement = registry.textMeasurement;
87
+ // The registry's own metrics, before the preparation guard below wraps them: the analysis measures held faces with them (RR-105).
88
+ const ownedMetrics = { measure: ownedMeasurement.measure, outlineBounds: ownedMeasurement.outlineBounds };
89
+ let ownedMeasure = ownedMeasurement.measure, prepareCoverage;
90
+ const coverage = (text,size,style) => {
91
+ // A caller replacement/accessor keeps its original full measurement and this binding.
92
+ const holder=Object.getOwnPropertyDescriptor(registry,'textMeasurement');
93
+ const measurement=registry.textMeasurement;
94
+ const descriptor=measurement===ownedMeasurement ? Object.getOwnPropertyDescriptor(measurement,'measure') : undefined;
95
+ if (holder && Object.hasOwn(holder,'value') && holder.value===ownedMeasurement && descriptor && Object.hasOwn(descriptor,'value') && descriptor.value===ownedMeasure && controls.canProbeGlyphs()) {
96
+ prepareCoverage?.(style);
97
+ controls.probeGlyphs(text,size,style);
98
+ } else measurement.measure(text,size,style);
99
+ };
100
+
101
+ const analysis = createFontAnalysis(),
102
+ scriptMemory = createScriptAnalysis({ fonts: analysis }),
103
+ fallbacks = new Set();
104
+ const skipped = new Set(),
105
+ diagnosed = new Set(),
106
+ order = new Map();
107
+ const remember = (faces) => {
108
+ for (const face of faces)
109
+ if (!order.has(key(face))) order.set(key(face), order.size);
110
+ };
111
+ remember(registry.describeFaces());
112
+ let generation = 0,
113
+ metadata;
114
+ const selections = new Map();
115
+ const pickMetadata = (style) => {
116
+ const requested = style?.fontFamily,
117
+ weight = style?.fontWeight ?? 400;
118
+ if (
119
+ typeof requested !== 'string' ||
120
+ !requested.trim() ||
121
+ /[\u0000-\u001f"'\\<>;]/.test(requested)
122
+ )
123
+ throw new OPFFontError(
124
+ 'invalid-font-family',
125
+ 'Font family must be a nonempty plain name.',
126
+ );
127
+ if (!Number.isFinite(weight) || weight < 1 || weight > 1000)
128
+ throw new OPFFontError(
129
+ 'invalid-font-weight',
130
+ 'Font weight must be between 1 and 1000.',
131
+ );
132
+ const theme = {
133
+ '+mj-lt': 'majorLatin',
134
+ '+mn-lt': 'minorLatin',
135
+ '+mj-ea': 'majorEastAsia',
136
+ '+mn-ea': 'minorEastAsia',
137
+ '+mj-cs': 'majorComplexScript',
138
+ '+mn-cs': 'minorComplexScript',
139
+ }[requested.toLowerCase()];
140
+ if (requested.startsWith('+') && !theme)
141
+ throw new OPFFontError(
142
+ 'unresolved-theme-font',
143
+ "Unknown theme font '" + requested + "'.",
144
+ { path: style.path },
145
+ );
146
+ const family = theme ? registryOptions.themeFonts?.[theme] : requested;
147
+ if (!family || family.startsWith('+'))
148
+ throw new OPFFontError(
149
+ 'unresolved-theme-font',
150
+ "Supply a concrete theme family for '" + requested + "'.",
151
+ { path: style.path },
152
+ );
153
+ const id = key({ family, weight, italic: !!style.italic });
154
+ let selected = selections.get(id);
155
+ if (!selected) {
156
+ selected = pickFace(metadata.faces, family, style, {
157
+ policy: registryOptions.substitutionPolicy ?? 'none',
158
+ aliases: metadata.aliases,
159
+ fallbackFamily: registryOptions.fallbackFamily,
160
+ });
161
+ if (selections.size >= 512) selections.clear();
162
+ selections.set(id, selected);
163
+ }
164
+ return selected;
165
+ };
166
+ // Role names need selection metadata, not physical glyphs. Actual drawing always keeps the real byte-backed measurement.
167
+ Object.defineProperty(registry, 'fontNames', {
168
+ value: {
169
+ resolveStyle(style) {
170
+ try {
171
+ const { face } = pickMetadata(style);
172
+ const resolved = {
173
+ ...style,
174
+ fontFamily: face.family,
175
+ fontWeight: face.weight,
176
+ italic: face.italic,
177
+ };
178
+ delete resolved.fontFace;
179
+ return resolved;
180
+ } catch (error) {
181
+ if (
182
+ ![
183
+ 'font-unavailable',
184
+ 'font-style-unavailable',
185
+ 'font-encoding-required',
186
+ ].includes(error.code)
187
+ )
188
+ throw error;
189
+ return { ...style };
190
+ }
191
+ },
192
+ resolveFont(style) {
193
+ try {
194
+ const { face, via } = pickMetadata(style);
195
+ return {
196
+ requestedFamily: style.fontFamily,
197
+ resolvedFamily: face.family,
198
+ substitute: via !== 'family',
199
+ };
200
+ } catch (error) {
201
+ if (
202
+ ![
203
+ 'font-unavailable',
204
+ 'font-style-unavailable',
205
+ 'font-encoding-required',
206
+ ].includes(error.code)
207
+ )
208
+ throw error;
209
+ return {
210
+ requestedFamily: style.fontFamily,
211
+ resolvedFamily: style.fontFamily,
212
+ substitute: false,
213
+ };
214
+ }
215
+ },
216
+ },
217
+ });
218
+ function context(presentation, renderOptions, initial = false, mapFamily, preserveChosenFamilies = false, measurementRequests = []) {
219
+ const empty =
220
+ Array.isArray(presentation.slides) && presentation.slides.length === 0;
221
+ const scriptAnalysis = empty
222
+ ? { profile: {}, detected: [], design: [], cjk: new Set() }
223
+ : analyzePresentationScripts(
224
+ presentation,
225
+ undefined,
226
+ renderOptions,
227
+ scriptMemory,
228
+ );
229
+ const mode = initial ? options.scripts : 'auto';
230
+ const selection =
231
+ mode === 'auto'
232
+ ? scriptSelectionOf(scriptAnalysis)
233
+ : { detected: [], scripts: [], unavailable: [] };
234
+ const scripts =
235
+ mode === 'auto'
236
+ ? scriptFontPackages(selection.scripts)
237
+ : mode === undefined
238
+ ? []
239
+ : scriptFontPackages(mode);
240
+ const required = new Set(scripts.map((pkg) => pkg.name));
241
+ const packs =
242
+ pack === 'office'
243
+ ? [
244
+ 'office',
245
+ ...(options.includeOpenFonts === false ? [] : ['open']),
246
+ ...(options.includeBaseFonts === false ? [] : ['base']),
247
+ ]
248
+ : pack === 'base'
249
+ ? ['base']
250
+ : [];
251
+ const packages = packs.flatMap((name) =>
252
+ BUNDLED_FONT_MANIFEST.packages.filter((pkg) => pkg.pack === name),
253
+ );
254
+ if (pack === 'office')
255
+ packages.push(
256
+ ...scriptFontPackages(['Latn']).filter(
257
+ (pkg) => !required.has(pkg.name),
258
+ ),
259
+ );
260
+ packages.push(
261
+ ...scripts,
262
+ ...BUNDLED_FONT_MANIFEST.packages.filter((pkg) =>
263
+ fallbacks.has(pkg.name),
264
+ ),
265
+ );
266
+ const seen = new Set(),
267
+ universe = [];
268
+ for (const pkg of packages) {
269
+ if (seen.has(pkg.name)) continue;
270
+ seen.add(pkg.name);
271
+ for (const face of pkg.faces)
272
+ universe.push(
273
+ candidate(
274
+ pkg,
275
+ face,
276
+ pack === 'office' &&
277
+ pkg.name === '@expo-google-fonts/noto-sans' &&
278
+ !required.has(pkg.name),
279
+ ),
280
+ );
281
+ }
282
+ const held = registry.describeFaces({ selection: true }),
283
+ heldKeys = new Set(held.map(key));
284
+ const faces = [
285
+ ...held,
286
+ ...universe.filter(
287
+ (face) => !heldKeys.has(key(face)) && !skipped.has(face.package),
288
+ ),
289
+ ];
290
+ const aliases = new Map(
291
+ Object.entries({
292
+ ...scriptFontAliases(
293
+ new Set(
294
+ faces
295
+ .filter((face) => face.scripts && !face.fallbackOnly)
296
+ .map((face) => face.family),
297
+ ),
298
+ ),
299
+ ...registryOptions.aliases,
300
+ }).map(([from, to]) => [from.toLowerCase(), to]),
301
+ );
302
+ const drawn =
303
+ Array.isArray(presentation.slides) && presentation.slides.length === 0
304
+ ? []
305
+ : analysis.faces(presentation, renderOptions, {
306
+ faces,
307
+ policy: registryOptions.substitutionPolicy ?? 'none',
308
+ aliases,
309
+ fallbackFamily: registryOptions.fallbackFamily,
310
+ coverageKey: generation,
311
+ mapFamily,
312
+ preserveChosenFamilies,
313
+ // RR-105: the real-metrics pass, so every face a real-width branch measures is prepared (see lazy-fonts.js).
314
+ metrics: { ...ownedMetrics, held },
315
+ coverage(text, size, style) {
316
+ if (
317
+ heldKeys.has(
318
+ key({
319
+ family: style.fontFamily,
320
+ weight: style.fontWeight ?? 400,
321
+ italic: !!style.italic,
322
+ }),
323
+ )
324
+ )
325
+ coverage(text, size, style);
326
+ else if (
327
+ !faces.some(
328
+ (face) =>
329
+ key(face) ===
330
+ key({
331
+ family: style.fontFamily,
332
+ weight: style.fontWeight ?? 400,
333
+ italic: !!style.italic,
334
+ }),
335
+ )
336
+ )
337
+ throw new OPFFontError(
338
+ 'font-unavailable',
339
+ 'No allowed candidate for this coverage probe.',
340
+ { path: style.path, fontFamily: style.fontFamily },
341
+ );
342
+ },
343
+ });
344
+ // Exporters may measure undrawn text (native wrap slack). Keep those explicit requests out of the SVG analysis/cache.
345
+ const measured = measurementRequests.filter(request => request.text !== '').map(request => {
346
+ const style = request.style;
347
+ const selected = pickFace(faces, style.fontFamily, style, {
348
+ policy: registryOptions.substitutionPolicy ?? 'none', aliases,
349
+ fallbackFamily: registryOptions.fallbackFamily,
350
+ }).face;
351
+ return {request, selected};
352
+ });
353
+ const wanted = new Set([...drawn, ...measured.map(({selected}) => selected)].map(key)), rasterRequired = new Set();
354
+ // A selected manifest colour face also needs its effective monochrome raster face.
355
+ // This is a dependency of the drawn face, not another script/pack or a caller-face substitution.
356
+ for (const face of universe) {
357
+ if (!wanted.has(key(face)) || callerFaceKeys.has(key(face)) || !face.pkg.color?.rasterFamily) continue;
358
+ const companion = pickFace(universe, face.pkg.color.rasterFamily, {fontWeight: face.weight, italic: face.italic}).face;
359
+ wanted.add(key(companion));
360
+ rasterRequired.add(companion.id);
361
+ }
362
+ return {
363
+ scriptAnalysis,
364
+ measured,
365
+ selection,
366
+ mode,
367
+ required,
368
+ orderedPackages: packages,
369
+ metadata: { faces, aliases },
370
+ universe,
371
+ rasterRequired,
372
+ needed: universe.filter(
373
+ (face) =>
374
+ wanted.has(key(face)) &&
375
+ !heldKeys.has(key(face)) &&
376
+ (!skipped.has(face.package) || rasterRequired.has(face.id)),
377
+ ),
378
+ };
379
+ }
380
+ function notify(code, details, message, diagnostic) {
381
+ const id = code + '\0' + (details.package ?? details.script);
382
+ if (diagnosed.has(id)) return;
383
+ diagnosed.add(id);
384
+ diagnostic?.({ code, ...details, message });
385
+ }
386
+ async function ensure(
387
+ presentation,
388
+ {
389
+ onDiagnostic = options.onDiagnostic,
390
+ renderOptions = options.renderOptions,
391
+ initial = false,
392
+ mapFamily,
393
+ preserveChosenFamilies = false,
394
+ measurementRequests = [],
395
+ } = {},
396
+ ) {
397
+ if (presentation === null || typeof presentation !== 'object')
398
+ throw new OPFFontError(
399
+ 'invalid-font-scripts',
400
+ 'ensure needs the presentation whose text decides its fonts.',
401
+ );
402
+ if (!Array.isArray(measurementRequests) || measurementRequests.some(request =>
403
+ !request || typeof request.text !== 'string' || !Number.isFinite(request.size) || request.size <= 0 ||
404
+ !request.style || typeof request.style.fontFamily !== 'string' || !request.style.fontFamily.trim() ||
405
+ !Number.isFinite(request.style.fontWeight ?? 400) || (request.style.fontWeight ?? 400) < 1 || (request.style.fontWeight ?? 400) > 1000))
406
+ throw new OPFFontError('invalid-font-measurement-request', 'Measurement requests need text, a positive finite size, and a concrete font style.');
407
+ const added = [],
408
+ addedPackages = new Set();
409
+ for (let round = 0; ; round++) {
410
+ const plan = context(presentation, renderOptions, initial, mapFamily, preserveChosenFamilies, measurementRequests);
411
+ // Preserve the historical whole-pack CSS order, independently of which styles an edit happens to add first.
412
+ for (const pkg of plan.orderedPackages) remember(pkg.faces);
413
+ if (plan.mode === 'auto') {
414
+ const selection = (loaded.selection ??= {
415
+ detected: [],
416
+ scripts: [],
417
+ unavailable: [],
418
+ packages: [],
419
+ notInstalled: [],
420
+ });
421
+ registry.scriptSelection = selection;
422
+ for (const name of ['detected', 'scripts', 'unavailable'])
423
+ for (const value of plan.selection[name])
424
+ if (!selection[name].includes(value)) selection[name].push(value);
425
+ for (const script of plan.selection.unavailable)
426
+ notify(
427
+ 'script-font-unavailable',
428
+ { script },
429
+ "No pinned open font serves script '" +
430
+ script +
431
+ "'; that text uses the design font.",
432
+ onDiagnostic,
433
+ );
434
+ }
435
+ if (
436
+ controls.activateScriptFamilies?.(
437
+ plan.universe
438
+ .filter((face) => face.scripts && !face.fallbackOnly)
439
+ .map((face) => face.family),
440
+ )
441
+ ) {
442
+ generation++;
443
+ continue;
444
+ }
445
+ metadata = plan.metadata;
446
+ selections.clear();
447
+ if (plan.needed.length && round >= MAX_ENSURE_ROUNDS)
448
+ throw new OPFFontError(
449
+ 'font-preparation-unsettled',
450
+ 'Preparing the fonts of this presentation did not settle: each pass measured faces the one before had not prepared.',
451
+ { faces: plan.needed.map(publicFace) },
452
+ );
453
+ if (plan.needed.length) {
454
+ const selected = [];
455
+ for (const face of plan.needed) {
456
+ let pkg = selected.find((pkg) => pkg.name === face.package);
457
+ if (!pkg) selected.push((pkg = { ...face.pkg, faces: [] }));
458
+ pkg.faces.push({ ...face, file: face.sourceFile });
459
+ }
460
+ const missing = [],
461
+ required = (pkg) => plan.mode !== 'auto' || !pkg.scripts || pkg.faces.some((face) => plan.rasterRequired.has(face.id)),
462
+ mandatory = selected.filter(required),
463
+ optional = selected.filter((pkg) => !required(pkg));
464
+ const batches = await Promise.all([
465
+ loadPackages(mandatory, undefined, {
466
+ what: 'The presentation selected font faces',
467
+ }),
468
+ loadPackages(optional, missing),
469
+ ]);
470
+ const successfulPackages = new Set(batches.flatMap((batch) => batch.packages).filter((name) => !missing.some((item) => item.package === name)));
471
+ const extra = {
472
+ entries: batches.flatMap((batch) => batch.entries),
473
+ fontFiles: batches.flatMap((batch) => batch.fontFiles),
474
+ packages: selected.map((pkg) => pkg.name).filter((name) => successfulPackages.has(name)), // Actual successes, in declared selection order.
475
+ };
476
+ if (extra.entries.length) {
477
+ registry.addFaces(
478
+ extra.entries.map((entry) =>
479
+ entry.scripts ? { ...entry, embed: 'used' } : entry,
480
+ ),
481
+ );
482
+ loaded.fontFiles.push(...extra.fontFiles);
483
+ generation++;
484
+ }
485
+ for (const pkg of extra.packages) {
486
+ if (
487
+ !missing.some((item) => item.package === pkg) &&
488
+ !loaded.packages.includes(pkg)
489
+ ) {
490
+ loaded.packages.push(pkg);
491
+ if (selected.find((item) => item.name === pkg)?.scripts)
492
+ addedPackages.add(pkg);
493
+ }
494
+ }
495
+ for (const face of plan.needed)
496
+ if (!missing.some((item) => item.package === face.package)) {
497
+ if (plan.rasterRequired.has(face.id)) {
498
+ skipped.delete(face.package);
499
+ if (loaded.selection) loaded.selection.notInstalled = loaded.selection.notInstalled.filter((name) => name !== face.package);
500
+ }
501
+ added.push(publicFace(face));
502
+ }
503
+ for (const item of missing) {
504
+ skipped.add(item.package);
505
+ if (
506
+ loaded.selection &&
507
+ !loaded.selection.notInstalled.includes(item.package)
508
+ )
509
+ loaded.selection.notInstalled.push(item.package);
510
+ notify(
511
+ 'script-font-not-installed',
512
+ { package: item.package, version: item.version, scripts: item.scripts },
513
+ 'Install ' +
514
+ item.package +
515
+ '@' +
516
+ item.version +
517
+ ' to preview ' +
518
+ item.scripts.join(', ') +
519
+ ' text with its designated open font.',
520
+ onDiagnostic,
521
+ );
522
+ }
523
+ continue;
524
+ }
525
+ if (plan.mode === 'auto') {
526
+ const covers = (character) => registry.scriptFacesCover(character),
527
+ seen = new Set([...loaded.packages, ...skipped, ...fallbacks]);
528
+ const next = nextFallbackPackage(plan.scriptAnalysis, {
529
+ covers,
530
+ loaded: seen,
531
+ });
532
+ if (next) {
533
+ fallbacks.add(next.name);
534
+ generation++;
535
+ continue;
536
+ }
537
+ const uncovered = uncoveredCjkCharacters(plan.scriptAnalysis, {
538
+ covers,
539
+ limit: 8,
540
+ });
541
+ if (uncovered.length || Object.hasOwn(loaded.selection, 'uncovered'))
542
+ loaded.selection.uncovered = uncovered;
543
+ if (uncovered.length)
544
+ notify(
545
+ 'script-glyph-uncovered',
546
+ { script: uncovered.join(''), characters: uncovered },
547
+ 'No loaded script face covers some drawn characters; the renderer reports missing-glyph for them.',
548
+ onDiagnostic,
549
+ );
550
+ // Physical reads can complete across several coverage passes. Report this ensure batch
551
+ // in the declared package order while retaining the already-reported prior-ensure prefix.
552
+ for (const {name} of plan.orderedPackages)
553
+ if (
554
+ loaded.packages.includes(name) &&
555
+ (plan.required.has(name) || fallbacks.has(name)) &&
556
+ !loaded.selection.packages.includes(name)
557
+ )
558
+ loaded.selection.packages.push(name);
559
+ }
560
+ for (const {request, selected} of plan.measured)
561
+ coverage(request.text, request.size, {...request.style, fontFamily: selected.family, fontWeight: selected.weight, italic: selected.italic});
562
+ return {
563
+ scripts: [...addedPackages],
564
+ lazy: added,
565
+ uncovered: [...(loaded.selection?.uncovered ?? [])],
566
+ };
567
+ }
568
+ }
569
+ function pending(presentation, renderOptions = options.renderOptions) {
570
+ const plan = context(presentation, renderOptions);
571
+ if (plan.needed.length)
572
+ return [
573
+ ...new Set(
574
+ plan.needed.map((face) => face.package + '/' + face.sourceFile),
575
+ ),
576
+ ];
577
+ const next = nextFallbackPackage(plan.scriptAnalysis, {
578
+ covers: (character) => registry.scriptFacesCover(character),
579
+ loaded: new Set([...loaded.packages, ...skipped, ...fallbacks]),
580
+ });
581
+ return next ? [next.name] : [];
582
+ }
583
+ await ensure(options.presentation, { initial: true });
584
+ // Style lookup is metadata-only. Never silently substitute a held weight when the full pack would select an unprepared face.
585
+ const real = { ...registry.textMeasurement },
586
+ realFont = registry.resolveFont;
587
+ let heldKeys = new Set(registry.describeFaces().map(key));
588
+ const add = registry.addFaces;
589
+ registry.addFaces = (entries) => {
590
+ const result = add(entries);
591
+ heldKeys = new Set(registry.describeFaces().map(key));
592
+ return result;
593
+ };
594
+ const prepared = (style) => {
595
+ let selected;
596
+ try {
597
+ selected = pickMetadata(style);
598
+ } catch (error) {
599
+ if (
600
+ error.code !== 'font-unavailable' &&
601
+ error.code !== 'font-style-unavailable'
602
+ )
603
+ throw error;
604
+ return undefined;
605
+ }
606
+ if (!heldKeys.has(key(selected.face)))
607
+ throw new OPFFontError(
608
+ 'font-unavailable',
609
+ 'The selected face is not prepared; await fonts.ensure(presentation) before measuring this style.',
610
+ {
611
+ path: style.path,
612
+ fontFamily: style.fontFamily,
613
+ fontWeight: selected.face.weight,
614
+ italic: selected.face.italic,
615
+ },
616
+ );
617
+ return selected;
618
+ };
619
+ registry.textMeasurement.resolveStyle = (style) => {
620
+ let selected;
621
+ try {
622
+ selected = pickMetadata(style);
623
+ } catch (error) {
624
+ return real.resolveStyle(style);
625
+ }
626
+ return heldKeys.has(key(selected.face))
627
+ ? real.resolveStyle(style)
628
+ : registry.fontNames.resolveStyle(style);
629
+ };
630
+ registry.textMeasurement.measure = (text, size, style) => {
631
+ prepared(style);
632
+ return real.measure(text, size, style);
633
+ };
634
+ ownedMeasure = registry.textMeasurement.measure;
635
+ prepareCoverage = prepared;
636
+ registry.textMeasurement.outlineBounds = (text, size, style) => {
637
+ prepared(style);
638
+ return real.outlineBounds(text, size, style);
639
+ };
640
+ const resolveFont = (style) => {
641
+ let selected;
642
+ try {
643
+ selected = pickMetadata(style);
644
+ } catch (error) {
645
+ return realFont(style);
646
+ }
647
+ if (heldKeys.has(key(selected.face))) return realFont(style);
648
+ return {
649
+ ...registry.fontNames.resolveFont(style),
650
+ sourceFamily: style.fontFamily,
651
+ requestedWeight: style.fontWeight ?? 400,
652
+ resolvedWeight: selected.face.weight,
653
+ italic: selected.face.italic,
654
+ compatibility: selected.compatibility,
655
+ ...(style.path ? { path: style.path } : {}),
656
+ };
657
+ };
658
+ registry.textMeasurement.resolveFont = resolveFont;
659
+ registry.resolveFont = resolveFont;
660
+
661
+ return {
662
+ registry,
663
+ loaded,
664
+ acceptOwnedShaper: () => controls.acceptOwnedShaper(),
665
+ ensure,
666
+ pending,
667
+ orderFaces: (faces) =>
668
+ faces.sort(
669
+ (a, b) =>
670
+ (order.get(key(a)) ?? Infinity) - (order.get(key(b)) ?? Infinity),
671
+ ),
672
+ };
673
+ }