@real-music-packages/web-core 0.42.0 → 0.42.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.
@@ -236,11 +236,13 @@ function verovioOnsetColumns(root, layout, onsets) {
236
236
  if (index == null) continue;
237
237
  const m = cols[index];
238
238
  const geom = measureEntries[index]?.geom;
239
- const box = noteEl && geom ? boxFromElement(noteEl, geom) : null;
239
+ const headGlyph = noteEl ? noteEl.querySelector(".notehead") ?? noteEl : null;
240
+ const box = headGlyph && geom ? boxFromElement(headGlyph, geom) : null;
240
241
  if (!box || !m) continue;
241
242
  const sx = Math.min(m.noteStartX, m.x + m.w);
242
243
  const denom = m.x + m.w - sx;
243
- const frac = denom > 0 ? Math.min(1, Math.max(0, (box.x - sx) / denom)) : 0;
244
+ const anchorX = box.x + box.w / 2;
245
+ const frac = denom > 0 ? Math.min(1, Math.max(0, (anchorX - sx) / denom)) : 0;
244
246
  positions.push(index + frac);
245
247
  }
246
248
  if (positions.length) return positions.reduce((a, b) => a + b, 0) / positions.length;
@@ -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\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 const box = noteEl && geom ? boxFromElement(noteEl, 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 frac = denom > 0 ? Math.min(1, Math.max(0, (box.x - 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 * 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// ─── 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. */\nexport const MAX_ENGRAVE_WIDTH_VRV = 1200;\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 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 toolkit = await getVerovioToolkit();\n if (destroyed) return;\n\n const widthPx = desiredEngraveWidthPx();\n const { scale, pageWidth } = verovioZoomOptions(widthPx, currentZoom);\n toolkit.setOptions({ scale, pageWidth, breaks: 'auto', adjustPageHeight: true });\n loaded = !!toolkit.loadData(stampedXml);\n if (destroyed) return;\n\n lastEngravedWidthPx = widthPx;\n if (loaded) renderAllPages(toolkit);\n rebuildLayoutFromDom();\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 toolkit = await getVerovioToolkit();\n if (destroyed) return;\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 const { scale, pageWidth } = verovioZoomOptions(widthPx, newZoom);\n toolkit.setOptions({ scale, pageWidth, breaks: 'auto', adjustPageHeight: true });\n // RECLAIM (see the module doc's \"SHARED TOOLKIT INSTANCE\" note): the\n // module-level toolkit is shared across every live player on the page —\n // and the real consumer (PlayerPage) keeps a harmony player AND a\n // written player alive SIMULTANEOUSLY (lazy-built, destroyed only on\n // piece switch), so `loadData` calls from the two players genuinely\n // interleave (e.g. harmony active -> resize while written hidden -> back\n // to written -> writtenPlayer.setZoom()). A plain `redoLayout()` here\n // would silently re-lay-out and render WHATEVER document the toolkit\n // currently holds — which may belong to the OTHER player if it rendered\n // more recently. So every reflow re-parses THIS player's own `musicXml`\n // synchronously, immediately before rendering (loadData does a full\n // parse + layout with the just-set options, making a separate\n // `redoLayout()` call redundant). Because this call and `renderAllPages`\n // below are both synchronous with NO `await` between them, and the only\n // preceding `await` (`getVerovioToolkit()`) already resolved, JS's\n // single-threaded run-to-completion semantics guarantee no other\n // player's reflow/initialEngrave can interleave between the reclaim and\n // the render — the shared singleton is therefore safe under alternating\n // use. See `tests/notationPlayerVerovio.test.ts`'s two-player\n // interleaved-reflow test for the regression this guards against.\n const ok = toolkit.loadData(stampedXml);\n if (destroyed || myToken !== rebuildToken) return;\n if (!ok) {\n loaded = false;\n return;\n }\n\n lastEngravedWidthPx = widthPx;\n currentZoom = newZoom;\n renderAllPages(toolkit);\n rebuildLayoutFromDom();\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 curr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AiB,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":[]}
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\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 * 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// ─── 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. */\nexport const MAX_ENGRAVE_WIDTH_VRV = 1200;\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 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 toolkit = await getVerovioToolkit();\n if (destroyed) return;\n\n const widthPx = desiredEngraveWidthPx();\n const { scale, pageWidth } = verovioZoomOptions(widthPx, currentZoom);\n toolkit.setOptions({ scale, pageWidth, breaks: 'auto', adjustPageHeight: true });\n loaded = !!toolkit.loadData(stampedXml);\n if (destroyed) return;\n\n lastEngravedWidthPx = widthPx;\n if (loaded) renderAllPages(toolkit);\n rebuildLayoutFromDom();\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 toolkit = await getVerovioToolkit();\n if (destroyed) return;\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 const { scale, pageWidth } = verovioZoomOptions(widthPx, newZoom);\n toolkit.setOptions({ scale, pageWidth, breaks: 'auto', adjustPageHeight: true });\n // RECLAIM (see the module doc's \"SHARED TOOLKIT INSTANCE\" note): the\n // module-level toolkit is shared across every live player on the page —\n // and the real consumer (PlayerPage) keeps a harmony player AND a\n // written player alive SIMULTANEOUSLY (lazy-built, destroyed only on\n // piece switch), so `loadData` calls from the two players genuinely\n // interleave (e.g. harmony active -> resize while written hidden -> back\n // to written -> writtenPlayer.setZoom()). A plain `redoLayout()` here\n // would silently re-lay-out and render WHATEVER document the toolkit\n // currently holds — which may belong to the OTHER player if it rendered\n // more recently. So every reflow re-parses THIS player's own `musicXml`\n // synchronously, immediately before rendering (loadData does a full\n // parse + layout with the just-set options, making a separate\n // `redoLayout()` call redundant). Because this call and `renderAllPages`\n // below are both synchronous with NO `await` between them, and the only\n // preceding `await` (`getVerovioToolkit()`) already resolved, JS's\n // single-threaded run-to-completion semantics guarantee no other\n // player's reflow/initialEngrave can interleave between the reclaim and\n // the render — the shared singleton is therefore safe under alternating\n // use. See `tests/notationPlayerVerovio.test.ts`'s two-player\n // interleaved-reflow test for the regression this guards against.\n const ok = toolkit.loadData(stampedXml);\n if (destroyed || myToken !== rebuildToken) return;\n if (!ok) {\n loaded = false;\n return;\n }\n\n lastEngravedWidthPx = widthPx;\n currentZoom = newZoom;\n renderAllPages(toolkit);\n rebuildLayoutFromDom();\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,QAAQ,MAAM,KAAK,QAAQ,QAAQ,EAAE,OAAO,CAAC,OAAO,GAAG,YAAY,MAAM;AAC/E,YAAM,QAAQ,CAAC,MAAM,YAAY;AAC/B,aAAK,aAAa,MAAM,KAAK,OAAO,IAAI,MAAM,IAAI,OAAO,EAAE;AAAA,MAC7D,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,SAAO,IAAI,cAAc,EAAE,kBAAkB,GAAG;AAClD;AA6DA,IAAM,gBAAwC,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG;AAE1F,SAAS,gBAAgB,IAAa,KAA6B;AACjE,aAAW,KAAK,MAAM,KAAK,GAAG,QAAQ,EAAG,KAAI,EAAE,YAAY,IAAK,QAAO;AACvE,SAAO;AACT;AACA,SAAS,cAAc,IAAa,KAAwB;AAC1D,SAAO,MAAM,KAAK,GAAG,QAAQ,EAAE,OAAO,CAAC,MAAM,EAAE,YAAY,GAAG;AACh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AM,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.42.0",
3
+ "version": "0.42.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",