@webmusic/kernel 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +435 -0
  3. package/dist/audio-context.cjs +10 -0
  4. package/dist/audio-context.cjs.map +1 -0
  5. package/dist/audio-context.d.cts +13 -0
  6. package/dist/audio-context.d.ts +13 -0
  7. package/dist/audio-context.js +10 -0
  8. package/dist/audio-context.js.map +1 -0
  9. package/dist/build-receipt.json +7 -0
  10. package/dist/chunk-3INDOVUC.cjs +134 -0
  11. package/dist/chunk-3INDOVUC.cjs.map +1 -0
  12. package/dist/chunk-53YD73OY.js +162 -0
  13. package/dist/chunk-53YD73OY.js.map +1 -0
  14. package/dist/chunk-7ZTZZ5PN.cjs +25 -0
  15. package/dist/chunk-7ZTZZ5PN.cjs.map +1 -0
  16. package/dist/chunk-BR63OD53.cjs +1 -0
  17. package/dist/chunk-BR63OD53.cjs.map +1 -0
  18. package/dist/chunk-C3YWUZW3.cjs +57 -0
  19. package/dist/chunk-C3YWUZW3.cjs.map +1 -0
  20. package/dist/chunk-FJLY3RWZ.js +134 -0
  21. package/dist/chunk-FJLY3RWZ.js.map +1 -0
  22. package/dist/chunk-GO4N5T27.js +94 -0
  23. package/dist/chunk-GO4N5T27.js.map +1 -0
  24. package/dist/chunk-HOKRTYPV.js +199 -0
  25. package/dist/chunk-HOKRTYPV.js.map +1 -0
  26. package/dist/chunk-HY2YIL75.js +16 -0
  27. package/dist/chunk-HY2YIL75.js.map +1 -0
  28. package/dist/chunk-HZQX4J2J.cjs +199 -0
  29. package/dist/chunk-HZQX4J2J.cjs.map +1 -0
  30. package/dist/chunk-ILKEVUJ3.js +57 -0
  31. package/dist/chunk-ILKEVUJ3.js.map +1 -0
  32. package/dist/chunk-JNXB74G3.cjs +987 -0
  33. package/dist/chunk-JNXB74G3.cjs.map +1 -0
  34. package/dist/chunk-N6KU2HYA.js +25 -0
  35. package/dist/chunk-N6KU2HYA.js.map +1 -0
  36. package/dist/chunk-PXG64RU4.js +25 -0
  37. package/dist/chunk-PXG64RU4.js.map +1 -0
  38. package/dist/chunk-SM5YPDDI.cjs +162 -0
  39. package/dist/chunk-SM5YPDDI.cjs.map +1 -0
  40. package/dist/chunk-TEM2I2NN.js +1 -0
  41. package/dist/chunk-TEM2I2NN.js.map +1 -0
  42. package/dist/chunk-UMTPJ76S.cjs +94 -0
  43. package/dist/chunk-UMTPJ76S.cjs.map +1 -0
  44. package/dist/chunk-VVZX7DQ6.cjs +254 -0
  45. package/dist/chunk-VVZX7DQ6.cjs.map +1 -0
  46. package/dist/chunk-VY6WWZSW.cjs +16 -0
  47. package/dist/chunk-VY6WWZSW.cjs.map +1 -0
  48. package/dist/chunk-WNFGDB7B.js +254 -0
  49. package/dist/chunk-WNFGDB7B.js.map +1 -0
  50. package/dist/chunk-XBJBY4J5.js +987 -0
  51. package/dist/chunk-XBJBY4J5.js.map +1 -0
  52. package/dist/chunk-ZMU72HJS.cjs +25 -0
  53. package/dist/chunk-ZMU72HJS.cjs.map +1 -0
  54. package/dist/effect.cjs +2 -0
  55. package/dist/effect.cjs.map +1 -0
  56. package/dist/effect.d.cts +19 -0
  57. package/dist/effect.d.ts +19 -0
  58. package/dist/effect.js +2 -0
  59. package/dist/effect.js.map +1 -0
  60. package/dist/elements.cjs +24 -0
  61. package/dist/elements.cjs.map +1 -0
  62. package/dist/elements.d.cts +76 -0
  63. package/dist/elements.d.ts +76 -0
  64. package/dist/elements.js +24 -0
  65. package/dist/elements.js.map +1 -0
  66. package/dist/events.cjs +8 -0
  67. package/dist/events.cjs.map +1 -0
  68. package/dist/events.d.cts +36 -0
  69. package/dist/events.d.ts +36 -0
  70. package/dist/events.js +8 -0
  71. package/dist/events.js.map +1 -0
  72. package/dist/index.cjs +77 -0
  73. package/dist/index.cjs.map +1 -0
  74. package/dist/index.d.cts +10 -0
  75. package/dist/index.d.ts +10 -0
  76. package/dist/index.js +77 -0
  77. package/dist/index.js.map +1 -0
  78. package/dist/meter.cjs +12 -0
  79. package/dist/meter.cjs.map +1 -0
  80. package/dist/meter.d.cts +76 -0
  81. package/dist/meter.d.ts +76 -0
  82. package/dist/meter.js +12 -0
  83. package/dist/meter.js.map +1 -0
  84. package/dist/player.cjs +16 -0
  85. package/dist/player.cjs.map +1 -0
  86. package/dist/player.d.cts +49 -0
  87. package/dist/player.d.ts +49 -0
  88. package/dist/player.js +16 -0
  89. package/dist/player.js.map +1 -0
  90. package/dist/sync.cjs +12 -0
  91. package/dist/sync.cjs.map +1 -0
  92. package/dist/sync.d.cts +304 -0
  93. package/dist/sync.d.ts +304 -0
  94. package/dist/sync.js +12 -0
  95. package/dist/sync.js.map +1 -0
  96. package/dist/tick.cjs +10 -0
  97. package/dist/tick.cjs.map +1 -0
  98. package/dist/tick.d.cts +48 -0
  99. package/dist/tick.d.ts +48 -0
  100. package/dist/tick.js +10 -0
  101. package/dist/tick.js.map +1 -0
  102. package/dist/transport.cjs +8 -0
  103. package/dist/transport.cjs.map +1 -0
  104. package/dist/transport.d.cts +114 -0
  105. package/dist/transport.d.ts +114 -0
  106. package/dist/transport.js +8 -0
  107. package/dist/transport.js.map +1 -0
  108. package/dist/worker.cjs +10 -0
  109. package/dist/worker.cjs.map +1 -0
  110. package/dist/worker.d.cts +49 -0
  111. package/dist/worker.d.ts +49 -0
  112. package/dist/worker.js +10 -0
  113. package/dist/worker.js.map +1 -0
  114. package/package.json +164 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sync.ts"],"sourcesContent":["// ============================================================================\n// Family-neutral synchronized-transport choreography: one master transport,\n// N schedulable followers, all positions on the MASTER's position axis\n// against one shared reference clock (typically AudioContext.currentTime).\n//\n// This is the sync machinery the score↔audio bridge proved out — command\n// serialization, generation guards, drift monitoring, scheduled joins,\n// master-self-stop reconciliation — hoisted here so every transport pairing\n// (score+clip, future families, external masters) reuses one hardened\n// implementation instead of re-writing it per pair. @webmusic/bridge remains\n// the domain assembly: it adapts ScorePlayer/AudioClipPlayer onto these role\n// contracts and keeps its public ScoreAudioSync surface.\n//\n// The master MUST expose a kernel TransportClockReader — the group anchors\n// by READING the clock, the exact affine map the master plays by, with no\n// sampling skew. A transport without a clock is wrapped in\n// {@link MirrorClockMaster}, which owns the sampled mirror-clock fallback\n// (dead-reckoning plus reconciliation) as ONE adapter instead of a second\n// code path inside the group.\n//\n// The group is the session command authority: revisioned invalidation and\n// settlement wrap its existing cancellation/re-entry choreography. Engines\n// still own their clocks. This is not same-instance writable-clock injection;\n// see platform/shared-clock-injection.md for that separate migration boundary.\n// ============================================================================\n\nimport {TransportClock, type TransportClockReader} from './transport';\nimport {\n MAX_TIMER_DELAY_MS,\n createTickSource,\n type TickSource,\n type TickSourceOptions,\n} from './tick';\n\n/**\n * Master role: the transport whose clock is the group's timeline. Everything\n * is on the master's own position axis (for a score player: nominal score\n * seconds; for a clip player: clip seconds).\n */\nexport interface SyncMasterTransport {\n /**\n * Start the transport. `when` (optional, absolute reference-clock seconds)\n * proposes an ARMED start: a master supporting scheduled starts arms its\n * clock there so followers can join at the very same instant. Masters\n * without the capability ignore the argument and start immediately — the\n * group detects which happened by observing `clock.holding`, never\n * through a declared flag.\n */\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n /**\n * Seek to a position on the master's axis. A returned promise settles\n * once the seek has been applied and any mid-playback restart attempted;\n * the group awaits it before re-anchoring followers. The promise MAY\n * resolve with the transport left paused when the restart failed — the\n * group treats that as a failed resume: it pauses the followers, settles\n * into the paused state and reports 'resume after seek' through\n * {@link TransportGroupOptions.onOperationError}. While playing, the\n * group passes a proposed re-entry time the same way {@link play} does.\n */\n seekPosition(position: number, when?: number): void | Promise<void>;\n setRate?(rate: number): void;\n /** Current position on the master's axis. */\n readonly position: number;\n /** Read-only transport clock (master position axis). REQUIRED — wrap a\n * clockless transport in {@link MirrorClockMaster}. */\n readonly clock: TransportClockReader;\n /**\n * Optional pre-drift-check reconciliation hook (adapters). Called once\n * per drift check with the current reference time; returning 'stalled'\n * tells the group the master stopped on its own (the adapter has already\n * paused its clock) — the group then wraps or settles exactly as for an\n * observed master stop.\n */\n reconcile?(now: number): 'ok' | 'stalled';\n dispose?(): void;\n}\n\n/** Follower role: a transport that can join the master's timeline. */\nexport interface SyncFollowerTransport {\n /**\n * Start playback. `when` (optional, absolute reference-clock seconds) is\n * the scheduled start the join dance relies on: the follower MUST honor\n * it sample-accurately for gapless joins (a follower that starts\n * immediately instead will sit one lead-in ahead and be re-corrected\n * forever by the drift monitor).\n */\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n seek(position: number): void;\n setRate?(rate: number): void;\n /** Current position on the follower's own axis. */\n readonly position: number;\n /** Whether the follower is running, when it can say (optional). */\n readonly running?: boolean;\n /**\n * Read-only clock on the follower's own axis, when the transport has one.\n * When present, the drift monitor reads position and running state from\n * it instead of sampling `position`/`running`.\n */\n readonly clock?: TransportClockReader;\n dispose?(): void;\n}\n\n/** Per-follower registration options. */\nexport interface FollowerOptions {\n /** Follower position corresponding to master position zero. Default 0. */\n offsetSeconds?: number;\n /** Positive affine scale: local position = offsetSeconds + master position × positionScale.\n * The follower's playback rate is scaled by the same factor. Default 1.\n * This is a constant map, not nonlinear warping. */\n positionScale?: number;\n /** Local loop bounds for a transport ALREADY configured to loop natively.\n * The group maps join/seek positions and drift into this phase; it does not\n * configure or schedule that native loop. Positions before the loop end\n * retain their intro; at/past the end they wrap into [start, end). */\n loop?: SyncLoopRegion;\n}\n\nexport interface TransportGroupOptions {\n /** Scheduling headroom before followers join, in seconds. Default 0.06. */\n leadInSeconds?: number;\n /** Re-join a follower when |follower − expected| exceeds this. Default 0.03 s. */\n driftToleranceSeconds?: number;\n /** Drift check cadence. Default 250 ms. 0 disables the monitor. */\n driftCheckIntervalMs?: number;\n /** Loop region on the master axis; also settable live via {@link TransportGroup.setLoop}. */\n loop?: SyncLoopRegion | null;\n /** Injectable tick source options (tests; custom hosting). */\n tick?: TickSourceOptions;\n /**\n * Observer for failures of the group's own fire-and-forget operations\n * (drift and rate re-joins, loop wraps, pause/stop reconciliation). Those\n * run behind the command queue with no caller promise to reject, and on\n * failure they settle the group into a paused state — without an observer\n * that settlement is silent. Observer exceptions are swallowed.\n */\n onOperationError?: (operation: string, error: unknown) => void;\n}\n\n/** A loop region on the master position axis. */\nexport interface SyncLoopRegion {\n startSeconds: number;\n endSeconds: number;\n}\n\n/** Commands accepted by the group's single authority. Positions use the master's\n * stable content axis, never a duration divided by the current playback rate. */\nexport type TransportCommand =\n | {readonly type: 'play' | 'pause' | 'stop'}\n | {readonly type: 'seek'; readonly position: number}\n | {readonly type: 'rate'; readonly rate: number}\n | {readonly type: 'loop'; readonly loop: SyncLoopRegion | null};\n\n/** Coherent observation at one reference-clock instant. This is a snapshot,\n * not a display timer; read again or use clock.positionAt for moving positions. */\nexport interface TransportSnapshot {\n readonly revision: number;\n readonly referenceTime: number;\n readonly position: number;\n readonly rate: number;\n readonly paused: boolean;\n readonly holding: boolean;\n readonly loop: Readonly<SyncLoopRegion> | null;\n readonly pending: boolean;\n readonly disposed: boolean;\n}\n\nexport interface TransportCommit {\n readonly revision: number;\n readonly command: TransportCommand;\n /** A newer command or disposal supersedes this operation's authority. */\n readonly status: 'committed' | 'superseded';\n readonly snapshot: TransportSnapshot;\n}\n\n/** Invalidation precedes participant commands, settlement follows their\n * asynchronous work. Engines retract/re-arm through their existing commands;\n * this observer protocol does not inject a shared writable clock. */\nexport type TransportEvent =\n | {readonly type: 'snapshot'; readonly snapshot: TransportSnapshot}\n | {readonly type: 'reconcile'; readonly operation: string; readonly phase: 'invalidate' | 'settled'; readonly snapshot: TransportSnapshot}\n | {readonly type: 'operation-error'; readonly operation: string; readonly error: unknown; readonly snapshot: TransportSnapshot}\n | {readonly type: 'invalidate'; readonly revision: number; readonly command: TransportCommand; readonly snapshot: TransportSnapshot}\n | {readonly type: 'commit'; readonly commit: TransportCommit; readonly snapshot: TransportSnapshot}\n | {readonly type: 'error'; readonly revision: number; readonly command: TransportCommand; readonly error: unknown; readonly snapshot: TransportSnapshot};\n\n/**\n * How many consecutive drift corrections may fail before the group stops\n * re-joining a follower and reports instead. Each correction restarts the\n * follower audibly, so a mismatch the corrections cannot fix must not\n * stutter forever.\n */\nconst MAX_CONSECUTIVE_DRIFT_JOINS = 3;\n\n/**\n * Relative slope error before {@link MirrorClockMaster} re-learns a\n * clockless transport's rate. Loose enough to ignore the quantization noise\n * of a transport whose position updates on a frame boundary, tight enough\n * that a refused or clamped rate is caught on the first reconcile that has\n * two samples.\n */\nconst MIRROR_RATE_TOLERANCE = 0.02;\n\ninterface FollowerRecord {\n transport: SyncFollowerTransport;\n offset: number;\n scale: number;\n loop: SyncLoopRegion | null;\n /** Reference time a scheduled join is armed for; drift holds off until then. */\n joinAt: number;\n /**\n * Last rate handed to this follower. Only consulted for followers without\n * a clock to read back; `undefined` until the first application, so a\n * follower constructed at its own rate is corrected rather than assumed.\n */\n lastRate?: number;\n /** Consecutive corrections that did not bring this follower into tolerance. */\n consecutiveDriftJoins: number;\n /** Set once corrections are proven not to converge; cleared by any command. */\n driftJoinsSuppressed: boolean;\n}\n\n/**\n * Drives one master transport and N schedulable followers as a single\n * transport. Positions are on the MASTER's axis; each follower runs\n * `offsetSeconds` ahead of the master's zero. The reference clock is\n * injected (`now`), so the group itself is Web-Audio-free and testable\n * against any monotonic time source.\n */\nexport class TransportGroup {\n #master: SyncMasterTransport;\n readonly #followers: FollowerRecord[] = [];\n readonly #now: () => number;\n #leadIn: number;\n #driftTolerance: number;\n #driftIntervalMs: number;\n #ticker: TickSource | null = null;\n #tickOptions: TickSourceOptions;\n #ticksPerDriftCheck: number;\n #tickCount = 0;\n #loop: SyncLoopRegion | null = null;\n #wrapping = false;\n #generation = 0;\n #revision = 0;\n readonly #pendingCommands = new Set<number>();\n readonly #observers = new Set<(event: TransportEvent) => void>();\n #lastSnapshot?: TransportSnapshot;\n #pendingTransitions = 0;\n /** Serializes transport commands so late async settlements cannot reorder state. */\n #commandActive = false;\n #queuedCommands: Array<() => void> = [];\n #intent: 'playing' | 'paused' | 'stopped' | 'disposed' = 'paused';\n #disposed = false;\n readonly #onOperationError: ((operation: string, error: unknown) => void) | undefined;\n\n constructor(\n master: SyncMasterTransport,\n now: () => number,\n options: TransportGroupOptions = {},\n ) {\n this.#master = master;\n this.#now = now;\n this.#leadIn = options.leadInSeconds ?? 0.06;\n this.#driftTolerance = options.driftToleranceSeconds ?? 0.03;\n this.#driftIntervalMs = options.driftCheckIntervalMs ?? 250;\n this.#onOperationError = options.onOperationError;\n this.#tickOptions = {intervalMs: 25, ...options.tick};\n assertFiniteNonNegative('leadInSeconds', this.#leadIn);\n assertFiniteNonNegative('driftToleranceSeconds', this.#driftTolerance);\n assertFiniteNonNegative('driftCheckIntervalMs', this.#driftIntervalMs);\n const tickInterval = this.#tickOptions.intervalMs ?? 25;\n if (!Number.isSafeInteger(tickInterval) || tickInterval < 1 || tickInterval > MAX_TIMER_DELAY_MS) {\n throw new RangeError(\n `tick.intervalMs must be a positive safe integer no greater than ${MAX_TIMER_DELAY_MS}.`,\n );\n }\n this.#ticksPerDriftCheck = Math.max(1, Math.round(this.#driftIntervalMs / (this.#tickOptions.intervalMs ?? 25)));\n if (options.loop) {\n assertValidLoop(options.loop);\n this.#loop = {...options.loop};\n }\n }\n\n /** The group timeline: a read-through to the master's own clock. */\n get clock(): TransportClockReader {\n return this.#master.clock;\n }\n\n /** Current position on the master axis. */\n get position(): number {\n return this.#master.position;\n }\n\n /** Read one coherent state on the master's stable position axis. */\n get snapshot(): TransportSnapshot {\n if (this.#disposed && this.#lastSnapshot) {\n return Object.freeze({...this.#lastSnapshot, revision: this.#revision, pending: false, disposed: true});\n }\n const referenceTime = this.#now();\n const clock = this.clock;\n const loop = this.loop;\n const snapshot: TransportSnapshot = Object.freeze({\n revision: this.#revision,\n referenceTime,\n position: clock.positionAt(referenceTime),\n rate: clock.rate,\n paused: clock.paused,\n holding: clock.holding && clock.state.originTime > referenceTime,\n loop: loop ? Object.freeze(loop) : null,\n pending: this.#pendingCommands.size > 0 || this.#pendingTransitions > 0,\n disposed: this.#disposed,\n });\n this.#lastSnapshot = snapshot;\n return snapshot;\n }\n\n /** Register before synchronously delivering the initial snapshot. Observer\n * failures are contained. Unsubscribe never stops borrowed playback. */\n subscribe(listener: (event: TransportEvent) => void): () => void {\n this.#assertActive();\n this.#observers.add(listener);\n try { listener({type: 'snapshot', snapshot: this.snapshot}); } catch {\n // A failed initial delivery must not leave an orphan subscription.\n this.#observers.delete(listener);\n }\n return () => { this.#observers.delete(listener); };\n }\n\n /** Submit a command and await its actual participant settlement. Failures\n * reject and emit an error; superseded work cannot claim a committed result.\n * Pause/stop take effect synchronously and await any late-start reconciliation.\n * Call this authority exclusively while coordinating a session. */\n dispatch(command: TransportCommand): Promise<TransportCommit> {\n return this.#dispatch(command, true);\n }\n\n #dispatch(input: TransportCommand, strict: boolean): Promise<TransportCommit> {\n this.#assertActive();\n validateCommand(input);\n const command = Object.freeze(input.type === 'loop'\n ? {...input, loop: input.loop ? Object.freeze({...input.loop}) : null}\n : {...input});\n const revision = ++this.#revision;\n this.#pendingCommands.add(revision);\n this.#publish({type: 'invalidate', revision, command, snapshot: this.snapshot});\n let operation: Promise<void> | void = undefined;\n try {\n // An observer may synchronously replace this command or dispose us.\n if (revision === this.#revision && !this.#disposed) {\n switch (command.type) {\n case 'play': operation = this.#play(strict); break;\n case 'pause': operation = this.#pause(); break;\n case 'stop': operation = this.#stop(); break;\n case 'seek': operation = this.#seek(command.position, strict); break;\n case 'rate': operation = this.#setRate(command.rate, strict, revision); break;\n case 'loop': operation = this.#setLoop(command.loop); break;\n }\n }\n } catch (error) {\n operation = Promise.reject(error);\n }\n return Promise.resolve(operation).then(() => {\n this.#pendingCommands.delete(revision);\n const snapshot = this.snapshot;\n const commit: TransportCommit = Object.freeze({\n revision, command,\n status: revision === this.#revision && !this.#disposed ? 'committed' : 'superseded',\n snapshot,\n });\n this.#publish({type: 'commit', commit, snapshot});\n return commit;\n }, (error: unknown) => {\n if (strict && revision === this.#revision && !this.#disposed) this.#rollbackFailedPlay();\n this.#pendingCommands.delete(revision);\n this.#publish({type: 'error', revision, command, error, snapshot: this.snapshot});\n throw error;\n });\n }\n\n #publish(event: TransportEvent): void {\n for (const listener of [...this.#observers]) {\n if (!this.#observers.has(listener)) continue;\n try { listener(event); } catch { /* Observers cannot interrupt transport cleanup. */ }\n // A reentrant command publishes its newer state first; do not then\n // deliver this stale snapshot to the remaining observers.\n if (event.snapshot.revision !== this.#revision) break;\n }\n }\n\n /**\n * Register a follower. While the group is playing, the follower joins the\n * running timeline on the next scheduled join.\n */\n addFollower(transport: SyncFollowerTransport, options: FollowerOptions = {}): void {\n this.#assertActive();\n const offset = options.offsetSeconds ?? 0;\n assertFiniteNonNegative('offsetSeconds', offset);\n const scale = options.positionScale ?? 1;\n if (!Number.isFinite(scale) || scale <= 0) throw new RangeError('positionScale must be finite and > 0.');\n if (scale !== 1 && !transport.setRate) throw new Error('A scaled follower must support setRate.');\n if (options.loop) assertValidLoop(options.loop);\n const record: FollowerRecord = {\n transport,\n offset,\n scale,\n loop: options.loop ? {...options.loop} : null,\n joinAt: 0,\n consecutiveDriftJoins: 0,\n driftJoinsSuppressed: false,\n };\n this.#followers.push(record);\n if (!this.clock.paused) {\n this.#observeReconciliation('follower join', () => this.#queueJoin(this.#generation, 'follower join', [record]));\n }\n }\n\n /**\n * Remove a follower from the group (the transport itself is left as-is,\n * still playing if it was; the caller owns its lifecycle from here).\n * Returns false when the transport was not a member.\n */\n removeFollower(transport: SyncFollowerTransport): boolean {\n const index = this.#followers.findIndex((record) => record.transport === transport);\n if (index < 0) return false;\n this.#followers.splice(index, 1);\n return true;\n }\n\n /** Number of registered followers. */\n get followerCount(): number {\n return this.#followers.length;\n }\n\n /**\n * Set (or clear) a loop region on the master axis, live. The wrap runs\n * through {@link seek}, so it inherits the shared re-entry origin; the\n * boundary is detected by a worker-backed tick watcher, so the wrap\n * instant may trail the boundary by the watcher/preparation delay and lead-in.\n * Browser throttling means this is not a bounded timing guarantee.\n */\n setLoop(loop: SyncLoopRegion | null): void {\n this.#assertActive();\n if (loop) assertValidLoop(loop);\n void this.#dispatch({type: 'loop', loop}, false).catch((error: unknown) => this.#reportOperationError('loop', error));\n }\n\n #setLoop(loop: SyncLoopRegion | null): void {\n this.#assertActive();\n if (loop) assertValidLoop(loop);\n this.#loop = loop ? {...loop} : null;\n if (this.clock.paused) {\n if (!this.#needsMonitor()) this.#stopDriftMonitor();\n } else if (this.#needsMonitor()) {\n this.#startDriftMonitor();\n } else {\n this.#stopDriftMonitor();\n }\n }\n\n get loop(): SyncLoopRegion | null {\n return this.#loop ? {...this.#loop} : null;\n }\n\n /**\n * Start master and followers on one shared origin. The group proposes\n * `now + leadInSeconds` to the master; one that supports scheduled starts\n * arms there and every follower joins at that very instant. A master that\n * ignores the proposal starts immediately and followers join a lead-in\n * later, offset-matched to its anchor.\n */\n async play(): Promise<void> {\n await this.#dispatch({type: 'play'}, false);\n }\n\n async #play(strict: boolean): Promise<void> {\n this.#assertActive();\n const generation = ++this.#generation;\n this.#pendingTransitions += 1;\n this.#intent = 'playing';\n this.#resetDriftConvergence();\n return this.#enqueueCommand(async () => {\n try {\n if (!this.#isCurrent(generation)) return;\n await this.#master.play(this.#now() + this.#leadIn);\n if (!this.#isCurrent(generation)) {\n this.#reapplySynchronousIntent();\n return;\n }\n if (strict && this.clock.paused) throw new Error('Master transport did not start.');\n await this.#joinFollowers(generation, this.#followers, strict);\n if (this.#isCurrent(generation)) this.#startDriftMonitor();\n } catch (error) {\n if (this.#isCurrent(generation)) this.#rollbackFailedPlay();\n throw error;\n } finally {\n this.#pendingTransitions -= 1;\n }\n });\n }\n\n pause(): void {\n if (this.#disposed) return;\n void this.#dispatch({type: 'pause'}, false).catch((error: unknown) => this.#reportOperationError('pause', error));\n }\n\n #pause(): Promise<void> | void {\n if (this.#disposed) return;\n const hadPendingTransition = this.#pendingTransitions > 0;\n ++this.#generation;\n this.#intent = 'paused';\n this.#resetDriftConvergence();\n this.#stopDriftMonitor();\n this.#applyPause();\n if (hadPendingTransition) {\n return this.#enqueueCommand(() => {\n if (!this.#disposed) this.#applyPause();\n });\n }\n }\n\n stop(): void {\n if (this.#disposed) return;\n void this.#dispatch({type: 'stop'}, false).catch((error: unknown) => this.#reportOperationError('stop', error));\n }\n\n #stop(): Promise<void> | void {\n if (this.#disposed) return;\n const hadPendingTransition = this.#pendingTransitions > 0;\n ++this.#generation;\n this.#intent = 'stopped';\n this.#resetDriftConvergence();\n this.#stopDriftMonitor();\n this.#applyStop();\n if (hadPendingTransition) {\n return this.#enqueueCommand(() => {\n if (!this.#disposed) this.#applyStop();\n });\n }\n }\n\n /**\n * Seek master and followers to a master-axis position. While playing, the\n * group proposes a shared re-entry origin exactly as {@link play} does\n * and re-joins the followers there, so all sides come back in together.\n * Loop wraps run through this path and inherit the same shared origin.\n */\n async seek(position: number): Promise<void> {\n await this.#dispatch({type: 'seek', position}, false);\n }\n\n async #seek(position: number, strict: boolean): Promise<void> {\n this.#assertActive();\n assertFiniteNonNegative('position', position);\n this.#pendingTransitions += 1;\n this.#resetDriftConvergence();\n return this.#enqueueCommand(async () => {\n try {\n if (this.#disposed) return;\n const generation = this.#generation;\n const wasRunning = !this.clock.paused;\n // Propose a shared re-entry origin only for a mid-playback seek: a\n // seek while paused must not start playback.\n await this.#master.seekPosition(\n position,\n wasRunning ? this.#now() + this.#leadIn : undefined,\n );\n const settled = this.#readSettledMasterPosition();\n if (!this.#isCurrent(generation)) {\n this.#reconcileStaleSeek(settled);\n this.#reapplySynchronousIntent();\n return;\n }\n if (this.clock.paused) {\n // A master that was running but comes back paused failed to\n // resume (seekPosition resolves even then) — mirror the stop\n // instead of seeking still-running followers out from under it.\n if (wasRunning && this.#intent === 'playing') {\n this.#settleFailedResume();\n if (strict) throw new Error('Master transport stayed paused after seek.');\n this.#reconcileStaleSeek(settled);\n return;\n }\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n record.transport.seek(this.#localPosition(record, settled));\n }\n } else {\n await this.#joinFollowers(generation, this.#followers, strict);\n }\n } finally {\n this.#pendingTransitions -= 1;\n }\n });\n }\n\n /**\n * Set the playback rate on the master and every follower. Followers\n * re-join immediately on the shared clock. NOTE: the group does not clamp\n * the rate beyond finite-and-positive — a domain wrapper owns any shared\n * range its transports require.\n */\n setRate(rate: number): void {\n this.#assertActive();\n validateCommand({type: 'rate', rate});\n void this.#dispatch({type: 'rate', rate}, false).catch((error: unknown) => this.#reportOperationError('rate', error));\n }\n\n #setRate(rate: number, strict: boolean, revision: number, queued = false): Promise<void> | void {\n if (strict && !queued) {\n this.#pendingTransitions += 1;\n return this.#enqueueCommand(async () => {\n try {\n if (revision !== this.#revision || this.#disposed) return;\n await this.#setRate(rate, strict, revision, true);\n } finally {\n this.#pendingTransitions -= 1;\n }\n });\n }\n this.#assertActive();\n if (!Number.isFinite(rate) || rate <= 0) {\n throw new RangeError(`rate must be finite and > 0, got ${rate}.`);\n }\n const generation = this.#generation;\n this.#resetDriftConvergence();\n try {\n this.#master.setRate?.(rate);\n } catch (error) {\n if (strict) throw error;\n this.#reportOperationError('master rate match', error);\n }\n if (revision !== this.#revision || this.#disposed) return;\n if (strict && this.clock.rate !== rate) throw new Error('Master transport did not accept the requested rate.');\n for (const record of [...this.#followers]) {\n if (revision !== this.#revision || this.#disposed) return;\n if (!this.#followers.includes(record)) continue;\n this.#applyFollowerRate(record, rate, strict);\n }\n if (revision !== this.#revision || this.#disposed) return;\n if (!this.clock.paused) {\n return queued\n ? this.#joinFollowers(generation, this.#followers, strict)\n : this.#queueJoin(generation, 'rate re-join', this.#followers, strict);\n }\n }\n\n dispose(): void {\n if (this.#disposed) return;\n this.#lastSnapshot = this.snapshot;\n this.#disposed = true;\n ++this.#revision;\n ++this.#generation;\n this.#intent = 'disposed';\n const ticker = this.#ticker;\n this.#ticker = null;\n const errors: unknown[] = [];\n const releases: Array<() => void> = [() => ticker?.dispose()];\n for (const record of this.#followers) {\n releases.push(() => record.transport.dispose?.());\n }\n releases.push(() => this.#master.dispose?.());\n for (const release of releases) {\n try {\n release();\n } catch (error) {\n errors.push(error);\n }\n }\n this.#publish({type: 'snapshot', snapshot: this.snapshot});\n this.#observers.clear();\n if (errors.length > 0) throw errors[0];\n }\n\n /**\n * One drift check: every follower is measured against the master clock,\n * and each one out of tolerance is re-joined on the shared clock (the\n * same scheduled-start dance as {@link play}). Returns the largest\n * absolute drift observed (0 with no followers or while holding off).\n */\n checkDrift(): number {\n this.#assertActive();\n if (this.#pendingTransitions > 0) return 0;\n const now = this.#now();\n if (this.#master.reconcile) {\n const verdict = this.#master.reconcile(now);\n if (verdict === 'stalled' && this.#intent === 'playing') {\n this.#handleMasterStopped();\n return 0;\n }\n }\n let worst = 0;\n const stragglers: FollowerRecord[] = [];\n for (const record of this.#followers) {\n // Hold off while a scheduled join is still pending — the follower's\n // position deliberately parks at its offset through the pre-roll.\n if (now < record.joinAt) continue;\n const expected = this.#localPosition(record, this.clock.positionAt(now));\n // Prefer the follower's own clock over sampling: exact read at `now`,\n // and `paused` is authoritative where the optional `running` getter\n // may be absent entirely.\n const followerClock = record.transport.clock;\n // A follower's own pre-roll may extend past the common join instant.\n // Its parked position is not drift until that actual start arrives.\n if (followerClock?.holding && now < followerClock.state.originTime) continue;\n const followerPosition = followerClock\n ? followerClock.positionAt(now)\n : record.transport.position;\n const followerRunning = followerClock\n ? !followerClock.paused\n : record.transport.running !== false;\n let localDrift = this.#wrapLocal(record, followerPosition) - expected;\n if (record.loop && followerPosition >= record.loop.startSeconds && expected >= record.loop.startSeconds) {\n const period = record.loop.endSeconds - record.loop.startSeconds;\n localDrift = ((localDrift + period / 2) % period + period) % period - period / 2;\n }\n const drift = localDrift / record.scale;\n // Drift is REPORTED for every member, running or not — a follower whose\n // clock reports paused (ended, torn down) is a real divergence a caller\n // may want to see. It is simply never corrected into a re-join thrash.\n if (Math.abs(drift) > Math.abs(worst)) worst = drift;\n if (!followerRunning) continue;\n // A slope mismatch counts as divergence in its own right: re-joining on\n // position alone re-diverges immediately, which is a re-join every\n // check forever rather than convergence. Both axes carry the same rate\n // scalar after applying the explicit local-axis scale, so an\n // inequality here is real divergence, not a unit difference.\n const rateMismatch = followerClock !== undefined && followerClock.rate !== this.clock.rate * record.scale;\n if (Math.abs(drift) <= this.#driftTolerance && !rateMismatch) {\n // In tolerance on both axes: whatever the last correction did, it stuck.\n record.consecutiveDriftJoins = 0;\n record.driftJoinsSuppressed = false;\n continue;\n }\n if (record.driftJoinsSuppressed) continue;\n record.consecutiveDriftJoins += 1;\n if (record.consecutiveDriftJoins > MAX_CONSECUTIVE_DRIFT_JOINS) {\n // Every correction so far re-anchored this follower and the drift\n // came straight back, so it cannot hold the master's slope (an\n // unclampable master rate, a follower without setRate). Re-joining\n // forever would just restart it once per check with no prospect of\n // converging; stop and say so instead. A check that lands back in\n // tolerance, or any explicit command, re-arms corrections.\n record.driftJoinsSuppressed = true;\n this.#reportOperationError(\n 'drift re-join',\n new Error(\n `TransportGroup: ${record.consecutiveDriftJoins} consecutive drift corrections failed to ` +\n `converge (drift ${drift.toFixed(4)}s, master rate ${this.clock.rate}). The follower ` +\n 'cannot follow the master rate; automatic re-joins are paused until they agree again.',\n ),\n );\n continue;\n }\n stragglers.push(record);\n }\n if (stragglers.length > 0) {\n this.#observeReconciliation('drift re-join', () => this.#queueJoin(this.#generation, 'drift re-join', stragglers));\n }\n return worst;\n }\n\n #wrapLocal(record: FollowerRecord, position: number): number {\n const loop = record.loop;\n if (!loop || position < loop.endSeconds) return position;\n return loop.startSeconds + (position - loop.startSeconds) % (loop.endSeconds - loop.startSeconds);\n }\n\n #localPosition(record: FollowerRecord, masterPosition: number): number {\n return this.#wrapLocal(record, record.offset + masterPosition * record.scale);\n }\n\n /**\n * Schedule followers to (re)join the running master: one reference-clock\n * read, the seek target exact-by-construction for `when` — the same\n * affine map the master plays by. A holding (scheduled-start) master\n * clock whose origin is still in the future is taken as-is, even inside\n * the lead-in horizon: the master has not made a sound yet, so joining\n * exactly at the armed origin is what makes the shared start gapless.\n */\n async #joinFollowers(generation: number, targets: readonly FollowerRecord[], strict = false): Promise<void> {\n if (!this.#isCurrent(generation)) return;\n // External callbacks may remove members while this operation is visiting\n // them. Preserve the visit order without skipping the next live member.\n const members = [...targets];\n for (const record of members) {\n if (!this.#isCurrent(generation)) return;\n if (this.#followers.includes(record)) record.transport.pause();\n }\n const clock = this.clock;\n if (clock.paused) return;\n const now = this.#now();\n const armedOrigin = clock.holding ? clock.state.originTime : -Infinity;\n const when = armedOrigin > now ? armedOrigin : now + this.#leadIn;\n const position = clock.positionAt(when);\n const starts: Array<Promise<void> | void> = [];\n for (const record of members) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n try {\n record.joinAt = when;\n // Align the local slope before seeking the mapped future phase.\n this.#applyFollowerRate(record, clock.rate, strict);\n // Rate callbacks can detach a follower or synchronously replace\n // the command. Its old join must not mutate either lifetime.\n if (!this.#isCurrent(generation) || !this.#followers.includes(record)) continue;\n record.transport.seek(this.#localPosition(record, position));\n if (!this.#isCurrent(generation) || !this.#followers.includes(record)) continue;\n starts.push(record.transport.play(when));\n } catch (error) {\n starts.push(Promise.reject(error));\n break;\n }\n }\n // A rejected participant must not leave a still-pending sibling able to\n // restart after failure cleanup has already been reported as complete.\n const settled = await Promise.allSettled(starts);\n if (!this.#isCurrent(generation)) this.#reapplySynchronousIntent();\n const failure = settled.find((result) => result.status === 'rejected');\n if (failure?.status === 'rejected') throw failure.reason;\n if (strict && this.#isCurrent(generation)) {\n for (const record of members) {\n if (!this.#followers.includes(record)) continue;\n const followerClock = record.transport.clock;\n const running = followerClock ? !followerClock.paused : record.transport.running;\n if (running === false) throw new Error('Follower transport did not start.');\n }\n }\n }\n\n /**\n * Hand a follower a rate, skipping the call when it already runs at it.\n * A follower with a clock is asked directly; for one without, the last\n * applied value is remembered. Best-effort by contract: `setRate` is\n * optional on {@link SyncFollowerTransport}, and a transport that has one\n * may still clamp or refuse it — the convergence check below is what\n * surfaces a mismatch neither side can resolve.\n */\n #applyFollowerRate(record: FollowerRecord, rate: number, strict = false): void {\n rate *= record.scale;\n if (!record.transport.setRate) {\n if (strict && (record.transport.clock?.rate ?? 1) !== rate) {\n throw new Error('Follower transport cannot accept the requested rate.');\n }\n return;\n }\n if (!Number.isFinite(rate) || rate <= 0) return;\n const current = record.transport.clock?.rate ?? record.lastRate;\n if (current === rate) return;\n try {\n record.transport.setRate(rate);\n if (strict && record.transport.clock && record.transport.clock.rate !== rate) {\n throw new Error('Follower transport did not accept the requested rate.');\n }\n record.lastRate = rate;\n } catch (error) {\n if (strict) throw error;\n this.#reportOperationError('follower rate match', error);\n }\n }\n\n /** Re-arm drift corrections; any explicit command counts as a fresh start. */\n #resetDriftConvergence(): void {\n for (const record of this.#followers) {\n record.consecutiveDriftJoins = 0;\n record.driftJoinsSuppressed = false;\n }\n }\n\n /**\n * One watcher drives every concern off a kernel tick source (worker-backed\n * where the platform allows, so background-tab throttling does not starve\n * it): master-stop reconciliation and the loop boundary every tick, drift\n * every `driftCheckIntervalMs` worth of ticks.\n */\n #onTick(): void {\n if (this.#disposed) return;\n const revision = this.#revision;\n try {\n this.#reconcileMasterStop();\n this.#checkLoop();\n this.#tickCount += 1;\n if (this.#driftIntervalMs > 0 && this.#tickCount % this.#ticksPerDriftCheck === 0) {\n this.checkDrift();\n }\n } catch (error) {\n // There is no awaiting caller for a timer callback. Report its failure\n // after settling the current session, without pausing a newer command\n // that an adapter may have synchronously dispatched before throwing.\n if (this.#disposed) return;\n if (revision === this.#revision) this.#rollbackFailedPlay();\n this.#reportOperationError('transport monitor', error);\n }\n }\n\n /**\n * The master can stop on its own (a score player finishing at its natural\n * end pauses and rewinds its clock, racing the group's boundary watcher\n * tick-for-tick). A self-stopped clock while the group means to play\n * either wraps (loop active — the loop's continuation intent outranks the\n * master's own finish) or settles into the paused state.\n */\n #reconcileMasterStop(): void {\n if (this.#intent !== 'playing' || this.#wrapping || this.#pendingTransitions > 0) return;\n if (!this.clock.paused) return;\n this.#handleMasterStopped();\n }\n\n #handleMasterStopped(): void {\n if (this.#loop && !this.#wrapping) {\n this.#wrap(this.#loop.startSeconds);\n } else {\n this.#settleMasterStopped();\n }\n }\n\n #checkLoop(): void {\n const loop = this.#loop;\n if (!loop || this.clock.paused || this.#wrapping || this.#pendingTransitions > 0) return;\n if (this.clock.positionAt(this.#now()) >= loop.endSeconds) {\n this.#wrap(loop.startSeconds);\n }\n }\n\n /**\n * Wrap to the loop start. A running master re-joins inside seek(); a\n * master that stopped on its own (natural finish at or past the loop end)\n * is restarted afterwards. A failed wrap settles into the paused state\n * instead of retrying every tick, and is reported as 'loop wrap'.\n */\n #wrap(startSeconds: number): void {\n this.#wrapping = true;\n void this.seek(startSeconds)\n .then(() => {\n if (!this.#disposed && this.#intent === 'playing' && this.clock.paused) {\n return this.play();\n }\n })\n .catch((error: unknown) => {\n this.#reportOperationError('loop wrap', error);\n if (!this.#disposed && this.#intent === 'playing') this.#settleMasterStopped();\n })\n .finally(() => {\n this.#wrapping = false;\n });\n }\n\n #startDriftMonitor(): void {\n if (!this.#needsMonitor()) {\n this.#stopDriftMonitor();\n return;\n }\n this.#ticker ??= createTickSource(this.#tickOptions);\n this.#ticker.start(() => this.#onTick());\n }\n\n #stopDriftMonitor(): void {\n this.#ticker?.stop();\n this.#tickCount = 0;\n }\n\n #needsMonitor(): boolean {\n return this.#loop !== null || this.#driftIntervalMs > 0;\n }\n\n #isCurrent(generation: number): boolean {\n return !this.#disposed && generation === this.#generation;\n }\n\n #reportOperationError(operation: string, error: unknown): void {\n this.#publish({type: 'operation-error', operation, error, snapshot: this.snapshot});\n try {\n this.#onOperationError?.(operation, error);\n } catch {\n // The observer must never disturb transport-state handling.\n }\n }\n\n /**\n * The master stopped although the group meant to be playing (a swallowed\n * restart failure, or the master ending on its own): pause the followers\n * and settle, exactly as an explicit pause() would.\n */\n #settleMasterStopped(): void {\n this.pause();\n }\n\n #settleFailedResume(): void {\n this.#settleMasterStopped();\n this.#reportOperationError(\n 'resume after seek',\n new Error('TransportGroup: the master transport stayed paused after a mid-playback seek.'),\n );\n }\n\n #assertActive(): void {\n if (this.#disposed) throw new Error('TransportGroup has been disposed.');\n }\n\n #observeReconciliation(operation: string, apply: () => Promise<void>): void {\n const revision = ++this.#revision;\n this.#pendingCommands.add(revision);\n this.#publish({type: 'reconcile', operation, phase: 'invalidate', snapshot: this.snapshot});\n const pending = revision === this.#revision && !this.#disposed ? apply() : Promise.resolve();\n void pending.catch((error: unknown) => this.#reportOperationError(operation, error)).finally(() => {\n this.#pendingCommands.delete(revision);\n this.#publish({type: 'reconcile', operation, phase: 'settled', snapshot: this.snapshot});\n });\n }\n\n /**\n * Queue an independent re-join as a visible transition. Public pause/stop\n * calls can then schedule one final reconciliation behind it, preventing\n * a late follower play() settlement from reviving playback.\n */\n #queueJoin(generation: number, operation: string, targets: readonly FollowerRecord[], strict = false): Promise<void> {\n const revision = this.#revision;\n this.#pendingTransitions += 1;\n return this.#enqueueCommand(async () => {\n try {\n await this.#joinFollowers(generation, targets, strict);\n } finally {\n this.#pendingTransitions -= 1;\n }\n }).catch((error: unknown) => {\n // The FIFO may already have begun a newer seek/rate command before\n // this rejection handler runs. Old failure must not pause that owner.\n if (this.#isCurrent(generation) && revision === this.#revision) this.#rollbackFailedPlay();\n if (!this.#disposed) this.#reportOperationError(operation, error);\n if (strict) throw error;\n });\n }\n\n /**\n * Run the first idle command immediately so master.play() remains inside\n * the browser's transient user-activation stack. Only commands that\n * actually have an async predecessor wait in the FIFO.\n */\n #enqueueCommand<Result>(operation: () => Result | PromiseLike<Result>): Promise<Result> {\n return new Promise<Result>((resolve, reject) => {\n const run = () => {\n let result: Result | PromiseLike<Result>;\n try {\n result = operation();\n } catch (error) {\n reject(error);\n this.#finishCommand();\n return;\n }\n Promise.resolve(result).then(\n (value) => {\n resolve(value);\n this.#finishCommand();\n },\n (error: unknown) => {\n reject(error);\n this.#finishCommand();\n },\n );\n };\n\n if (this.#commandActive) {\n this.#queuedCommands.push(run);\n } else {\n this.#commandActive = true;\n run();\n }\n });\n }\n\n #finishCommand(): void {\n const next = this.#queuedCommands.shift();\n if (next) {\n next();\n } else {\n this.#commandActive = false;\n }\n }\n\n /** Read the master's actual post-seek position (it may clamp). */\n #readSettledMasterPosition(): number {\n const position = this.#master.position;\n if (!Number.isFinite(position) || position < 0) {\n throw new RangeError('Master transport returned an invalid position after seek.');\n }\n return position;\n }\n\n /** Preserve the completed seek position when pause superseded it. */\n #reconcileStaleSeek(position: number): void {\n if (this.#disposed || this.#intent !== 'paused') return;\n const generation = this.#generation;\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n record.transport.seek(this.#localPosition(record, position));\n }\n }\n\n /** Re-apply pause/stop after an older async master command settles late. */\n #reapplySynchronousIntent(): void {\n if (this.#disposed) return;\n if (this.#intent === 'paused') {\n this.#applyPause();\n } else if (this.#intent === 'stopped') {\n this.#applyStop();\n }\n }\n\n #applyPause(): void {\n const generation = this.#generation;\n const errors: unknown[] = [];\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n try { record.transport.pause(); } catch (error) { errors.push(error); }\n }\n if (this.#isCurrent(generation)) {\n try { this.#master.pause(); } catch (error) { errors.push(error); }\n }\n if (errors.length > 0) throw errors[0];\n }\n\n #applyStop(): void {\n const generation = this.#generation;\n const errors: unknown[] = [];\n for (const record of [...this.#followers]) {\n if (!this.#isCurrent(generation)) break;\n if (!this.#followers.includes(record)) continue;\n try { record.transport.stop(); } catch (error) { errors.push(error); }\n }\n if (this.#isCurrent(generation)) {\n try { this.#master.stop(); } catch (error) { errors.push(error); }\n }\n if (errors.length > 0) throw errors[0];\n }\n\n #rollbackFailedPlay(): void {\n ++this.#generation;\n this.#intent = 'paused';\n this.#stopDriftMonitor();\n try {\n this.#applyPause();\n } catch {\n // Preserve the original failure while respecting callback re-entry.\n }\n }\n}\n\n/**\n * Minimal command surface a clockless transport must offer so\n * {@link MirrorClockMaster} can adapt it into the master role.\n */\nexport interface ClocklessMasterTransport {\n play(when?: number): Promise<void> | void;\n pause(): void;\n stop(): void;\n seekPosition(position: number, when?: number): void | Promise<void>;\n setRate?(rate: number): void;\n readonly position: number;\n dispose?(): void;\n}\n\n/**\n * Adapts a transport WITHOUT a readable clock into the required-clock\n * master role by dead-reckoning a mirror TransportClock across the command\n * surface, and reconciling the reckoning against the transport's actual\n * position on every drift check:\n *\n * - two identical position samples while the mirror advanced past the\n * tolerance mean the transport stopped on its own (ended, clamped at its\n * duration, paused out of band) — the adapter pauses the mirror and\n * reports 'stalled', which the group treats as a master stop;\n * - a moving transport that diverged from the extrapolation (refused or\n * clamped rate, tempo automation) re-anchors the mirror so drift is\n * measured against the transport, not the reckoning.\n *\n * This is the ONE home of the sampled fallback the score↔audio bridge used\n * to interleave through its clocked path.\n */\nexport class MirrorClockMaster implements SyncMasterTransport {\n readonly #inner: ClocklessMasterTransport;\n readonly #mirror: TransportClock;\n readonly #now: () => number;\n #tolerance: number;\n #lastSample: {position: number; mirrorPosition: number; time: number} | null = null;\n\n constructor(inner: ClocklessMasterTransport, now: () => number, options: {reconcileToleranceSeconds?: number} = {}) {\n this.#inner = inner;\n this.#now = now;\n this.#tolerance = options.reconcileToleranceSeconds ?? 0.03;\n assertFiniteNonNegative('reconcileToleranceSeconds', this.#tolerance);\n this.#mirror = new TransportClock(now);\n }\n\n get clock(): TransportClockReader {\n return this.#mirror;\n }\n\n get position(): number {\n return this.#inner.position;\n }\n\n async play(when?: number): Promise<void> {\n await this.#inner.play(when);\n this.#lastSample = null;\n this.#mirror.start(this.#now(), this.#inner.position);\n }\n\n pause(): void {\n this.#inner.pause();\n this.#lastSample = null;\n this.#mirror.pause(this.#now());\n }\n\n stop(): void {\n this.#inner.stop();\n this.#lastSample = null;\n const now = this.#now();\n this.#mirror.pause(now);\n this.#mirror.seekTo(0, now);\n }\n\n async seekPosition(position: number, when?: number): Promise<void> {\n await this.#inner.seekPosition(position, when);\n this.#lastSample = null;\n this.#mirror.seekTo(this.#inner.position, this.#now());\n }\n\n setRate(rate: number): void {\n this.#inner.setRate?.(rate);\n this.#lastSample = null;\n this.#mirror.setRate(rate, this.#now());\n }\n\n reconcile(now: number): 'ok' | 'stalled' {\n const actual = this.#inner.position;\n if (!Number.isFinite(actual) || actual < 0) return 'ok';\n const mirrorPosition = this.#mirror.positionAt(now);\n const sample = this.#lastSample;\n this.#lastSample = {position: actual, mirrorPosition, time: now};\n if (\n sample !== null &&\n actual === sample.position &&\n mirrorPosition - sample.mirrorPosition > this.#tolerance &&\n !this.#mirror.paused\n ) {\n this.#lastSample = null;\n this.#mirror.pause(now);\n return 'stalled';\n }\n // Correct the reckoning's SLOPE, not only its intercept. A transport\n // that clamped or refused the shared rate advances at a rate the mirror\n // does not know; re-anchoring the position alone leaves the mirror\n // drifting away again before the next check, which is what turns a rate\n // mismatch into an endless correction loop. The next join then hands the\n // followers the rate the transport actually runs at.\n if (sample !== null && !this.#mirror.paused) {\n const elapsed = now - sample.time;\n const advanced = actual - sample.position;\n if (elapsed > 0 && advanced > 0) {\n const measured = advanced / elapsed;\n const current = this.#mirror.rate;\n if (\n Number.isFinite(measured) &&\n measured > 0 &&\n Math.abs(measured - current) > MIRROR_RATE_TOLERANCE * current\n ) {\n this.#mirror.setRate(measured, now);\n }\n }\n }\n if (Math.abs(mirrorPosition - actual) > this.#tolerance) {\n this.#mirror.seekTo(actual, now);\n }\n return 'ok';\n }\n\n dispose(): void {\n this.#inner.dispose?.();\n }\n}\n\nfunction assertFiniteNonNegative(name: string, value: number): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new RangeError(`${name} must be finite and >= 0.`);\n }\n}\n\nfunction assertValidLoop(loop: SyncLoopRegion): void {\n if (\n !Number.isFinite(loop.startSeconds) || loop.startSeconds < 0 ||\n !Number.isFinite(loop.endSeconds) || !(loop.endSeconds > loop.startSeconds)\n ) {\n throw new RangeError('Loop bounds must be finite, non-negative, and endSeconds must be greater than startSeconds.');\n }\n}\n\n/** Validate before changing revision or touching participants. */\nfunction validateCommand(command: TransportCommand): void {\n switch (command.type) {\n case 'play': case 'pause': case 'stop': return;\n case 'seek': assertFiniteNonNegative('position', command.position); return;\n case 'rate':\n if (!Number.isFinite(command.rate) || command.rate <= 0) throw new RangeError('rate must be finite and > 0.');\n return;\n case 'loop': if (command.loop) assertValidLoop(command.loop); return;\n default: throw new TypeError('Unknown transport command.');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmMA,IAAM,8BAA8B;AASpC,IAAM,wBAAwB;AA5M9B;AAwOO,IAAM,iBAAN,MAAqB;AAAA,EA0B1B,YACE,QACA,KACA,UAAiC,CAAC,GAClC;AA9BG;AACL;AACA,uBAAS,YAA+B,CAAC;AACzC,uBAAS;AACT;AACA;AACA;AACA,gCAA6B;AAC7B;AACA;AACA,mCAAa;AACb,8BAA+B;AAC/B,kCAAY;AACZ,oCAAc;AACd,kCAAY;AACZ,uBAAS,kBAAmB,oBAAI,IAAY;AAC5C,uBAAS,YAAa,oBAAI,IAAqC;AAC/D;AACA,4CAAsB;AAEtB;AAAA,uCAAiB;AACjB,wCAAqC,CAAC;AACtC,gCAAyD;AACzD,kCAAY;AACZ,uBAAS;AAOP,uBAAK,SAAU;AACf,uBAAK,MAAO;AACZ,uBAAK,SAAU,QAAQ,iBAAiB;AACxC,uBAAK,iBAAkB,QAAQ,yBAAyB;AACxD,uBAAK,kBAAmB,QAAQ,wBAAwB;AACxD,uBAAK,mBAAoB,QAAQ;AACjC,uBAAK,cAAe,EAAC,YAAY,IAAI,GAAG,QAAQ,KAAI;AACpD,4BAAwB,iBAAiB,mBAAK,QAAO;AACrD,4BAAwB,yBAAyB,mBAAK,gBAAe;AACrE,4BAAwB,wBAAwB,mBAAK,iBAAgB;AACrE,UAAM,eAAe,mBAAK,cAAa,cAAc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AE,KAAK,aAAa,KAAK,eAC9D;AACA,UAAM,IAAI,WAAW,6FAA6F;AAAA,EACpH;AACF;AAGA,SAAS,gBAAgB,SAAiC;AACxD,UAAQ,QAAQ,MAAM;AAAA,IACpB,KAAK;AAAA,IAAQ,KAAK;AAAA,IAAS,KAAK;AAAQ;AAAA,IACxC,KAAK;AAAQ,8BAAwB,YAAY,QAAQ,QAAQ;AAAG;AAAA,IACpE,KAAK;AACH,UAAI,CAAC,OAAO,SAAS,QAAQ,IAAI,KAAK,QAAQ,QAAQ,EAAG,OAAM,IAAI,WAAW,8BAA8B;AAC5G;AAAA,IACF,KAAK;AAAQ,UAAI,QAAQ,KAAM,iBAAgB,QAAQ,IAAI;AAAG;AAAA,IAC9D;AAAS,YAAM,IAAI,UAAU,4BAA4B;AAAA,EAC3D;AACF;","names":["_now"]}
