@real-music-packages/web-core 0.45.0 → 0.45.2

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.
@@ -148,6 +148,22 @@ interface CreateVerovioNotationPlayerOpts {
148
148
  * "why" behind the defaults themselves).
149
149
  */
150
150
  verovioOptions?: VerovioLayoutOptions;
151
+ /**
152
+ * TEST-ONLY SEAM — not part of this player's real production behavior.
153
+ * When set, `engraveOnce`'s fit-pass/fallback-decision math reads system
154
+ * widths from this function (called with `svgHost`) instead of
155
+ * `currentLayout.systems`. Exists because jsdom implements neither
156
+ * `getBBox` nor a real `getBoundingClientRect` (both always report
157
+ * zero-size boxes), so `currentLayout.systems` widths — and therefore
158
+ * `fitZoomFactor`'s result — are always 0/`1` (fits) in a headless test
159
+ * regardless of how dense the underlying MusicXML actually is. A test can
160
+ * pass a fixed fake (e.g. `() => [1200]`) to exercise the readability-floor
161
+ * fallback (`VerovioLayoutOptions.minFitFactor`) end-to-end against a REAL
162
+ * Verovio engrave, asserting on the resulting DOM shape
163
+ * (`systemMeasureCounts`) rather than on geometry a real browser would be
164
+ * needed to produce. Never used by any real caller.
165
+ */
166
+ measureSystemWidths?: (root: Element) => number[];
151
167
  }
152
168
  interface VerovioNotationPlayer {
153
169
  /** Resolves once the engraving is in the DOM and ready to draw. `setTime`/
@@ -202,6 +218,21 @@ interface VerovioNotationPlayer {
202
218
  * INSTANCE" note) — it is reused by the next player, if any. */
203
219
  destroy(): void;
204
220
  }
221
+ /**
222
+ * Rendered measure count per SYSTEM, in DOCUMENT ORDER (`.system` elements
223
+ * across every `.vrv-page`, each one's OWN `.measure` descendant count) —
224
+ * the widow-detection input for `engraveOnce`'s widow pass (see that
225
+ * function's own doc). Deliberately PLAIN DOM traversal — no
226
+ * `getBoundingClientRect`/geometry involved at all, unlike
227
+ * `verovioNotationLayout`/`collectMeasureElements` (which both need a real
228
+ * layout engine to report non-zero boxes) — so this works against ANY
229
+ * rendered SVG DOM, including jsdom's own (which reports zero-size rects for
230
+ * everything by default): a real Verovio render loaded into jsdom is enough
231
+ * to exercise the widow pass end-to-end purely by DOM shape, with no
232
+ * `getBoundingClientRect` mocking required (see this module's real-Verovio
233
+ * widow test). Never throws; a root with no `.system` elements yields `[]`.
234
+ */
235
+ declare function systemMeasureCounts(root: Element): number[];
205
236
  /**
206
237
  * Pure(ish) — DOM-in, `NotationLayout`-out — Verovio-backend geometry
207
238
  * extractor. `root` is the container holding every rendered `.vrv-page`
@@ -330,6 +361,42 @@ interface VerovioLayoutOptions {
330
361
  minLastJustification?: number;
331
362
  spacingSystem?: number;
332
363
  spacingStaff?: number;
364
+ /**
365
+ * Player-level widow guard — see `engraveOnce`'s own "Widow pass" doc.
366
+ * NOT the same mechanism as `breaksNoWidow` above (Verovio's own option,
367
+ * which only prevents a lone measure on the last PAGE — confirmed on a
368
+ * live page to do nothing for a lone measure on the last SYSTEM of a
369
+ * single-page excerpt, the common case for this player). This is a
370
+ * PLAYER option, not a Verovio one: it is stripped out in
371
+ * `verovioRenderOptions` before `setOptions` ever sees it (Verovio has no
372
+ * such option of its own to receive it). Default `true` — every engrave
373
+ * gets the widow guard unless a caller opts out. Only takes effect when
374
+ * the EFFECTIVE `breaks` is `'auto'` (this object's `breaks`, or
375
+ * `VEROVIO_LAYOUT_DEFAULTS.breaks` when unset) — a caller who already
376
+ * encoded exact break points (`breaks: 'line'`, e.g. Stave's own
377
+ * per-line-break usage) has made their own layout choice, which this pass
378
+ * never second-guesses.
379
+ */
380
+ avoidWidows?: boolean;
381
+ /**
382
+ * Readability floor for CALLER-ENCODED breaks (`breaks: 'line'` or
383
+ * `'encoded'`) — see `engraveOnce`'s own "Fallback pass" doc. Stave's own
384
+ * motivating case: `<print new-system="yes"/>` every 4 bars + `breaks:
385
+ * 'line'` gets exact N-bars-per-line on normal music, but on dense music
386
+ * (e.g. a Bach fugue excerpt) the one system between two encoded breaks
387
+ * can be too wide to fit even at Verovio's minimum spacing — the ONLY
388
+ * lever `fitZoomFactor` then has left is shrinking the effective zoom,
389
+ * which on a dense-enough system means unreadably small glyphs. Good
390
+ * sight-reading software prefers readable glyphs over a fixed bar count.
391
+ *
392
+ * A PLAYER option, not a Verovio one — like `avoidWidows`, stripped out in
393
+ * `verovioRenderOptions` before `setOptions` ever sees it. Default 0.75
394
+ * (see `shouldFallbackToAutoBreaks`'s own doc for the exact trigger
395
+ * condition). `minFitFactor: 0` disables the fallback entirely — a caller
396
+ * who always wants their exact encoded bar count, however small the
397
+ * glyphs get, can opt back into the pre-existing behavior.
398
+ */
399
+ minFitFactor?: number;
333
400
  }
334
401
  /**
335
402
  * Layout defaults applied to EVERY engrave (initial + every reflow) unless a
@@ -375,6 +442,27 @@ declare const VEROVIO_LAYOUT_DEFAULTS: {
375
442
  * Pure — exists so the merge itself is unit-testable without a DOM or a real
376
443
  * Verovio toolkit (`tests/notationPlayerVerovio.test.ts`'s "options merge"
377
444
  * tests call this directly).
445
+ *
446
+ * `avoidWidows`/`minFitFactor` (see `VerovioLayoutOptions`'s own docs) are
447
+ * PLAYER options, not Verovio ones — destructured out here and never
448
+ * forwarded to `setOptions`, same "narrow the passthrough" spirit as this
449
+ * function only accepting `VerovioLayoutOptions`'s typed surface at all.
450
+ *
451
+ * `pageHeight: 60000` (Verovio's own max) + `pageMarginTop`/`pageMarginBottom:
452
+ * 0` are unconditional, like `adjustPageHeight` — not in `VerovioLayoutOptions`
453
+ * at all, so a caller cannot override them. WHY: this player's own "whole
454
+ * score, page-flow, no pagination" framing (module doc, "PAGES" section)
455
+ * renders every Verovio PAGE as its own `.vrv-page` block; Verovio's default
456
+ * page height (~2970, a real printed-page height) paginates a long score
457
+ * into several such blocks with a page-margin gap between them, which reads
458
+ * as a broken PDF rather than one continuous score. A tall-enough
459
+ * `pageHeight` (combined with `adjustPageHeight: true`, already unconditional
460
+ * above) keeps `getPageCount() === 1` regardless of how long the piece is —
461
+ * confirmed against a real 40-bar fixture (2 pages at Verovio's own default
462
+ * height, 1 page at 60000 — see this module's real-Verovio pageHeight test).
463
+ * Zeroing the page margins removes the (now pointless, since there is only
464
+ * ever one page) top/bottom whitespace Verovio would otherwise still budget
465
+ * for a "page".
378
466
  */
379
467
  declare function verovioRenderOptions(hostWidthPx: number, zoom: number, layout?: VerovioLayoutOptions): Record<string, unknown>;
380
468
  /**
@@ -402,6 +490,27 @@ declare function verovioRenderOptions(hostWidthPx: number, zoom: number, layout?
402
490
  * available width.
403
491
  */
404
492
  declare function fitZoomFactor(systemWidthsPx: readonly number[], engraveWidthPx: number): number;
493
+ /** Default `VerovioLayoutOptions.minFitFactor` — see that field's own doc. */
494
+ declare const DEFAULT_MIN_FIT_FACTOR = 0.75;
495
+ /**
496
+ * Pure decision for the readability floor (`VerovioLayoutOptions.minFitFactor`,
497
+ * `engraveOnce`'s "Fallback pass") — true exactly when ALL of:
498
+ * - `factor` (a `fitZoomFactor` result) is finite and strictly below
499
+ * `minFitFactor`;
500
+ * - `minFitFactor` is a positive, finite floor (0 — or anything
501
+ * non-positive/non-finite — disables the fallback unconditionally, the
502
+ * documented opt-out);
503
+ * - `breaks` is `'line'` or `'encoded'` — the two ways a caller can hand
504
+ * Verovio EXACT, pre-decided break points (as opposed to `'auto'`/
505
+ * `'smart'`/`'none'`/unset, where Verovio already owns the line-breaking
506
+ * decision and there is no "caller's encoded bar count" to fall back
507
+ * FROM in the first place).
508
+ *
509
+ * Never throws; no DOM/Verovio access — this is the single source of truth
510
+ * `engraveOnce` calls after every fit-factor computation, so the trigger
511
+ * condition is unit-testable independent of a real engrave.
512
+ */
513
+ declare function shouldFallbackToAutoBreaks(factor: number, breaks: VerovioLayoutOptions['breaks'] | undefined, minFitFactor: number): boolean;
405
514
  /**
406
515
  * Semantic zoom → Verovio options. The migration spike's `zoom-test*.mjs`
407
516
  * proved `pageWidth` (Verovio's line-breaking width, in ITS OWN units)
@@ -448,4 +557,4 @@ declare const MAX_ENGRAVE_WIDTH_VRV = 1400;
448
557
  * (in stave-web-sightread) §2 for the full design. */
449
558
  declare function createVerovioNotationPlayer(opts: CreateVerovioNotationPlayerOpts): VerovioNotationPlayer;
450
559
 
451
- export { type CreateVerovioNotationPlayerOpts, EngravedNote, MARKED_NOTE_CLASS, MAX_ENGRAVE_WIDTH_VRV, VEROVIO_BASE_SCALE, VEROVIO_LAYOUT_DEFAULTS, VEROVIO_MAX_SCALE, VEROVIO_MIN_SCALE, type VerovioLayoutOptions, type VerovioNotationPlayer, type VerovioOnset, type VerovioRenderOptions, applyPrintObjectHiding, createVerovioNotationPlayer, fitZoomFactor, verovioEngravedNotes, verovioNotationLayout, verovioNotesAtColumn, verovioOnsetColumns, verovioRenderOptions, verovioZoomOptions };
560
+ export { type CreateVerovioNotationPlayerOpts, DEFAULT_MIN_FIT_FACTOR, EngravedNote, MARKED_NOTE_CLASS, MAX_ENGRAVE_WIDTH_VRV, VEROVIO_BASE_SCALE, VEROVIO_LAYOUT_DEFAULTS, VEROVIO_MAX_SCALE, VEROVIO_MIN_SCALE, type VerovioLayoutOptions, type VerovioNotationPlayer, type VerovioOnset, type VerovioRenderOptions, applyPrintObjectHiding, createVerovioNotationPlayer, fitZoomFactor, shouldFallbackToAutoBreaks, systemMeasureCounts, verovioEngravedNotes, verovioNotationLayout, verovioNotesAtColumn, verovioOnsetColumns, verovioRenderOptions, verovioZoomOptions };
@@ -27,6 +27,36 @@ function stampNoteIds(xml) {
27
27
  });
28
28
  return new XMLSerializer().serializeToString(doc);
29
29
  }
30
+ function injectSystemBreaks(xml, breakBeforeBarIndexes) {
31
+ const doc = new DOMParser().parseFromString(xml, "application/xml");
32
+ if (doc.querySelector("parsererror")) return xml;
33
+ const root = doc.documentElement;
34
+ if (!root || root.tagName !== "score-partwise") return xml;
35
+ for (const part of childrenNamed(root, "part")) {
36
+ const measures = childrenNamed(part, "measure");
37
+ for (const pos of breakBeforeBarIndexes) {
38
+ if (!Number.isInteger(pos) || pos <= 0 || pos >= measures.length) continue;
39
+ const measure = measures[pos];
40
+ const existingPrint = firstChildNamed(measure, "print");
41
+ if (existingPrint) {
42
+ existingPrint.setAttribute("new-system", "yes");
43
+ } else {
44
+ const printEl = doc.createElement("print");
45
+ printEl.setAttribute("new-system", "yes");
46
+ measure.insertBefore(printEl, measure.firstChild);
47
+ }
48
+ }
49
+ }
50
+ return new XMLSerializer().serializeToString(doc);
51
+ }
52
+ function balancedSystemBreaks(totalMeasures, systems) {
53
+ if (systems <= 1 || totalMeasures <= 0) return [];
54
+ const per = Math.ceil(totalMeasures / systems);
55
+ if (per <= 0) return [];
56
+ const breaks = [];
57
+ for (let b = per; b < totalMeasures; b += per) breaks.push(b);
58
+ return breaks;
59
+ }
30
60
  var STEP_SEMITONE = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
31
61
  function firstChildNamed(el, tag) {
32
62
  for (const c of Array.from(el.children)) if (c.tagName === tag) return c;
@@ -171,6 +201,9 @@ function collectMeasureElements(pageGeoms) {
171
201
  }
172
202
  return out;
173
203
  }