@@ -0,0 +1,25 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/player.ts
2
+ function isTimedPlayer(player) {
3
+ return typeof player.seconds === "number" && typeof player.duration === "number";
4
+ }
5
+ function isStatefulPlayer(player) {
6
+ return typeof player.playing === "boolean";
7
+ }
8
+ function isRateControlledPlayer(player) {
9
+ return typeof player.setRate === "function";
10
+ }
11
+ function isVolumeControlledPlayer(player) {
12
+ return typeof player.setVolume === "function";
13
+ }
14
+ function isDisposablePlayer(player) {
15
+ return typeof player.dispose === "function";
16
+ }
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+ exports.isTimedPlayer = isTimedPlayer; exports.isStatefulPlayer = isStatefulPlayer; exports.isRateControlledPlayer = isRateControlledPlayer; exports.isVolumeControlledPlayer = isVolumeControlledPlayer; exports.isDisposablePlayer = isDisposablePlayer;
25
+ //# sourceMappingURL=chunk-ZMU72HJS.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/chunk-ZMU72HJS.cjs","../src/player.ts"],"names":[],"mappings":"AAAA;ACkEO,SAAS,aAAA,CAAc,MAAA,EAA+C;AAC3E,EAAA,OAAO,OAAO,MAAA,CAAO,QAAA,IAAY,SAAA,GAAY,OAAO,MAAA,CAAO,SAAA,IAAa,QAAA;AAC1E;AAEO,SAAS,gBAAA,CAAiB,MAAA,EAAkD;AACjF,EAAA,OAAO,OAAO,MAAA,CAAO,QAAA,IAAY,SAAA;AACnC;AAEO,SAAS,sBAAA,CAAuB,MAAA,EAAwD;AAC7F,EAAA,OAAO,OAAO,MAAA,CAAO,QAAA,IAAY,UAAA;AACnC;AAEO,SAAS,wBAAA,CAAyB,MAAA,EAA0D;AACjG,EAAA,OAAO,OAAO,MAAA,CAAO,UAAA,IAAc,UAAA;AACrC;AAEO,SAAS,kBAAA,CAAmB,MAAA,EAAoD;AACrF,EAAA,OAAO,OAAO,MAAA,CAAO,QAAA,IAAY,UAAA;AACnC;ADpEA;AACA;AACE;AACA;AACA;AACA;AACA;AACF,0PAAC","file":"/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/chunk-ZMU72HJS.cjs","sourcesContent":[null,"// ============================================================================\n// Playback control contract shared by both families. AudioClipPlayer\n// satisfies it on the audio side; ScorePlayer and TonePlayer satisfy it\n// structurally on the score side. Each family pins its players against the\n// contract in its own src/play/headless/playerlike-contract.ts. For the pure\n// clock/anchor math a player uses internally, see ./transport.\n// ============================================================================\n\n/**\n * Structural playback control contract.\n *\n * Members use method shorthand syntax DELIBERATELY: method bivariance is what\n * lets a typed-emitter `on<K extends keyof E>(...)` satisfy the loose\n * `on(event: string, ...)` here. Do not convert to arrow-property signatures —\n * under strictFunctionTypes that rejects every typed-emitter implementer.\n */\nexport interface PlayerLike {\n play(): Promise<void> | void;\n pause(): void;\n stop(): void;\n seek(seconds: number): void;\n setRate?(rate: number): void;\n setVolume?(volume: number): void;\n readonly seconds?: number;\n readonly duration?: number;\n readonly playing?: boolean;\n on(event: string, listener: (data: unknown) => void): () => void;\n dispose?(): void;\n}\n\n// ----------------------------------------------------------------------------\n// Capability tiers. PlayerLike's optional members are deliberate: the base\n// contract is the lowest common denominator both families can always promise.\n// The interfaces below NAME each optional capability, and the guards are the\n// supported feature-testing protocol — a generic consumer narrows with a\n// guard once instead of poking optional members everywhere. Implementers\n// advertise a capability by making its members non-optional; consumers must\n// treat a failed guard as \"capability absent\", never as an error.\n// ----------------------------------------------------------------------------\n\n/** A player that reports timeline position and total duration in seconds. */\nexport interface TimedPlayerLike extends PlayerLike {\n readonly seconds: number;\n readonly duration: number;\n}\n\n/** A player whose playing state is readable synchronously. */\nexport interface StatefulPlayerLike extends PlayerLike {\n readonly playing: boolean;\n}\n\n/** A player with adjustable playback rate. */\nexport interface RateControlledPlayerLike extends PlayerLike {\n setRate(rate: number): void;\n}\n\n/** A player with adjustable output volume. */\nexport interface VolumeControlledPlayerLike extends PlayerLike {\n setVolume(volume: number): void;\n}\n\n/** A player owning resources that must be released when it is done. */\nexport interface DisposablePlayerLike extends PlayerLike {\n dispose(): void;\n}\n\nexport function isTimedPlayer(player: PlayerLike): player is TimedPlayerLike {\n return typeof player.seconds === 'number' && typeof player.duration === 'number';\n}\n\nexport function isStatefulPlayer(player: PlayerLike): player is StatefulPlayerLike {\n return typeof player.playing === 'boolean';\n}\n\nexport function isRateControlledPlayer(player: PlayerLike): player is RateControlledPlayerLike {\n return typeof player.setRate === 'function';\n}\n\nexport function isVolumeControlledPlayer(player: PlayerLike): player is VolumeControlledPlayerLike {\n return typeof player.setVolume === 'function';\n}\n\nexport function isDisposablePlayer(player: PlayerLike): player is DisposablePlayerLike {\n return typeof player.dispose === 'function';\n}\n"]}
@@ -0,0 +1,2 @@
1
+ "use strict";require('./chunk-BR63OD53.cjs');
2
+ //# sourceMappingURL=effect.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/effect.cjs"],"names":[],"mappings":"AAAA,6CAA6B","file":"/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/effect.cjs"}
@@ -0,0 +1,19 @@
1
+ /** A built effect sub-graph: signal enters `input`, leaves `output`. */
2
+ interface EffectNodes {
3
+ readonly input: AudioNode;
4
+ readonly output: AudioNode;
5
+ /** Live, adjustable parameters (e.g. `frequency`, `wet`) for real-time control. */
6
+ params?: Record<string, AudioParam>;
7
+ dispose?(): void;
8
+ }
9
+ /**
10
+ * The structural Effect contract. The single method `createAudioNodes` lets
11
+ * effects cross between the families by shape alone.
12
+ */
13
+ interface Effect {
14
+ /** Optional label — UIs can caption controls with it. */
15
+ label?: string;
16
+ createAudioNodes(context: BaseAudioContext): EffectNodes;
17
+ }
18
+
19
+ export type { Effect, EffectNodes };
@@ -0,0 +1,19 @@
1
+ /** A built effect sub-graph: signal enters `input`, leaves `output`. */
2
+ interface EffectNodes {
3
+ readonly input: AudioNode;
4
+ readonly output: AudioNode;
5
+ /** Live, adjustable parameters (e.g. `frequency`, `wet`) for real-time control. */
6
+ params?: Record<string, AudioParam>;
7
+ dispose?(): void;
8
+ }
9
+ /**
10
+ * The structural Effect contract. The single method `createAudioNodes` lets
11
+ * effects cross between the families by shape alone.
12
+ */
13
+ interface Effect {
14
+ /** Optional label — UIs can caption controls with it. */
15
+ label?: string;
16
+ createAudioNodes(context: BaseAudioContext): EffectNodes;
17
+ }
18
+
19
+ export type { Effect, EffectNodes };
package/dist/effect.js ADDED
@@ -0,0 +1,2 @@
1
+ import "./chunk-TEM2I2NN.js";
2
+ //# sourceMappingURL=effect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,24 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+ var _chunkVVZX7DQ6cjs = require('./chunk-VVZX7DQ6.cjs');
12
+ require('./chunk-7ZTZZ5PN.cjs');
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+ exports.HTMLElementBase = _chunkVVZX7DQ6cjs.HTMLElementBase; exports.WebMusicElement = _chunkVVZX7DQ6cjs.WebMusicElement; exports.boolAttr = _chunkVVZX7DQ6cjs.boolAttr; exports.cssSizeAttr = _chunkVVZX7DQ6cjs.cssSizeAttr; exports.defineOnce = _chunkVVZX7DQ6cjs.defineOnce; exports.numAttr = _chunkVVZX7DQ6cjs.numAttr; exports.observeElementTarget = _chunkVVZX7DQ6cjs.observeElementTarget; exports.upgradeProperties = _chunkVVZX7DQ6cjs.upgradeProperties; exports.upgradeProperty = _chunkVVZX7DQ6cjs.upgradeProperty;
24
+ //# sourceMappingURL=elements.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/elements.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,kgBAAC","file":"/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/elements.cjs"}
@@ -0,0 +1,76 @@
1
+ declare const HTMLElementBase: typeof HTMLElement;
2
+ /** Cleanup owned by one connected lifetime of a {@link WebMusicElement}. */
3
+ type ElementCleanup = () => void;
4
+ /**
5
+ * Minimal lifecycle base for WebMusic custom elements.
6
+ *
7
+ * It deliberately owns no Shadow DOM, UI profile, presenter, registration or
8
+ * domain state. Subclasses mount those concerns in {@link onMount}, and either
9
+ * return a cleanup or register several cleanups with {@link own}. Every
10
+ * connection gets a fresh cleanup scope, so disconnect/reconnect is safe.
11
+ */
12
+ declare abstract class WebMusicElement extends HTMLElementBase {
13
+ #private;
14
+ /** Browser lifecycle entry point. Prefer overriding {@link onMount}. */
15
+ connectedCallback(): void;
16
+ /** Browser lifecycle entry point. Prefer overriding {@link onUnmount}. */
17
+ disconnectedCallback(): void;
18
+ /** Mount UI and domain bindings for the current connected lifetime. */
19
+ protected onMount(): ElementCleanup | void;
20
+ /** Run subclass-specific unmount work before owned cleanups are released. */
21
+ protected onUnmount(): void;
22
+ /**
23
+ * Own a cleanup for the current connected lifetime.
24
+ *
25
+ * Cleanups run once in reverse registration order. Registering outside an
26
+ * active mount is rejected, preventing resources from silently leaking.
27
+ */
28
+ protected own<T extends ElementCleanup>(cleanup: T): T;
29
+ /**
30
+ * Handle a mount, unmount or cleanup failure after rollback has completed.
31
+ * Override to integrate an application's error reporting policy.
32
+ */
33
+ protected onLifecycleError(error: unknown): void;
34
+ }
35
+ /**
36
+ * Classic "lazy properties" upgrade fix: if a property was assigned on the
37
+ * instance BEFORE the element was upgraded (e.g. `el.score = s` ran before
38
+ * `customElements.define`), the plain own property shadows the class accessor.
39
+ * Re-routing it through the (now installed) prototype setter makes the value
40
+ * take effect. Call from `connectedCallback` for each public property.
41
+ */
42
+ declare function upgradeProperty(el: HTMLElement, prop: string): void;
43
+ /** {@link upgradeProperty} for several properties at once. */
44
+ declare function upgradeProperties(el: HTMLElement, props: readonly string[]): void;
45
+ /**
46
+ * Read a numeric attribute with a fallback and optional clamping. Unlike
47
+ * `Number(this.getAttribute(...))`, an absent, empty or non-numeric value
48
+ * (e.g. `pixels-per-second="abc"` → NaN) falls back instead of poisoning
49
+ * downstream maths (NaN widths, NaN lane heights, …).
50
+ */
51
+ declare function numAttr(el: Element, name: string, fallback: number, min?: number, max?: number): number;
52
+ /**
53
+ * Read a tri-state boolean attribute: absent → `fallback`; present reads
54
+ * `false` / `0` / `no` / `off` (any case) as false and anything else —
55
+ * including the bare attribute — as true.
56
+ */
57
+ declare function boolAttr(el: Element, name: string, fallback?: boolean): boolean;
58
+ /**
59
+ * Interpret a size attribute as a CSS length: a bare number is pixels
60
+ * (`width="640"` → `640px`), anything else passes through untouched
61
+ * (`width="100%"`, `height="12rem"`). Empty / absent → `undefined`.
62
+ */
63
+ declare function cssSizeAttr(el: Element, name: string): string | undefined;
64
+ /** Register `ctor` at `tag` once; a no-op outside the browser or if taken. */
65
+ declare function defineOnce(tag: string, ctor: CustomElementConstructor): void;
66
+ type ElementTargetState = 'ready' | 'missing' | 'invalid' | 'ambiguous';
67
+ /**
68
+ * Observe one unique selector match in the host's own Document/ShadowRoot.
69
+ * The callback runs immediately and after target replacement or late upgrade.
70
+ * The caller owns the returned cleanup for the host's connected lifetime.
71
+ * A custom target replacing a non-reflected object property can dispatch
72
+ * `webmusic:sourcechange` to request a fresh connection to the same element.
73
+ */
74
+ declare function observeElementTarget(host: Element, selector: string, listener: (target: Element | undefined, state: ElementTargetState) => void): () => void;
75
+
76
+ export { type ElementCleanup, type ElementTargetState, HTMLElementBase, WebMusicElement, boolAttr, cssSizeAttr, defineOnce, numAttr, observeElementTarget, upgradeProperties, upgradeProperty };
@@ -0,0 +1,76 @@
1
+ declare const HTMLElementBase: typeof HTMLElement;
2
+ /** Cleanup owned by one connected lifetime of a {@link WebMusicElement}. */
3
+ type ElementCleanup = () => void;
4
+ /**
5
+ * Minimal lifecycle base for WebMusic custom elements.
6
+ *
7
+ * It deliberately owns no Shadow DOM, UI profile, presenter, registration or
8
+ * domain state. Subclasses mount those concerns in {@link onMount}, and either
9
+ * return a cleanup or register several cleanups with {@link own}. Every
10
+ * connection gets a fresh cleanup scope, so disconnect/reconnect is safe.
11
+ */
12
+ declare abstract class WebMusicElement extends HTMLElementBase {
13
+ #private;
14
+ /** Browser lifecycle entry point. Prefer overriding {@link onMount}. */
15
+ connectedCallback(): void;
16
+ /** Browser lifecycle entry point. Prefer overriding {@link onUnmount}. */
17
+ disconnectedCallback(): void;
18
+ /** Mount UI and domain bindings for the current connected lifetime. */
19
+ protected onMount(): ElementCleanup | void;
20
+ /** Run subclass-specific unmount work before owned cleanups are released. */
21
+ protected onUnmount(): void;
22
+ /**
23
+ * Own a cleanup for the current connected lifetime.
24
+ *
25
+ * Cleanups run once in reverse registration order. Registering outside an
26
+ * active mount is rejected, preventing resources from silently leaking.
27
+ */
28
+ protected own<T extends ElementCleanup>(cleanup: T): T;
29
+ /**
30
+ * Handle a mount, unmount or cleanup failure after rollback has completed.
31
+ * Override to integrate an application's error reporting policy.
32
+ */
33
+ protected onLifecycleError(error: unknown): void;
34
+ }
35
+ /**
36
+ * Classic "lazy properties" upgrade fix: if a property was assigned on the
37
+ * instance BEFORE the element was upgraded (e.g. `el.score = s` ran before
38
+ * `customElements.define`), the plain own property shadows the class accessor.
39
+ * Re-routing it through the (now installed) prototype setter makes the value
40
+ * take effect. Call from `connectedCallback` for each public property.
41
+ */
42
+ declare function upgradeProperty(el: HTMLElement, prop: string): void;
43
+ /** {@link upgradeProperty} for several properties at once. */
44
+ declare function upgradeProperties(el: HTMLElement, props: readonly string[]): void;
45
+ /**
46
+ * Read a numeric attribute with a fallback and optional clamping. Unlike
47
+ * `Number(this.getAttribute(...))`, an absent, empty or non-numeric value
48
+ * (e.g. `pixels-per-second="abc"` → NaN) falls back instead of poisoning
49
+ * downstream maths (NaN widths, NaN lane heights, …).
50
+ */
51
+ declare function numAttr(el: Element, name: string, fallback: number, min?: number, max?: number): number;
52
+ /**
53
+ * Read a tri-state boolean attribute: absent → `fallback`; present reads
54
+ * `false` / `0` / `no` / `off` (any case) as false and anything else —
55
+ * including the bare attribute — as true.
56
+ */
57
+ declare function boolAttr(el: Element, name: string, fallback?: boolean): boolean;
58
+ /**
59
+ * Interpret a size attribute as a CSS length: a bare number is pixels
60
+ * (`width="640"` → `640px`), anything else passes through untouched
61
+ * (`width="100%"`, `height="12rem"`). Empty / absent → `undefined`.
62
+ */
63
+ declare function cssSizeAttr(el: Element, name: string): string | undefined;
64
+ /** Register `ctor` at `tag` once; a no-op outside the browser or if taken. */
65
+ declare function defineOnce(tag: string, ctor: CustomElementConstructor): void;
66
+ type ElementTargetState = 'ready' | 'missing' | 'invalid' | 'ambiguous';
67
+ /**
68
+ * Observe one unique selector match in the host's own Document/ShadowRoot.
69
+ * The callback runs immediately and after target replacement or late upgrade.
70
+ * The caller owns the returned cleanup for the host's connected lifetime.
71
+ * A custom target replacing a non-reflected object property can dispatch
72
+ * `webmusic:sourcechange` to request a fresh connection to the same element.
73
+ */
74
+ declare function observeElementTarget(host: Element, selector: string, listener: (target: Element | undefined, state: ElementTargetState) => void): () => void;
75
+
76
+ export { type ElementCleanup, type ElementTargetState, HTMLElementBase, WebMusicElement, boolAttr, cssSizeAttr, defineOnce, numAttr, observeElementTarget, upgradeProperties, upgradeProperty };
@@ -0,0 +1,24 @@
1
+ import {
2
+ HTMLElementBase,
3
+ WebMusicElement,
4
+ boolAttr,
5
+ cssSizeAttr,
6
+ defineOnce,
7
+ numAttr,
8
+ observeElementTarget,
9
+ upgradeProperties,
10
+ upgradeProperty
11
+ } from "./chunk-WNFGDB7B.js";
12
+ import "./chunk-PXG64RU4.js";
13
+ export {
14
+ HTMLElementBase,
15
+ WebMusicElement,
16
+ boolAttr,
17
+ cssSizeAttr,
18
+ defineOnce,
19
+ numAttr,
20
+ observeElementTarget,
21
+ upgradeProperties,
22
+ upgradeProperty
23
+ };
24
+ //# sourceMappingURL=elements.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,8 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkUMTPJ76Scjs = require('./chunk-UMTPJ76S.cjs');
4
+ require('./chunk-7ZTZZ5PN.cjs');
5
+
6
+
7
+ exports.EventEmitter = _chunkUMTPJ76Scjs.EventEmitter;
8
+ //# sourceMappingURL=events.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/events.cjs"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACF,sDAAC","file":"/Users/mamingchen/GitHub/public/WebMusic/platform/kernel/dist/events.cjs"}
@@ -0,0 +1,36 @@
1
+ type Listener<T> = (data: T) => unknown;
2
+ type EventListenerFailureMode = 'throw' | 'rejection';
3
+ /**
4
+ * Tiny typed pub-sub.
5
+ * Subscribers receive a typed payload per event name.
6
+ */
7
+ declare class EventEmitter<TEvents extends object = Record<string, unknown>> {
8
+ private readonly listeners;
9
+ on<K extends keyof TEvents>(event: K, listener: Listener<TEvents[K]>): () => void;
10
+ once<K extends keyof TEvents>(event: K, listener: Listener<TEvents[K]>): () => void;
11
+ off<K extends keyof TEvents>(event: K, listener: Listener<TEvents[K]>): void;
12
+ /**
13
+ * Delivery snapshots the subscribers present at dispatch start — the same
14
+ * membership semantics as {@link emitSafely}. Iterating the live set instead
15
+ * would deliver the in-flight event to listeners added during dispatch,
16
+ * making the ordinary self-rearming `once` idiom an infinite loop.
17
+ */
18
+ emit<K extends keyof TEvents>(event: K, data: TEvents[K]): void;
19
+ /**
20
+ * Deliver an event without allowing one subscriber to prevent later
21
+ * subscribers from running. The ordinary {@link emit} method deliberately
22
+ * retains its historic exception propagation; lifecycle-sensitive owners
23
+ * such as playback engines opt into this boundary explicitly.
24
+ *
25
+ * Delivery snapshots the subscribers present at dispatch start. Synchronous
26
+ * throws and rejected promises are both reported. Errors thrown or rejected
27
+ * by the observer are ignored: a diagnostic hook must never become a second
28
+ * path out of a scheduler callback.
29
+ */
30
+ emitSafely<K extends keyof TEvents>(event: K, data: TEvents[K], onError: (error: unknown, mode: EventListenerFailureMode) => void | PromiseLike<void>): number;
31
+ removeAllListeners(event?: keyof TEvents): void;
32
+ /** Alias of removeAllListeners for backward compatibility. */
33
+ clear(event?: keyof TEvents): void;
34
+ }
35
+
36
+ export { EventEmitter, type EventListenerFailureMode };
@@ -0,0 +1,36 @@
1
+ type Listener<T> = (data: T) => unknown;
2
+ type EventListenerFailureMode = 'throw' | 'rejection';
3
+ /**
4
+ * Tiny typed pub-sub.
5
+ * Subscribers receive a typed payload per event name.
6
+ */
7
+ declare class EventEmitter<TEvents extends object = Record<string, unknown>> {
8
+ private readonly listeners;
9
+ on<K extends keyof TEvents>(event: K, listener: Listener<TEvents[K]>): () => void;
10
+ once<K extends keyof TEvents>(event: K, listener: Listener<TEvents[K]>): () => void;
11
+ off<K extends keyof TEvents>(event: K, listener: Listener<TEvents[K]>): void;
12
+ /**
13
+ * Delivery snapshots the subscribers present at dispatch start — the same
14
+ * membership semantics as {@link emitSafely}. Iterating the live set instead
15
+ * would deliver the in-flight event to listeners added during dispatch,
16
+ * making the ordinary self-rearming `once` idiom an infinite loop.
17
+ */
18
+ emit<K extends keyof TEvents>(event: K, data: TEvents[K]): void;
19
+ /**
20
+ * Deliver an event without allowing one subscriber to prevent later
21
+ * subscribers from running. The ordinary {@link emit} method deliberately
22
+ * retains its historic exception propagation; lifecycle-sensitive owners
23
+ * such as playback engines opt into this boundary explicitly.
24
+ *
25
+ * Delivery snapshots the subscribers present at dispatch start. Synchronous
26
+ * throws and rejected promises are both reported. Errors thrown or rejected
27
+ * by the observer are ignored: a diagnostic hook must never become a second
28
+ * path out of a scheduler callback.
29
+ */
30
+ emitSafely<K extends keyof TEvents>(event: K, data: TEvents[K], onError: (error: unknown, mode: EventListenerFailureMode) => void | PromiseLike<void>): number;
31
+ removeAllListeners(event?: keyof TEvents): void;
32
+ /** Alias of removeAllListeners for backward compatibility. */
33
+ clear(event?: keyof TEvents): void;
34
+ }
35
+
36
+ export { EventEmitter, type EventListenerFailureMode };
package/dist/events.js ADDED
@@ -0,0 +1,8 @@
1
+ import {
2
+ EventEmitter
3
+ } from "./chunk-GO4N5T27.js";
4
+ import "./chunk-PXG64RU4.js";
5
+ export {
6
+ EventEmitter
7
+ };
8
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}