204
+ function systemMeasureCounts(root) {
205
+ return Array.from(root.querySelectorAll(".system")).map((sysEl) => sysEl.querySelectorAll(".measure").length);
206
+ }
174
207
  function verovioNotationLayout(root) {
175
208
  try {
176
209
  const pageGeoms = computePageGeometries(root);
@@ -363,7 +396,17 @@ var VEROVIO_LAYOUT_DEFAULTS = {
363
396
  };
364
397
  function verovioRenderOptions(hostWidthPx, zoom, layout) {
365
398
  const { scale, pageWidth } = verovioZoomOptions(hostWidthPx, zoom);
366
- return { ...VEROVIO_LAYOUT_DEFAULTS, ...layout, scale, pageWidth, adjustPageHeight: true };
399
+ const { avoidWidows: _avoidWidows, minFitFactor: _minFitFactor, ...verovioLayout } = layout ?? {};
400
+ return {
401
+ ...VEROVIO_LAYOUT_DEFAULTS,
402
+ ...verovioLayout,
403
+ scale,
404
+ pageWidth,
405
+ adjustPageHeight: true,
406
+ pageHeight: 6e4,
407
+ pageMarginTop: 0,
408
+ pageMarginBottom: 0
409
+ };
367
410
  }
368
411
  function fitZoomFactor(systemWidthsPx, engraveWidthPx) {
369
412
  if (!systemWidthsPx.length) return 1;
@@ -374,6 +417,13 @@ function fitZoomFactor(systemWidthsPx, engraveWidthPx) {
374
417
  const factor = engraveWidthPx / widest;
375
418
  return Number.isFinite(factor) && factor > 0 ? factor : 1;
376
419
  }
420
+ var DEFAULT_MIN_FIT_FACTOR = 0.75;
421
+ function shouldFallbackToAutoBreaks(factor, breaks, minFitFactor) {
422
+ if (!Number.isFinite(factor)) return false;
423
+ if (!(minFitFactor > 0)) return false;
424
+ if (breaks !== "line" && breaks !== "encoded") return false;
425
+ return factor < minFitFactor;
426
+ }
377
427
  function verovioZoomOptions(hostWidthPx, zoom) {
378
428
  const z = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
379
429
  const scale = Math.max(VEROVIO_MIN_SCALE, Math.min(VEROVIO_MAX_SCALE, VEROVIO_BASE_SCALE * z));
@@ -510,20 +560,65 @@ function createVerovioNotationPlayer(opts) {
510
560
  }
511
561
  }
512
562
  }
563
+ function runWidowPass(toolkit, widthPx, zoom, xml, layoutOpts) {
564
+ const counts = systemMeasureCounts(svgHost);
565
+ if (counts.length >= 2 && counts[counts.length - 1] === 1) {
566
+ const totalMeasures = counts.reduce((a, b) => a + b, 0);
567
+ const breakPositions = balancedSystemBreaks(totalMeasures, counts.length);
568
+ if (breakPositions.length) {
569
+ const widowXml = injectSystemBreaks(xml, breakPositions);
570
+ const widowLayoutOpts = { ...layoutOpts, breaks: "line" };
571
+ toolkit.setOptions(verovioRenderOptions(widthPx, zoom, widowLayoutOpts));
572
+ const okWidow = !!toolkit.loadData(widowXml);
573
+ if (okWidow) {
574
+ renderAllPages(toolkit);
575
+ rebuildLayoutFromDom();
576
+ return { xml: widowXml, layoutOpts: widowLayoutOpts };
577
+ }
578
+ }
579
+ }
580
+ return { xml, layoutOpts };
581
+ }
513
582
  function engraveOnce(toolkit, widthPx, zoom) {
514
- toolkit.setOptions(verovioRenderOptions(widthPx, zoom, opts.verovioOptions));
515
- const ok = !!toolkit.loadData(stampedXml);
583
+ const layoutOpts = opts.verovioOptions;
584
+ const effectiveBreaks = layoutOpts?.breaks ?? VEROVIO_LAYOUT_DEFAULTS.breaks;
585
+ const minFitFactor = layoutOpts?.minFitFactor ?? DEFAULT_MIN_FIT_FACTOR;
586
+ const avoidWidows = layoutOpts?.avoidWidows !== false;
587
+ let xmlToRender = stampedXml;
588
+ let renderLayoutOpts = layoutOpts;
589
+ toolkit.setOptions(verovioRenderOptions(widthPx, zoom, renderLayoutOpts));
590
+ const ok = !!toolkit.loadData(xmlToRender);
516
591
  if (ok) renderAllPages(toolkit);
517
592
  rebuildLayoutFromDom();
593
+ if (ok && avoidWidows && effectiveBreaks === "auto") {
594
+ const widowed = runWidowPass(toolkit, widthPx, zoom, xmlToRender, renderLayoutOpts);
595
+ xmlToRender = widowed.xml;
596
+ renderLayoutOpts = widowed.layoutOpts;
597
+ }
518
598
  if (ok && currentLayout) {
519
- const factor = fitZoomFactor(
520
- currentLayout.systems.map((s) => s.w),
521
- widthPx
522
- );
599
+ const systemWidthsPx = () => opts.measureSystemWidths ? opts.measureSystemWidths(svgHost) : currentLayout.systems.map((s) => s.w);
600
+ let factor = fitZoomFactor(systemWidthsPx(), widthPx);
601
+ if (shouldFallbackToAutoBreaks(factor, effectiveBreaks, minFitFactor)) {
602
+ const autoLayoutOpts = { ...layoutOpts, breaks: "auto" };
603
+ toolkit.setOptions(verovioRenderOptions(widthPx, zoom, autoLayoutOpts));
604
+ const okAuto = !!toolkit.loadData(stampedXml);
605
+ if (okAuto) {
606
+ renderAllPages(toolkit);
607
+ rebuildLayoutFromDom();
608
+ xmlToRender = stampedXml;
609
+ renderLayoutOpts = autoLayoutOpts;
610
+ if (avoidWidows) {
611
+ const widowed = runWidowPass(toolkit, widthPx, zoom, xmlToRender, renderLayoutOpts);
612
+ xmlToRender = widowed.xml;
613
+ renderLayoutOpts = widowed.layoutOpts;
614
+ }
615
+ factor = fitZoomFactor(systemWidthsPx(), widthPx);
616
+ }
617
+ }
523
618
  if (factor < 1) {
524
619
  const effectiveZoom = zoom * factor;
525
- toolkit.setOptions(verovioRenderOptions(widthPx, effectiveZoom, opts.verovioOptions));
526
- const ok2 = !!toolkit.loadData(stampedXml);
620
+ toolkit.setOptions(verovioRenderOptions(widthPx, effectiveZoom, renderLayoutOpts));
621
+ const ok2 = !!toolkit.loadData(xmlToRender);
527
622
  if (ok2) {
528
623
  renderAllPages(toolkit);
529
624
  rebuildLayoutFromDom();
@@ -641,6 +736,7 @@ function createVerovioNotationPlayer(opts) {
641
736
  };
642
737
  }
643
738
  export {
739
+ DEFAULT_MIN_FIT_FACTOR,
644
740
  MARKED_NOTE_CLASS,
645
741
  MAX_ENGRAVE_WIDTH_VRV,
646
742
  VEROVIO_BASE_SCALE,
@@ -650,6 +746,8 @@ export {
650
746
  applyPrintObjectHiding,
651
747
  createVerovioNotationPlayer,
652
748
  fitZoomFactor,
749
+ shouldFallbackToAutoBreaks,
750
+ systemMeasureCounts,
653
751
  verovioEngravedNotes,
654
752
  verovioNotationLayout,
655
753
  verovioNotesAtColumn,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/notationXml.ts","../src/notationPlayerVerovio.ts"],"sourcesContent":["// Pure MusicXML→MusicXML/model helpers for `createVerovioNotationPlayer`\n// (notationPlayerVerovio.ts, 0.40.0) — the id-stamping + note-model half of\n// its \"join model ids to Verovio's rendered SVG\" approach (that module's\n// header doc, point 1). No DOM rendering here; everything in this file is\n// pure XML-in → XML/data-out, unit-testable with no live SVG at all.\n//\n// OWNERSHIP NOTE — `stampNoteIds`'s deterministic id scheme\n// (`n-{partIdx}-{measureNumber}-{noteIdxInMeasure}`) is DELIBERATELY\n// duplicated, byte-for-byte, from stave-web-sightread's\n// `src/lib/bach/xmlTransforms.ts:stampNoteIds` (part of that repo's Verovio\n// transform pipeline, docs/superpowers/specs/2026-08-11-verovio-player-design.md\n// §1). stave's copy is the one actually wired into `parseReduction` (its\n// `noteIds` per span must match what got stamped onto the MusicXML BEFORE\n// Verovio ever saw it), so stave remains that scheme's owner for the\n// pipeline's purposes. This copy exists so `createVerovioNotationPlayer`\n// works correctly for ANY caller — including ones that hand in un-stamped\n// MusicXML — without a runtime dependency from web-core back into an app\n// repo (the wrong direction for a shared package). Both copies are pure\n// functions of a note's POSITION (never of any id already present), so\n// calling either one on already-stamped input reproduces the exact same\n// ids — the two copies can never drift apart in OBSERVABLE behavior even\n// though they are physically two files. If the scheme ever needs to change,\n// change it in BOTH places (this file's own tests pin the scheme\n// independently of stave's, so a one-sided edit fails a test here).\nexport function stampNoteIds(xml: string): string {\n const doc = new DOMParser().parseFromString(xml, 'application/xml');\n if (doc.querySelector('parsererror')) return xml;\n\n const parts = Array.from(doc.querySelectorAll('score-partwise > part'));\n parts.forEach((part, partIdx) => {\n for (const measure of Array.from(part.querySelectorAll('measure'))) {\n const number = measure.getAttribute('number') ?? '0';\n const notes = Array.from(measure.children).filter((el) => el.tagName === 'note');\n notes.forEach((note, noteIdx) => {\n note.setAttribute('id', `n-${partIdx}-${number}-${noteIdx}`);\n });\n }\n });\n\n return new XMLSerializer().serializeToString(doc);\n}\n\n// ─── noteModelFromXml — the note MODEL half of the join ───────────────────\n\n/** One `<note>`'s MODEL identity — the ground truth `EngravedNote`\n * (notationPlayerSvg.ts) needs that Verovio's rendered SVG cannot supply on\n * its own (a rendered `g.note`/`g.rest` carries geometry, not pitch/tie/\n * duration semantics). Keyed by the note's stamped `id` in\n * `notePositions()`'s return of `verovioEngravedNotes`\n * (notationPlayerVerovio.ts). */\nexport interface NoteModel {\n /** `12*(octave+1) + stepSemitone + alter` — the standard MusicXML→MIDI\n * conversion (the same formula stave-web-sightread's own\n * `practice/probeInputs.ts:pitchMidi` uses — a universal formula, not app\n * logic, so this is not an owned-layer violation to restate here). `null`\n * for a rest or an `<unpitched>` note (no `<pitch>` child) — mirrors\n * `EngravedNote.midi`'s own \"null covers both\" contract. */\n midi: number | null;\n /** Has a `<rest/>` child. */\n isRest: boolean;\n /** True for the STOP half of a tie — a direct `<tie type=\"stop\">` child OR\n * `<notations><tied type=\"stop\">` (exporters vary on which they emit;\n * either counts) — matches `EngravedNote.tieContinuation`'s \"continuation\n * note of a tie, not the struck start\" contract. */\n tieContinuation: boolean;\n /** 0-based, matching `EngravedNote.staffIndex`'s \"0 = top staff of the\n * system\" contract: every `<part>` is walked in document order, and\n * every DISTINCT staff within it (by `<attributes><staves>` when\n * present, else the highest `<staff>` number any of its notes uses, else\n * 1) is assigned the next index — so a single-part 2-staff piano score\n * numbers 0/1 by `<staff>`, and a 2-part 1-staff-per-part reduction (this\n * app's own chord+bass shape) numbers 0/1 by PART, with neither case\n * needing different code. */\n staffIndex: number;\n /** Whole-note fraction (0.25 = quarter) — `duration / divisions / 4`,\n * divisions tracked per-part from the LAST `<attributes><divisions>`\n * seen at or before this note (MusicXML: divisions persist until\n * overridden, default 1). 0 for a grace note (no `<duration>` child —\n * the true, spec-correct signal; never guessed from `<type>`). */\n durationReal: number;\n /** 0-based position of this note's `<measure>` among its OWN `<part>`'s\n * measure children, in document order. Informational only — the live\n * join (`verovioOnsetColumns`/`verovioEngravedNotes`, both in\n * notationPlayerVerovio.ts) resolves the note's RENDERED measure index\n * from the live SVG DOM independently (Verovio's own render order, which\n * is what geometry/hit-testing must agree with), never from this field. */\n measureIndex: number;\n /** `print-object=\"no\"` on the source `<note>` (stave's `hideDoubledNotes`\n * sets this on editorially-doubled notes/rests before handing MusicXML to\n * this player). Verovio's importer HONORS this for `<note>` elements\n * carrying a `<pitch>` (renders `visibility=\"hidden\"` on its own,\n * empirically confirmed against a real 6.2.0 render) but does NOT honor\n * it for `<rest>` notes (the `<g class=\"rest\">` renders fully visible\n * regardless — same empirical check). `createVerovioNotationPlayer`\n * reads this field to force `visibility=\"hidden\"` after every render for\n * ANY id where it's true — a no-op re-application on notes Verovio\n * already hid, and the actual fix on the rests it doesn't (see that\n * module's `applyPrintObjectHiding`). */\n hidden: boolean;\n}\n\nconst STEP_SEMITONE: Record<string, number> = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };\n\nfunction firstChildNamed(el: Element, tag: string): Element | null {\n for (const c of Array.from(el.children)) if (c.tagName === tag) return c;\n return null;\n}\nfunction childrenNamed(el: Element, tag: string): Element[] {\n return Array.from(el.children).filter((c) => c.tagName === tag);\n}\nfunction textOf(el: Element | null): string | null {\n return el && el.textContent != null ? el.textContent.trim() : null;\n}\n\nfunction pitchMidiFromElement(pitchEl: Element): number {\n const step = textOf(firstChildNamed(pitchEl, 'step')) ?? 'C';\n const octave = Number(textOf(firstChildNamed(pitchEl, 'octave')) ?? '4');\n const alter = Number(textOf(firstChildNamed(pitchEl, 'alter')) ?? '0');\n return 12 * (octave + 1) + (STEP_SEMITONE[step] ?? 0) + Math.trunc(alter);\n}\n\n/** How many staves `part` uses: the max `<attributes><staves>N</staves>`\n * seen anywhere in it (the authoritative declaration when present), else\n * the highest `<note><staff>N</staff></note>` number any of its notes\n * uses, else 1 (a plain single-staff part declares neither). */\nfunction partStaffCount(part: Element): number {\n let maxDeclared = 0;\n for (const attrs of childrenNamed(part, 'measure').flatMap((m) => childrenNamed(m, 'attributes'))) {\n const staves = Number(textOf(firstChildNamed(attrs, 'staves')) ?? '0');\n if (staves > maxDeclared) maxDeclared = staves;\n }\n if (maxDeclared > 0) return maxDeclared;\n\n let maxStaff = 0;\n for (const measure of childrenNamed(part, 'measure')) {\n for (const note of childrenNamed(measure, 'note')) {\n const staff = Number(textOf(firstChildNamed(note, 'staff')) ?? '0');\n if (staff > maxStaff) maxStaff = staff;\n }\n }\n return Math.max(1, maxStaff);\n}\n\n/**\n * Pure(ish) — MusicXML-in, `id → NoteModel`-out. Walks every `<part>` in\n * document order, then every `<measure>` in document order, then every\n * DIRECT child in document order — `<attributes>` updates the part's own\n * `divisions` cursor; every other non-`<note>` child (`<backup>`,\n * `<forward>`, `<direction>`, …) is a structural/timeline element this\n * function has NO use for (it reads each note's OWN `<duration>` directly,\n * never a cursor POSITION — see `durationReal`'s doc — so unlike\n * `walkMeasureNotes`-style position walks, `<backup>`/`<forward>` need no\n * special handling here beyond being correctly skipped, which plain\n * tag-name filtering already does) — and every `<note>` becomes one model\n * entry, keyed by its `id` attribute (a note with NO `id` — i.e. input that\n * was never run through `stampNoteIds` — is silently skipped: it has no key\n * to join the render against, so there is nothing useful to record).\n *\n * Never throws: malformed input (fails to parse, or no `<score-partwise>`\n * root) returns an empty Map.\n */\nexport function noteModelFromXml(stampedXml: string): Map<string, NoteModel> {\n const model = new Map<string, NoteModel>();\n let doc: Document;\n try {\n doc = new DOMParser().parseFromString(stampedXml, 'application/xml');\n } catch {\n return model;\n }\n if (doc.querySelector('parsererror')) return model;\n const root = doc.documentElement;\n if (!root || root.tagName !== 'score-partwise') return model;\n\n const parts = childrenNamed(root, 'part');\n let staffOffset = 0;\n\n for (const part of parts) {\n const staffCount = partStaffCount(part);\n let divisions = 1;\n const measureEls = childrenNamed(part, 'measure');\n\n measureEls.forEach((measureEl, measureIndex) => {\n for (const child of Array.from(measureEl.children)) {\n if (child.tagName === 'attributes') {\n const divText = textOf(firstChildNamed(child, 'divisions'));\n if (divText) divisions = Number(divText) || divisions;\n continue;\n }\n if (child.tagName !== 'note') continue;\n const note = child;\n const id = note.getAttribute('id');\n if (!id) continue;\n\n const isGrace = !!firstChildNamed(note, 'grace');\n const isRest = !!firstChildNamed(note, 'rest');\n const pitchEl = firstChildNamed(note, 'pitch');\n const staffNumber = Number(textOf(firstChildNamed(note, 'staff')) ?? '1') || 1;\n const durationText = textOf(firstChildNamed(note, 'duration'));\n const durationReal =\n isGrace || !durationText ? 0 : Number(durationText) / divisions / 4;\n\n const tieStopDirect = childrenNamed(note, 'tie').some((t) => t.getAttribute('type') === 'stop');\n const notationsEl = firstChildNamed(note, 'notations');\n const tieStopNotated = notationsEl\n ? childrenNamed(notationsEl, 'tied').some((t) => t.getAttribute('type') === 'stop')\n : false;\n\n model.set(id, {\n midi: pitchEl ? pitchMidiFromElement(pitchEl) : null,\n isRest,\n tieContinuation: tieStopDirect || tieStopNotated,\n staffIndex: staffOffset + Math.max(0, staffNumber - 1),\n durationReal,\n measureIndex,\n hidden: note.getAttribute('print-object') === 'no',\n });\n }\n });\n\n staffOffset += staffCount;\n }\n\n return model;\n}\n","// createVerovioNotationPlayer — the Verovio (vector) sibling of\n// createSvgNotationPlayer (notationPlayerSvg.ts). Same job (a live,\n// caller-driven notation + gliding-playhead widget) and the same swap-friendly\n// API shape, different rendering engine: Verovio's own MusicXML→SVG engraver\n// instead of OSMD. See\n// docs/superpowers/specs/2026-08-11-verovio-player-design.md (stave-web-sightread)\n// §2 for the full design rationale.\n//\n// THE BINDING REFRAME (design doc, top): \"Timing is ours; Verovio renders.\"\n// This module NEVER calls `renderToTimemap` or `getElementsAtTime` — Verovio's\n// timemap is proven wrong on tuplets (the root-cause finding that motivated\n// this whole migration). All timing (`onsets`) is supplied by the caller,\n// derived from `parseReduction`'s spans/offsets; this module's only job is\n// SVG + id→geometry, exactly like notationPlayerSvg.ts's job is OSMD SVG +\n// id→geometry. (Grep gate — see the build report.)\n//\n// REUSED, VERBATIM, NO NEW MATH (same hard rule as notationPlayerSvg.ts):\n// - `vstackAudioPlayheadLine` (scene/notationGeometry.ts) — the exact same\n// onset-anchored, carriage-return playhead interpolation both SVG-family\n// players use. It only ever reads a `NotationLayout`; it does not care\n// that THIS module's layout came from Verovio's rendered SVG DOM instead\n// of OSMD's `GraphicalMusicSheet` object model.\n// - `hitTestMeasureAt`, `measureColumnsFromLayout`, `distinctOnsets`\n// (scene/notationGeometry.ts) — reused as-is, identical to\n// notationPlayerSvg.ts's usage.\n// - `computeReflowScrollDelta` + the auto-follow discriminator\n// (`createFollowController`) — EXTRACTED (0.39.0) out of\n// notationPlayerSvg.ts into `./notationCommon`, so both SVG-family\n// players share one implementation. See that module's doc.\n//\n// WHAT'S NEW (not a re-derivation of any of the above):\n// - `verovioNotationLayout` — a Verovio-backend geometry extractor, this\n// module's counterpart to notationPlayerSvg.ts's `svgNotationLayout`.\n// Verovio exposes NO object model to JS (unlike OSMD's `GraphicSheet`) —\n// only rendered SVG + MEI/timemap (timemap being off-limits per the\n// binding reframe above) — so this reads the ACTUAL rendered SVG DOM:\n// `<g class=\"measure\">` / `<g class=\"staff\">` / `<g class=\"system\">` /\n// `<g class=\"note\">` are Verovio's own stable, documented SVG output\n// classes (confirmed against a real 6.2.0 render — see the migration\n// spike's `id-test*.mjs`). Measure `index` is assigned by DOCUMENT ORDER\n// (musical order) across however many pages were rendered — no reliance\n// on Verovio's own (internal, non-deterministic) generated ids.\n// - Stamped-id note lookups (`verovioOnsetColumns`): Task 1 (stave repo)\n// stamps a deterministic `xml:id` per note before handing MusicXML to\n// Verovio; Verovio PRESERVES caller-supplied ids as the rendered SVG\n// element's own `id` attribute (confirmed: `<note id=\"n-0-0-0\">` in the\n// source round-trips to `<g id=\"n-0-0-0\" class=\"note\">` in the output —\n// an EXACT lookup, no heuristics, unlike the ordinal-spread fallback\n// `vstackAudioPlayheadLine` uses when no `noteCols` are supplied at all).\n// - `verovioZoomOptions` — the semantic zoom→Verovio-options mapping. The\n// migration spike's `zoom-test*.mjs` proved `pageWidth` (Verovio's\n// line-breaking width, in ITS OWN units) drives measures-per-system\n// while `scale` (glyph size) alone does NOT (avgMeasuresPerSystem stayed\n// 3.61 across scale 40/80/150 at a fixed pageWidth; it moved from 2.24 to\n// 3.61 to 5.91 as pageWidth alone rose 1000→1600→2400). Verovio's\n// rendered SVG width in CSS px is EXACTLY `pageWidth * scale / 100`\n// (confirmed empirically) — so solving that identity for `pageWidth`\n// given a TARGET output width (the host's width, held fixed across zoom\n// levels) and a zoom-driven `scale` makes both halves of the semantic\n// (\"bigger zoom ⇒ bigger glyphs AND fewer measures/system, width still\n// fits host\") fall out of ONE formula, not two independently-tuned ones.\n// - The unit-conversion for any element's `getBBox()` (Verovio's rendered\n// SVG user-unit space) → CSS px: each rendered page is\n// `<svg width=\"Wpx\" height=\"Hpx\">` (no viewBox) wrapping a nested\n// `<svg class=\"definition-scale\" viewBox=\"0 0 VBW VBH\">` (Verovio's own\n// structure) — so `cssPx = userUnit * (W / VBW)`, the SAME \"read the\n// scale factor from the live render, never hardcode it\" principle\n// `svgNotationLayout`'s `unitInPixels` derivation uses, just sourced from\n// the DOM (Verovio exposes no JS-side unit constant) instead of an\n// imported library constant.\n//\n// PAGES: \"all rendered, stacked in flow\" (design doc §2) — every Verovio\n// page (`getPageCount()`) is rendered to its own `<svg>` and appended, in\n// order, inside its own `.vrv-page` wrapper `<div>`, inside `svgHost`. Normal\n// block layout stacks them vertically; `verovioNotationLayout` reads each\n// page's OWN offset (`getBoundingClientRect()` relative to the shared root)\n// so geometry from every page lands in ONE continuous coordinate space, the\n// same space the playhead overlay is positioned in. No \"current page\" /\n// pagination concept anywhere in this module — the whole score is always in\n// the DOM; the PAGE scrolls it (identical framing to notationPlayerSvg.ts).\n//\n// SHARED TOOLKIT INSTANCE: Verovio's own package doc: \"only one instance can\n// be created for now\" (`VerovioToolkit.instances`, a static array the C++\n// bridge expects to hold at most one live toolkit). This module therefore\n// keeps ONE module-level toolkit init promise for the whole session — every\n// player created on the page shares it. This is NOT a \"one live player at a\n// time\" assumption — the real consumer (PlayerPage) keeps a harmony player\n// AND a written player alive SIMULTANEOUSLY (lazy-built, destroyed only on\n// piece switch), so two players' `loadData` calls genuinely interleave over\n// the toolkit's lifetime. Safety comes from RECLAIM: every toolkit-consuming\n// path (initial engrave; `reflow`, shared by `setZoom`/`resize`) re-parses\n// ITS OWN `musicXml` via `loadData` synchronously, immediately before\n// rendering — never assumes the toolkit still holds what it loaded last\n// time. Because the reclaim call and the render calls that follow it have no\n// `await` between them, JS's single-threaded run-to-completion semantics\n// guarantee no other player's reflow can interleave mid-sequence — see\n// `reflow`'s own comment + `tests/notationPlayerVerovio.test.ts`'s\n// two-player interleaved-reflow test (the regression this guards against).\n//\n// IMPORT PATH: subpath-only —\n// `@real-music-packages/web-core/notationPlayerVerovio` — not re-exported\n// from the root barrel (same reasoning as notationPlayer.ts/\n// notationPlayerSvg.ts: the root barrel is theory-only/zero-dependency).\n// `verovio` itself is a dynamic `import('verovio/wasm')` /\n// `import('verovio/esm')` INSIDE this module only, marked `external` in\n// tsup.config.ts, so the ~2.3MB gzip WASM only loads on pages that actually\n// construct a player — see the build report's dist-grep evidence.\n//\n// 0.40.0 — FULL API PARITY WITH notationPlayerSvg.ts (stave-web-sightread's\n// reading/recording stack can now swap backends without touching a call\n// site): `notePositions()`, `markNotes()`, the `[data-rmp-playhead]`\n// attribute, and `osmdOptions.autoBeam` (accepted + ignored, logged once —\n// Verovio always beams from the source MusicXML's own `<beam>` data, so\n// there is nothing for this option to toggle). The join that makes\n// `notePositions()`/`markNotes()` possible: `stampNoteIds`/`noteModelFromXml`\n// (./notationXml.ts, NEW) turn the input MusicXML into `id → NoteModel`\n// (pitch/rest/tie/staff/duration — the ground truth Verovio's rendered SVG\n// alone cannot supply), and `verovioEngravedNotes`/`verovioNotesAtColumn`\n// below join those ids to the live rendered `g.note`/`g.rest` elements —\n// same id-preservation guarantee `verovioOnsetColumns` already relies on\n// (see point 2 above), just consumed for notehead identity/geometry instead\n// of playhead columns. `musicXml` is stamped INTERNALLY (idempotent — a\n// caller that already ran it through stave's own `stampNoteIds` gets\n// byte-identical ids back) so this module never assumes the caller stamped\n// first. See ./notationXml.ts's own doc for why that scheme is duplicated\n// rather than imported from stave-web-sightread (wrong dependency\n// direction for a shared package) and `applyPrintObjectHiding`'s doc below\n// for the print-object empirical finding (Verovio honors it for notes, NOT\n// for rests).\n\nimport {\n vstackAudioPlayheadLine,\n distinctOnsets,\n hitTestMeasureAt,\n measureColumnsFromLayout,\n systemIndexOfBox,\n type NotationLayout,\n} from './scene/notationGeometry';\nimport type { Box, StaffMeasureBox } from './promo';\nimport { computeReflowScrollDelta, createFollowController } from './notationCommon';\nimport type { EngravedNote } from './notationPlayerSvg';\nimport { stampNoteIds, noteModelFromXml, type NoteModel } from './notationXml';\n\n// Re-exported (TYPE-ONLY import above — erased at compile time, zero\n// runtime cost) so a caller that only imports from `notationPlayerVerovio`\n// still gets the SAME type `notePositions()` returns (identical shape to\n// notationPlayerSvg.ts's own export — not redefined here, to guarantee the\n// \"same exported interface\" contract can never drift between the two\n// SVG-family players).\nexport type { EngravedNote };\n\n/** Restated independently, not imported as a VALUE from notationPlayerSvg.ts\n * — same reasoning as `MAX_ENGRAVE_WIDTH_VRV` vs `MAX_ENGRAVE_WIDTH_SVG`\n * (below): a runtime (non-`type`) import from notationPlayerSvg.ts would\n * pull that module's ENTIRE implementation — including its own\n * `createSvgNotationPlayer` closure (harmless at runtime, since its OSMD\n * import stays lazy/dynamic either way) — into this entry's own tsup\n * chunk graph, which is exactly the cross-entry bundle coupling the\n * module doc's \"IMPORT PATH\" section (and the build report's dist-grep\n * gate) exists to prevent between the two SVG-family players. Must stay\n * byte-identical to `notationPlayerSvg.ts`'s own `MARKED_NOTE_CLASS` — a\n * test in this file's own suite pins that. */\nexport const MARKED_NOTE_CLASS = 'rmp-note-marked';\n\n// ─── Public types ───────────────────────────────────────────────────────────\n\n/** One distinct note-onset instant: the audio-clock time it sounds at, and\n * the stamped `xml:id`s (Task 1, stave repo) of every note that sounds at\n * that instant (>1 for a chord). Multiple entries sharing the same `tMs`\n * are merged (their `noteIds` unioned) — the caller does not need to\n * pre-group chords into one entry. */\nexport interface VerovioOnset {\n tMs: number;\n noteIds: string[];\n}\n\nexport interface CreateVerovioNotationPlayerOpts {\n /** Element the player's content is mounted into. Takes NATURAL content\n * height (the whole score, page-flow layout, ALL Verovio pages stacked)\n * — the host must not clip a fixed height; the PAGE scrolls the score. */\n host: HTMLElement;\n /** Display MusicXML to engrave (Task 1's transform-pipeline output — ids\n * already stamped). Ignored when `rendered` (the test seam) is set. */\n musicXml: string;\n /** Note onsets the playhead locks to, WITH the stamped ids of the notes\n * sounding at each onset — see `VerovioOnset`. Distinct/sorted\n * automatically (duplicates by `tMs` are merged, not required to be\n * pre-sorted). */\n onsets: VerovioOnset[];\n /** Parks a followed system this many px below the viewport top — pass the\n * height of any fixed top chrome (header, docked transport) plus a gap.\n * Default SYSTEM_TOP_MARGIN_PX. */\n followTopMarginPx?: number;\n /** Playhead line color. Default `'#2f6f4f'`. */\n playheadColor?: string;\n /** Initial semantic zoom — see `verovioZoomOptions`'s doc for the mapping.\n * Default 1 (a normal readable size that fits the host's width). */\n zoom?: number;\n /**\n * Advanced / test seam: a pre-built `NotationLayout`, bypassing the real\n * Verovio engrave (`musicXml` is still required by the type but is\n * ignored when this is set). Mirrors `CreateSvgNotationPlayerOpts.rendered`\n * in notationPlayerSvg.ts for the identical reason: real Verovio rendering\n * needs a real SVG DOM (`getBBox`/`getBoundingClientRect`) that jsdom can't\n * provide — see notationPlayerSvg.ts's module doc for why headless can't do\n * a real one. When set, `noteIds`-based note lookups have no live DOM to\n * resolve against, so the playhead falls back to `vstackAudioPlayheadLine`'s\n * own ordinal spread (same graceful-degradation path as \"no `noteCols`\n * supplied\" on the SVG player) — fine for a lifecycle test, not for\n * notehead-accurate positioning. `setZoom`/`resize` update the tracked zoom\n * /width but perform no real re-engrave (there is nothing to re-engrave).\n */\n rendered?: NotationLayout;\n /**\n * Narrow passthrough matching `CreateSvgNotationPlayerOpts.osmdOptions`'s\n * shape exactly, so a caller driving BOTH players behind one interface\n * (the swap this player exists for) never has to branch per backend.\n * `autoBeam` has NO Verovio equivalent — Verovio always beams straight\n * from the MusicXML's own `<beam>` elements (it has no \"re-beam from\n * scratch\" pass the way OSMD's `autoBeam` option does) — so this is\n * accepted and silently ignored, with a ONE-TIME `console.warn` (module-\n * level, not per-instance — a caller that builds many players with the\n * same options object should not get spammed) rather than a hard error,\n * since ignoring it is genuinely harmless: synthesized rhythm XML with no\n * `<beam>` data renders unbeamed either way, which is a cosmetic\n * difference the caller can fix upstream (emit real `<beam>` elements)\n * rather than this player faking OSMD's re-beam heuristic.\n */\n osmdOptions?: { autoBeam?: boolean };\n /**\n * Passthrough for Verovio's own layout/line-breaking options — merged\n * UNDER `VEROVIO_LAYOUT_DEFAULTS` and OVER `scale`/`pageWidth`/\n * `adjustPageHeight` (see `verovioRenderOptions`'s own doc for the exact\n * merge order and why: a caller's `breaks` must be able to override the\n * default, but a caller can never smuggle in `scale`/`pageWidth` — those\n * stay derived from `zoom`/host width, not caller-suppliable). Stave's own\n * use case: inject `<print new-system=\"yes\"/>` into MusicXML and pass\n * `breaks: 'line'` to get exact N-bars-per-line, rather than Verovio's own\n * automatic line-breaking (see `VEROVIO_LAYOUT_DEFAULTS`'s doc for the\n * \"why\" behind the defaults themselves).\n */\n verovioOptions?: VerovioLayoutOptions;\n}\n\nexport interface VerovioNotationPlayer {\n /** Resolves once the engraving is in the DOM and ready to draw. `setTime`/\n * click hit-testing are safe to call before this resolves (no-op until\n * ready, same contract as the SVG player). */\n readonly ready: Promise<void>;\n /** Drive the playhead for absolute playback time `tMs`. Caller owns the\n * audio clock + rAF loop. */\n setTime(tMs: number): void;\n /** Re-engrave at a new semantic zoom (systems reflow — see\n * `verovioZoomOptions`). The scroll position is restored afterward so the\n * content that was centered in the viewport before the reflow is still\n * centered after it. */\n setZoom(z: number): Promise<void>;\n /** Re-measure the host and reflow to match its current width, with the\n * same scroll-position preservation as `setZoom`. Call on host resize /\n * orientation change. */\n resize(): Promise<void>;\n /** Gate the auto-follow scroll on the app's transport state: pass `true`\n * on play, `false` on pause/stop (see FollowController.setEnabled — while\n * disabled NOTHING may scroll the sheet, including the idle-rearm's\n * off-screen rescue). Defaults to enabled. */\n setFollowEnabled(on: boolean): void;\n /** Register a measure-click handler (measure index, matching the DOM-order\n * index `verovioNotationLayout` assigns). Returns an unsubscribe fn. */\n onMeasureClick(cb: (measureIndex: number) => void): () => void;\n /**\n * Mark the engraved noteheads/rests nearest the given columns (same\n * `measureIndex + fraction-through-the-measure` units as `onsets`'\n * derived columns); pass `null` or `[]` to clear. Same contract and CSS\n * class (`MARKED_NOTE_CLASS` = `'rmp-note-marked'`) as\n * `SvgNotationPlayer.markNotes` — a consumer's existing CSS keeps working\n * unmodified across a backend swap. Survives re-engraving: reapplied\n * after every `setZoom`/`resize`.\n */\n markNotes(cols: number[] | null): void;\n /** Every engraved note/rest with MODEL identity (pitch, rest, tie, staff)\n * and host-relative notehead position — same `EngravedNote` shape\n * `SvgNotationPlayer.notePositions()` returns (re-exported from this\n * module, not redefined). `headEl` is Verovio's rendered `.notehead`\n * sub-group when present (a tighter box than the outer `g.note`, closer\n * in spirit to OSMD's `.vf-notehead`), else the outer `g.note`/`g.rest`\n * group. `[]` before the initial engrave resolves or under the\n * `rendered` test seam (no live SVG to join against — same graceful\n * degradation as `verovioOnsetColumns`). */\n notePositions(): EngravedNote[];\n /** Tear down: removes the mounted DOM (engraving + playhead overlay) from\n * `host`, and drops every listener this instance added (click, window\n * scroll) and pending async work (a token guard drops any in-flight\n * reflow's effects). Idempotent. Does NOT destroy the shared module-level\n * Verovio toolkit instance (see the module doc's \"SHARED TOOLKIT\n * INSTANCE\" note) — it is reused by the next player, if any. */\n destroy(): void;\n}\n\n// ─── Verovio-backend geometry extraction (DOM-based) ───────────────────────\n\nconst EMPTY_LAYOUT: NotationLayout = {\n src: { x: 0, y: 0, w: 0, h: 0 },\n rect: { dx: 0, dy: 0, dw: 0, dh: 0 },\n systems: [],\n measures: [],\n};\n\n/** Per-page unit-conversion + placement: `cssPx = userUnit * scale`, plus\n * this page's own `(offsetX, offsetY)` within the shared root's coordinate\n * space (see the module doc's \"unit-conversion\" + \"PAGES\" sections).\n * `root` is carried alongside purely so `boxFromElement` can go straight to\n * `getBoundingClientRect()` diffing (see that function's own doc for why) —\n * `scale`/`offsetX`/`offsetY` stay as the page-validity check\n * (`pageGeometry`'s own \"is this page's markup well-formed\" guard) and are\n * no longer consumed for box math. */\ninterface PageGeom {\n scale: number;\n offsetX: number;\n offsetY: number;\n root: Element;\n}\n\nfunction safeRect(el: Element): DOMRect | null {\n return typeof el.getBoundingClientRect === 'function' ? el.getBoundingClientRect() : null;\n}\n\nfunction readViewBox(svgEl: SVGSVGElement): { w: number; h: number } | null {\n const baseVal = svgEl.viewBox && svgEl.viewBox.baseVal;\n if (baseVal && baseVal.width > 0) return { w: baseVal.width, h: baseVal.height };\n const attr = svgEl.getAttribute('viewBox');\n if (!attr) return null;\n const parts = attr.trim().split(/[\\s,]+/).map(Number);\n if (parts.length !== 4 || !(parts[2] > 0)) return null;\n return { w: parts[2], h: parts[3] };\n}\n\n/** One page's unit-conversion factor + placement offset, derived ENTIRELY\n * from the live DOM (Verovio's rendered SVG is self-describing — outer\n * `<svg width>` + inner `<svg viewBox>` — no external constant needed; see\n * the module doc). Returns null (never throws) if the page's markup is\n * missing the expected structure. */\nfunction pageGeometry(root: Element, pageEl: Element): PageGeom | null {\n const outerSvg = pageEl.querySelector('svg');\n if (!outerSvg) return null;\n const innerSvg = (outerSvg.querySelector('svg[viewBox]') ?? outerSvg) as unknown as SVGSVGElement;\n const vb = readViewBox(innerSvg);\n if (!vb) return null;\n const outerRect = safeRect(outerSvg);\n const rootRect = safeRect(root);\n const pageRect = safeRect(pageEl);\n if (!outerRect || !rootRect || !pageRect) return null;\n if (!(outerRect.width > 0)) return null;\n const scale = outerRect.width / vb.w;\n if (!(scale > 0) || !Number.isFinite(scale)) return null;\n return { scale, offsetX: pageRect.left - rootRect.left, offsetY: pageRect.top - rootRect.top, root };\n}\n\n/**\n * An element's box, in CSS px relative to the shared `root` —\n * `getBoundingClientRect()` diffed against `geom.root`'s own rect. Same\n * approach `notationPlayerSvg.ts` uses throughout for its OSMD geometry\n * (`hostRect`/`rootRect` diffing — see that module), chosen here for the\n * SAME reason: `getBoundingClientRect()` already resolves every ancestor\n * transform between the element and the viewport, so it needs no separate\n * per-page `scale`/`offsetX`/`offsetY` math layered on top.\n *\n * PRIOR BUG (found via the OSMD->Verovio default-backend swap's ghost-\n * placement acceptance check, ~17px off on real pieces): this used to do\n * `el.getBBox()` (Verovio's rendered user-unit space) converted via\n * `geom.offsetX/offsetY + bbox.x/y * geom.scale` — correct ONLY if the only\n * transform between `el` and the page's own outer `<svg>` is the page's own\n * placement + viewBox scale. Verovio's real output wraps EVERY page's\n * content in `<g class=\"page-margin\" transform=\"translate(500, 500)\">`\n * (confirmed against a real 6.2.0 render) — an ancestor transform `getBBox()`\n * does NOT bake in (`getBBox()` is local to the element's own user space,\n * before any ancestor's transform is applied) and the old formula never\n * accounted for. Empirically: `500 * scale` (~17px at this fixture's\n * `outerRect.width / viewBox.width` ratio) matched the observed drift\n * exactly in both axes — every note landed ~17px up-and-left of its real\n * rendered position. `getBoundingClientRect()` has no such blind spot: it\n * is the browser's own answer to \"where is this actually painted,\" immune\n * to however many ancestor groups carry their own transform.\n *\n * Null for anything that isn't a real element or has a degenerate\n * (zero-area) box — same defensive style the old implementation had.\n */\nfunction boxFromElement(el: Element, geom: PageGeom): Box | null {\n const r = safeRect(el);\n const rootRect = safeRect(geom.root);\n if (!r || !rootRect || !(r.width > 0) || !(r.height > 0)) return null;\n return { x: r.left - rootRect.left, y: r.top - rootRect.top, w: r.width, h: r.height };\n}\n\nfunction computePageGeometries(root: Element): Map<Element, PageGeom> {\n const map = new Map<Element, PageGeom>();\n for (const pageEl of Array.from(root.querySelectorAll('.vrv-page'))) {\n const geom = pageGeometry(root, pageEl);\n if (geom) map.set(pageEl, geom);\n }\n return map;\n}\n\n/**\n * Every `<g class=\"measure\">` across all rendered pages that has at least\n * one `<g class=\"staff\">` child, in DOCUMENT ORDER (= musical order, since\n * pages are stacked in `.vrv-page` DOM order and Verovio renders each page's\n * measures left-to-right/top-to-bottom). This exact list's POSITION is the\n * single source of truth for the `index` every measure/note lookup in this\n * module uses (`verovioNotationLayout` AND `verovioOnsetColumns` both call\n * this, so they can never drift out of sync with each other — no separate\n * re-derivation of \"which position is this measure\" anywhere else).\n */\nfunction collectMeasureElements(pageGeoms: Map<Element, PageGeom>): { el: Element; geom: PageGeom }[] {\n const out: { el: Element; geom: PageGeom }[] = [];\n for (const [pageEl, geom] of pageGeoms) {\n for (const measureEl of Array.from(pageEl.querySelectorAll('g.measure'))) {\n if (measureEl.querySelector('g.staff')) out.push({ el: measureEl, geom });\n }\n }\n return out;\n}\n\n/**\n * Pure(ish) — DOM-in, `NotationLayout`-out — Verovio-backend geometry\n * extractor. `root` is the container holding every rendered `.vrv-page`\n * wrapper `<div>` (this player's `svgHost`; a test fixture must reproduce\n * that same wrapper structure — see the extractor tests). Builds the SAME\n * `NotationLayout` shape `svgNotationLayout` (notationPlayerSvg.ts) does,\n * from Verovio's rendered SVG DOM instead of OSMD's object model — see the\n * module doc for the full derivation (measure/staff/system/note lookup via\n * Verovio's own stable SVG classes, unit conversion via the live\n * width/viewBox on each page). Never throws; returns `EMPTY_LAYOUT` on any\n * missing/malformed structure.\n */\nexport function verovioNotationLayout(root: Element): NotationLayout {\n try {\n const pageGeoms = computePageGeometries(root);\n if (!pageGeoms.size) return EMPTY_LAYOUT;\n const measureEntries = collectMeasureElements(pageGeoms);\n if (!measureEntries.length) return EMPTY_LAYOUT;\n\n const measures: StaffMeasureBox[] = [];\n measureEntries.forEach(({ el: measureEl, geom }, index) => {\n const staffEls = Array.from(measureEl.querySelectorAll('g.staff'));\n const staffBoxes = staffEls\n .map((el) => ({ el, box: boxFromElement(el, geom) }))\n .filter((s): s is { el: Element; box: Box } => !!s.box)\n .sort((a, b) => a.box.y - b.box.y);\n staffBoxes.forEach(({ el: staffEl, box }, staff) => {\n const noteEls = Array.from(measureEl.querySelectorAll('g.note')).filter(\n (n) => n.closest('g.staff') === staffEl,\n );\n const noteXs = noteEls.map((n) => boxFromElement(n, geom)?.x).filter((x): x is number => x != null);\n const noteStartX = noteXs.length ? Math.min(...noteXs) : box.x;\n measures.push({ index, staff, box, noteStartX });\n });\n });\n if (!measures.length) return EMPTY_LAYOUT;\n\n const systems: Box[] = [];\n for (const [pageEl, geom] of pageGeoms) {\n for (const sysEl of Array.from(pageEl.querySelectorAll('g.system'))) {\n const box = boxFromElement(sysEl, geom);\n if (box) systems.push(box);\n }\n }\n\n const rootRect = safeRect(root);\n const fallbackW = Math.max(0, ...measures.map((m) => m.box.x + m.box.w));\n const fallbackH = Math.max(0, ...measures.map((m) => m.box.y + m.box.h));\n const dw = rootRect && rootRect.width > 0 ? rootRect.width : fallbackW;\n const dh = rootRect && rootRect.height > 0 ? rootRect.height : fallbackH;\n\n return { src: { x: 0, y: 0, w: dw, h: dh }, rect: { dx: 0, dy: 0, dw, dh }, systems, measures };\n } catch {\n return EMPTY_LAYOUT;\n }\n}\n\n/**\n * Resolve each DISTINCT onset (see `distinctOnsets`) to a `noteCols` entry —\n * the SAME \"real engraved column\" format `vstackAudioPlayheadLine` already\n * accepts from the SVG/canvas players (`measureIndex + fractionWithinMeasure`\n * — see that function's doc for how it's consumed). For each onset, every\n * stamped `noteId` sounding at that instant (a chord may have several) is\n * looked up by id in the live DOM (`document.getElementById` — Task 1 stamps\n * ids that Verovio preserves verbatim as SVG element ids), mapped to its\n * measure via `collectMeasureElements`'s canonical indexing (so it lines up\n * EXACTLY with `verovioNotationLayout`'s own `index` numbering), and its\n * fractional x-position within that measure's column computed with the exact\n * same formula `vstackAudioPlayheadLine`'s own `colX` uses internally (not\n * re-derived independently — this is the note's ANCHOR position, not new\n * interpolation math). A chord's several ids are averaged. Any onset with NO\n * resolvable id (missing from the DOM, e.g. a `rendered`-seam layout with no\n * live SVG) falls back to the ordinal spread `vstackAudioPlayheadLine` itself\n * uses when `noteCols` is entirely absent — so one bad id degrades ONLY that\n * onset, not the whole piece. Returns `undefined` (not a partially-bad array)\n * only when there is no usable layout/DOM at all to resolve against.\n */\nexport function verovioOnsetColumns(\n root: Element,\n layout: NotationLayout,\n onsets: VerovioOnset[],\n): number[] | undefined {\n try {\n const distinctMs = distinctOnsets(onsets.map((o) => ({ onsetMs: o.tMs })));\n if (!distinctMs.length) return undefined;\n const cols = measureColumnsFromLayout(layout.measures);\n if (!cols.length) return undefined;\n\n const pageGeoms = computePageGeometries(root);\n const measureEntries = collectMeasureElements(pageGeoms);\n if (!measureEntries.length) return undefined;\n const measureIndexOf = new Map<Element, number>();\n measureEntries.forEach((m, i) => measureIndexOf.set(m.el, i));\n\n const idsByOnset = new Map<number, string[]>();\n for (const o of onsets) {\n const arr = idsByOnset.get(o.tMs) ?? [];\n for (const id of o.noteIds) if (!arr.includes(id)) arr.push(id);\n idsByOnset.set(o.tMs, arr);\n }\n\n const doc = root.ownerDocument;\n\n return distinctMs.map((tMs, k) => {\n const ids = idsByOnset.get(tMs) ?? [];\n const positions: number[] = [];\n for (const id of ids) {\n const noteEl = doc ? doc.getElementById(id) : null;\n const measureEl = noteEl ? noteEl.closest('g.measure') : null;\n const index = measureEl ? measureIndexOf.get(measureEl) : undefined;\n if (index == null) continue;\n const m = cols[index];\n const geom = measureEntries[index]?.geom;\n // Anchor the onset at the NOTEHEAD CENTER, matching the OSMD\n // backend's column semantics. The whole-group left edge biased every\n // time->x position (and so every ghost) ~half a notehead LEFT — the\n // group box also includes accidentals/stems (user-visible drift,\n // 2026-08-20).\n const headGlyph = noteEl ? (noteEl.querySelector('.notehead') ?? noteEl) : null;\n const box = headGlyph && geom ? boxFromElement(headGlyph, geom) : null;\n if (!box || !m) continue;\n const sx = Math.min(m.noteStartX, m.x + m.w);\n const denom = m.x + m.w - sx;\n const anchorX = box.x + box.w / 2;\n const frac = denom > 0 ? Math.min(1, Math.max(0, (anchorX - sx) / denom)) : 0;\n positions.push(index + frac);\n }\n if (positions.length) return positions.reduce((a, b) => a + b, 0) / positions.length;\n // Same ordinal-spread fallback vstackAudioPlayheadLine uses internally\n // when no noteCols are supplied at all — degrades this ONE onset only.\n return distinctMs.length === 1 ? 0 : (k / (distinctMs.length - 1)) * cols.length;\n });\n } catch {\n return undefined;\n }\n}\n\n// ─── Note geometry (notePositions) + column→note lookup (markNotes) ───────\n\n/**\n * Every rendered note/rest joined to its MODEL identity (`noteModel`, from\n * `noteModelFromXml` — ./notationXml.ts) by stamped id — this player's\n * `notePositions()`. Same shape and host-relative-px contract as\n * notationPlayerSvg.ts's `engravedNotes` (its own doc: \"Positions are px\n * relative to the HOST element, at the notehead's center\"), but the join\n * itself is simpler here: unlike OSMD (one graphical group per CHORD,\n * requiring the pitch-rank head-sorting `engravedNotes` does), Verovio\n * renders every chord member as its OWN `<g id=\"...\" class=\"note\">`\n * (empirically confirmed — see the module doc's point 2) — so this is a\n * flat id→element→model join, no grouping/sorting.\n *\n * `headEl` prefers the note's own `.notehead` child (Verovio's real nested\n * glyph group — empirically confirmed as `<g class=\"notehead\">` inside\n * `<g class=\"note\">`) over the outer `g.note`/`g.rest` wrapper when\n * present — a TIGHTER box (closer to notationPlayerSvg.ts's\n * `.vf-notehead`-only box) than the wrapper, which also spans the\n * stem/flag/accidental. Falls back to the wrapper itself for a rest (no\n * `.notehead` child) or if that lookup's own `getBBox` fails.\n *\n * `root` is the container holding every rendered `.vrv-page` (this\n * player's `svgHost`); `host` is the player's OWN host element — `x`/`y`\n * are computed relative to `host` (per `EngravedNote`'s contract), NOT to\n * `root`, which may itself sit offset within `host`. Never throws; returns\n * `[]` for any missing/malformed structure (same defensive style as\n * `verovioNotationLayout`).\n */\nexport function verovioEngravedNotes(\n root: Element,\n host: HTMLElement,\n noteModel: Map<string, NoteModel>,\n): EngravedNote[] {\n try {\n const pageGeoms = computePageGeometries(root);\n if (!pageGeoms.size || !noteModel.size) return [];\n const measureEntries = collectMeasureElements(pageGeoms);\n if (!measureEntries.length) return [];\n\n const systems: Box[] = [];\n for (const [pageEl, geom] of pageGeoms) {\n for (const sysEl of Array.from(pageEl.querySelectorAll('g.system'))) {\n const box = boxFromElement(sysEl, geom);\n if (box) systems.push(box);\n }\n }\n\n const rootRect = safeRect(root);\n const hostRect = safeRect(host);\n const offX = rootRect && hostRect ? rootRect.left - hostRect.left : 0;\n const offY = rootRect && hostRect ? rootRect.top - hostRect.top : 0;\n\n const out: EngravedNote[] = [];\n for (const { el: measureEl, geom } of measureEntries) {\n const noteEls = Array.from(measureEl.querySelectorAll('g.note, g.rest'));\n for (const noteEl of noteEls) {\n const id = noteEl.getAttribute('id');\n if (!id) continue;\n const nm = noteModel.get(id);\n if (!nm) continue;\n\n const glyphEl = noteEl.querySelector('.notehead') ?? noteEl;\n let box = boxFromElement(glyphEl, geom);\n let headEl: Element = glyphEl;\n if (!box && glyphEl !== noteEl) {\n box = boxFromElement(noteEl, geom);\n headEl = noteEl;\n }\n if (!box) continue;\n\n out.push({\n midi: nm.midi,\n isRest: nm.isRest,\n tieContinuation: nm.tieContinuation,\n staffIndex: nm.staffIndex,\n systemIndex: systemIndexOfBox(systems, box),\n durationReal: nm.durationReal,\n x: offX + box.x + box.w / 2,\n y: offY + box.y + box.h / 2,\n w: box.w,\n h: box.h,\n headEl,\n });\n }\n }\n return out;\n } catch {\n return [];\n }\n}\n\n/**\n * Every rendered note/rest nearest engraved column `col`\n * (`measureIndex + fraction`, same units as `markNotes`' argument and\n * `noteCols`), one per staff of that measure — the Verovio-backend\n * counterpart to notationPlayerSvg.ts's `graphicalNotesAtColumn`. That\n * function searches OSMD's object model (`relInMeasureTimestamp` vs bar\n * duration); this searches the live rendered geometry instead (Verovio\n * exposes no per-element timestamp) — same \"nearest entry by position gap,\n * search every staff of the bar\" shape, just sourced from `getBBox` instead\n * of a timeline field. The fractional-position FORMULA itself\n * (`(box.x - sx) / denom`) is the exact one `verovioOnsetColumns` already\n * uses (not re-derived) — this function runs it in the opposite direction\n * (nearest note TO a column, rather than a column FROM a note id).\n */\nexport function verovioNotesAtColumn(root: Element, layout: NotationLayout, col: number): Element[] {\n try {\n if (!Number.isFinite(col)) return [];\n const cols = measureColumnsFromLayout(layout.measures);\n if (!cols.length) return [];\n const measureIndex = Math.max(0, Math.min(cols.length - 1, Math.floor(col)));\n const wanted = col - measureIndex;\n\n const pageGeoms = computePageGeometries(root);\n const measureEntries = collectMeasureElements(pageGeoms);\n const entry = measureEntries[measureIndex];\n if (!entry) return [];\n const m = cols[measureIndex];\n const sx = Math.min(m.noteStartX, m.x + m.w);\n const denom = m.x + m.w - sx;\n\n const found: Element[] = [];\n for (const staffEl of Array.from(entry.el.querySelectorAll('g.staff'))) {\n const noteEls = Array.from(staffEl.querySelectorAll('g.note, g.rest'));\n let best: Element | null = null;\n let bestGap = Number.POSITIVE_INFINITY;\n for (const noteEl of noteEls) {\n const box = boxFromElement(noteEl, entry.geom);\n if (!box) continue;\n const frac = denom > 0 ? (box.x - sx) / denom : 0;\n const gap = Math.abs(frac - wanted);\n if (gap < bestGap) {\n bestGap = gap;\n best = noteEl;\n }\n }\n if (best) found.push(best);\n }\n return found;\n } catch {\n return [];\n }\n}\n\n/**\n * CRITICAL empirical finding (verified against a real 6.2.0 render — see\n * the migration spike's follow-up, `.superpowers/…/print-object-test.mjs`\n * equivalent run for this task): Verovio's MusicXML importer HONORS\n * `print-object=\"no\"` for a pitched `<note>` (renders `visibility=\"hidden\"`\n * on its own `<g class=\"note\">`) but does NOT honor it for a `<note><rest/>`\n * — the `<g class=\"rest\">` renders fully visible regardless. This matters\n * because stave-web-sightread's `hideDoubledNotes` feature sets\n * `print-object=\"no\"` on BOTH doubled notes AND the rests of a voice that\n * lost every visible note (see that function's own \"second pass\" doc) —\n * without this fix, a hidden-doubled-note's voice would still show a\n * floating rest, exactly the \"extra voice\" clutter that feature exists to\n * remove.\n *\n * Fix: force `visibility=\"hidden\"` on every rendered id whose model says\n * `hidden` (`NoteModel.hidden`, from `noteModelFromXml`). Re-applying it to\n * a NOTE Verovio already hid itself is a harmless no-op; applying it to a\n * REST is the actual fix. Call after every render (`renderAllPages`) — a\n * fresh render is a fresh DOM, so a prior call's effect never carries over\n * (nothing to \"undo\" on a note/rest that's no longer print-object=\"no\").\n * Never throws.\n */\nexport function applyPrintObjectHiding(root: Element, noteModel: Map<string, NoteModel>): void {\n try {\n const doc = root.ownerDocument;\n if (!doc || !noteModel.size) return;\n for (const [id, nm] of noteModel) {\n if (!nm.hidden) continue;\n const el = doc.getElementById(id);\n if (el) el.setAttribute('visibility', 'hidden');\n }\n } catch {\n /* best-effort — a render this can't patch stays as Verovio drew it */\n }\n}\n\n// ─── Semantic zoom mapping ──────────────────────────────────────────────────\n\n/** Verovio glyph-size percent at semantic zoom 1 (matches the migration\n * spike's own default — a normal, readable size at typical host widths). */\nexport const VEROVIO_BASE_SCALE = 40;\n/** Clamp band for the derived `scale`, so an extreme `zoom` never collapses\n * glyphs to unreadable or blows them up past sane bounds. */\nexport const VEROVIO_MIN_SCALE = 20;\nexport const VEROVIO_MAX_SCALE = 120;\n\nexport interface VerovioRenderOptions {\n scale: number;\n pageWidth: number;\n}\n\n/**\n * Verovio layout/line-breaking options a caller may override — see\n * `CreateVerovioNotationPlayerOpts.verovioOptions`'s doc for the merge\n * contract and Stave's own motivating use case (encoded `<print\n * new-system=\"yes\"/>` breaks + `breaks: 'line'`, exact N-bars-per-line).\n * Deliberately NARROWER than Verovio's full option surface — only the knobs\n * this integration has an actual caller for; add more here (not a raw\n * `Record<string, unknown>` passthrough) as real needs arise, so a typo in a\n * caller's options object is a compile error, not a silently-ignored no-op.\n */\nexport interface VerovioLayoutOptions {\n breaks?: 'none' | 'auto' | 'line' | 'smart' | 'encoded';\n breaksSmartSb?: number;\n breaksNoWidow?: boolean;\n minLastJustification?: number;\n spacingSystem?: number;\n spacingStaff?: number;\n}\n\n/**\n * Layout defaults applied to EVERY engrave (initial + every reflow) unless a\n * caller's own `verovioOptions` overrides a given key — see\n * `verovioRenderOptions`'s doc for the merge order.\n *\n * WHY: Verovio only justifies a page's LAST system when its unstretched\n * width is already ≥ `minLastJustification` (Verovio's own default: 0.8) of\n * the page width — confirmed empirically (a 4-bar-of-whole-notes fixture at\n * pageWidth 2400 renders its single system at ~41% of the page width with\n * Verovio's own default, ~96% with `minLastJustification: 0`; see this\n * module's real-Verovio justification test). A short excerpt — the common\n * case for both this player's normal usage (a few bars at a time) AND\n * Stave's per-line-break usage (section below) — is ALWAYS a \"last system\"\n * (it's the only one), so Verovio's default leaves it looking\n * left-justified/shrunk rather than filling the available width. Overriding\n * to 0 makes every system justify unconditionally, matching this player's\n * own \"fill the host width\" semantic (`verovioZoomOptions`'s own doc).\n * `breaksNoWidow: true` prevents Verovio leaving a single trailing bar\n * orphaned on its own system (a related \"short excerpt\" artifact, same\n * spirit as the justification fix). `breaks: 'auto'` (Verovio's own default\n * line-breaking algorithm) is the base default; Stave overrides it to\n * `'line'` when it has ALREADY encoded exact break points (see\n * `VerovioLayoutOptions`'s doc) — see the \"caller's `breaks` wins\" case in\n * `verovioRenderOptions`'s own tests.\n */\nexport const VEROVIO_LAYOUT_DEFAULTS = {\n breaks: 'auto',\n minLastJustification: 0,\n breaksNoWidow: true,\n} as const;\n\n/**\n * The full `toolkit.setOptions(...)` argument for one engrave: layout\n * defaults, overridden by the caller's own `layout` (a caller's `breaks`\n * WINS over `VEROVIO_LAYOUT_DEFAULTS.breaks` — this is the whole point of\n * exposing the override), overridden AGAIN by `scale`/`pageWidth` (derived\n * from `hostWidthPx`/`zoom` via `verovioZoomOptions` — a caller's\n * `verovioOptions` has no `scale`/`pageWidth` keys per `VerovioLayoutOptions`\n * own (narrower) type, so this last spread is really just making the\n * derived-vs-defaulted precedence explicit, not fighting a real collision)\n * and `adjustPageHeight: true` (always on — this player's own \"whole score,\n * page-flow, no pagination\" framing, see the module doc's \"PAGES\" section).\n * Pure — exists so the merge itself is unit-testable without a DOM or a real\n * Verovio toolkit (`tests/notationPlayerVerovio.test.ts`'s \"options merge\"\n * tests call this directly).\n */\nexport function verovioRenderOptions(\n hostWidthPx: number,\n zoom: number,\n layout?: VerovioLayoutOptions,\n): Record<string, unknown> {\n const { scale, pageWidth } = verovioZoomOptions(hostWidthPx, zoom);\n return { ...VEROVIO_LAYOUT_DEFAULTS, ...layout, scale, pageWidth, adjustPageHeight: true };\n}\n\n/**\n * 1 when every system already fits within `engraveWidthPx` (widest ≤ width\n * × 1.01 — a small tolerance for sub-pixel rounding in the DOM geometry, not\n * a real \"close enough\" fudge); otherwise `engraveWidthPx / widest` (< 1) —\n * the zoom-scaling factor that would bring the widest system back down to\n * exactly `engraveWidthPx`. Never NaN/Infinity: an empty `systemWidthsPx`,\n * a non-finite/non-positive widest width, or a non-finite/non-positive\n * `engraveWidthPx` all return 1 (the safe \"don't touch the zoom\" default —\n * see the module doc's \"Fit-to-width\" section for how the caller uses this:\n * a factor < 1 triggers exactly ONE re-engrave at `requestedZoom * factor`,\n * never a loop).\n *\n * WHY THIS IS NEEDED (see `VEROVIO_LAYOUT_DEFAULTS`'s doc for the\n * complementary justification fix): with ENCODED breaks (`breaks: 'line'` +\n * Stave's own `<print new-system=\"yes\"/>` markers), Verovio must put\n * whatever notes fall between two encoded break points onto one system —\n * unlike `breaks: 'auto'`, it cannot relieve overcrowding by moving a\n * measure to the next line. If that system is too dense to fit\n * `engraveWidthPx` even at Verovio's own minimum inter-note spacing, Verovio\n * renders it WIDER than the requested page width instead of silently\n * clipping it. Shrinking the effective zoom (smaller glyphs, smaller\n * spacing) is the only lever left to bring it back within the host's\n * available width.\n */\nexport function fitZoomFactor(systemWidthsPx: readonly number[], engraveWidthPx: number): number {\n if (!systemWidthsPx.length) return 1;\n if (!(engraveWidthPx > 0) || !Number.isFinite(engraveWidthPx)) return 1;\n const widest = Math.max(...systemWidthsPx);\n if (!(widest > 0) || !Number.isFinite(widest)) return 1;\n if (widest <= engraveWidthPx * 1.01) return 1;\n const factor = engraveWidthPx / widest;\n return Number.isFinite(factor) && factor > 0 ? factor : 1;\n}\n\n/**\n * Semantic zoom → Verovio options. The migration spike's `zoom-test*.mjs`\n * proved `pageWidth` (Verovio's line-breaking width, in ITS OWN units)\n * drives measures-per-system while `scale` (glyph size) alone does NOT\n * (avgMeasuresPerSystem was IDENTICAL — 3.61 — across scale 40/80/150 at a\n * fixed pageWidth 1600; it moved 2.24→3.61→5.91 as pageWidth alone rose\n * 1000→1600→2400 at a fixed scale). Verovio's own rendered SVG width in CSS\n * px is EXACTLY `pageWidth * scale / 100` (confirmed empirically against\n * real 6.2.0 renders) — an identity, not an approximation.\n *\n * This function picks `scale` proportional to `zoom` (bigger zoom ⇒ bigger\n * glyphs) and then SOLVES that identity for the `pageWidth` that makes the\n * rendered width land EXACTLY on `hostWidthPx` regardless of zoom\n * (`pageWidth = hostWidthPx * 100 / scale`). Composing it this way — instead\n * of tuning `scale` and `pageWidth` independently — makes BOTH halves of the\n * spec's semantic fall out of the ONE formula: as `zoom` rises, `scale`\n * rises (glyphs bigger) AND the required `pageWidth` (in Verovio units)\n * SHRINKS proportionally (since it's inversely proportional to `scale` at a\n * fixed target width) — and per the spike's own finding, a smaller\n * `pageWidth` fits FEWER measures per system. So \"bigger zoom ⇒ fewer\n * measures/system, glyphs larger, width still fits host\" (design doc §2) is\n * a direct consequence of this one identity, pinned by\n * `tests/notationPlayerVerovio.test.ts`'s real-Verovio monotonicity test.\n *\n * No floor on `pageWidth` beyond what the identity itself produces: `scale`\n * is already clamped to `[VEROVIO_MIN_SCALE, VEROVIO_MAX_SCALE]` (both > 0)\n * and `hostWidthPx` is floored to a sane fallback when invalid, so\n * `pageWidth = w * 100 / scale` is ALWAYS finite and positive — an\n * additional floor would only ever fire by breaking the width-fits-host\n * identity (clamping the OUTPUT width away from the host's actual width),\n * which is worse than a small `pageWidth`.\n */\nexport function verovioZoomOptions(hostWidthPx: number, zoom: number): VerovioRenderOptions {\n const z = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;\n const scale = Math.max(VEROVIO_MIN_SCALE, Math.min(VEROVIO_MAX_SCALE, VEROVIO_BASE_SCALE * z));\n const w = Number.isFinite(hostWidthPx) && hostWidthPx > 0 ? hostWidthPx : MAX_ENGRAVE_WIDTH_VRV;\n const pageWidth = (w * 100) / scale;\n return { scale, pageWidth };\n}\n\n// ─── Shared module-level toolkit (see the module doc's \"SHARED TOOLKIT\n// INSTANCE\" section) ─────────────────────────────────────────────────\n\n/** The subset of `VerovioToolkit`'s instance API this module calls — see\n * `src/types/verovio.d.ts` for the ambient module declaration backing the\n * dynamic imports below (the `verovio` npm package ships no types of its\n * own). Deliberately duck-typed/local rather than importing the real class\n * type statically, so nothing about this module's own type-checking\n * depends on a STATIC import of `verovio/esm` (only the dynamic one inside\n * `getVerovioToolkit` touches the package at all, which is what tsup's\n * `external` + the build-audit grep gate verify). */\ninterface VerovioToolkitInstance {\n loadData(data: string): boolean;\n getPageCount(): number;\n renderToSVG(page: number): string;\n setOptions(options: Record<string, unknown>): void;\n redoLayout(options?: Record<string, unknown>): void;\n}\n\nlet toolkitPromise: Promise<VerovioToolkitInstance> | null = null;\n\nfunction getVerovioToolkit(): Promise<VerovioToolkitInstance> {\n if (!toolkitPromise) {\n toolkitPromise = (async () => {\n // Literal dynamic imports — consumers' bundlers must statically see\n // these specifiers to code-split Verovio out of every OTHER dist\n // entry (tsup marks `verovio` external — see tsup.config.ts + the\n // build report's dist-grep evidence). A caller that only ever uses\n // the `rendered` test seam never pulls Verovio in at all.\n const [{ default: createVerovioModule }, { VerovioToolkit }] = await Promise.all([\n import('verovio/wasm'),\n import('verovio/esm'),\n ]);\n const VerovioModule = await createVerovioModule();\n return new VerovioToolkit(VerovioModule) as unknown as VerovioToolkitInstance;\n })();\n }\n return toolkitPromise;\n}\n\n/**\n * Module-level SERIAL queue over the shared toolkit — bug E7M-322: in\n * production, remounting a player component several times in quick\n * succession (destroying each instance before its `ready` resolved, EVERY\n * instance awaiting the SAME shared `getVerovioToolkit()` promise) produced\n * an Emscripten \"null function\" error from the WASM bridge. `withToolkit`\n * makes every `setOptions -> loadData -> getPageCount/renderToSVG` sequence,\n * across EVERY live player, run to completion strictly one at a time — even\n * across the async wasm-load boundary the very first call incurs. Each\n * queued task is chained off the PREVIOUS task's own settled promise (not\n * off `toolkitPromise` directly), so two tasks queued back-to-back before\n * the toolkit even exists yet still serialize correctly once it resolves;\n * without this, both would `await` the same not-yet-resolved\n * `getVerovioToolkit()` promise and their synchronous toolkit-touching code\n * could run in whatever order the two continuations happen to be scheduled,\n * which is exactly the \"several players hammering the one shared instance\n * at once\" shape the production bug had.\n *\n * `fn` MUST stay synchronous (no `await` inside it) — same \"no interleaving\n * because no await between reclaim and render\" rule `reflow`'s own doc\n * already relied on; the queue is what now makes that rule hold ACROSS\n * players' tasks, not just within one player's own call. A task that has\n * gone stale while queued (its player was destroyed while waiting for its\n * turn) must check `destroyed` as the FIRST thing inside `fn` and return a\n * no-op result — `withToolkit` itself has no opinion on staleness, only\n * serialization (see `initialEngrave`/`reflow`'s own `fn` bodies).\n *\n * A rejecting task never wedges the queue for tasks queued after it (the\n * internal chain swallows the rejection); the ORIGINAL caller still sees\n * their own task's rejection via the promise `withToolkit` returns, since\n * that is tracked separately from the internal queue chain.\n */\nlet toolkitQueue: Promise<unknown> = Promise.resolve();\n\nfunction withToolkit<T>(fn: (toolkit: VerovioToolkitInstance) => T): Promise<T> {\n const run = toolkitQueue.then(() => getVerovioToolkit()).then((toolkit) => fn(toolkit));\n toolkitQueue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n}\n\n// ─── createVerovioNotationPlayer ────────────────────────────────────────────\n\n// Module-level (not per-instance) — see `osmdOptions`'s doc: a caller\n// building many players with the same options object should see this once\n// per SESSION, not once per player.\nlet loggedAutoBeamIgnored = false;\n\nconst DEFAULT_PLAYHEAD_COLOR = '#2f6f4f';\n/** Engrave-width ceiling, CSS px — same policy as notationPlayerSvg.ts's\n * `MAX_ENGRAVE_WIDTH_SVG` (design doc §\"Render\": \"cap ~1200px\"), restated\n * independently since the two players' constants are independently\n * tunable. Raised 1200 -> 1400: Stave's encoded-break usage\n * (`verovioOptions.breaks: 'line'`, exact N-bars-per-line) wants more\n * breathing room per system than the original OSMD-parity cap allowed\n * before glyphs get cramped at typical desktop widths. */\nexport const MAX_ENGRAVE_WIDTH_VRV = 1400;\n/** Floor so a not-yet-laid-out / zero-width host never engraves at 0px. */\nconst MIN_ENGRAVE_WIDTH_VRV = 280;\n\n/** Build a live, interactive Verovio (vector) notation player. See the\n * module doc + `docs/superpowers/specs/2026-08-11-verovio-player-design.md`\n * (in stave-web-sightread) §2 for the full design. */\nexport function createVerovioNotationPlayer(opts: CreateVerovioNotationPlayerOpts): VerovioNotationPlayer {\n const { host, musicXml, onsets: rawOnsets } = opts;\n const playheadColor = opts.playheadColor ?? DEFAULT_PLAYHEAD_COLOR;\n const onsets = distinctOnsets(rawOnsets.map((o) => ({ onsetMs: o.tMs })));\n\n if (opts.osmdOptions?.autoBeam !== undefined && !loggedAutoBeamIgnored) {\n loggedAutoBeamIgnored = true;\n // eslint-disable-next-line no-console\n console.warn(\n '[notationPlayerVerovio] osmdOptions.autoBeam has no Verovio equivalent (Verovio always beams from the ' +\n 'MusicXML <beam> data) — ignored.',\n );\n }\n\n // Stamp once, up front — pure/idempotent (./notationXml.ts's doc), so\n // re-stamping a caller's already-stamped xml (e.g. stave's own transform\n // pipeline) reproduces the exact same ids. `noteModel` is likewise a pure\n // function of this same stamped string, computed once and reused across\n // every re-engrave (`setZoom`/`resize` never change note IDENTITY, only\n // geometry). The `rendered` test seam has no real document to stamp/model\n // against — `notePositions()`/`markNotes()` degrade gracefully to `[]`/\n // no-op there, same as `verovioOnsetColumns` already does for that seam.\n const stampedXml = opts.rendered ? musicXml : stampNoteIds(musicXml);\n const noteModel: Map<string, NoteModel> = opts.rendered ? new Map() : noteModelFromXml(stampedXml);\n\n const root = document.createElement('div');\n root.style.position = 'relative';\n root.style.width = '100%';\n // Same \"optical zoom is free\" reasoning as notationPlayerSvg.ts — let\n // native pinch-zoom + vertical page-scroll gestures through unimpeded.\n root.style.touchAction = 'pan-y pinch-zoom';\n host.appendChild(root);\n\n const svgHost = document.createElement('div');\n root.appendChild(svgHost);\n\n const playheadEl = document.createElement('div');\n // Published contract: hosts may locate the playhead (e.g. to keep it in\n // view inside their own scroll container) via [data-rmp-playhead] — same\n // attribute notationPlayerSvg.ts sets, same reasoning (see its own\n // comment). The element stays owned by this component — position/size\n // are not API.\n playheadEl.dataset.rmpPlayhead = '1';\n playheadEl.style.position = 'absolute';\n playheadEl.style.left = '0px';\n playheadEl.style.top = '0px';\n playheadEl.style.width = '2px';\n playheadEl.style.height = '0px';\n playheadEl.style.background = playheadColor;\n playheadEl.style.opacity = '0';\n playheadEl.style.pointerEvents = 'none';\n root.appendChild(playheadEl);\n\n let currentLayout: NotationLayout | null = null;\n let currentNoteCols: number[] | undefined;\n let currentZoom = opts.zoom ?? 1;\n let lastEngravedWidthPx = 0;\n let loaded = false; // toolkit.loadData succeeded (rendered-seam path never sets this)\n let destroyed = false;\n let lastTMs = 0;\n // Stale-reflow guard — same \"each async re-engrave captures its own\n // token\" rule as notationPlayerSvg.ts's `rebuildToken`.\n let rebuildToken = 0;\n\n function desiredEngraveWidthPx(): number {\n const w = host.clientWidth || 0;\n return Math.max(MIN_ENGRAVE_WIDTH_VRV, Math.min(w || MAX_ENGRAVE_WIDTH_VRV, MAX_ENGRAVE_WIDTH_VRV));\n }\n\n // ─── Playhead + auto-follow (createFollowController — notationCommon.ts) ─\n\n const follow = createFollowController({ topMarginPx: opts.followTopMarginPx });\n\n function renderPlayhead(tMs: number): void {\n lastTMs = tMs;\n if (!currentLayout) return;\n const nBars = currentLayout.measures.length\n ? Math.max(...currentLayout.measures.map((m) => m.index)) + 1\n : 0;\n const line = vstackAudioPlayheadLine(currentLayout, onsets, tMs, nBars, currentNoteCols);\n if (!line) {\n playheadEl.style.opacity = '0';\n return;\n }\n playheadEl.style.opacity = String(line.alpha);\n playheadEl.style.left = `${line.x}px`;\n playheadEl.style.top = `${line.y0}px`;\n playheadEl.style.height = `${Math.max(0, line.y1 - line.y0)}px`;\n const layoutForFollow = currentLayout;\n const sys = line.sys ?? -1;\n follow.follow({\n systemIndex: sys,\n getSystemRect: () => {\n const box = layoutForFollow.systems[sys];\n if (!box) return null;\n const rootRect = safeRect(root);\n if (!rootRect) return null;\n return { top: rootRect.top + box.y, bottom: rootRect.top + box.y + box.h };\n },\n getPlayheadRect: () => safeRect(playheadEl),\n });\n }\n\n function setTime(tMs: number): void {\n if (destroyed) return;\n follow.onSetTime(tMs);\n renderPlayhead(tMs);\n }\n\n // ─── Engrave / reflow ──────────────────────────────────────────────────\n\n function rebuildLayoutFromDom(): void {\n currentLayout = verovioNotationLayout(svgHost);\n currentNoteCols = verovioOnsetColumns(svgHost, currentLayout, rawOnsets);\n }\n\n function renderAllPages(toolkit: VerovioToolkitInstance): void {\n svgHost.replaceChildren();\n const pageCount = Math.max(0, toolkit.getPageCount());\n for (let p = 1; p <= pageCount; p++) {\n const pageDiv = document.createElement('div');\n pageDiv.className = 'vrv-page';\n pageDiv.innerHTML = toolkit.renderToSVG(p);\n svgHost.appendChild(pageDiv);\n }\n // Verovio honors print-object=\"no\" for pitched notes on its own but NOT\n // for rests (empirical finding — see applyPrintObjectHiding's own doc);\n // this patches the gap. Every fresh render is a fresh DOM, so this must\n // run after EVERY renderAllPages call, not just the initial one.\n applyPrintObjectHiding(svgHost, noteModel);\n }\n\n // ─── markNotes (survives re-engraving — reapplied after every render) ──\n\n let markedCols: number[] = [];\n\n function applyMarks(): void {\n for (const el of svgHost.querySelectorAll(`.${MARKED_NOTE_CLASS}`)) {\n el.classList.remove(MARKED_NOTE_CLASS);\n }\n if (!currentLayout || !markedCols.length) return;\n for (const col of markedCols) {\n for (const el of verovioNotesAtColumn(svgHost, currentLayout, col)) {\n el.classList.add(MARKED_NOTE_CLASS);\n }\n }\n }\n\n /**\n * Engrave `stampedXml` into the shared toolkit at (`widthPx`, `zoom`),\n * read the resulting layout back from the DOM, and — if `verovioOptions`\n * (encoded/forced breaks) produced a system wider than the page — re-\n * engrave ONCE more at a proportionally smaller effective zoom (see\n * `fitZoomFactor`'s own doc for why this can happen and the module doc's\n * \"Fit-to-width\" section). MUST run synchronously start-to-finish (no\n * `await` inside) — this is the `fn` passed to `withToolkit`, and its\n * single-sequence-at-a-time guarantee depends on that (see `withToolkit`'s\n * own doc). `currentZoom` is intentionally NOT updated here for the fit\n * correction — only the caller (`initialEngrave`/`reflow`) tracks the\n * user's REQUESTED zoom, so a later `setZoom(z)` steps from that requested\n * value, not from whatever the fit correction happened to render at; the\n * fit is recomputed fresh on every engrave rather than remembered.\n * Returns whether the FIRST pass's `loadData` succeeded — a failed fit\n * re-engrave (rare: would need the same document to parse twice\n * differently) just leaves the first pass's already-rendered content in\n * place rather than blanking the player.\n */\n function engraveOnce(toolkit: VerovioToolkitInstance, widthPx: number, zoom: number): boolean {\n toolkit.setOptions(verovioRenderOptions(widthPx, zoom, opts.verovioOptions));\n const ok = !!toolkit.loadData(stampedXml);\n if (ok) renderAllPages(toolkit);\n rebuildLayoutFromDom();\n\n if (ok && currentLayout) {\n const factor = fitZoomFactor(\n currentLayout.systems.map((s) => s.w),\n widthPx,\n );\n if (factor < 1) {\n const effectiveZoom = zoom * factor;\n toolkit.setOptions(verovioRenderOptions(widthPx, effectiveZoom, opts.verovioOptions));\n const ok2 = !!toolkit.loadData(stampedXml);\n if (ok2) {\n renderAllPages(toolkit);\n rebuildLayoutFromDom();\n }\n // A failed second loadData leaves the FIRST pass's render (still in\n // svgHost/currentLayout from just above) untouched — degrade to\n // \"unfit but rendered\" rather than blank.\n }\n }\n return ok;\n }\n\n async function initialEngrave(): Promise<void> {\n if (opts.rendered) {\n currentLayout = opts.rendered;\n lastEngravedWidthPx = desiredEngraveWidthPx();\n renderPlayhead(lastTMs);\n return;\n }\n\n const widthPx = desiredEngraveWidthPx();\n const ok = await withToolkit((toolkit) => {\n if (destroyed) return false; // stale — this player died while queued\n return engraveOnce(toolkit, widthPx, currentZoom);\n });\n if (destroyed) return;\n\n lastEngravedWidthPx = widthPx;\n loaded = ok;\n applyMarks();\n renderPlayhead(lastTMs);\n }\n\n const ready = initialEngrave();\n\n /** Re-engrave at `newZoom` and the host's CURRENT width, preserving the\n * scroll position of whatever content is centered in the viewport right\n * now. Shared by both `setZoom` and `resize` — same shape as\n * notationPlayerSvg.ts's `reflow`. No-op when neither the width nor the\n * zoom actually changed, or when using the `rendered` test seam / the\n * initial load never succeeded (nothing to re-engrave). */\n async function reflow(newZoom: number): Promise<void> {\n if (destroyed) return;\n const widthPx = desiredEngraveWidthPx();\n if (widthPx === lastEngravedWidthPx && newZoom === currentZoom) return;\n if (opts.rendered || !loaded) {\n currentZoom = newZoom;\n return;\n }\n\n const myToken = ++rebuildToken;\n const oldLayout = currentLayout;\n const hasWin = typeof window !== 'undefined';\n let anchorY: number | null = null;\n const anchorX = widthPx / 2;\n if (hasWin && typeof root.getBoundingClientRect === 'function') {\n const r = root.getBoundingClientRect();\n anchorY = window.innerHeight / 2 - r.top;\n }\n\n // RECLAIM (see the module doc's \"SHARED TOOLKIT INSTANCE\" note, and\n // `withToolkit`'s own doc for bug E7M-322): the module-level toolkit is\n // shared across every live player on the page — and the real consumer\n // (PlayerPage) keeps a harmony player AND a written player alive\n // SIMULTANEOUSLY (lazy-built, destroyed only on piece switch), so\n // `loadData` calls from the two players genuinely interleave (e.g.\n // harmony active -> resize while written hidden -> back to written ->\n // writtenPlayer.setZoom()). A plain `redoLayout()` here would silently\n // re-lay-out and render WHATEVER document the toolkit currently holds —\n // which may belong to the OTHER player if it rendered more recently. So\n // `engraveOnce` re-parses THIS player's own `musicXml` synchronously,\n // immediately before rendering (loadData does a full parse + layout with\n // the just-set options, making a separate `redoLayout()` call\n // redundant). `withToolkit` now additionally guarantees no OTHER\n // player's queued task can run its own setOptions/loadData/render\n // sequence in between this task's own steps — the shared singleton is\n // therefore safe under alternating AND concurrent use. See\n // `tests/notationPlayerVerovio.test.ts`'s two-player interleaved-reflow\n // test for the regression this guards against.\n const ok = await withToolkit((toolkit) => {\n if (destroyed || myToken !== rebuildToken) return false; // stale\n return engraveOnce(toolkit, widthPx, newZoom);\n });\n\n if (destroyed || myToken !== rebuildToken) return;\n if (!ok) {\n loaded = false;\n return;\n }\n\n lastEngravedWidthPx = widthPx;\n currentZoom = newZoom;\n applyMarks();\n\n if (oldLayout && currentLayout && anchorY != null && hasWin) {\n const delta = computeReflowScrollDelta(oldLayout, currentLayout, anchorX, anchorY);\n if (Number.isFinite(delta) && Math.abs(delta) > 0.5) {\n window.scrollTo({ top: Math.max(0, window.scrollY + delta), left: window.scrollX, behavior: 'auto' });\n }\n }\n if (!destroyed) renderPlayhead(lastTMs);\n }\n\n // ─── Click-to-seek ─────────────────────────────────────────────────────\n\n const clickListeners: Array<(measureIndex: number) => void> = [];\n function onRootClick(e: MouseEvent): void {\n if (!currentLayout) return;\n const rect = root.getBoundingClientRect();\n const mx = e.clientX - rect.left;\n const my = e.clientY - rect.top;\n const idx = hitTestMeasureAt(currentLayout, mx, my);\n if (idx != null) for (const cb of clickListeners) cb(idx);\n }\n root.addEventListener('click', onRootClick);\n\n return {\n ready,\n setTime,\n markNotes(cols: number[] | null): void {\n markedCols = cols ?? [];\n applyMarks();\n },\n notePositions(): EngravedNote[] {\n return verovioEngravedNotes(svgHost, host, noteModel);\n },\n setFollowEnabled(on) {\n follow.setEnabled(on);\n },\n async setZoom(z: number): Promise<void> {\n await ready;\n await reflow(z);\n },\n async resize(): Promise<void> {\n await ready;\n await reflow(currentZoom);\n },\n onMeasureClick(cb: (measureIndex: number) => void): () => void {\n clickListeners.push(cb);\n return () => {\n const i = clickListeners.indexOf(cb);\n if (i >= 0) clickListeners.splice(i, 1);\n };\n },\n destroy(): void {\n if (destroyed) return;\n destroyed = true;\n rebuildToken++;\n root.removeEventListener('click', onRootClick);\n follow.destroy();\n clickListeners.length = 0;\n markedCols = [];\n currentLayout = null;\n currentNoteCols = undefined;\n if (root.parentNode === host) host.removeChild(root);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBO,SAAS,aAAa,KAAqB;AAChD,QAAM,MAAM,IAAI,UAAU,EAAE,gBAAgB,KAAK,iBAAiB;AAClE,MAAI,IAAI,cAAc,aAAa,EAAG,QAAO;AAE7C,QAAM,QAAQ,MAAM,KAAK,IAAI,iBAAiB,uBAAuB,CAAC;AACtE,QAAM,QAAQ,CAAC,MAAM,YAAY;AAC/B,eAAW,WAAW,MAAM,KAAK,KAAK,iBAAiB,SAAS,CAAC,GAAG;AAClE,YAAM,SAAS,QAAQ,aAAa,QAAQ,KAAK;AACjD,YAAM,QA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A,IACA,UAAgB;AACd,UAAI,UAAW;AACf,kBAAY;AACZ;AACA,WAAK,oBAAoB,SAAS,WAAW;AAC7C,aAAO,QAAQ;AACf,qBAAe,SAAS;AACxB,mBAAa,CAAC;AACd,sBAAgB;AAChB,wBAAkB;AAClB,UAAI,KAAK,eAAe,KAAM,MAAK,YAAY,IAAI;AAAA,IACrD;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/notationXml.ts","../src/notationPlayerVerovio.ts"],"sourcesContent":["// Pure MusicXML→MusicXML/model helpers for `createVerovioNotationPlayer`\n// (notationPlayerVerovio.ts, 0.40.0) — the id-stamping + note-model half of\n// its \"join model ids to Verovio's rendered SVG\" approach (that module's\n// header doc, point 1). No DOM rendering here; everything in this file is\n// pure XML-in → XML/data-out, unit-testable with no live SVG at all.\n//\n// OWNERSHIP NOTE — `stampNoteIds`'s deterministic id scheme\n// (`n-{partIdx}-{measureNumber}-{noteIdxInMeasure}`) is DELIBERATELY\n// duplicated, byte-for-byte, from stave-web-sightread's\n// `src/lib/bach/xmlTransforms.ts:stampNoteIds` (part of that repo's Verovio\n// transform pipeline, docs/superpowers/specs/2026-08-11-verovio-player-design.md\n// §1). stave's copy is the one actually wired into `parseReduction` (its\n// `noteIds` per span must match what got stamped onto the MusicXML BEFORE\n// Verovio ever saw it), so stave remains that scheme's owner for the\n// pipeline's purposes. This copy exists so `createVerovioNotationPlayer`\n// works correctly for ANY caller — including ones that hand in un-stamped\n// MusicXML — without a runtime dependency from web-core back into an app\n// repo (the wrong direction for a shared package). Both copies are pure\n// functions of a note's POSITION (never of any id already present), so\n// calling either one on already-stamped input reproduces the exact same\n// ids — the two copies can never drift apart in OBSERVABLE behavior even\n// though they are physically two files. If the scheme ever needs to change,\n// change it in BOTH places (this file's own tests pin the scheme\n// independently of stave's, so a one-sided edit fails a test here).\nexport function stampNoteIds(xml: string): string {\n const doc = new DOMParser().parseFromString(xml, 'application/xml');\n if (doc.querySelector('parsererror')) return xml;\n\n const parts = Array.from(doc.querySelectorAll('score-partwise > part'));\n parts.forEach((part, partIdx) => {\n for (const measure of Array.from(part.querySelectorAll('measure'))) {\n const number = measure.getAttribute('number') ?? '0';\n const notes = Array.from(measure.children).filter((el) => el.tagName === 'note');\n notes.forEach((note, noteIdx) => {\n note.setAttribute('id', `n-${partIdx}-${number}-${noteIdx}`);\n });\n }\n });\n\n return new XMLSerializer().serializeToString(doc);\n}\n\n// ─── injectSystemBreaks / balancedSystemBreaks — widow-avoidance helpers ──\n//\n// Used by notationPlayerVerovio.ts's widow pass (`engraveOnce`): when\n// `breaks: 'auto'` leaves a lone trailing measure on its own system (a\n// \"widow\" — Verovio's own `breaksNoWidow` only guards the last PAGE, not the\n// last SYSTEM, per that module's doc), the player forces exact line breaks\n// via `injectSystemBreaks` + `breaks: 'line'`, choosing the break points with\n// `balancedSystemBreaks` so the same number of systems comes out evenly\n// filled instead of front-loaded-then-orphaned.\n//\n// CONTRACT DUPLICATION NOTICE (same reasoning as `stampNoteIds`'s own\n// OWNERSHIP NOTE above): stave-web-sightread's `src/lib/bach/xmlTransforms.ts`\n// has its OWN `injectSystemBreaks` implementing this EXACT contract\n// independently — a shared package must not runtime-depend on an app repo\n// for something this small, so the logic is duplicated rather than imported.\n// Keep both copies in sync if the contract ever changes; each repo's own\n// tests pin its own copy independently.\n\n/**\n * Insert `<print new-system=\"yes\"/>` as the FIRST child of the `<measure>`\n * at each 0-based position in `breakBeforeBarIndexes`, in EVERY `<part>`\n * (a score's parts share one measure timeline, so a break must be encoded\n * once per part for Verovio to line the systems up across staves). A\n * position that is ≤ 0 or ≥ that part's own measure count is silently\n * ignored FOR THAT PART (0 is a no-op — a part already starts a new system\n * at its own first measure). Idempotent: a measure that already carries a\n * `<print>` element (from a prior call, or from the source data) gets\n * `new-system=\"yes\"` SET on that existing element rather than gaining a\n * second one — calling this twice with the same positions serializes\n * identically both times. Malformed input (fails to parse) is returned\n * unchanged, same defensive style as `stampNoteIds` above. Only ever ADDS\n * `<print>` elements — never touches a `<note>` — so `stampNoteIds`'s\n * position-based id scheme is unaffected by a prior or subsequent call to\n * this function (see this file's own tests for the pinned invariant).\n */\nexport function injectSystemBreaks(xml: string, breakBeforeBarIndexes: readonly number[]): string {\n const doc = new DOMParser().parseFromString(xml, 'application/xml');\n if (doc.querySelector('parsererror')) return xml;\n\n const root = doc.documentElement;\n if (!root || root.tagName !== 'score-partwise') return xml;\n\n for (const part of childrenNamed(root, 'part')) {\n const measures = childrenNamed(part, 'measure');\n for (const pos of breakBeforeBarIndexes) {\n if (!Number.isInteger(pos) || pos <= 0 || pos >= measures.length) continue;\n const measure = measures[pos];\n const existingPrint = firstChildNamed(measure, 'print');\n if (existingPrint) {\n existingPrint.setAttribute('new-system', 'yes');\n } else {\n const printEl = doc.createElement('print');\n printEl.setAttribute('new-system', 'yes');\n measure.insertBefore(printEl, measure.firstChild);\n }\n }\n }\n\n return new XMLSerializer().serializeToString(doc);\n}\n\n/**\n * Evenly-spread system-break positions for `totalMeasures` measures across\n * `systems` systems: `[per, 2·per, …]` (each strictly `< totalMeasures`),\n * with `per = Math.ceil(totalMeasures / systems)` — `Math.ceil` naturally\n * front-loads any remainder into the EARLIER systems (e.g. 7 measures / 2\n * systems -> per=4 -> systems of 4+3, never 3+4), which is what keeps a\n * later system from being the short/orphaned one. `systems <= 1` (nothing to\n * break between) returns `[]`.\n */\nexport function balancedSystemBreaks(totalMeasures: number, systems: number): number[] {\n if (systems <= 1 || totalMeasures <= 0) return [];\n const per = Math.ceil(totalMeasures / systems);\n if (per <= 0) return [];\n const breaks: number[] = [];\n for (let b = per; b < totalMeasures; b += per) breaks.push(b);\n return breaks;\n}\n\n// ─── noteModelFromXml — the note MODEL half of the join ───────────────────\n\n/** One `<note>`'s MODEL identity — the ground truth `EngravedNote`\n * (notationPlayerSvg.ts) needs that Verovio's rendered SVG cannot supply on\n * its own (a rendered `g.note`/`g.rest` carries geometry, not pitch/tie/\n * duration semantics). Keyed by the note's stamped `id` in\n * `notePositions()`'s return of `verovioEngravedNotes`\n * (notationPlayerVerovio.ts). */\nexport interface NoteModel {\n /** `12*(octave+1) + stepSemitone + alter` — the standard MusicXML→MIDI\n * conversion (the same formula stave-web-sightread's own\n * `practice/probeInputs.ts:pitchMidi` uses — a universal formula, not app\n * logic, so this is not an owned-layer violation to restate here). `null`\n * for a rest or an `<unpitched>` note (no `<pitch>` child) — mirrors\n * `EngravedNote.midi`'s own \"null covers both\" contract. */\n midi: number | null;\n /** Has a `<rest/>` child. */\n isRest: boolean;\n /** True for the STOP half of a tie — a direct `<tie type=\"stop\">` child OR\n * `<notations><tied type=\"stop\">` (exporters vary on which they emit;\n * either counts) — matches `EngravedNote.tieContinuation`'s \"continuation\n * note of a tie, not the struck start\" contract. */\n tieContinuation: boolean;\n /** 0-based, matching `EngravedNote.staffIndex`'s \"0 = top staff of the\n * system\" contract: every `<part>` is walked in document order, and\n * every DISTINCT staff within it (by `<attributes><staves>` when\n * present, else the highest `<staff>` number any of its notes uses, else\n * 1) is assigned the next index — so a single-part 2-staff piano score\n * numbers 0/1 by `<staff>`, and a 2-part 1-staff-per-part reduction (this\n * app's own chord+bass shape) numbers 0/1 by PART, with neither case\n * needing different code. */\n staffIndex: number;\n /** Whole-note fraction (0.25 = quarter) — `duration / divisions / 4`,\n * divisions tracked per-part from the LAST `<attributes><divisions>`\n * seen at or before this note (MusicXML: divisions persist until\n * overridden, default 1). 0 for a grace note (no `<duration>` child —\n * the true, spec-correct signal; never guessed from `<type>`). */\n durationReal: number;\n /** 0-based position of this note's `<measure>` among its OWN `<part>`'s\n * measure children, in document order. Informational only — the live\n * join (`verovioOnsetColumns`/`verovioEngravedNotes`, both in\n * notationPlayerVerovio.ts) resolves the note's RENDERED measure index\n * from the live SVG DOM independently (Verovio's own render order, which\n * is what geometry/hit-testing must agree with), never from this field. */\n measureIndex: number;\n /** `print-object=\"no\"` on the source `<note>` (stave's `hideDoubledNotes`\n * sets this on editorially-doubled notes/rests before handing MusicXML to\n * this player). Verovio's importer HONORS this for `<note>` elements\n * carrying a `<pitch>` (renders `visibility=\"hidden\"` on its own,\n * empirically confirmed against a real 6.2.0 render) but does NOT honor\n * it for `<rest>` notes (the `<g class=\"rest\">` renders fully visible\n * regardless — same empirical check). `createVerovioNotationPlayer`\n * reads this field to force `visibility=\"hidden\"` after every render for\n * ANY id where it's true — a no-op re-application on notes Verovio\n * already hid, and the actual fix on the rests it doesn't (see that\n * module's `applyPrintObjectHiding`). */\n hidden: boolean;\n}\n\nconst STEP_SEMITONE: Record<string, number> = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };\n\nfunction firstChildNamed(el: Element, tag: string): Element | null {\n for (const c of Array.from(el.children)) if (c.tagName === tag) return c;\n return null;\n}\nfunction childrenNamed(el: Element, tag: string): Element[] {\n return Array.from(el.children).filter((c) => c.tagName === tag);\n}\nfunction textOf(el: Element | null): string | null {\n return el && el.textContent != null ? el.textContent.trim() : null;\n}\n\nfunction pitchMidiFromElement(pitchEl: Element): number {\n const step = textOf(firstChildNamed(pitchEl, 'step')) ?? 'C';\n const octave = Number(textOf(firstChildNamed(pitchEl, 'octave')) ?? '4');\n const alter = Number(textOf(firstChildNamed(pitchEl, 'alter')) ?? '0');\n return 12 * (octave + 1) + (STEP_SEMITONE[step] ?? 0) + Math.trunc(alter);\n}\n\n/** How many staves `part` uses: the max `<attributes><staves>N</staves>`\n * seen anywhere in it (the authoritative declaration when present), else\n * the highest `<note><staff>N</staff></note>` number any of its notes\n * uses, else 1 (a plain single-staff part declares neither). */\nfunction partStaffCount(part: Element): number {\n let maxDeclared = 0;\n for (const attrs of childrenNamed(part, 'measure').flatMap((m) => childrenNamed(m, 'attributes'))) {\n const staves = Number(textOf(firstChildNamed(attrs, 'staves')) ?? '0');\n if (staves > maxDeclared) maxDeclared = staves;\n }\n if (maxDeclared > 0) return maxDeclared;\n\n let maxStaff = 0;\n for (const measure of childrenNamed(part, 'measure')) {\n for (const note of childrenNamed(measure, 'note')) {\n const staff = Number(textOf(firstChildNamed(note, 'staff')) ?? '0');\n if (staff > maxStaff) maxStaff = staff;\n }\n }\n return Math.max(1, maxStaff);\n}\n\n/**\n * Pure(ish) — MusicXML-in, `id → NoteModel`-out. Walks every `<part>` in\n * document order, then every `<measure>` in document order, then every\n * DIRECT child in document order — `<attributes>` updates the part's own\n * `divisions` cursor; every other non-`<note>` child (`<backup>`,\n * `<forward>`, `<direction>`, …) is a structural/timeline element this\n * function has NO use for (it reads each note's OWN `<duration>` directly,\n * never a cursor POSITION — see `durationReal`'s doc — so unlike\n * `walkMeasureNotes`-style position walks, `<backup>`/`<forward>` need no\n * special handling here beyond being correctly skipped, which plain\n * tag-name filtering already does) — and every `<note>` becomes one model\n * entry, keyed by its `id` attribute (a note with NO `id` — i.e. input that\n * was never run through `stampNoteIds` — is silently skipped: it has no key\n * to join the render against, so there is nothing useful to record).\n *\n * Never throws: malformed input (fails to parse, or no `<score-partwise>`\n * root) returns an empty Map.\n */\nexport function noteModelFromXml(stampedXml: string): Map<string, NoteModel> {\n const model = new Map<string, NoteModel>();\n let doc: Document;\n try {\n doc = new DOMParser().parseFromString(stampedXml, 'application/xml');\n } catch {\n return model;\n }\n if (doc.querySelector('parsererror')) return model;\n const root = doc.documentElement;\n if (!root || root.tagName !== 'score-partwise') return model;\n\n const parts = childrenNamed(root, 'part');\n let staffOffset = 0;\n\n for (const part of parts) {\n const staffCount = partStaffCount(part);\n let divisions = 1;\n const measureEls = childrenNamed(part, 'measure');\n\n measureEls.forEach((measureEl, measureIndex) => {\n for (const child of Array.from(measureEl.children)) {\n if (child.tagName === 'attributes') {\n const divText = textOf(firstChildNamed(child, 'divisions'));\n if (divText) divisions = Number(divText) || divisions;\n continue;\n }\n if (child.tagName !== 'note') continue;\n const note = child;\n const id = note.getAttribute('id');\n if (!id) continue;\n\n const isGrace = !!firstChildNamed(note, 'grace');\n const isRest = !!firstChildNamed(note, 'rest');\n const pitchEl = firstChildNamed(note, 'pitch');\n const staffNumber = Number(textOf(firstChildNamed(note, 'staff')) ?? '1') || 1;\n const durationText = textOf(firstChildNamed(note, 'duration'));\n const durationReal =\n isGrace || !durationText ? 0 : Number(durationText) / divisions / 4;\n\n const tieStopDirect = childrenNamed(note, 'tie').some((t) => t.getAttribute('type') === 'stop');\n const notationsEl = firstChildNamed(note, 'notations');\n const tieStopNotated = notationsEl\n ? childrenNamed(notationsEl, 'tied').some((t) => t.getAttribute('type') === 'stop')\n : false;\n\n model.set(id, {\n midi: pitchEl ? pitchMidiFromElement(pitchEl) : null,\n isRest,\n tieContinuation: tieStopDirect || tieStopNotated,\n staffIndex: staffOffset + Math.max(0, staffNumber - 1),\n durationReal,\n measureIndex,\n hidden: note.getAttribute('print-object') === 'no',\n });\n }\n });\n\n staffOffset += staffCount;\n }\n\n return model;\n}\n","// createVerovioNotationPlayer — the Verovio (vector) sibling of\n// createSvgNotationPlayer (notationPlayerSvg.ts). Same job (a live,\n// caller-driven notation + gliding-playhead widget) and the same swap-friendly\n// API shape, different rendering engine: Verovio's own MusicXML→SVG engraver\n// instead of OSMD. See\n// docs/superpowers/specs/2026-08-11-verovio-player-design.md (stave-web-sightread)\n// §2 for the full design rationale.\n//\n// THE BINDING REFRAME (design doc, top): \"Timing is ours; Verovio renders.\"\n// This module NEVER calls `renderToTimemap` or `getElementsAtTime` — Verovio's\n// timemap is proven wrong on tuplets (the root-cause finding that motivated\n// this whole migration). All timing (`onsets`) is supplied by the caller,\n// derived from `parseReduction`'s spans/offsets; this module's only job is\n// SVG + id→geometry, exactly like notationPlayerSvg.ts's job is OSMD SVG +\n// id→geometry. (Grep gate — see the build report.)\n//\n// REUSED, VERBATIM, NO NEW MATH (same hard rule as notationPlayerSvg.ts):\n// - `vstackAudioPlayheadLine` (scene/notationGeometry.ts) — the exact same\n// onset-anchored, carriage-return playhead interpolation both SVG-family\n// players use. It only ever reads a `NotationLayout`; it does not care\n// that THIS module's layout came from Verovio's rendered SVG DOM instead\n// of OSMD's `GraphicalMusicSheet` object model.\n// - `hitTestMeasureAt`, `measureColumnsFromLayout`, `distinctOnsets`\n// (scene/notationGeometry.ts) — reused as-is, identical to\n// notationPlayerSvg.ts's usage.\n// - `computeReflowScrollDelta` + the auto-follow discriminator\n// (`createFollowController`) — EXTRACTED (0.39.0) out of\n// notationPlayerSvg.ts into `./notationCommon`, so both SVG-family\n// players share one implementation. See that module's doc.\n//\n// WHAT'S NEW (not a re-derivation of any of the above):\n// - `verovioNotationLayout` — a Verovio-backend geometry extractor, this\n// module's counterpart to notationPlayerSvg.ts's `svgNotationLayout`.\n// Verovio exposes NO object model to JS (unlike OSMD's `GraphicSheet`) —\n// only rendered SVG + MEI/timemap (timemap being off-limits per the\n// binding reframe above) — so this reads the ACTUAL rendered SVG DOM:\n// `<g class=\"measure\">` / `<g class=\"staff\">` / `<g class=\"system\">` /\n// `<g class=\"note\">` are Verovio's own stable, documented SVG output\n// classes (confirmed against a real 6.2.0 render — see the migration\n// spike's `id-test*.mjs`). Measure `index` is assigned by DOCUMENT ORDER\n// (musical order) across however many pages were rendered — no reliance\n// on Verovio's own (internal, non-deterministic) generated ids.\n// - Stamped-id note lookups (`verovioOnsetColumns`): Task 1 (stave repo)\n// stamps a deterministic `xml:id` per note before handing MusicXML to\n// Verovio; Verovio PRESERVES caller-supplied ids as the rendered SVG\n// element's own `id` attribute (confirmed: `<note id=\"n-0-0-0\">` in the\n// source round-trips to `<g id=\"n-0-0-0\" class=\"note\">` in the output —\n// an EXACT lookup, no heuristics, unlike the ordinal-spread fallback\n// `vstackAudioPlayheadLine` uses when no `noteCols` are supplied at all).\n// - `verovioZoomOptions` — the semantic zoom→Verovio-options mapping. The\n// migration spike's `zoom-test*.mjs` proved `pageWidth` (Verovio's\n// line-breaking width, in ITS OWN units) drives measures-per-system\n// while `scale` (glyph size) alone does NOT (avgMeasuresPerSystem stayed\n// 3.61 across scale 40/80/150 at a fixed pageWidth; it moved from 2.24 to\n// 3.61 to 5.91 as pageWidth alone rose 1000→1600→2400). Verovio's\n// rendered SVG width in CSS px is EXACTLY `pageWidth * scale / 100`\n// (confirmed empirically) — so solving that identity for `pageWidth`\n// given a TARGET output width (the host's width, held fixed across zoom\n// levels) and a zoom-driven `scale` makes both halves of the semantic\n// (\"bigger zoom ⇒ bigger glyphs AND fewer measures/system, width still\n// fits host\") fall out of ONE formula, not two independently-tuned ones.\n// - The unit-conversion for any element's `getBBox()` (Verovio's rendered\n// SVG user-unit space) → CSS px: each rendered page is\n// `<svg width=\"Wpx\" height=\"Hpx\">` (no viewBox) wrapping a nested\n// `<svg class=\"definition-scale\" viewBox=\"0 0 VBW VBH\">` (Verovio's own\n// structure) — so `cssPx = userUnit * (W / VBW)`, the SAME \"read the\n// scale factor from the live render, never hardcode it\" principle\n// `svgNotationLayout`'s `unitInPixels` derivation uses, just sourced from\n// the DOM (Verovio exposes no JS-side unit constant) instead of an\n// imported library constant.\n//\n// PAGES: \"all rendered, stacked in flow\" (design doc §2) — every Verovio\n// page (`getPageCount()`) is rendered to its own `<svg>` and appended, in\n// order, inside its own `.vrv-page` wrapper `<div>`, inside `svgHost`. Normal\n// block layout stacks them vertically; `verovioNotationLayout` reads each\n// page's OWN offset (`getBoundingClientRect()` relative to the shared root)\n// so geometry from every page lands in ONE continuous coordinate space, the\n// same space the playhead overlay is positioned in. No \"current page\" /\n// pagination concept anywhere in this module — the whole score is always in\n// the DOM; the PAGE scrolls it (identical framing to notationPlayerSvg.ts).\n//\n// SHARED TOOLKIT INSTANCE: Verovio's own package doc: \"only one instance can\n// be created for now\" (`VerovioToolkit.instances`, a static array the C++\n// bridge expects to hold at most one live toolkit). This module therefore\n// keeps ONE module-level toolkit init promise for the whole session — every\n// player created on the page shares it. This is NOT a \"one live player at a\n// time\" assumption — the real consumer (PlayerPage) keeps a harmony player\n// AND a written player alive SIMULTANEOUSLY (lazy-built, destroyed only on\n// piece switch), so two players' `loadData` calls genuinely interleave over\n// the toolkit's lifetime. Safety comes from RECLAIM: every toolkit-consuming\n// path (initial engrave; `reflow`, shared by `setZoom`/`resize`) re-parses\n// ITS OWN `musicXml` via `loadData` synchronously, immediately before\n// rendering — never assumes the toolkit still holds what it loaded last\n// time. Because the reclaim call and the render calls that follow it have no\n// `await` between them, JS's single-threaded run-to-completion semantics\n// guarantee no other player's reflow can interleave mid-sequence — see\n// `reflow`'s own comment + `tests/notationPlayerVerovio.test.ts`'s\n// two-player interleaved-reflow test (the regression this guards against).\n//\n// IMPORT PATH: subpath-only —\n// `@real-music-packages/web-core/notationPlayerVerovio` — not re-exported\n// from the root barrel (same reasoning as notationPlayer.ts/\n// notationPlayerSvg.ts: the root barrel is theory-only/zero-dependency).\n// `verovio` itself is a dynamic `import('verovio/wasm')` /\n// `import('verovio/esm')` INSIDE this module only, marked `external` in\n// tsup.config.ts, so the ~2.3MB gzip WASM only loads on pages that actually\n// construct a player — see the build report's dist-grep evidence.\n//\n// 0.40.0 — FULL API PARITY WITH notationPlayerSvg.ts (stave-web-sightread's\n// reading/recording stack can now swap backends without touching a call\n// site): `notePositions()`, `markNotes()`, the `[data-rmp-playhead]`\n// attribute, and `osmdOptions.autoBeam` (accepted + ignored, logged once —\n// Verovio always beams from the source MusicXML's own `<beam>` data, so\n// there is nothing for this option to toggle). The join that makes\n// `notePositions()`/`markNotes()` possible: `stampNoteIds`/`noteModelFromXml`\n// (./notationXml.ts, NEW) turn the input MusicXML into `id → NoteModel`\n// (pitch/rest/tie/staff/duration — the ground truth Verovio's rendered SVG\n// alone cannot supply), and `verovioEngravedNotes`/`verovioNotesAtColumn`\n// below join those ids to the live rendered `g.note`/`g.rest` elements —\n// same id-preservation guarantee `verovioOnsetColumns` already relies on\n// (see point 2 above), just consumed for notehead identity/geometry instead\n// of playhead columns. `musicXml` is stamped INTERNALLY (idempotent — a\n// caller that already ran it through stave's own `stampNoteIds` gets\n// byte-identical ids back) so this module never assumes the caller stamped\n// first. See ./notationXml.ts's own doc for why that scheme is duplicated\n// rather than imported from stave-web-sightread (wrong dependency\n// direction for a shared package) and `applyPrintObjectHiding`'s doc below\n// for the print-object empirical finding (Verovio honors it for notes, NOT\n// for rests).\n\nimport {\n vstackAudioPlayheadLine,\n distinctOnsets,\n hitTestMeasureAt,\n measureColumnsFromLayout,\n systemIndexOfBox,\n type NotationLayout,\n} from './scene/notationGeometry';\nimport type { Box, StaffMeasureBox } from './promo';\nimport { computeReflowScrollDelta, createFollowController } from './notationCommon';\nimport type { EngravedNote } from './notationPlayerSvg';\nimport {\n stampNoteIds,\n noteModelFromXml,\n injectSystemBreaks,\n balancedSystemBreaks,\n type NoteModel,\n} from './notationXml';\n\n// Re-exported (TYPE-ONLY import above — erased at compile time, zero\n// runtime cost) so a caller that only imports from `notationPlayerVerovio`\n// still gets the SAME type `notePositions()` returns (identical shape to\n// notationPlayerSvg.ts's own export — not redefined here, to guarantee the\n// \"same exported interface\" contract can never drift between the two\n// SVG-family players).\nexport type { EngravedNote };\n\n/** Restated independently, not imported as a VALUE from notationPlayerSvg.ts\n * — same reasoning as `MAX_ENGRAVE_WIDTH_VRV` vs `MAX_ENGRAVE_WIDTH_SVG`\n * (below): a runtime (non-`type`) import from notationPlayerSvg.ts would\n * pull that module's ENTIRE implementation — including its own\n * `createSvgNotationPlayer` closure (harmless at runtime, since its OSMD\n * import stays lazy/dynamic either way) — into this entry's own tsup\n * chunk graph, which is exactly the cross-entry bundle coupling the\n * module doc's \"IMPORT PATH\" section (and the build report's dist-grep\n * gate) exists to prevent between the two SVG-family players. Must stay\n * byte-identical to `notationPlayerSvg.ts`'s own `MARKED_NOTE_CLASS` — a\n * test in this file's own suite pins that. */\nexport const MARKED_NOTE_CLASS = 'rmp-note-marked';\n\n// ─── Public types ───────────────────────────────────────────────────────────\n\n/** One distinct note-onset instant: the audio-clock time it sounds at, and\n * the stamped `xml:id`s (Task 1, stave repo) of every note that sounds at\n * that instant (>1 for a chord). Multiple entries sharing the same `tMs`\n * are merged (their `noteIds` unioned) — the caller does not need to\n * pre-group chords into one entry. */\nexport interface VerovioOnset {\n tMs: number;\n noteIds: string[];\n}\n\nexport interface CreateVerovioNotationPlayerOpts {\n /** Element the player's content is mounted into. Takes NATURAL content\n * height (the whole score, page-flow layout, ALL Verovio pages stacked)\n * — the host must not clip a fixed height; the PAGE scrolls the score. */\n host: HTMLElement;\n /** Display MusicXML to engrave (Task 1's transform-pipeline output — ids\n * already stamped). Ignored when `rendered` (the test seam) is set. */\n musicXml: string;\n /** Note onsets the playhead locks to, WITH the stamped ids of the notes\n * sounding at each onset — see `VerovioOnset`. Distinct/sorted\n * automatically (duplicates by `tMs` are merged, not required to be\n * pre-sorted). */\n onsets: VerovioOnset[];\n /** Parks a followed system this many px below the viewport top — pass the\n * height of any fixed top chrome (header, docked transport) plus a gap.\n * Default SYSTEM_TOP_MARGIN_PX. */\n followTopMarginPx?: number;\n /** Playhead line color. Default `'#2f6f4f'`. */\n playheadColor?: string;\n /** Initial semantic zoom — see `verovioZoomOptions`'s doc for the mapping.\n * Default 1 (a normal readable size that fits the host's width). */\n zoom?: number;\n /**\n * Advanced / test seam: a pre-built `NotationLayout`, bypassing the real\n * Verovio engrave (`musicXml` is still required by the type but is\n * ignored when this is set). Mirrors `CreateSvgNotationPlayerOpts.rendered`\n * in notationPlayerSvg.ts for the identical reason: real Verovio rendering\n * needs a real SVG DOM (`getBBox`/`getBoundingClientRect`) that jsdom can't\n * provide — see notationPlayerSvg.ts's module doc for why headless can't do\n * a real one. When set, `noteIds`-based note lookups have no live DOM to\n * resolve against, so the playhead falls back to `vstackAudioPlayheadLine`'s\n * own ordinal spread (same graceful-degradation path as \"no `noteCols`\n * supplied\" on the SVG player) — fine for a lifecycle test, not for\n * notehead-accurate positioning. `setZoom`/`resize` update the tracked zoom\n * /width but perform no real re-engrave (there is nothing to re-engrave).\n */\n rendered?: NotationLayout;\n /**\n * Narrow passthrough matching `CreateSvgNotationPlayerOpts.osmdOptions`'s\n * shape exactly, so a caller driving BOTH players behind one interface\n * (the swap this player exists for) never has to branch per backend.\n * `autoBeam` has NO Verovio equivalent — Verovio always beams straight\n * from the MusicXML's own `<beam>` elements (it has no \"re-beam from\n * scratch\" pass the way OSMD's `autoBeam` option does) — so this is\n * accepted and silently ignored, with a ONE-TIME `console.warn` (module-\n * level, not per-instance — a caller that builds many players with the\n * same options object should not get spammed) rather than a hard error,\n * since ignoring it is genuinely harmless: synthesized rhythm XML with no\n * `<beam>` data renders unbeamed either way, which is a cosmetic\n * difference the caller can fix upstream (emit real `<beam>` elements)\n * rather than this player faking OSMD's re-beam heuristic.\n */\n osmdOptions?: { autoBeam?: boolean };\n /**\n * Passthrough for Verovio's own layout/line-breaking options — merged\n * UNDER `VEROVIO_LAYOUT_DEFAULTS` and OVER `scale`/`pageWidth`/\n * `adjustPageHeight` (see `verovioRenderOptions`'s own doc for the exact\n * merge order and why: a caller's `breaks` must be able to override the\n * default, but a caller can never smuggle in `scale`/`pageWidth` — those\n * stay derived from `zoom`/host width, not caller-suppliable). Stave's own\n * use case: inject `<print new-system=\"yes\"/>` into MusicXML and pass\n * `breaks: 'line'` to get exact N-bars-per-line, rather than Verovio's own\n * automatic line-breaking (see `VEROVIO_LAYOUT_DEFAULTS`'s doc for the\n * \"why\" behind the defaults themselves).\n */\n verovioOptions?: VerovioLayoutOptions;\n /**\n * TEST-ONLY SEAM — not part of this player's real production behavior.\n * When set, `engraveOnce`'s fit-pass/fallback-decision math reads system\n * widths from this function (called with `svgHost`) instead of\n * `currentLayout.systems`. Exists because jsdom implements neither\n * `getBBox` nor a real `getBoundingClientRect` (both always report\n * zero-size boxes), so `currentLayout.systems` widths — and therefore\n * `fitZoomFactor`'s result — are always 0/`1` (fits) in a headless test\n * regardless of how dense the underlying MusicXML actually is. A test can\n * pass a fixed fake (e.g. `() => [1200]`) to exercise the readability-floor\n * fallback (`VerovioLayoutOptions.minFitFactor`) end-to-end against a REAL\n * Verovio engrave, asserting on the resulting DOM shape\n * (`systemMeasureCounts`) rather than on geometry a real browser would be\n * needed to produce. Never used by any real caller.\n */\n measureSystemWidths?: (root: Element) => number[];\n}\n\nexport interface VerovioNotationPlayer {\n /** Resolves once the engraving is in the DOM and ready to draw. `setTime`/\n * click hit-testing are safe to call before this resolves (no-op until\n * ready, same contract as the SVG player). */\n readonly ready: Promise<void>;\n /** Drive the playhead for absolute playback time `tMs`. Caller owns the\n * audio clock + rAF loop. */\n setTime(tMs: number): void;\n /** Re-engrave at a new semantic zoom (systems reflow — see\n * `verovioZoomOptions`). The scroll position is restored afterward so the\n * content that was centered in the viewport before the reflow is still\n * centered after it. */\n setZoom(z: number): Promise<void>;\n /** Re-measure the host and reflow to match its current width, with the\n * same scroll-position preservation as `setZoom`. Call on host resize /\n * orientation change. */\n resize(): Promise<void>;\n /** Gate the auto-follow scroll on the app's transport state: pass `true`\n * on play, `false` on pause/stop (see FollowController.setEnabled — while\n * disabled NOTHING may scroll the sheet, including the idle-rearm's\n * off-screen rescue). Defaults to enabled. */\n setFollowEnabled(on: boolean): void;\n /** Register a measure-click handler (measure index, matching the DOM-order\n * index `verovioNotationLayout` assigns). Returns an unsubscribe fn. */\n onMeasureClick(cb: (measureIndex: number) => void): () => void;\n /**\n * Mark the engraved noteheads/rests nearest the given columns (same\n * `measureIndex + fraction-through-the-measure` units as `onsets`'\n * derived columns); pass `null` or `[]` to clear. Same contract and CSS\n * class (`MARKED_NOTE_CLASS` = `'rmp-note-marked'`) as\n * `SvgNotationPlayer.markNotes` — a consumer's existing CSS keeps working\n * unmodified across a backend swap. Survives re-engraving: reapplied\n * after every `setZoom`/`resize`.\n */\n markNotes(cols: number[] | null): void;\n /** Every engraved note/rest with MODEL identity (pitch, rest, tie, staff)\n * and host-relative notehead position — same `EngravedNote` shape\n * `SvgNotationPlayer.notePositions()` returns (re-exported from this\n * module, not redefined). `headEl` is Verovio's rendered `.notehead`\n * sub-group when present (a tighter box than the outer `g.note`, closer\n * in spirit to OSMD's `.vf-notehead`), else the outer `g.note`/`g.rest`\n * group. `[]` before the initial engrave resolves or under the\n * `rendered` test seam (no live SVG to join against — same graceful\n * degradation as `verovioOnsetColumns`). */\n notePositions(): EngravedNote[];\n /** Tear down: removes the mounted DOM (engraving + playhead overlay) from\n * `host`, and drops every listener this instance added (click, window\n * scroll) and pending async work (a token guard drops any in-flight\n * reflow's effects). Idempotent. Does NOT destroy the shared module-level\n * Verovio toolkit instance (see the module doc's \"SHARED TOOLKIT\n * INSTANCE\" note) — it is reused by the next player, if any. */\n destroy(): void;\n}\n\n// ─── Verovio-backend geometry extraction (DOM-based) ───────────────────────\n\nconst EMPTY_LAYOUT: NotationLayout = {\n src: { x: 0, y: 0, w: 0, h: 0 },\n rect: { dx: 0, dy: 0, dw: 0, dh: 0 },\n systems: [],\n measures: [],\n};\n\n/** Per-page unit-conversion + placement: `cssPx = userUnit * scale`, plus\n * this page's own `(offsetX, offsetY)` within the shared root's coordinate\n * space (see the module doc's \"unit-conversion\" + \"PAGES\" sections).\n * `root` is carried alongside purely so `boxFromElement` can go straight to\n * `getBoundingClientRect()` diffing (see that function's own doc for why) —\n * `scale`/`offsetX`/`offsetY` stay as the page-validity check\n * (`pageGeometry`'s own \"is this page's markup well-formed\" guard) and are\n * no longer consumed for box math. */\ninterface PageGeom {\n scale: number;\n offsetX: number;\n offsetY: number;\n root: Element;\n}\n\nfunction safeRect(el: Element): DOMRect | null {\n return typeof el.getBoundingClientRect === 'function' ? el.getBoundingClientRect() : null;\n}\n\nfunction readViewBox(svgEl: SVGSVGElement): { w: number; h: number } | null {\n const baseVal = svgEl.viewBox && svgEl.viewBox.baseVal;\n if (baseVal && baseVal.width > 0) return { w: baseVal.width, h: baseVal.height };\n const attr = svgEl.getAttribute('viewBox');\n if (!attr) return null;\n const parts = attr.trim().split(/[\\s,]+/).map(Number);\n if (parts.length !== 4 || !(parts[2] > 0)) return null;\n return { w: parts[2], h: parts[3] };\n}\n\n/** One page's unit-conversion factor + placement offset, derived ENTIRELY\n * from the live DOM (Verovio's rendered SVG is self-describing — outer\n * `<svg width>` + inner `<svg viewBox>` — no external constant needed; see\n * the module doc). Returns null (never throws) if the page's markup is\n * missing the expected structure. */\nfunction pageGeometry(root: Element, pageEl: Element): PageGeom | null {\n const outerSvg = pageEl.querySelector('svg');\n if (!outerSvg) return null;\n const innerSvg = (outerSvg.querySelector('svg[viewBox]') ?? outerSvg) as unknown as SVGSVGElement;\n const vb = readViewBox(innerSvg);\n if (!vb) return null;\n const outerRect = safeRect(outerSvg);\n const rootRect = safeRect(root);\n const pageRect = safeRect(pageEl);\n if (!outerRect || !rootRect || !pageRect) return null;\n if (!(outerRect.width > 0)) return null;\n const scale = outerRect.width / vb.w;\n if (!(scale > 0) || !Number.isFinite(scale)) return null;\n return { scale, offsetX: pageRect.left - rootRect.left, offsetY: pageRect.top - rootRect.top, root };\n}\n\n/**\n * An element's box, in CSS px relative to the shared `root` —\n * `getBoundingClientRect()` diffed against `geom.root`'s own rect. Same\n * approach `notationPlayerSvg.ts` uses throughout for its OSMD geometry\n * (`hostRect`/`rootRect` diffing — see that module), chosen here for the\n * SAME reason: `getBoundingClientRect()` already resolves every ancestor\n * transform between the element and the viewport, so it needs no separate\n * per-page `scale`/`offsetX`/`offsetY` math layered on top.\n *\n * PRIOR BUG (found via the OSMD->Verovio default-backend swap's ghost-\n * placement acceptance check, ~17px off on real pieces): this used to do\n * `el.getBBox()` (Verovio's rendered user-unit space) converted via\n * `geom.offsetX/offsetY + bbox.x/y * geom.scale` — correct ONLY if the only\n * transform between `el` and the page's own outer `<svg>` is the page's own\n * placement + viewBox scale. Verovio's real output wraps EVERY page's\n * content in `<g class=\"page-margin\" transform=\"translate(500, 500)\">`\n * (confirmed against a real 6.2.0 render) — an ancestor transform `getBBox()`\n * does NOT bake in (`getBBox()` is local to the element's own user space,\n * before any ancestor's transform is applied) and the old formula never\n * accounted for. Empirically: `500 * scale` (~17px at this fixture's\n * `outerRect.width / viewBox.width` ratio) matched the observed drift\n * exactly in both axes — every note landed ~17px up-and-left of its real\n * rendered position. `getBoundingClientRect()` has no such blind spot: it\n * is the browser's own answer to \"where is this actually painted,\" immune\n * to however many ancestor groups carry their own transform.\n *\n * Null for anything that isn't a real element or has a degenerate\n * (zero-area) box — same defensive style the old implementation had.\n */\nfunction boxFromElement(el: Element, geom: PageGeom): Box | null {\n const r = safeRect(el);\n const rootRect = safeRect(geom.root);\n if (!r || !rootRect || !(r.width > 0) || !(r.height > 0)) return null;\n return { x: r.left - rootRect.left, y: r.top - rootRect.top, w: r.width, h: r.height };\n}\n\nfunction computePageGeometries(root: Element): Map<Element, PageGeom> {\n const map = new Map<Element, PageGeom>();\n for (const pageEl of Array.from(root.querySelectorAll('.vrv-page'))) {\n const geom = pageGeometry(root, pageEl);\n if (geom) map.set(pageEl, geom);\n }\n return map;\n}\n\n/**\n * Every `<g class=\"measure\">` across all rendered pages that has at least\n * one `<g class=\"staff\">` child, in DOCUMENT ORDER (= musical order, since\n * pages are stacked in `.vrv-page` DOM order and Verovio renders each page's\n * measures left-to-right/top-to-bottom). This exact list's POSITION is the\n * single source of truth for the `index` every measure/note lookup in this\n * module uses (`verovioNotationLayout` AND `verovioOnsetColumns` both call\n * this, so they can never drift out of sync with each other — no separate\n * re-derivation of \"which position is this measure\" anywhere else).\n */\nfunction collectMeasureElements(pageGeoms: Map<Element, PageGeom>): { el: Element; geom: PageGeom }[] {\n const out: { el: Element; geom: PageGeom }[] = [];\n for (const [pageEl, geom] of pageGeoms) {\n for (const measureEl of Array.from(pageEl.querySelectorAll('g.measure'))) {\n if (measureEl.querySelector('g.staff')) out.push({ el: measureEl, geom });\n }\n }\n return out;\n}\n\n/**\n * Rendered measure count per SYSTEM, in DOCUMENT ORDER (`.system` elements\n * across every `.vrv-page`, each one's OWN `.measure` descendant count) —\n * the widow-detection input for `engraveOnce`'s widow pass (see that\n * function's own doc). Deliberately PLAIN DOM traversal — no\n * `getBoundingClientRect`/geometry involved at all, unlike\n * `verovioNotationLayout`/`collectMeasureElements` (which both need a real\n * layout engine to report non-zero boxes) — so this works against ANY\n * rendered SVG DOM, including jsdom's own (which reports zero-size rects for\n * everything by default): a real Verovio render loaded into jsdom is enough\n * to exercise the widow pass end-to-end purely by DOM shape, with no\n * `getBoundingClientRect` mocking required (see this module's real-Verovio\n * widow test). Never throws; a root with no `.system` elements yields `[]`.\n */\nexport function systemMeasureCounts(root: Element): number[] {\n return Array.from(root.querySelectorAll('.system')).map((sysEl) => sysEl.querySelectorAll('.measure').length);\n}\n\n/**\n * Pure(ish) — DOM-in, `NotationLayout`-out — Verovio-backend geometry\n * extractor. `root` is the container holding every rendered `.vrv-page`\n * wrapper `<div>` (this player's `svgHost`; a test fixture must reproduce\n * that same wrapper structure — see the extractor tests). Builds the SAME\n * `NotationLayout` shape `svgNotationLayout` (notationPlayerSvg.ts) does,\n * from Verovio's rendered SVG DOM instead of OSMD's object model — see the\n * module doc for the full derivation (measure/staff/system/note lookup via\n * Verovio's own stable SVG classes, unit conversion via the live\n * width/viewBox on each page). Never throws; returns `EMPTY_LAYOUT` on any\n * missing/malformed structure.\n */\nexport function verovioNotationLayout(root: Element): NotationLayout {\n try {\n const pageGeoms = computePageGeometries(root);\n if (!pageGeoms.size) return EMPTY_LAYOUT;\n const measureEntries = collectMeasureElements(pageGeoms);\n if (!measureEntries.length) return EMPTY_LAYOUT;\n\n const measures: StaffMeasureBox[] = [];\n measureEntries.forEach(({ el: measureEl, geom }, index) => {\n const staffEls = Array.from(measureEl.querySelectorAll('g.staff'));\n const staffBoxes = staffEls\n .map((el) => ({ el, box: boxFromElement(el, geom) }))\n .filter((s): s is { el: Element; box: Box } => !!s.box)\n .sort((a, b) => a.box.y - b.box.y);\n staffBoxes.forEach(({ el: staffEl, box }, staff) => {\n const noteEls = Array.from(measureEl.querySelectorAll('g.note')).filter(\n (n) => n.closest('g.staff') === staffEl,\n );\n const noteXs = noteEls.map((n) => boxFromElement(n, geom)?.x).filter((x): x is number => x != null);\n const noteStartX = noteXs.length ? Math.min(...noteXs) : box.x;\n measures.push({ index, staff, box, noteStartX });\n });\n });\n if (!measures.length) return EMPTY_LAYOUT;\n\n const systems: Box[] = [];\n for (const [pageEl, geom] of pageGeoms) {\n for (const sysEl of Array.from(pageEl.querySelectorAll('g.system'))) {\n const box = boxFromElement(sysEl, geom);\n if (box) systems.push(box);\n }\n }\n\n const rootRect = safeRect(root);\n const fallbackW = Math.max(0, ...measures.map((m) => m.box.x + m.box.w));\n const fallbackH = Math.max(0, ...measures.map((m) => m.box.y + m.box.h));\n const dw = rootRect && rootRect.width > 0 ? rootRect.width : fallbackW;\n const dh = rootRect && rootRect.height > 0 ? rootRect.height : fallbackH;\n\n return { src: { x: 0, y: 0, w: dw, h: dh }, rect: { dx: 0, dy: 0, dw, dh }, systems, measures };\n } catch {\n return EMPTY_LAYOUT;\n }\n}\n\n/**\n * Resolve each DISTINCT onset (see `distinctOnsets`) to a `noteCols` entry —\n * the SAME \"real engraved column\" format `vstackAudioPlayheadLine` already\n * accepts from the SVG/canvas players (`measureIndex + fractionWithinMeasure`\n * — see that function's doc for how it's consumed). For each onset, every\n * stamped `noteId` sounding at that instant (a chord may have several) is\n * looked up by id in the live DOM (`document.getElementById` — Task 1 stamps\n * ids that Verovio preserves verbatim as SVG element ids), mapped to its\n * measure via `collectMeasureElements`'s canonical indexing (so it lines up\n * EXACTLY with `verovioNotationLayout`'s own `index` numbering), and its\n * fractional x-position within that measure's column computed with the exact\n * same formula `vstackAudioPlayheadLine`'s own `colX` uses internally (not\n * re-derived independently — this is the note's ANCHOR position, not new\n * interpolation math). A chord's several ids are averaged. Any onset with NO\n * resolvable id (missing from the DOM, e.g. a `rendered`-seam layout with no\n * live SVG) falls back to the ordinal spread `vstackAudioPlayheadLine` itself\n * uses when `noteCols` is entirely absent — so one bad id degrades ONLY that\n * onset, not the whole piece. Returns `undefined` (not a partially-bad array)\n * only when there is no usable layout/DOM at all to resolve against.\n */\nexport function verovioOnsetColumns(\n root: Element,\n layout: NotationLayout,\n onsets: VerovioOnset[],\n): number[] | undefined {\n try {\n const distinctMs = distinctOnsets(onsets.map((o) => ({ onsetMs: o.tMs })));\n if (!distinctMs.length) return undefined;\n const cols = measureColumnsFromLayout(layout.measures);\n if (!cols.length) return undefined;\n\n const pageGeoms = computePageGeometries(root);\n const measureEntries = collectMeasureElements(pageGeoms);\n if (!measureEntries.length) return undefined;\n const measureIndexOf = new Map<Element, number>();\n measureEntries.forEach((m, i) => measureIndexOf.set(m.el, i));\n\n const idsByOnset = new Map<number, string[]>();\n for (const o of onsets) {\n const arr = idsByOnset.get(o.tMs) ?? [];\n for (const id of o.noteIds) if (!arr.includes(id)) arr.push(id);\n idsByOnset.set(o.tMs, arr);\n }\n\n const doc = root.ownerDocument;\n\n return distinctMs.map((tMs, k) => {\n const ids = idsByOnset.get(tMs) ?? [];\n const positions: number[] = [];\n for (const id of ids) {\n const noteEl = doc ? doc.getElementById(id) : null;\n const measureEl = noteEl ? noteEl.closest('g.measure') : null;\n const index = measureEl ? measureIndexOf.get(measureEl) : undefined;\n if (index == null) continue;\n const m = cols[index];\n const geom = measureEntries[index]?.geom;\n // Anchor the onset at the NOTEHEAD CENTER, matching the OSMD\n // backend's column semantics. The whole-group left edge biased every\n // time->x position (and so every ghost) ~half a notehead LEFT — the\n // group box also includes accidentals/stems (user-visible drift,\n // 2026-08-20).\n const headGlyph = noteEl ? (noteEl.querySelector('.notehead') ?? noteEl) : null;\n const box = headGlyph && geom ? boxFromElement(headGlyph, geom) : null;\n if (!box || !m) continue;\n const sx = Math.min(m.noteStartX, m.x + m.w);\n const denom = m.x + m.w - sx;\n const anchorX = box.x + box.w / 2;\n const frac = denom > 0 ? Math.min(1, Math.max(0, (anchorX - sx) / denom)) : 0;\n positions.push(index + frac);\n }\n if (positions.length) return positions.reduce((a, b) => a + b, 0) / positions.length;\n // Same ordinal-spread fallback vstackAudioPlayheadLine uses internally\n // when no noteCols are supplied at all — degrades this ONE onset only.\n return distinctMs.length === 1 ? 0 : (k / (distinctMs.length - 1)) * cols.length;\n });\n } catch {\n return undefined;\n }\n}\n\n// ─── Note geometry (notePositions) + column→note lookup (markNotes) ───────\n\n/**\n * Every rendered note/rest joined to its MODEL identity (`noteModel`, from\n * `noteModelFromXml` — ./notationXml.ts) by stamped id — this player's\n * `notePositions()`. Same shape and host-relative-px contract as\n * notationPlayerSvg.ts's `engravedNotes` (its own doc: \"Positions are px\n * relative to the HOST element, at the notehead's center\"), but the join\n * itself is simpler here: unlike OSMD (one graphical group per CHORD,\n * requiring the pitch-rank head-sorting `engravedNotes` does), Verovio\n * renders every chord member as its OWN `<g id=\"...\" class=\"note\">`\n * (empirically confirmed — see the module doc's point 2) — so this is a\n * flat id→element→model join, no grouping/sorting.\n *\n * `headEl` prefers the note's own `.notehead` child (Verovio's real nested\n * glyph group — empirically confirmed as `<g class=\"notehead\">` inside\n * `<g class=\"note\">`) over the outer `g.note`/`g.rest` wrapper when\n * present — a TIGHTER box (closer to notationPlayerSvg.ts's\n * `.vf-notehead`-only box) than the wrapper, which also spans the\n * stem/flag/accidental. Falls back to the wrapper itself for a rest (no\n * `.notehead` child) or if that lookup's own `getBBox` fails.\n *\n * `root` is the container holding every rendered `.vrv-page` (this\n * player's `svgHost`); `host` is the player's OWN host element — `x`/`y`\n * are computed relative to `host` (per `EngravedNote`'s contract), NOT to\n * `root`, which may itself sit offset within `host`. Never throws; returns\n * `[]` for any missing/malformed structure (same defensive style as\n * `verovioNotationLayout`).\n */\nexport function verovioEngravedNotes(\n root: Element,\n host: HTMLElement,\n noteModel: Map<string, NoteModel>,\n): EngravedNote[] {\n try {\n const pageGeoms = computePageGeometries(root);\n if (!pageGeoms.size || !noteModel.size) return [];\n const measureEntries = collectMeasureElements(pageGeoms);\n if (!measureEntries.length) return [];\n\n const systems: Box[] = [];\n for (const [pageEl, geom] of pageGeoms) {\n for (const sysEl of Array.from(pageEl.querySelectorAll('g.system'))) {\n const box = boxFromElement(sysEl, geom);\n if (box) systems.push(box);\n }\n }\n\n const rootRect = safeRect(root);\n const hostRect = safeRect(host);\n const offX = rootRect && hostRect ? rootRect.left - hostRect.left : 0;\n const offY = rootRect && hostRect ? rootRect.top - hostRect.top : 0;\n\n const out: EngravedNote[] = [];\n for (const { el: measureEl, geom } of measureEntries) {\n const noteEls = Array.from(measureEl.querySelectorAll('g.note, g.rest'));\n for (const noteEl of noteEls) {\n const id = noteEl.getAttribute('id');\n if (!id) continue;\n const nm = noteModel.get(id);\n if (!nm) continue;\n\n const glyphEl = noteEl.querySelector('.notehead') ?? noteEl;\n let box = boxFromElement(glyphEl, geom);\n let headEl: Element = glyphEl;\n if (!box && glyphEl !== noteEl) {\n box = boxFromElement(noteEl, geom);\n headEl = noteEl;\n }\n if (!box) continue;\n\n out.push({\n midi: nm.midi,\n isRest: nm.isRest,\n tieContinuation: nm.tieContinuation,\n staffIndex: nm.staffIndex,\n systemIndex: systemIndexOfBox(systems, box),\n durationReal: nm.durationReal,\n x: offX + box.x + box.w / 2,\n y: offY + box.y + box.h / 2,\n w: box.w,\n h: box.h,\n headEl,\n });\n }\n }\n return out;\n } catch {\n return [];\n }\n}\n\n/**\n * Every rendered note/rest nearest engraved column `col`\n * (`measureIndex + fraction`, same units as `markNotes`' argument and\n * `noteCols`), one per staff of that measure — the Verovio-backend\n * counterpart to notationPlayerSvg.ts's `graphicalNotesAtColumn`. That\n * function searches OSMD's object model (`relInMeasureTimestamp` vs bar\n * duration); this searches the live rendered geometry instead (Verovio\n * exposes no per-element timestamp) — same \"nearest entry by position gap,\n * search every staff of the bar\" shape, just sourced from `getBBox` instead\n * of a timeline field. The fractional-position FORMULA itself\n * (`(box.x - sx) / denom`) is the exact one `verovioOnsetColumns` already\n * uses (not re-derived) — this function runs it in the opposite direction\n * (nearest note TO a column, rather than a column FROM a note id).\n */\nexport function verovioNotesAtColumn(root: Element, layout: NotationLayout, col: number): Element[] {\n try {\n if (!Number.isFinite(col)) return [];\n const cols = measureColumnsFromLayout(layout.measures);\n if (!cols.length) return [];\n const measureIndex = Math.max(0, Math.min(cols.length - 1, Math.floor(col)));\n const wanted = col - measureIndex;\n\n const pageGeoms = computePageGeometries(root);\n const measureEntries = collectMeasureElements(pageGeoms);\n const entry = measureEntries[measureIndex];\n if (!entry) return [];\n const m = cols[measureIndex];\n const sx = Math.min(m.noteStartX, m.x + m.w);\n const denom = m.x + m.w - sx;\n\n const found: Element[] = [];\n for (const staffEl of Array.from(entry.el.querySelectorAll('g.staff'))) {\n const noteEls = Array.from(staffEl.querySelectorAll('g.note, g.rest'));\n let best: Element | null = null;\n let bestGap = Number.POSITIVE_INFINITY;\n for (const noteEl of noteEls) {\n const box = boxFromElement(noteEl, entry.geom);\n if (!box) continue;\n const frac = denom > 0 ? (box.x - sx) / denom : 0;\n const gap = Math.abs(frac - wanted);\n if (gap < bestGap) {\n bestGap = gap;\n best = noteEl;\n }\n }\n if (best) found.push(best);\n }\n return found;\n } catch {\n return [];\n }\n}\n\n/**\n * CRITICAL empirical finding (verified against a real 6.2.0 render — see\n * the migration spike's follow-up, `.superpowers/…/print-object-test.mjs`\n * equivalent run for this task): Verovio's MusicXML importer HONORS\n * `print-object=\"no\"` for a pitched `<note>` (renders `visibility=\"hidden\"`\n * on its own `<g class=\"note\">`) but does NOT honor it for a `<note><rest/>`\n * — the `<g class=\"rest\">` renders fully visible regardless. This matters\n * because stave-web-sightread's `hideDoubledNotes` feature sets\n * `print-object=\"no\"` on BOTH doubled notes AND the rests of a voice that\n * lost every visible note (see that function's own \"second pass\" doc) —\n * without this fix, a hidden-doubled-note's voice would still show a\n * floating rest, exactly the \"extra voice\" clutter that feature exists to\n * remove.\n *\n * Fix: force `visibility=\"hidden\"` on every rendered id whose model says\n * `hidden` (`NoteModel.hidden`, from `noteModelFromXml`). Re-applying it to\n * a NOTE Verovio already hid itself is a harmless no-op; applying it to a\n * REST is the actual fix. Call after every render (`renderAllPages`) — a\n * fresh render is a fresh DOM, so a prior call's effect never carries over\n * (nothing to \"undo\" on a note/rest that's no longer print-object=\"no\").\n * Never throws.\n */\nexport function applyPrintObjectHiding(root: Element, noteModel: Map<string, NoteModel>): void {\n try {\n const doc = root.ownerDocument;\n if (!doc || !noteModel.size) return;\n for (const [id, nm] of noteModel) {\n if (!nm.hidden) continue;\n const el = doc.getElementById(id);\n if (el) el.setAttribute('visibility', 'hidden');\n }\n } catch {\n /* best-effort — a render this can't patch stays as Verovio drew it */\n }\n}\n\n// ─── Semantic zoom mapping ──────────────────────────────────────────────────\n\n/** Verovio glyph-size percent at semantic zoom 1 (matches the migration\n * spike's own default — a normal, readable size at typical host widths). */\nexport const VEROVIO_BASE_SCALE = 40;\n/** Clamp band for the derived `scale`, so an extreme `zoom` never collapses\n * glyphs to unreadable or blows them up past sane bounds. */\nexport const VEROVIO_MIN_SCALE = 20;\nexport const VEROVIO_MAX_SCALE = 120;\n\nexport interface VerovioRenderOptions {\n scale: number;\n pageWidth: number;\n}\n\n/**\n * Verovio layout/line-breaking options a caller may override — see\n * `CreateVerovioNotationPlayerOpts.verovioOptions`'s doc for the merge\n * contract and Stave's own motivating use case (encoded `<print\n * new-system=\"yes\"/>` breaks + `breaks: 'line'`, exact N-bars-per-line).\n * Deliberately NARROWER than Verovio's full option surface — only the knobs\n * this integration has an actual caller for; add more here (not a raw\n * `Record<string, unknown>` passthrough) as real needs arise, so a typo in a\n * caller's options object is a compile error, not a silently-ignored no-op.\n */\nexport interface VerovioLayoutOptions {\n breaks?: 'none' | 'auto' | 'line' | 'smart' | 'encoded';\n breaksSmartSb?: number;\n breaksNoWidow?: boolean;\n minLastJustification?: number;\n spacingSystem?: number;\n spacingStaff?: number;\n /**\n * Player-level widow guard — see `engraveOnce`'s own \"Widow pass\" doc.\n * NOT the same mechanism as `breaksNoWidow` above (Verovio's own option,\n * which only prevents a lone measure on the last PAGE — confirmed on a\n * live page to do nothing for a lone measure on the last SYSTEM of a\n * single-page excerpt, the common case for this player). This is a\n * PLAYER option, not a Verovio one: it is stripped out in\n * `verovioRenderOptions` before `setOptions` ever sees it (Verovio has no\n * such option of its own to receive it). Default `true` — every engrave\n * gets the widow guard unless a caller opts out. Only takes effect when\n * the EFFECTIVE `breaks` is `'auto'` (this object's `breaks`, or\n * `VEROVIO_LAYOUT_DEFAULTS.breaks` when unset) — a caller who already\n * encoded exact break points (`breaks: 'line'`, e.g. Stave's own\n * per-line-break usage) has made their own layout choice, which this pass\n * never second-guesses.\n */\n avoidWidows?: boolean;\n /**\n * Readability floor for CALLER-ENCODED breaks (`breaks: 'line'` or\n * `'encoded'`) — see `engraveOnce`'s own \"Fallback pass\" doc. Stave's own\n * motivating case: `<print new-system=\"yes\"/>` every 4 bars + `breaks:\n * 'line'` gets exact N-bars-per-line on normal music, but on dense music\n * (e.g. a Bach fugue excerpt) the one system between two encoded breaks\n * can be too wide to fit even at Verovio's minimum spacing — the ONLY\n * lever `fitZoomFactor` then has left is shrinking the effective zoom,\n * which on a dense-enough system means unreadably small glyphs. Good\n * sight-reading software prefers readable glyphs over a fixed bar count.\n *\n * A PLAYER option, not a Verovio one — like `avoidWidows`, stripped out in\n * `verovioRenderOptions` before `setOptions` ever sees it. Default 0.75\n * (see `shouldFallbackToAutoBreaks`'s own doc for the exact trigger\n * condition). `minFitFactor: 0` disables the fallback entirely — a caller\n * who always wants their exact encoded bar count, however small the\n * glyphs get, can opt back into the pre-existing behavior.\n */\n minFitFactor?: number;\n}\n\n/**\n * Layout defaults applied to EVERY engrave (initial + every reflow) unless a\n * caller's own `verovioOptions` overrides a given key — see\n * `verovioRenderOptions`'s doc for the merge order.\n *\n * WHY: Verovio only justifies a page's LAST system when its unstretched\n * width is already ≥ `minLastJustification` (Verovio's own default: 0.8) of\n * the page width — confirmed empirically (a 4-bar-of-whole-notes fixture at\n * pageWidth 2400 renders its single system at ~41% of the page width with\n * Verovio's own default, ~96% with `minLastJustification: 0`; see this\n * module's real-Verovio justification test). A short excerpt — the common\n * case for both this player's normal usage (a few bars at a time) AND\n * Stave's per-line-break usage (section below) — is ALWAYS a \"last system\"\n * (it's the only one), so Verovio's default leaves it looking\n * left-justified/shrunk rather than filling the available width. Overriding\n * to 0 makes every system justify unconditionally, matching this player's\n * own \"fill the host width\" semantic (`verovioZoomOptions`'s own doc).\n * `breaksNoWidow: true` prevents Verovio leaving a single trailing bar\n * orphaned on its own system (a related \"short excerpt\" artifact, same\n * spirit as the justification fix). `breaks: 'auto'` (Verovio's own default\n * line-breaking algorithm) is the base default; Stave overrides it to\n * `'line'` when it has ALREADY encoded exact break points (see\n * `VerovioLayoutOptions`'s doc) — see the \"caller's `breaks` wins\" case in\n * `verovioRenderOptions`'s own tests.\n */\nexport const VEROVIO_LAYOUT_DEFAULTS = {\n breaks: 'auto',\n minLastJustification: 0,\n breaksNoWidow: true,\n} as const;\n\n/**\n * The full `toolkit.setOptions(...)` argument for one engrave: layout\n * defaults, overridden by the caller's own `layout` (a caller's `breaks`\n * WINS over `VEROVIO_LAYOUT_DEFAULTS.breaks` — this is the whole point of\n * exposing the override), overridden AGAIN by `scale`/`pageWidth` (derived\n * from `hostWidthPx`/`zoom` via `verovioZoomOptions` — a caller's\n * `verovioOptions` has no `scale`/`pageWidth` keys per `VerovioLayoutOptions`\n * own (narrower) type, so this last spread is really just making the\n * derived-vs-defaulted precedence explicit, not fighting a real collision)\n * and `adjustPageHeight: true` (always on — this player's own \"whole score,\n * page-flow, no pagination\" framing, see the module doc's \"PAGES\" section).\n * Pure — exists so the merge itself is unit-testable without a DOM or a real\n * Verovio toolkit (`tests/notationPlayerVerovio.test.ts`'s \"options merge\"\n * tests call this directly).\n *\n * `avoidWidows`/`minFitFactor` (see `VerovioLayoutOptions`'s own docs) are\n * PLAYER options, not Verovio ones — destructured out here and never\n * forwarded to `setOptions`, same \"narrow the passthrough\" spirit as this\n * function only accepting `VerovioLayoutOptions`'s typed surface at all.\n *\n * `pageHeight: 60000` (Verovio's own max) + `pageMarginTop`/`pageMarginBottom:\n * 0` are unconditional, like `adjustPageHeight` — not in `VerovioLayoutOptions`\n * at all, so a caller cannot override them. WHY: this player's own \"whole\n * score, page-flow, no pagination\" framing (module doc, \"PAGES\" section)\n * renders every Verovio PAGE as its own `.vrv-page` block; Verovio's default\n * page height (~2970, a real printed-page height) paginates a long score\n * into several such blocks with a page-margin gap between them, which reads\n * as a broken PDF rather than one continuous score. A tall-enough\n * `pageHeight` (combined with `adjustPageHeight: true`, already unconditional\n * above) keeps `getPageCount() === 1` regardless of how long the piece is —\n * confirmed against a real 40-bar fixture (2 pages at Verovio's own default\n * height, 1 page at 60000 — see this module's real-Verovio pageHeight test).\n * Zeroing the page margins removes the (now pointless, since there is only\n * ever one page) top/bottom whitespace Verovio would otherwise still budget\n * for a \"page\".\n */\nexport function verovioRenderOptions(\n hostWidthPx: number,\n zoom: number,\n layout?: VerovioLayoutOptions,\n): Record<string, unknown> {\n const { scale, pageWidth } = verovioZoomOptions(hostWidthPx, zoom);\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { avoidWidows: _avoidWidows, minFitFactor: _minFitFactor, ...verovioLayout } = layout ?? {};\n return {\n ...VEROVIO_LAYOUT_DEFAULTS,\n ...verovioLayout,\n scale,\n pageWidth,\n adjustPageHeight: true,\n pageHeight: 60000,\n pageMarginTop: 0,\n pageMarginBottom: 0,\n };\n}\n\n/**\n * 1 when every system already fits within `engraveWidthPx` (widest ≤ width\n * × 1.01 — a small tolerance for sub-pixel rounding in the DOM geometry, not\n * a real \"close enough\" fudge); otherwise `engraveWidthPx / widest` (< 1) —\n * the zoom-scaling factor that would bring the widest system back down to\n * exactly `engraveWidthPx`. Never NaN/Infinity: an empty `systemWidthsPx`,\n * a non-finite/non-positive widest width, or a non-finite/non-positive\n * `engraveWidthPx` all return 1 (the safe \"don't touch the zoom\" default —\n * see the module doc's \"Fit-to-width\" section for how the caller uses this:\n * a factor < 1 triggers exactly ONE re-engrave at `requestedZoom * factor`,\n * never a loop).\n *\n * WHY THIS IS NEEDED (see `VEROVIO_LAYOUT_DEFAULTS`'s doc for the\n * complementary justification fix): with ENCODED breaks (`breaks: 'line'` +\n * Stave's own `<print new-system=\"yes\"/>` markers), Verovio must put\n * whatever notes fall between two encoded break points onto one system —\n * unlike `breaks: 'auto'`, it cannot relieve overcrowding by moving a\n * measure to the next line. If that system is too dense to fit\n * `engraveWidthPx` even at Verovio's own minimum inter-note spacing, Verovio\n * renders it WIDER than the requested page width instead of silently\n * clipping it. Shrinking the effective zoom (smaller glyphs, smaller\n * spacing) is the only lever left to bring it back within the host's\n * available width.\n */\nexport function fitZoomFactor(systemWidthsPx: readonly number[], engraveWidthPx: number): number {\n if (!systemWidthsPx.length) return 1;\n if (!(engraveWidthPx > 0) || !Number.isFinite(engraveWidthPx)) return 1;\n const widest = Math.max(...systemWidthsPx);\n if (!(widest > 0) || !Number.isFinite(widest)) return 1;\n if (widest <= engraveWidthPx * 1.01) return 1;\n const factor = engraveWidthPx / widest;\n return Number.isFinite(factor) && factor > 0 ? factor : 1;\n}\n\n/** Default `VerovioLayoutOptions.minFitFactor` — see that field's own doc. */\nexport const DEFAULT_MIN_FIT_FACTOR = 0.75;\n\n/**\n * Pure decision for the readability floor (`VerovioLayoutOptions.minFitFactor`,\n * `engraveOnce`'s \"Fallback pass\") — true exactly when ALL of:\n * - `factor` (a `fitZoomFactor` result) is finite and strictly below\n * `minFitFactor`;\n * - `minFitFactor` is a positive, finite floor (0 — or anything\n * non-positive/non-finite — disables the fallback unconditionally, the\n * documented opt-out);\n * - `breaks` is `'line'` or `'encoded'` — the two ways a caller can hand\n * Verovio EXACT, pre-decided break points (as opposed to `'auto'`/\n * `'smart'`/`'none'`/unset, where Verovio already owns the line-breaking\n * decision and there is no \"caller's encoded bar count\" to fall back\n * FROM in the first place).\n *\n * Never throws; no DOM/Verovio access — this is the single source of truth\n * `engraveOnce` calls after every fit-factor computation, so the trigger\n * condition is unit-testable independent of a real engrave.\n */\nexport function shouldFallbackToAutoBreaks(\n factor: number,\n breaks: VerovioLayoutOptions['breaks'] | undefined,\n minFitFactor: number,\n): boolean {\n if (!Number.isFinite(factor)) return false;\n if (!(minFitFactor > 0)) return false;\n if (breaks !== 'line' && breaks !== 'encoded') return false;\n return factor < minFitFactor;\n}\n\n/**\n * Semantic zoom → Verovio options. The migration spike's `zoom-test*.mjs`\n * proved `pageWidth` (Verovio's line-breaking width, in ITS OWN units)\n * drives measures-per-system while `scale` (glyph size) alone does NOT\n * (avgMeasuresPerSystem was IDENTICAL — 3.61 — across scale 40/80/150 at a\n * fixed pageWidth 1600; it moved 2.24→3.61→5.91 as pageWidth alone rose\n * 1000→1600→2400 at a fixed scale). Verovio's own rendered SVG width in CSS\n * px is EXACTLY `pageWidth * scale / 100` (confirmed empirically against\n * real 6.2.0 renders) — an identity, not an approximation.\n *\n * This function picks `scale` proportional to `zoom` (bigger zoom ⇒ bigger\n * glyphs) and then SOLVES that identity for the `pageWidth` that makes the\n * rendered width land EXACTLY on `hostWidthPx` regardless of zoom\n * (`pageWidth = hostWidthPx * 100 / scale`). Composing it this way — instead\n * of tuning `scale` and `pageWidth` independently — makes BOTH halves of the\n * spec's semantic fall out of the ONE formula: as `zoom` rises, `scale`\n * rises (glyphs bigger) AND the required `pageWidth` (in Verovio units)\n * SHRINKS proportionally (since it's inversely proportional to `scale` at a\n * fixed target width) — and per the spike's own finding, a smaller\n * `pageWidth` fits FEWER measures per system. So \"bigger zoom ⇒ fewer\n * measures/system, glyphs larger, width still fits host\" (design doc §2) is\n * a direct consequence of this one identity, pinned by\n * `tests/notationPlayerVerovio.test.ts`'s real-Verovio monotonicity test.\n *\n * No floor on `pageWidth` beyond what the identity itself produces: `scale`\n * is already clamped to `[VEROVIO_MIN_SCALE, VEROVIO_MAX_SCALE]` (both > 0)\n * and `hostWidthPx` is floored to a sane fallback when invalid, so\n * `pageWidth = w * 100 / scale` is ALWAYS finite and positive — an\n * additional floor would only ever fire by breaking the width-fits-host\n * identity (clamping the OUTPUT width away from the host's actual width),\n * which is worse than a small `pageWidth`.\n */\nexport function verovioZoomOptions(hostWidthPx: number, zoom: number): VerovioRenderOptions {\n const z = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;\n const scale = Math.max(VEROVIO_MIN_SCALE, Math.min(VEROVIO_MAX_SCALE, VEROVIO_BASE_SCALE * z));\n const w = Number.isFinite(hostWidthPx) && hostWidthPx > 0 ? hostWidthPx : MAX_ENGRAVE_WIDTH_VRV;\n const pageWidth = (w * 100) / scale;\n return { scale, pageWidth };\n}\n\n// ─── Shared module-level toolkit (see the module doc's \"SHARED TOOLKIT\n// INSTANCE\" section) ─────────────────────────────────────────────────\n\n/** The subset of `VerovioToolkit`'s instance API this module calls — see\n * `src/types/verovio.d.ts` for the ambient module declaration backing the\n * dynamic imports below (the `verovio` npm package ships no types of its\n * own). Deliberately duck-typed/local rather than importing the real class\n * type statically, so nothing about this module's own type-checking\n * depends on a STATIC import of `verovio/esm` (only the dynamic one inside\n * `getVerovioToolkit` touches the package at all, which is what tsup's\n * `external` + the build-audit grep gate verify). */\ninterface VerovioToolkitInstance {\n loadData(data: string): boolean;\n getPageCount(): number;\n renderToSVG(page: number): string;\n setOptions(options: Record<string, unknown>): void;\n redoLayout(options?: Record<string, unknown>): void;\n}\n\nlet toolkitPromise: Promise<VerovioToolkitInstance> | null = null;\n\nfunction getVerovioToolkit(): Promise<VerovioToolkitInstance> {\n if (!toolkitPromise) {\n toolkitPromise = (async () => {\n // Literal dynamic imports — consumers' bundlers must statically see\n // these specifiers to code-split Verovio out of every OTHER dist\n // entry (tsup marks `verovio` external — see tsup.config.ts + the\n // build report's dist-grep evidence). A caller that only ever uses\n // the `rendered` test seam never pulls Verovio in at all.\n const [{ default: createVerovioModule }, { VerovioToolkit }] = await Promise.all([\n import('verovio/wasm'),\n import('verovio/esm'),\n ]);\n const VerovioModule = await createVerovioModule();\n return new VerovioToolkit(VerovioModule) as unknown as VerovioToolkitInstance;\n })();\n }\n return toolkitPromise;\n}\n\n/**\n * Module-level SERIAL queue over the shared toolkit — bug E7M-322: in\n * production, remounting a player component several times in quick\n * succession (destroying each instance before its `ready` resolved, EVERY\n * instance awaiting the SAME shared `getVerovioToolkit()` promise) produced\n * an Emscripten \"null function\" error from the WASM bridge. `withToolkit`\n * makes every `setOptions -> loadData -> getPageCount/renderToSVG` sequence,\n * across EVERY live player, run to completion strictly one at a time — even\n * across the async wasm-load boundary the very first call incurs. Each\n * queued task is chained off the PREVIOUS task's own settled promise (not\n * off `toolkitPromise` directly), so two tasks queued back-to-back before\n * the toolkit even exists yet still serialize correctly once it resolves;\n * without this, both would `await` the same not-yet-resolved\n * `getVerovioToolkit()` promise and their synchronous toolkit-touching code\n * could run in whatever order the two continuations happen to be scheduled,\n * which is exactly the \"several players hammering the one shared instance\n * at once\" shape the production bug had.\n *\n * `fn` MUST stay synchronous (no `await` inside it) — same \"no interleaving\n * because no await between reclaim and render\" rule `reflow`'s own doc\n * already relied on; the queue is what now makes that rule hold ACROSS\n * players' tasks, not just within one player's own call. A task that has\n * gone stale while queued (its player was destroyed while waiting for its\n * turn) must check `destroyed` as the FIRST thing inside `fn` and return a\n * no-op result — `withToolkit` itself has no opinion on staleness, only\n * serialization (see `initialEngrave`/`reflow`'s own `fn` bodies).\n *\n * A rejecting task never wedges the queue for tasks queued after it (the\n * internal chain swallows the rejection); the ORIGINAL caller still sees\n * their own task's rejection via the promise `withToolkit` returns, since\n * that is tracked separately from the internal queue chain.\n */\nlet toolkitQueue: Promise<unknown> = Promise.resolve();\n\nfunction withToolkit<T>(fn: (toolkit: VerovioToolkitInstance) => T): Promise<T> {\n const run = toolkitQueue.then(() => getVerovioToolkit()).then((toolkit) => fn(toolkit));\n toolkitQueue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n}\n\n// ─── createVerovioNotationPlayer ────────────────────────────────────────────\n\n// Module-level (not per-instance) — see `osmdOptions`'s doc: a caller\n// building many players with the same options object should see this once\n// per SESSION, not once per player.\nlet loggedAutoBeamIgnored = false;\n\nconst DEFAULT_PLAYHEAD_COLOR = '#2f6f4f';\n/** Engrave-width ceiling, CSS px — same policy as notationPlayerSvg.ts's\n * `MAX_ENGRAVE_WIDTH_SVG` (design doc §\"Render\": \"cap ~1200px\"), restated\n * independently since the two players' constants are independently\n * tunable. Raised 1200 -> 1400: Stave's encoded-break usage\n * (`verovioOptions.breaks: 'line'`, exact N-bars-per-line) wants more\n * breathing room per system than the original OSMD-parity cap allowed\n * before glyphs get cramped at typical desktop widths. */\nexport const MAX_ENGRAVE_WIDTH_VRV = 1400;\n/** Floor so a not-yet-laid-out / zero-width host never engraves at 0px. */\nconst MIN_ENGRAVE_WIDTH_VRV = 280;\n\n/** Build a live, interactive Verovio (vector) notation player. See the\n * module doc + `docs/superpowers/specs/2026-08-11-verovio-player-design.md`\n * (in stave-web-sightread) §2 for the full design. */\nexport function createVerovioNotationPlayer(opts: CreateVerovioNotationPlayerOpts): VerovioNotationPlayer {\n const { host, musicXml, onsets: rawOnsets } = opts;\n const playheadColor = opts.playheadColor ?? DEFAULT_PLAYHEAD_COLOR;\n const onsets = distinctOnsets(rawOnsets.map((o) => ({ onsetMs: o.tMs })));\n\n if (opts.osmdOptions?.autoBeam !== undefined && !loggedAutoBeamIgnored) {\n loggedAutoBeamIgnored = true;\n // eslint-disable-next-line no-console\n console.warn(\n '[notationPlayerVerovio] osmdOptions.autoBeam has no Verovio equivalent (Verovio always beams from the ' +\n 'MusicXML <beam> data) — ignored.',\n );\n }\n\n // Stamp once, up front — pure/idempotent (./notationXml.ts's doc), so\n // re-stamping a caller's already-stamped xml (e.g. stave's own transform\n // pipeline) reproduces the exact same ids. `noteModel` is likewise a pure\n // function of this same stamped string, computed once and reused across\n // every re-engrave (`setZoom`/`resize` never change note IDENTITY, only\n // geometry). The `rendered` test seam has no real document to stamp/model\n // against — `notePositions()`/`markNotes()` degrade gracefully to `[]`/\n // no-op there, same as `verovioOnsetColumns` already does for that seam.\n const stampedXml = opts.rendered ? musicXml : stampNoteIds(musicXml);\n const noteModel: Map<string, NoteModel> = opts.rendered ? new Map() : noteModelFromXml(stampedXml);\n\n const root = document.createElement('div');\n root.style.position = 'relative';\n root.style.width = '100%';\n // Same \"optical zoom is free\" reasoning as notationPlayerSvg.ts — let\n // native pinch-zoom + vertical page-scroll gestures through unimpeded.\n root.style.touchAction = 'pan-y pinch-zoom';\n host.appendChild(root);\n\n const svgHost = document.createElement('div');\n root.appendChild(svgHost);\n\n const playheadEl = document.createElement('div');\n // Published contract: hosts may locate the playhead (e.g. to keep it in\n // view inside their own scroll container) via [data-rmp-playhead] — same\n // attribute notationPlayerSvg.ts sets, same reasoning (see its own\n // comment). The element stays owned by this component — position/size\n // are not API.\n playheadEl.dataset.rmpPlayhead = '1';\n playheadEl.style.position = 'absolute';\n playheadEl.style.left = '0px';\n playheadEl.style.top = '0px';\n playheadEl.style.width = '2px';\n playheadEl.style.height = '0px';\n playheadEl.style.background = playheadColor;\n playheadEl.style.opacity = '0';\n playheadEl.style.pointerEvents = 'none';\n root.appendChild(playheadEl);\n\n let currentLayout: NotationLayout | null = null;\n let currentNoteCols: number[] | undefined;\n let currentZoom = opts.zoom ?? 1;\n let lastEngravedWidthPx = 0;\n let loaded = false; // toolkit.loadData succeeded (rendered-seam path never sets this)\n let destroyed = false;\n let lastTMs = 0;\n // Stale-reflow guard — same \"each async re-engrave captures its own\n // token\" rule as notationPlayerSvg.ts's `rebuildToken`.\n let rebuildToken = 0;\n\n function desiredEngraveWidthPx(): number {\n const w = host.clientWidth || 0;\n return Math.max(MIN_ENGRAVE_WIDTH_VRV, Math.min(w || MAX_ENGRAVE_WIDTH_VRV, MAX_ENGRAVE_WIDTH_VRV));\n }\n\n // ─── Playhead + auto-follow (createFollowController — notationCommon.ts) ─\n\n const follow = createFollowController({ topMarginPx: opts.followTopMarginPx });\n\n function renderPlayhead(tMs: number): void {\n lastTMs = tMs;\n if (!currentLayout) return;\n const nBars = currentLayout.measures.length\n ? Math.max(...currentLayout.measures.map((m) => m.index)) + 1\n : 0;\n const line = vstackAudioPlayheadLine(currentLayout, onsets, tMs, nBars, currentNoteCols);\n if (!line) {\n playheadEl.style.opacity = '0';\n return;\n }\n playheadEl.style.opacity = String(line.alpha);\n playheadEl.style.left = `${line.x}px`;\n playheadEl.style.top = `${line.y0}px`;\n playheadEl.style.height = `${Math.max(0, line.y1 - line.y0)}px`;\n const layoutForFollow = currentLayout;\n const sys = line.sys ?? -1;\n follow.follow({\n systemIndex: sys,\n getSystemRect: () => {\n const box = layoutForFollow.systems[sys];\n if (!box) return null;\n const rootRect = safeRect(root);\n if (!rootRect) return null;\n return { top: rootRect.top + box.y, bottom: rootRect.top + box.y + box.h };\n },\n getPlayheadRect: () => safeRect(playheadEl),\n });\n }\n\n function setTime(tMs: number): void {\n if (destroyed) return;\n follow.onSetTime(tMs);\n renderPlayhead(tMs);\n }\n\n // ─── Engrave / reflow ──────────────────────────────────────────────────\n\n function rebuildLayoutFromDom(): void {\n currentLayout = verovioNotationLayout(svgHost);\n currentNoteCols = verovioOnsetColumns(svgHost, currentLayout, rawOnsets);\n }\n\n function renderAllPages(toolkit: VerovioToolkitInstance): void {\n svgHost.replaceChildren();\n const pageCount = Math.max(0, toolkit.getPageCount());\n for (let p = 1; p <= pageCount; p++) {\n const pageDiv = document.createElement('div');\n pageDiv.className = 'vrv-page';\n pageDiv.innerHTML = toolkit.renderToSVG(p);\n svgHost.appendChild(pageDiv);\n }\n // Verovio honors print-object=\"no\" for pitched notes on its own but NOT\n // for rests (empirical finding — see applyPrintObjectHiding's own doc);\n // this patches the gap. Every fresh render is a fresh DOM, so this must\n // run after EVERY renderAllPages call, not just the initial one.\n applyPrintObjectHiding(svgHost, noteModel);\n }\n\n // ─── markNotes (survives re-engraving — reapplied after every render) ──\n\n let markedCols: number[] = [];\n\n function applyMarks(): void {\n for (const el of svgHost.querySelectorAll(`.${MARKED_NOTE_CLASS}`)) {\n el.classList.remove(MARKED_NOTE_CLASS);\n }\n if (!currentLayout || !markedCols.length) return;\n for (const col of markedCols) {\n for (const el of verovioNotesAtColumn(svgHost, currentLayout, col)) {\n el.classList.add(MARKED_NOTE_CLASS);\n }\n }\n }\n\n /**\n * WIDOW PASS helper (E7M — \"good sight-reading software never shows a\n * one-bar last line\") — extracted so `engraveOnce` can run it from TWO\n * places: after the normal first pass (breaks:'auto', as before), AND\n * after the readability-floor fallback pass forces `breaks: 'auto'` on a\n * caller-encoded document (see `engraveOnce`'s own \"Fallback pass\" doc).\n * Assumes `xml`/`layoutOpts` is ALREADY loaded+rendered into\n * `svgHost`/`currentLayout` (the caller just did that) — this only reads\n * `svgHost`'s current DOM shape and, if a widow is found, re-engraves.\n *\n * Verovio's own `breaksNoWidow` (in `VEROVIO_LAYOUT_DEFAULTS`) only\n * prevents a lone measure on the last PAGE — verified on a live page that\n * a 6-bar excerpt under `breaks: 'auto'` still renders as systems of 5+1\n * within a SINGLE page. This reads the rendered measure count per system\n * straight from the DOM (`systemMeasureCounts` — plain `.system`/\n * `.measure` traversal, no geometry needed). If there are ≥ 2 systems and\n * the LAST one has exactly 1 measure, it computes evenly-spread break\n * points for the SAME number of systems (`balancedSystemBreaks`) and\n * re-engraves ONCE with those breaks encoded (`injectSystemBreaks` +\n * `breaks: 'line'`) in place of `xml`/`layoutOpts`'s own render —\n * `injectSystemBreaks` only ever ADDS `<print>` elements (never touches a\n * `<note>`), so this never disturbs `stampedXml`'s own note ids /\n * `noteModel` join (pinned by this file's own re-balanced-render test).\n *\n * Returns the (xml, layoutOpts) pair that now reflects `svgHost`'s\n * content: unchanged on \"no widow found\" or \"re-engrave failed\" (the\n * caller's own already-rendered pass is left in place — same \"degrade to\n * the prior render, never blank\" style as the rest of `engraveOnce`), or\n * the widow-fixed pair on success.\n */\n function runWidowPass(\n toolkit: VerovioToolkitInstance,\n widthPx: number,\n zoom: number,\n xml: string,\n layoutOpts: VerovioLayoutOptions | undefined,\n ): { xml: string; layoutOpts: VerovioLayoutOptions | undefined } {\n const counts = systemMeasureCounts(svgHost);\n if (counts.length >= 2 && counts[counts.length - 1] === 1) {\n const totalMeasures = counts.reduce((a, b) => a + b, 0);\n const breakPositions = balancedSystemBreaks(totalMeasures, counts.length);\n if (breakPositions.length) {\n const widowXml = injectSystemBreaks(xml, breakPositions);\n const widowLayoutOpts: VerovioLayoutOptions = { ...layoutOpts, breaks: 'line' };\n toolkit.setOptions(verovioRenderOptions(widthPx, zoom, widowLayoutOpts));\n const okWidow = !!toolkit.loadData(widowXml);\n if (okWidow) {\n renderAllPages(toolkit);\n rebuildLayoutFromDom();\n return { xml: widowXml, layoutOpts: widowLayoutOpts };\n }\n // A failed widow re-engrave leaves the caller's own render (still in\n // svgHost/currentLayout from before this call) in place.\n }\n }\n return { xml, layoutOpts };\n }\n\n /**\n * Engrave `stampedXml` into the shared toolkit at (`widthPx`, `zoom`),\n * read the resulting layout back from the DOM, run the WIDOW PASS\n * (`runWidowPass`, above), then — if the effective breaks are still\n * caller-encoded (`'line'`/`'encoded'`) and the fit factor is below the\n * readability floor — run the FALLBACK PASS (below); finally, if whatever\n * ended up rendered produced a system wider than the page, re-engrave ONCE\n * more at a proportionally smaller effective zoom (see `fitZoomFactor`'s\n * own doc for why this can happen and the module doc's \"Fit-to-width\"\n * section). MUST run synchronously start-to-finish (no `await` inside) —\n * this is the `fn` passed to `withToolkit`, and its\n * single-sequence-at-a-time guarantee depends on that (see `withToolkit`'s\n * own doc). `currentZoom` is intentionally NOT updated here for the fit\n * correction — only the caller (`initialEngrave`/`reflow`) tracks the\n * user's REQUESTED zoom, so a later `setZoom(z)` steps from that requested\n * value, not from whatever the fit correction happened to render at; the\n * fit is recomputed fresh on every engrave rather than remembered. Returns\n * whether the FIRST pass's `loadData` succeeded — a failed later\n * re-engrave (rare) just leaves the most-recent successful pass's\n * already-rendered content in place rather than blanking the player.\n *\n * FALLBACK PASS (readability floor — `VerovioLayoutOptions.minFitFactor`,\n * default `DEFAULT_MIN_FIT_FACTOR`): with ENCODED breaks (Stave's own\n * `<print new-system=\"yes\"/>` + `breaks: 'line'` usage), Verovio must put\n * whatever notes fall between two encoded break points onto one system,\n * however dense — unlike `breaks: 'auto'`, it cannot relieve overcrowding\n * by moving a measure to the next line (see `fitZoomFactor`'s own doc).\n * The fit pass's only lever for a too-wide system is shrinking the\n * effective zoom, which on dense-enough music (e.g. a Bach fugue excerpt\n * that only fits 2 bars/line at zoom 0.85) shrinks glyphs to unreadable —\n * \"good sight-reading software prefers readable glyphs over a fixed bar\n * count.\" `shouldFallbackToAutoBreaks` (pure, own tests) is the exact\n * trigger condition, checked against the effective `breaks` the CALLER\n * asked for (`layoutOpts?.breaks` — never the widow pass's OWN\n * auto→'line' rewrite, since that never fires on already-caller-encoded\n * breaks in the first place, per the widow pass's own \"only ever applies\n * to breaks:'auto'\" rule). When it fires, this re-engraves ONCE with\n * `breaks: 'auto'` on the ORIGINAL `stampedXml` (ignoring the caller's\n * encoded breaks entirely — Verovio's own line-breaking algorithm decides\n * bar count instead), then runs the widow pass again on THAT result\n * (auto-breaking a short excerpt can itself produce a widow, same as the\n * normal 'auto' path). A failed fallback re-engrave leaves the\n * caller-encoded (post-widow-pass) render in place — degrade to \"unfit but\n * rendered,\" never blank. At most one fallback re-engrave per\n * `engraveOnce` call (the check runs once, off the FIRST pass's — or its\n * own widow pass's — fit factor only).\n */\n function engraveOnce(toolkit: VerovioToolkitInstance, widthPx: number, zoom: number): boolean {\n const layoutOpts = opts.verovioOptions;\n const effectiveBreaks = layoutOpts?.breaks ?? VEROVIO_LAYOUT_DEFAULTS.breaks;\n const minFitFactor = layoutOpts?.minFitFactor ?? DEFAULT_MIN_FIT_FACTOR;\n const avoidWidows = layoutOpts?.avoidWidows !== false;\n let xmlToRender = stampedXml;\n let renderLayoutOpts = layoutOpts;\n\n toolkit.setOptions(verovioRenderOptions(widthPx, zoom, renderLayoutOpts));\n const ok = !!toolkit.loadData(xmlToRender);\n if (ok) renderAllPages(toolkit);\n rebuildLayoutFromDom();\n\n if (ok && avoidWidows && effectiveBreaks === 'auto') {\n const widowed = runWidowPass(toolkit, widthPx, zoom, xmlToRender, renderLayoutOpts);\n xmlToRender = widowed.xml;\n renderLayoutOpts = widowed.layoutOpts;\n }\n\n if (ok && currentLayout) {\n const systemWidthsPx = () =>\n opts.measureSystemWidths ? opts.measureSystemWidths(svgHost) : currentLayout!.systems.map((s) => s.w);\n let factor = fitZoomFactor(systemWidthsPx(), widthPx);\n\n if (shouldFallbackToAutoBreaks(factor, effectiveBreaks, minFitFactor)) {\n const autoLayoutOpts: VerovioLayoutOptions = { ...layoutOpts, breaks: 'auto' };\n toolkit.setOptions(verovioRenderOptions(widthPx, zoom, autoLayoutOpts));\n const okAuto = !!toolkit.loadData(stampedXml);\n if (okAuto) {\n renderAllPages(toolkit);\n rebuildLayoutFromDom();\n xmlToRender = stampedXml;\n renderLayoutOpts = autoLayoutOpts;\n\n if (avoidWidows) {\n const widowed = runWidowPass(toolkit, widthPx, zoom, xmlToRender, renderLayoutOpts);\n xmlToRender = widowed.xml;\n renderLayoutOpts = widowed.layoutOpts;\n }\n factor = fitZoomFactor(systemWidthsPx(), widthPx);\n }\n // A failed fallback re-engrave leaves the caller-encoded render\n // (still in svgHost/currentLayout from before this block) in place —\n // xmlToRender/renderLayoutOpts/factor stay at their pre-fallback\n // values, so the fit-to-width pass below reflows THAT document.\n }\n\n if (factor < 1) {\n const effectiveZoom = zoom * factor;\n toolkit.setOptions(verovioRenderOptions(widthPx, effectiveZoom, renderLayoutOpts));\n const ok2 = !!toolkit.loadData(xmlToRender);\n if (ok2) {\n renderAllPages(toolkit);\n rebuildLayoutFromDom();\n }\n // A failed second loadData leaves the prior render (still in\n // svgHost/currentLayout from just above) untouched — degrade to\n // \"unfit but rendered\" rather than blank.\n }\n }\n return ok;\n }\n\n async function initialEngrave(): Promise<void> {\n if (opts.rendered) {\n currentLayout = opts.rendered;\n lastEngravedWidthPx = desiredEngraveWidthPx();\n renderPlayhead(lastTMs);\n return;\n }\n\n const widthPx = desiredEngraveWidthPx();\n const ok = await withToolkit((toolkit) => {\n if (destroyed) return false; // stale — this player died while queued\n return engraveOnce(toolkit, widthPx, currentZoom);\n });\n if (destroyed) return;\n\n lastEngravedWidthPx = widthPx;\n loaded = ok;\n applyMarks();\n renderPlayhead(lastTMs);\n }\n\n const ready = initialEngrave();\n\n /** Re-engrave at `newZoom` and the host's CURRENT width, preserving the\n * scroll position of whatever content is centered in the viewport right\n * now. Shared by both `setZoom` and `resize` — same shape as\n * notationPlayerSvg.ts's `reflow`. No-op when neither the width nor the\n * zoom actually changed, or when using the `rendered` test seam / the\n * initial load never succeeded (nothing to re-engrave). */\n async function reflow(newZoom: number): Promise<void> {\n if (destroyed) return;\n const widthPx = desiredEngraveWidthPx();\n if (widthPx === lastEngravedWidthPx && newZoom === currentZoom) return;\n if (opts.rendered || !loaded) {\n currentZoom = newZoom;\n return;\n }\n\n const myToken = ++rebuildToken;\n const oldLayout = currentLayout;\n const hasWin = typeof window !== 'undefined';\n let anchorY: number | null = null;\n const anchorX = widthPx / 2;\n if (hasWin && typeof root.getBoundingClientRect === 'function') {\n const r = root.getBoundingClientRect();\n anchorY = window.innerHeight / 2 - r.top;\n }\n\n // RECLAIM (see the module doc's \"SHARED TOOLKIT INSTANCE\" note, and\n // `withToolkit`'s own doc for bug E7M-322): the module-level toolkit is\n // shared across every live player on the page — and the real consumer\n // (PlayerPage) keeps a harmony player AND a written player alive\n // SIMULTANEOUSLY (lazy-built, destroyed only on piece switch), so\n // `loadData` calls from the two players genuinely interleave (e.g.\n // harmony active -> resize while written hidden -> back to written ->\n // writtenPlayer.setZoom()). A plain `redoLayout()` here would silently\n // re-lay-out and render WHATEVER document the toolkit currently holds —\n // which may belong to the OTHER player if it rendered more recently. So\n // `engraveOnce` re-parses THIS player's own `musicXml` synchronously,\n // immediately before rendering (loadData does a full parse + layout with\n // the just-set options, making a separate `redoLayout()` call\n // redundant). `withToolkit` now additionally guarantees no OTHER\n // player's queued task can run its own setOptions/loadData/render\n // sequence in between this task's own steps — the shared singleton is\n // therefore safe under alternating AND concurrent use. See\n // `tests/notationPlayerVerovio.test.ts`'s two-player interleaved-reflow\n // test for the regression this guards against.\n const ok = await withToolkit((toolkit) => {\n if (destroyed || myToken !== rebuildToken) return false; // stale\n return engraveOnce(toolkit, widthPx, newZoom);\n });\n\n if (destroyed || myToken !== rebuildToken) return;\n if (!ok) {\n loaded = false;\n return;\n }\n\n lastEngravedWidthPx = widthPx;\n currentZoom = newZoom;\n applyMarks();\n\n if (oldLayout && currentLayout && anchorY != null && hasWin) {\n const delta = computeReflowScrollDelta(oldLayout, currentLayout, anchorX, anchorY);\n if (Number.isFinite(delta) && Math.abs(delta) > 0.5) {\n window.scrollTo({ top: Math.max(0, window.scrollY + delta), left: window.scrollX, behavior: 'auto' });\n }\n }\n if (!destroyed) renderPlayhead(lastTMs);\n }\n\n // ─── Click-to-seek ─────────────────────────────────────────────────────\n\n const clickListeners: Array<(measureIndex: number) => void> = [];\n function onRootClick(e: MouseEvent): void {\n if (!currentLayout) return;\n const rect = root.getBoundingClientRect();\n const mx = e.clientX - rect.left;\n const my = e.clientY - rect.top;\n const idx = hitTestMeasureAt(currentLayout, mx, my);\n if (idx != null) for (const cb of clickListeners) cb(idx);\n }\n root.addEventListener('click', onRootClick);\n\n return {\n ready,\n setTime,\n markNotes(cols: number[] | null): void {\n markedCols = cols ?? [];\n applyMarks();\n },\n notePositions(): EngravedNote[] {\n return verovioEngravedNotes(svgHost, host, noteModel);\n },\n setFollowEnabled(on) {\n follow.setEnabled(on);\n },\n async setZoom(z: number): Promise<void> {\n await ready;\n await reflow(z);\n },\n async resize(): Promise<void> {\n await ready;\n await reflow(currentZoom);\n },\n onMeasureClick(cb: (measureIndex: number) => void): () => void {\n clickListeners.push(cb);\n return () => {\n const i = clickListeners.indexOf(cb);\n if (i >= 0) clickListeners.splice(i, 1);\n };\n },\n destroy(): void {\n if (destroyed) return;\n destroyed = true;\n rebuildToken++;\n root.removeEventListener('click', onRootClick);\n follow.destroy();\n clickListeners.length = 0;\n markedCols = [];\n currentLayout = null;\n currentNoteCols = undefined;\n if (root.parentNode === host) host.removeChild(root);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBO,SAAS,aAAa,KAAqB;AAChD,QAAM,MAAM,IAAI,UAAU,EAAE,gBAAgB,KAAK,iBAAiB;AAClE,MAAI,IA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sB;AACxC,UAAM,KAAK,EAAE,UAAU,KAAK;AAC5B,UAAM,KAAK,EAAE,UAAU,KAAK;AAC5B,UAAM,MAAM,iBAAiB,eAAe,IAAI,EAAE;AAClD,QAAI,OAAO,KAAM,YAAW,MAAM,eAAgB,IAAG,GAAG;AAAA,EAC1D;AACA,OAAK,iBAAiB,SAAS,WAAW;AAE1C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,UAAU,MAA6B;AACrC,mBAAa,QAAQ,CAAC;AACtB,iBAAW;AAAA,IACb;AAAA,IACA,gBAAgC;AAC9B,aAAO,qBAAqB,SAAS,MAAM,SAAS;AAAA,IACtD;AAAA,IACA,iBAAiB,IAAI;AACnB,aAAO,WAAW,EAAE;AAAA,IACtB;AAAA,IACA,MAAM,QAAQ,GAA0B;AACtC,YAAM;AACN,YAAM,OAAO,CAAC;AAAA,IAChB;AAAA,IACA,MAAM,SAAwB;AAC5B,YAAM;AACN,YAAM,OAAO,WAAW;AAAA,IAC1B;AAAA,IACA,eAAe,IAAgD;AAC7D,qBAAe,KAAK,EAAE;AACtB,aAAO,MAAM;AACX,cAAM,IAAI,eAAe,QAAQ,EAAE;AACnC,YAAI,KAAK,EAAG,gBAAe,OAAO,GAAG,CAAC;AAAA,MACxC;AAAA,IACF;AAAA,IACA,UAAgB;AACd,UAAI,UAAW;AACf,kBAAY;AACZ;AACA,WAAK,oBAAoB,SAAS,WAAW;AAC7C,aAAO,QAAQ;AACf,qBAAe,SAAS;AACxB,mBAAa,CAAC;AACd,sBAAgB;AAChB,wBAAkB;AAClB,UAAI,KAAK,eAAe,KAAM,MAAK,YAAY,IAAI;AAAA,IACrD;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@real-music-packages/web-core",
3
- "version": "0.45.0",
3
+ "version": "0.45.2",
4
4
  "description": "Shared music-theory + audio primitives for the music-suite web apps",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",