@webmusic/kernel 0.2.0 → 0.4.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 (188) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +2 -0
  3. package/README.md +103 -64
  4. package/dist/audio-context.cjs.map +1 -1
  5. package/dist/build-receipt.json +3 -3
  6. package/dist/chunk-27LH6QLZ.cjs +277 -0
  7. package/dist/chunk-27LH6QLZ.cjs.map +1 -0
  8. package/dist/chunk-3INDOVUC.cjs.map +1 -1
  9. package/dist/chunk-3RR2VIKA.js +393 -0
  10. package/dist/chunk-3RR2VIKA.js.map +1 -0
  11. package/dist/chunk-3YTKIKKX.cjs +378 -0
  12. package/dist/chunk-3YTKIKKX.cjs.map +1 -0
  13. package/dist/chunk-4RG4WQKC.js +360 -0
  14. package/dist/chunk-4RG4WQKC.js.map +1 -0
  15. package/dist/chunk-5AHVQXTF.cjs +620 -0
  16. package/dist/chunk-5AHVQXTF.cjs.map +1 -0
  17. package/dist/chunk-624KWJWZ.js +170 -0
  18. package/dist/chunk-624KWJWZ.js.map +1 -0
  19. package/dist/chunk-6HGFEKD3.cjs +851 -0
  20. package/dist/chunk-6HGFEKD3.cjs.map +1 -0
  21. package/dist/chunk-7ZTZZ5PN.cjs.map +1 -1
  22. package/dist/chunk-ALWV4P7D.js +726 -0
  23. package/dist/chunk-ALWV4P7D.js.map +1 -0
  24. package/dist/chunk-BADJJ6DV.cjs +143 -0
  25. package/dist/chunk-BADJJ6DV.cjs.map +1 -0
  26. package/dist/chunk-C3LMS36L.cjs +393 -0
  27. package/dist/chunk-C3LMS36L.cjs.map +1 -0
  28. package/dist/chunk-C3YWUZW3.cjs.map +1 -1
  29. package/dist/chunk-CR6OUWBJ.cjs +726 -0
  30. package/dist/chunk-CR6OUWBJ.cjs.map +1 -0
  31. package/dist/chunk-CYWDZLWC.js +2141 -0
  32. package/dist/chunk-CYWDZLWC.js.map +1 -0
  33. package/dist/chunk-DDOGX2D5.js +378 -0
  34. package/dist/chunk-DDOGX2D5.js.map +1 -0
  35. package/dist/chunk-DVN6E5U3.js +620 -0
  36. package/dist/chunk-DVN6E5U3.js.map +1 -0
  37. package/dist/chunk-EURMRU2S.js +208 -0
  38. package/dist/chunk-EURMRU2S.js.map +1 -0
  39. package/dist/chunk-EXDCK2VL.cjs +20 -0
  40. package/dist/chunk-EXDCK2VL.cjs.map +1 -0
  41. package/dist/chunk-G5EIUP52.js +114 -0
  42. package/dist/chunk-G5EIUP52.js.map +1 -0
  43. package/dist/chunk-GB4DGKLZ.js +143 -0
  44. package/dist/chunk-GB4DGKLZ.js.map +1 -0
  45. package/dist/chunk-GPOEAYOW.js +2147 -0
  46. package/dist/chunk-GPOEAYOW.js.map +1 -0
  47. package/dist/chunk-I4YMA5VM.cjs +120 -0
  48. package/dist/chunk-I4YMA5VM.cjs.map +1 -0
  49. package/dist/chunk-IVWHMDCB.cjs +4383 -0
  50. package/dist/chunk-IVWHMDCB.cjs.map +1 -0
  51. package/dist/chunk-JFCBJMA7.cjs +2147 -0
  52. package/dist/chunk-JFCBJMA7.cjs.map +1 -0
  53. package/dist/chunk-JLVSAZ3K.cjs +813 -0
  54. package/dist/chunk-JLVSAZ3K.cjs.map +1 -0
  55. package/dist/chunk-K7FYH6UG.cjs +208 -0
  56. package/dist/chunk-K7FYH6UG.cjs.map +1 -0
  57. package/dist/chunk-L4MYCETM.cjs +970 -0
  58. package/dist/chunk-L4MYCETM.cjs.map +1 -0
  59. package/dist/chunk-MNCMYNYL.js +970 -0
  60. package/dist/chunk-MNCMYNYL.js.map +1 -0
  61. package/dist/chunk-NT2BZ3QM.js +120 -0
  62. package/dist/chunk-NT2BZ3QM.js.map +1 -0
  63. package/dist/chunk-O7SA5GLC.js +277 -0
  64. package/dist/chunk-O7SA5GLC.js.map +1 -0
  65. package/dist/chunk-OCKAHITL.cjs +548 -0
  66. package/dist/chunk-OCKAHITL.cjs.map +1 -0
  67. package/dist/chunk-OTXYWCLA.js +206 -0
  68. package/dist/chunk-OTXYWCLA.js.map +1 -0
  69. package/dist/chunk-P6ZA63J7.js +548 -0
  70. package/dist/chunk-P6ZA63J7.js.map +1 -0
  71. package/dist/chunk-QLF3BOST.js +20 -0
  72. package/dist/chunk-QLF3BOST.js.map +1 -0
  73. package/dist/chunk-RCWFRZDR.js +4383 -0
  74. package/dist/chunk-RCWFRZDR.js.map +1 -0
  75. package/dist/chunk-RZBLPM3L.cjs +206 -0
  76. package/dist/chunk-RZBLPM3L.cjs.map +1 -0
  77. package/dist/chunk-TA3TNJZU.cjs +360 -0
  78. package/dist/chunk-TA3TNJZU.cjs.map +1 -0
  79. package/dist/chunk-TZSRPTQL.cjs +2141 -0
  80. package/dist/chunk-TZSRPTQL.cjs.map +1 -0
  81. package/dist/chunk-UMTPJ76S.cjs.map +1 -1
  82. package/dist/chunk-UY77FXDW.js +813 -0
  83. package/dist/chunk-UY77FXDW.js.map +1 -0
  84. package/dist/chunk-VFU3S7OC.js +851 -0
  85. package/dist/chunk-VFU3S7OC.js.map +1 -0
  86. package/dist/chunk-VY6WWZSW.cjs.map +1 -1
  87. package/dist/chunk-WN5DZOVT.cjs +170 -0
  88. package/dist/chunk-WN5DZOVT.cjs.map +1 -0
  89. package/dist/chunk-WOPW6WLR.cjs.map +1 -1
  90. package/dist/chunk-XBSIYUHM.cjs +114 -0
  91. package/dist/chunk-XBSIYUHM.cjs.map +1 -0
  92. package/dist/chunk-ZMU72HJS.cjs.map +1 -1
  93. package/dist/context-DSa0ymyN.d.cts +664 -0
  94. package/dist/context-DaxfAg3b.d.ts +664 -0
  95. package/dist/effect-chain-Cu03O5Y0.d.ts +91 -0
  96. package/dist/effect-chain-Do75T7uK.d.cts +91 -0
  97. package/dist/effect.cjs +16 -1
  98. package/dist/effect.cjs.map +1 -1
  99. package/dist/effect.d.cts +56 -14
  100. package/dist/effect.d.ts +56 -14
  101. package/dist/effect.js +16 -1
  102. package/dist/elements.cjs +37 -2
  103. package/dist/elements.cjs.map +1 -1
  104. package/dist/elements.d.cts +197 -8
  105. package/dist/elements.d.ts +197 -8
  106. package/dist/elements.js +36 -1
  107. package/dist/events.cjs.map +1 -1
  108. package/dist/index.cjs +555 -8
  109. package/dist/index.cjs.map +1 -1
  110. package/dist/index.d.cts +16 -4
  111. package/dist/index.d.ts +16 -4
  112. package/dist/index.js +566 -19
  113. package/dist/message.cjs +104 -0
  114. package/dist/message.cjs.map +1 -0
  115. package/dist/message.d.cts +738 -0
  116. package/dist/message.d.ts +738 -0
  117. package/dist/message.js +104 -0
  118. package/dist/meter.cjs.map +1 -1
  119. package/dist/module-control-C25BMtH7.d.ts +61 -0
  120. package/dist/module-control-yH6nTJM9.d.cts +61 -0
  121. package/dist/module-plugin-BnPmq1VP.d.ts +198 -0
  122. package/dist/module-plugin-CHb-5W0Y.d.cts +198 -0
  123. package/dist/module.cjs +263 -0
  124. package/dist/module.cjs.map +1 -0
  125. package/dist/module.d.cts +1112 -0
  126. package/dist/module.d.ts +1112 -0
  127. package/dist/module.js +263 -0
  128. package/dist/parameter-DwQzFmBR.d.cts +172 -0
  129. package/dist/parameter-DwQzFmBR.d.ts +172 -0
  130. package/dist/player.cjs.map +1 -1
  131. package/dist/processor-worklet.cjs +18 -0
  132. package/dist/processor-worklet.cjs.map +1 -0
  133. package/dist/processor-worklet.d.cts +166 -0
  134. package/dist/processor-worklet.d.ts +166 -0
  135. package/dist/processor-worklet.js +18 -0
  136. package/dist/processor-worklet.js.map +1 -0
  137. package/dist/processor.cjs +51 -0
  138. package/dist/processor.cjs.map +1 -0
  139. package/dist/processor.d.cts +397 -0
  140. package/dist/processor.d.ts +397 -0
  141. package/dist/processor.js +51 -0
  142. package/dist/processor.js.map +1 -0
  143. package/dist/project-types-BU4awMnL.d.ts +323 -0
  144. package/dist/project-types-DufCV8Ma.d.cts +323 -0
  145. package/dist/ring-C-i9N90a.d.cts +139 -0
  146. package/dist/ring-DkcMt2Eg.d.ts +139 -0
  147. package/dist/sequence.cjs +68 -0
  148. package/dist/sequence.cjs.map +1 -0
  149. package/dist/sequence.d.cts +303 -0
  150. package/dist/sequence.d.ts +303 -0
  151. package/dist/sequence.js +68 -0
  152. package/dist/sequence.js.map +1 -0
  153. package/dist/session.cjs +16 -0
  154. package/dist/session.cjs.map +1 -0
  155. package/dist/session.d.cts +407 -0
  156. package/dist/session.d.ts +407 -0
  157. package/dist/session.js +16 -0
  158. package/dist/session.js.map +1 -0
  159. package/dist/tick.cjs.map +1 -1
  160. package/dist/transport.cjs +50 -2
  161. package/dist/transport.cjs.map +1 -1
  162. package/dist/transport.d.cts +145 -1
  163. package/dist/transport.d.ts +145 -1
  164. package/dist/transport.js +51 -3
  165. package/dist/worker.cjs.map +1 -1
  166. package/package.json +61 -10
  167. package/dist/chunk-53YD73OY.js +0 -162
  168. package/dist/chunk-53YD73OY.js.map +0 -1
  169. package/dist/chunk-54JYWB5X.cjs +0 -1051
  170. package/dist/chunk-54JYWB5X.cjs.map +0 -1
  171. package/dist/chunk-BR63OD53.cjs +0 -1
  172. package/dist/chunk-BR63OD53.cjs.map +0 -1
  173. package/dist/chunk-ON64FRCF.js +0 -1051
  174. package/dist/chunk-ON64FRCF.js.map +0 -1
  175. package/dist/chunk-SM5YPDDI.cjs +0 -162
  176. package/dist/chunk-SM5YPDDI.cjs.map +0 -1
  177. package/dist/chunk-TEM2I2NN.js +0 -1
  178. package/dist/chunk-VVZX7DQ6.cjs +0 -254
  179. package/dist/chunk-VVZX7DQ6.cjs.map +0 -1
  180. package/dist/chunk-WNFGDB7B.js +0 -254
  181. package/dist/chunk-WNFGDB7B.js.map +0 -1
  182. package/dist/sync.cjs +0 -12
  183. package/dist/sync.cjs.map +0 -1
  184. package/dist/sync.d.cts +0 -307
  185. package/dist/sync.d.ts +0 -307
  186. package/dist/sync.js +0 -12
  187. /package/dist/{chunk-TEM2I2NN.js.map → message.js.map} +0 -0
  188. /package/dist/{sync.js.map → module.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/element-target.ts","../src/element-module.ts","../src/host-rule.ts","../src/host-fit.ts","../src/elements.ts"],"sourcesContent":["export type ElementTargetState = 'ready' | 'missing' | 'invalid' | 'ambiguous';\n\n/** Release the host callback even if an unknown custom element is never defined. */\nfunction observeDefinition(registry: CustomElementRegistry, name: string, onReady: () => void): () => void {\n let callback: (() => void) | undefined = onReady;\n void registry.whenDefined(name).then(\n () => {\n const ready = callback;\n callback = undefined;\n ready?.();\n },\n () => { callback = undefined; },\n );\n return () => { callback = undefined; };\n}\n\n/**\n * Observe one unique selector match in the host's own Document/ShadowRoot.\n * The callback runs immediately and after target replacement or late upgrade.\n * The caller owns the returned cleanup for the host's connected lifetime.\n * A custom target replacing a non-reflected object property can dispatch\n * `webmusic:sourcechange` to request a fresh connection to the same element.\n */\nexport function observeElementTarget(\n host: Element,\n selector: string,\n listener: (target: Element | undefined, state: ElementTargetState) => void,\n): () => void {\n const root = host.getRootNode() as ParentNode & Node;\n let active = true;\n let previous: Element | undefined;\n let previousState: ElementTargetState | undefined;\n const waiting = new Set<string>();\n const upgradeCleanups: Array<() => void> = [];\n const registry = host.ownerDocument?.defaultView?.customElements;\n const resolve = (force = false): void => {\n if (!active) return;\n let target: Element | undefined;\n let state: ElementTargetState;\n try {\n const matches = typeof root.querySelectorAll === 'function'\n ? root.querySelectorAll(selector)\n : [root.querySelector(selector)].filter(Boolean);\n state = matches.length > 1 ? 'ambiguous' : matches.length === 1 ? 'ready' : 'missing';\n if (state === 'ready') target = matches[0] ?? undefined;\n } catch {\n state = 'invalid';\n }\n if (target && registry && target.localName.includes('-') && !registry.get(target.localName) && !waiting.has(target.localName)) {\n const name = target.localName;\n waiting.add(name);\n upgradeCleanups.push(observeDefinition(registry, name, () => {\n if (active) resolve(previous?.localName === name);\n }));\n }\n if (!force && target === previous && state === previousState) return;\n previous = target;\n previousState = state;\n listener(target, state);\n };\n // Source replacement is local to the selected element. A different player\n // in the same root must not reset this target's subscribers. Still resolve\n // the selector so a replacement announced before mutation delivery is seen.\n const onSourceChange = (event: Event): void => resolve(event.target === previous);\n const Observer = host.ownerDocument?.defaultView?.MutationObserver;\n const observer = Observer ? new Observer(() => resolve()) : undefined;\n observer?.observe(root, {childList: true, subtree: true, attributes: true});\n root.addEventListener?.('webmusic:sourcechange', onSourceChange);\n try {\n resolve();\n } catch (error) {\n active = false;\n observer?.disconnect();\n for (const cleanup of upgradeCleanups.splice(0)) cleanup();\n root.removeEventListener?.('webmusic:sourcechange', onSourceChange);\n throw error;\n }\n return () => {\n if (!active) return;\n active = false;\n observer?.disconnect();\n for (const cleanup of upgradeCleanups.splice(0)) cleanup();\n root.removeEventListener?.('webmusic:sourcechange', onSourceChange);\n };\n}\n","import type {ModuleContext} from './module/context';\nimport type {PortDirection, PortFamily} from './module/port';\nimport {getModulePort, type ModuleHandle, type ModulePortMap} from './module/registry';\nimport {observeElementTarget, type ElementTargetState} from './element-target';\nimport type {CapabilityKey} from './module/capability';\nimport type {SourcePort} from './module/source-port';\nimport {sourceOrigin} from './module/source-relay';\n\nconst requestEvent = 'webmusic-context-request';\nconst contextEvent = 'webmusic:contextchange';\nconst moduleEvent = 'webmusic:modulechange';\nconst providers = new WeakMap<Element, () => ModuleContext | undefined>();\n\nexport type ModuleContextState = 'ready' | 'pending' | 'missing';\ninterface ContextRequest {\n requester: Element;\n claimed: boolean;\n context?: ModuleContext;\n}\n\nfunction parentElement(element: Element): Element | undefined {\n if (element.assignedSlot) return element.assignedSlot;\n if (element.parentElement) return element.parentElement;\n const root = element.getRootNode?.();\n return root && typeof root === 'object' && 'host' in root ? (root as ShadowRoot).host : undefined;\n}\n\nfunction unknownCustomElement(element: Element): boolean {\n return typeof element.localName === 'string' && element.localName.includes('-') &&\n !element.ownerDocument?.defaultView?.customElements.get(element.localName);\n}\n\n/** Whether a real provider sits above `element`. */\nfunction providerAbove(element: Element): boolean {\n for (let ancestor = parentElement(element); ancestor; ancestor = parentElement(ancestor)) {\n if (providers.has(ancestor)) return true;\n }\n return false;\n}\n\n/**\n * The nearest boundary above `host`: a provider or a not-yet-defined custom\n * element that may upgrade into a provider. An\n * undefined element counts only inside a provider's scope, where borrowing\n * through it could reach the wrong authority; outside any provider an\n * undefined layout wrapper is just markup.\n */\nfunction boundary(host: Element): Element | undefined {\n for (let element = parentElement(host); element; element = parentElement(element)) {\n if (providers.has(element) || (unknownCustomElement(element) && providerAbove(element))) return element;\n }\n return undefined;\n}\n\nfunction dispatch(host: Element, name: string, detail?: unknown): void {\n const Constructor = host.ownerDocument?.defaultView?.CustomEvent;\n if (Constructor && typeof host.dispatchEvent === 'function') host.dispatchEvent(new Constructor(name, {bubbles: true, composed: true, detail}));\n}\n\n/** Provide a pending boundary until read() returns a context. Disposal revokes only this provider. */\nexport function provideModuleContext(host: Element, read: () => ModuleContext | undefined): () => void {\n if (providers.has(host)) throw new Error('Element already provides a module context');\n providers.set(host, read);\n const onRequest = (event: Event): void => {\n const request = (event as CustomEvent<ContextRequest>).detail;\n if (!request || request.claimed || request.requester === host) return;\n // The composed path includes slot providers visible to this listener even in a closed root.\n const nearest = event.composedPath().find(candidate => {\n if (candidate === request.requester || !('nodeType' in candidate) || candidate.nodeType !== 1) return false;\n const element = candidate as Element;\n return providers.has(element) || unknownCustomElement(element);\n });\n if (nearest !== host) return;\n request.claimed = true;\n request.context = read();\n };\n // Native slotchange is not composed. A provider inside a closed root can\n // announce reassignment without exposing or scanning its private tree.\n const onSlotChange = (): void => notifyModuleContext(host);\n // A host outside a real DOM (server rendering, stubs) has no requests to answer.\n const listening = typeof host.addEventListener === 'function';\n if (listening) {\n host.addEventListener(requestEvent, onRequest);\n host.addEventListener('slotchange', onSlotChange);\n }\n notifyModuleContext(host);\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n if (listening) {\n host.removeEventListener(requestEvent, onRequest);\n host.removeEventListener('slotchange', onSlotChange);\n }\n if (providers.get(host) === read) providers.delete(host);\n notifyModuleContext(host);\n };\n}\n\nfunction resolveContext(host: Element): {context?: ModuleContext; state: ModuleContextState} {\n const nearest = boundary(host);\n const request: ContextRequest = {requester: host, claimed: false};\n dispatch(host, requestEvent, request);\n return {context: request.context, state: request.context ? 'ready' : request.claimed || nearest ? 'pending' : 'missing'};\n}\n\nexport function requestModuleContext(host: Element): ModuleContext | undefined { return resolveContext(host).context; }\nexport function getModuleContextState(host: Element): ModuleContextState { return resolveContext(host).state; }\nexport function hasModuleContextBoundary(host: Element): boolean { return resolveContext(host).state !== 'missing'; }\nexport function notifyModuleContext(host: Element): void { dispatch(host, contextEvent); }\nexport function notifyModuleChange(host: Element): void {\n rememberOwner(host);\n dispatch(host, moduleEvent);\n}\n\n/** Which Element exposes each module it announced (DEC-094): a companion given a module finds the Element that owns it. */\nconst owners = new WeakMap<ModuleHandle, Element>();\nfunction rememberOwner(host: Element): void {\n const module = (host as {module?: unknown}).module;\n if (module && typeof module === 'object') owners.set(module as ModuleHandle, host);\n}\n\n/**\n * The Element that exposes `module` (DEC-094), through any source relays it\n * stands behind: the one that announced it with `notifyModuleChange`, as long\n * as that Element still exposes it. Undefined for a module no Element owns.\n */\nexport function moduleOwner(module: ModuleHandle | undefined): Element | undefined {\n const origin = sourceOrigin(module);\n const owner = origin ? owners.get(origin) : undefined;\n return owner && (owner as {module?: unknown}).module === origin ? owner : undefined;\n}\n\n/**\n * Follow the `module` an Element exposes (DEC-094): `callback` runs with the\n * current module now, then each time the Element's `module` is another one.\n * An Element announces a new module with `webmusic:modulechange`, or a new\n * scope that makes one with `webmusic:contextchange`; this hears both, from\n * the Element and what it holds, and reports only a change of identity, so a\n * host binds to it without listening for either itself. Returns the release\n * function.\n */\nexport function observeElementModule(element: Element, callback: (module: ModuleHandle | undefined) => void): () => void {\n rememberOwner(element);\n let current = (element as {module?: ModuleHandle}).module;\n let active = true;\n const check = (): void => {\n if (!active) return;\n const next = (element as {module?: ModuleHandle}).module;\n if (next === current) return;\n current = next;\n rememberOwner(element);\n callback(next);\n };\n const listening = typeof element.addEventListener === 'function';\n if (listening) for (const name of [moduleEvent, contextEvent]) element.addEventListener(name, check);\n callback(current);\n return () => {\n if (!active) return;\n active = false;\n if (listening) for (const name of [moduleEvent, contextEvent]) element.removeEventListener(name, check);\n };\n}\n\ntype MutationListener = (records: readonly MutationRecord[]) => void;\nconst rootObservers = new WeakMap<Node, {observer: MutationObserver; listeners: Set<MutationListener>}>();\n\n/**\n * One shared observer per Document/ShadowRoot fans out to every discovering\n * element. Each consumer filters records by its own ancestry, so unrelated\n * DOM churn costs an ancestor walk instead of a context request per element.\n */\nfunction observeRootMutations(Observer: typeof MutationObserver, root: Node, listener: MutationListener): () => void {\n let entry = rootObservers.get(root);\n if (!entry) {\n const listeners = new Set<MutationListener>();\n const observer = new Observer((records) => {\n for (const callback of [...listeners]) {\n if (!listeners.has(callback)) continue;\n // One consumer's failure must not starve the others of this batch.\n try { callback(records); } catch (error) { queueMicrotask(() => { throw error; }); }\n }\n });\n observer.observe(root, {childList: true, subtree: true, attributes: true, attributeFilter: ['slot', 'name']});\n entry = {observer, listeners};\n rootObservers.set(root, entry);\n }\n const owned = entry;\n owned.listeners.add(listener);\n return () => {\n if (!owned.listeners.delete(listener) || owned.listeners.size > 0) return;\n owned.observer.disconnect();\n if (rootObservers.get(root) === owned) rootObservers.delete(root);\n };\n}\n\nfunction ancestorsOf(host: Element): Element[] {\n const chain: Element[] = [];\n for (let element = parentElement(host); element; element = parentElement(element)) chain.push(element);\n return chain;\n}\n\n/** Discovery is synchronous; observations re-evaluate after provider changes, upgrades and layout moves. */\nexport function observeModuleContext(\n host: Element,\n callback: (context: ModuleContext | undefined, state: ModuleContextState) => void,\n): () => void {\n let active = true;\n let initialized = false;\n let previous: ModuleContext | undefined;\n let previousState: ModuleContextState | undefined;\n let ancestry: readonly Element[] = [];\n const waiting = new Map<string, {ready?: () => void}>();\n const registry = host.ownerDocument?.defaultView?.customElements;\n const roots = new Map<EventTarget, (() => void) | undefined>();\n const Observer = host.ownerDocument?.defaultView?.MutationObserver;\n // Context depends only on this host's composed ancestry, the composition/\n // slot attributes along it, upgrades and provider notifications. Mutations\n // elsewhere in the document cannot change it.\n const onMutation = (records: readonly MutationRecord[]): void => {\n if (!active) return;\n const chain = ancestorsOf(host);\n const moved = chain.length !== ancestry.length || chain.some((element, index) => element !== ancestry[index]);\n if (moved || records.some((record) => record.type === 'attributes' &&\n (record.target === host || ancestry.includes(record.target as Element)))) resolve();\n };\n const unobserveRoot = (root: EventTarget, unobserve: (() => void) | undefined): void => {\n root.removeEventListener(contextEvent, resolve);\n root.removeEventListener('slotchange', resolve);\n unobserve?.();\n };\n const refreshRoots = (chain: readonly Element[]): void => {\n // Hosts outside a real document (server rendering, stubs) have no roots to observe.\n const next = new Set<EventTarget>();\n const add = (root: unknown) => {\n if (root && typeof (root as EventTarget).addEventListener === 'function') next.add(root as EventTarget);\n };\n add(host.ownerDocument);\n add(host.getRootNode?.());\n for (const element of chain) add(element.getRootNode?.());\n if (next.size === roots.size && [...next].every(root => roots.has(root))) return;\n for (const [root, unobserve] of [...roots]) {\n if (next.has(root)) continue;\n roots.delete(root);\n unobserveRoot(root, unobserve);\n }\n for (const root of next) {\n if (roots.has(root)) continue;\n root.addEventListener(contextEvent, resolve);\n root.addEventListener('slotchange', resolve);\n roots.set(root, Observer && 'nodeType' in root ? observeRootMutations(Observer, root as Node, onMutation) : undefined);\n }\n };\n const resolve = (): void => {\n if (!active) return;\n const chain = ancestorsOf(host);\n ancestry = chain;\n refreshRoots(chain);\n for (const element of chain) {\n if (unknownCustomElement(element) && registry && !waiting.has(element.localName)) {\n const name = element.localName;\n const entry = {ready: resolve as (() => void) | undefined};\n waiting.set(name, entry);\n // A never-defined custom element must not retain a released host.\n void registry.whenDefined(name).then(() => {\n const ready = entry.ready;\n entry.ready = undefined;\n ready?.();\n }, () => { entry.ready = undefined; });\n }\n }\n const {context, state} = resolveContext(host);\n if (initialized && context === previous && state === previousState) return;\n initialized = true;\n previous = context;\n previousState = state;\n callback(context, state);\n };\n const dispose = (): void => {\n if (!active) return;\n active = false;\n for (const [root, unobserve] of roots) unobserveRoot(root, unobserve);\n roots.clear();\n for (const entry of waiting.values()) entry.ready = undefined;\n waiting.clear();\n };\n try { resolve(); } catch (error) { dispose(); throw error; }\n return dispose;\n}\n\n/** Observe an explicit same-root selector's .module and its public capability invalidations. */\nexport function observeModuleTarget(\n host: Element,\n selector: string,\n callback: (target: ModuleHandle | undefined) => void,\n): () => void {\n let active = true;\n let target: Element | undefined;\n let stopModule: (() => void) | undefined;\n let stopElement: (() => void) | undefined;\n let module: ModuleHandle | undefined;\n let subscription: object | undefined;\n let reading = false;\n let dirty = false;\n let selectionRoot: Node | undefined;\n const Observer = host.ownerDocument?.defaultView?.MutationObserver;\n const observer = Observer ? new Observer(() => refreshSelection()) : undefined;\n\n const dispose = (): void => {\n if (!active) return;\n active = false;\n subscription = undefined;\n observer?.disconnect();\n target?.removeEventListener(moduleEvent, onChange);\n target = undefined;\n module = undefined;\n const releases = [stopElement, stopModule];\n stopElement = stopModule = undefined;\n let failure: unknown;\n for (const release of releases) {\n try { release?.(); } catch (error) { failure ??= error; }\n }\n if (failure !== undefined) throw failure;\n };\n\n const read = (): void => {\n if (!active) return;\n if (reading) { dirty = true; return; }\n reading = true;\n try {\n do {\n dirty = false;\n const current = (target as (Element & {module?: ModuleHandle}) | undefined)?.module;\n if (!active) return;\n if (current !== module || (current !== undefined && subscription === undefined)) {\n // Invalidate callbacks before any external unsubscribe can re-enter.\n subscription = undefined;\n module = current;\n const release = stopModule;\n stopModule = undefined;\n release?.();\n if (!active) return;\n if (dirty) continue;\n const token = {};\n subscription = token;\n let subscribing = true;\n const stop = current?.subscribe?.(() => {\n if (!active || subscription !== token) return;\n // Coalesce immediate subscription delivery until its disposer is\n // available, so an initial callback failure can release it.\n if (!subscribing) read();\n });\n subscribing = false;\n if (active && subscription === token) stopModule = stop;\n else stop?.();\n }\n if (!active) return;\n if (dirty) continue;\n callback(module);\n } while (active && dirty);\n } catch (error) {\n try { dispose(); } catch { /* Preserve the callback/subscription failure. */ }\n throw error;\n } finally {\n reading = false;\n }\n };\n const onChange = (event: Event): void => {\n if (event.composedPath()[0] === target) read();\n };\n\n const bind = (next: Element | undefined): void => {\n if (!active) return;\n target?.removeEventListener(moduleEvent, onChange);\n target = next;\n target?.addEventListener(moduleEvent, onChange);\n read();\n };\n\n const refreshSelection = (): void => {\n if (!active) return;\n const root = host.getRootNode();\n if (root === selectionRoot) return;\n selectionRoot = root;\n observer?.disconnect();\n observer?.observe(root, {childList: true, subtree: true});\n if (host.ownerDocument && root !== host.ownerDocument) observer?.observe(host.ownerDocument, {childList: true, subtree: true});\n const previous = stopElement;\n stopElement = undefined;\n try {\n previous?.();\n const stop = observeElementTarget(host, selector, bind);\n if (active && selectionRoot === root) stopElement = stop;\n else stop();\n } catch (error) {\n try { dispose(); } catch { /* Preserve the setup failure. */ }\n throw error;\n }\n };\n try { refreshSelection(); } catch (error) {\n try { dispose(); } catch { /* See above. */ }\n throw error;\n }\n return dispose;\n}\n\n/** What an input-observing Element currently borrows. */\nexport interface ModuleInputState<F extends PortFamily> {\n readonly module?: ModuleHandle;\n readonly port?: ModulePortMap[F];\n readonly error?: unknown;\n}\n\nexport interface ObserveModuleInputOptions<F extends PortFamily> {\n family: F;\n direction?: PortDirection;\n /** Port name when the host has no `port` attribute. */\n port: string;\n /** Explicit object binding: a module binds it, null unbinds, undefined discovers. */\n assigned?: ModuleHandle | null;\n /** Host-level generation guard; a false result stops the observation. */\n isCurrent?: () => boolean;\n}\n\n/**\n * Resolve the module an Element consumes — explicit object, then the `input`\n * selector, then the nearest provider's target — and the named port of one\n * family on it. `update` runs when the module or the port identity changes,\n * including when a port detaches. The caller owns whatever it builds on the\n * port (a tap, a subscription); this observation owns only its discovery.\n */\nexport function observeModuleInput<F extends PortFamily>(\n host: Element,\n options: ObserveModuleInputOptions<F>,\n update: (state: ModuleInputState<F>) => void,\n): () => void {\n const isCurrent = options.isCurrent ?? (() => true);\n let active = true;\n let generation = 0;\n let initialized = false;\n let target: ModuleHandle | undefined;\n let port: ModulePortMap[F] | undefined;\n let unsubscribe: (() => void) | undefined;\n let stopDiscovery: (() => void) | undefined;\n let resolving = false;\n let dirty = false;\n const current = (revision: number) => active && isCurrent() && generation === revision;\n const dispose = (): void => {\n if (!active) return;\n active = false;\n generation++;\n const discovery = stopDiscovery;\n const subscription = unsubscribe;\n stopDiscovery = unsubscribe = undefined;\n target = port = undefined;\n try { discovery?.(); } finally { subscription?.(); }\n };\n const resolvePort = (): void => {\n const module = target;\n if (!active || !isCurrent() || !module) return;\n if (resolving) { dirty = true; return; }\n resolving = true;\n const revision = generation;\n try {\n do {\n dirty = false;\n let next: ModulePortMap[F] | undefined;\n try {\n next = getModulePort(module, host.getAttribute('port') ?? options.port, options.family, options.direction);\n } catch (error) {\n if (!current(revision)) return;\n port = undefined;\n update({module, error});\n continue;\n }\n if (!current(revision)) return;\n if (next && next.readiness === 'detached') next = undefined;\n if (next === port) continue;\n port = next;\n update(next ? {module, port: next} : {module});\n } while (dirty && current(revision));\n } finally {\n if (generation === revision) resolving = false;\n if (active && !isCurrent()) dispose();\n }\n };\n const attach = (module: ModuleHandle | undefined): void => {\n if (!active || !isCurrent()) return;\n if (initialized && target === module) { resolvePort(); return; }\n initialized = true;\n const revision = ++generation;\n resolving = false;\n const previous = unsubscribe;\n unsubscribe = undefined;\n target = module;\n port = undefined;\n previous?.();\n if (!current(revision)) return;\n update(module ? {module} : {});\n if (!current(revision) || !module) return;\n const subscription = module.subscribe?.(() => resolvePort());\n if (!current(revision)) { subscription?.(); return; }\n unsubscribe = subscription;\n resolvePort();\n };\n try {\n if (options.assigned !== undefined) attach(options.assigned ?? undefined);\n else {\n const discovery = host.hasAttribute('input')\n ? observeModuleTarget(host, host.getAttribute('input') ?? '', attach)\n : observeModuleContext(host, (context) => attach(context?.target));\n if (active && isCurrent()) stopDiscovery = discovery;\n else discovery();\n }\n if (!isCurrent()) dispose();\n } catch (error) {\n dispose();\n throw error;\n }\n return dispose;\n}\n\n/** What a companion (a view or analysis that borrows a player) currently follows. */\nexport interface CompanionInput {\n /** Owner element: the `input` selector's target, or the owner a provider lends by containment. */\n readonly element?: Element;\n /** Module whose named source port is followed (explicit object or a `port` attribute). */\n readonly module?: ModuleHandle;\n /** The resolved source port, once its module publishes it. */\n readonly port?: SourcePort<unknown>;\n /** `pending`: a module was found but has not published the port yet. */\n readonly state: ElementTargetState | 'pending';\n readonly error?: unknown;\n}\n\nexport interface ObserveCompanionInputOptions {\n /** Capability a provider scope lends to companions found by containment. */\n readonly capability: CapabilityKey<unknown>;\n /** Explicit object binding: a module binds its source port, null unbinds, undefined discovers. */\n readonly assigned?: ModuleHandle | null;\n /** Schema the followed source port must publish. */\n readonly schemaId?: string;\n /** Source port name when the host has no `port` attribute. */\n readonly port?: string;\n /** False when the host's `port` attribute names another family (an audio tap), so it never selects the source path. */\n readonly portAttribute?: boolean;\n readonly isCurrent?: () => boolean;\n}\n\n/**\n * Resolve what a companion follows, in the DEC-068 order: an explicit module\n * (its named source port), then the `input` selector, then the owner the\n * nearest provider lends. A `port` attribute selects the module path for a\n * selector or containment too: the companion follows that module's source\n * port instead of the owner element. Only discovery is owned here.\n */\nexport function observeCompanionInput(\n host: Element,\n options: ObserveCompanionInputOptions,\n update: (input: CompanionInput) => void,\n): () => void {\n if (options.assigned !== undefined || (options.portAttribute !== false && host.getAttribute('port') !== null)) {\n return observeModuleInput(host, {\n family: 'source', direction: 'output', port: options.port ?? 'source',\n assigned: options.assigned, isCurrent: options.isCurrent,\n }, (state) => {\n const {module, error} = state;\n const port = state.port as SourcePort<unknown> | undefined;\n if (error !== undefined) update({module, state: 'invalid', error});\n else if (!port) update(module ? {module, state: 'pending'} : {state: 'missing'});\n else if (options.schemaId && port.schemaId !== options.schemaId) {\n update({module, state: 'invalid', error: new TypeError(`Port ${port.id} publishes ${port.schemaId}, not ${options.schemaId}.`)});\n } else update({module, port, state: 'ready'});\n });\n }\n const selector = host.getAttribute('input');\n if (selector) return observeElementTarget(host, selector, (element, state) => update(element ? {element, state} : {state}));\n return observeModuleContext(host, (context) => {\n const owner = context?.capabilities.get(options.capability);\n update(owner && typeof owner === 'object' ? {element: owner as Element, state: 'ready'} : {state: 'missing'});\n });\n}\n","const adopted = new WeakMap<Node, Map<string, HTMLStyleElement>>();\n\n/**\n * Give an Element's tag a default style the page can override (DEC-094): one\n * rule per `key` in the root the Element is in — prepended to the document's\n * head, or to the shadow root — written with the tag as a `:where()`\n * selector so it has no specificity. This is what an inline style cannot\n * be: a page's rule, the `hidden` attribute and a host's own inline style\n * all still win. `rule` receives the escaped tag name and returns the CSS.\n * A rule a page removed is added again. Returns whether this call added it.\n */\nexport function adoptHostRule(element: Element, key: string, rule: (selector: string) => string): boolean {\n const root = element.getRootNode?.();\n const document = element.ownerDocument;\n if (!root || !document) return false;\n const into = root === document ? document.head : typeof (root as ShadowRoot).host === 'object' ? root as ShadowRoot : undefined;\n if (!into) return false;\n const name = `${element.localName}:${key}`;\n const styles = adopted.get(root) ?? new Map<string, HTMLStyleElement>();\n if (styles.get(name)?.isConnected) return false;\n const style = document.createElement('style');\n styles.set(name, style);\n adopted.set(root, styles);\n style.textContent = rule(element.localName.replace(/[^a-z0-9-]/gi, (char) => `\\\\${char.codePointAt(0)!.toString(16)} `));\n style.dataset.webmusicHost = name;\n into.prepend(style);\n return true;\n}\n","/**\n * How an Element is made as tall as the box a host gives it (DEC-094). An\n * Element that draws on a surface whose height it chooses declares one as\n * the static `hostFit` of its class; a host applies it with\n * {@link fitElementHeight} and needs to know nothing else about the Element.\n */\nexport type ElementHeightFit =\n /** A height token on the Element sizes `surface`, measured inside `content`: both are selectors in its shadow root, or in the Element. */\n | {readonly kind: 'token'; readonly property: string; readonly content: string; readonly surface: string; readonly least: number}\n /** The Element's `height` attribute, in CSS pixels; `content`, when given, is measured to find what its tools take. */\n | {readonly kind: 'attribute'; readonly least: number; readonly content?: string};\n\nexport interface ElementFitOptions {\n /** The fit to apply instead of the one the Element's class declares. */\n readonly fit?: ElementHeightFit;\n /**\n * What the Element's height goes back to when the fit is released: the\n * `height` attribute's value, or the token's, and `null` to remove it.\n * `initial` is what it was when fitting began, which is the default.\n */\n readonly restore?: (initial: string | null) => string | null;\n /**\n * Show all of the Element in a box too small for it (DEC-099). When the\n * Element cannot be laid out as small as its box — its drawing is at its\n * least height, it declares no fit and is taller than the box, or what it\n * holds is wider than the box — it is laid out as large as it needs, in the\n * box's proportions, and scaled down to the box, so nothing is cut off and\n * nothing has to be scrolled into view. The fit then owns the Element's\n * inline `width`, `height`, `transform` and `transform-origin` as well, and\n * gives them back when released. With it, an Element that declares no fit\n * is fitted too. Default false: the Element is left to its box's overflow.\n */\n readonly contain?: boolean;\n}\n\nconst text = (value: unknown): value is string => typeof value === 'string' && value.length > 0;\n\n/** The fit an Element's class declares as its static `hostFit`, if it is a well-formed one. */\nexport function elementFitOf(element: Element): ElementHeightFit | undefined {\n const fit = (element.constructor as {hostFit?: unknown} | undefined)?.hostFit as Partial<Record<string, unknown>> | undefined;\n if (!fit || typeof fit !== 'object' || typeof fit.least !== 'number' || !(fit.least >= 0)) return undefined;\n if (fit.kind === 'token') return text(fit.property) && text(fit.content) && text(fit.surface) ? fit as unknown as ElementHeightFit : undefined;\n if (fit.kind === 'attribute') return fit.content === undefined || text(fit.content) ? fit as unknown as ElementHeightFit : undefined;\n return undefined;\n}\n\n/** How a fit is applied: which part is measured and what is written. */\ninterface Fitting {\n parts?(root: ParentNode): {content: HTMLElement | null; surface: HTMLElement | null};\n read(element: HTMLElement): string | null;\n write(element: HTMLElement, pixels: number): void;\n clear(element: HTMLElement, own: string | null): void;\n readonly least: number;\n}\n\nfunction fittingOf(fit: ElementHeightFit): Fitting {\n if (fit.kind === 'token') return {\n parts: root => ({content: root.querySelector<HTMLElement>(fit.content), surface: root.querySelector<HTMLElement>(fit.surface)}),\n read: element => element.style.getPropertyValue(fit.property) || null,\n write: (element, pixels) => element.style.setProperty(fit.property, `${pixels}px`),\n clear: (element, own) => { if (own === null) element.style.removeProperty(fit.property); else element.style.setProperty(fit.property, own); },\n least: fit.least,\n };\n const content = fit.content;\n return {\n ...(content ? {parts: (root: ParentNode) => ({content: root.querySelector<HTMLElement>(content), surface: null})} : {}),\n read: element => element.getAttribute('height'),\n write: (element, pixels) => { if (element.getAttribute('height') !== String(pixels)) element.setAttribute('height', String(pixels)); },\n clear: (element, own) => { if (own === null) element.removeAttribute('height'); else element.setAttribute('height', own); },\n least: fit.least,\n };\n}\n\n/**\n * Make an Element as tall as its box (DEC-094): the part that draws takes\n * the height its tools and readouts leave, and follows the box when it is\n * resized. The Element must already be inside `box`, by default its parent,\n * which sets its width and has a height of its own. An Element that declares\n * no fit, and is given none, keeps its own height. With `contain`, an\n * Element that cannot be as small as its box is scaled down to it (DEC-099).\n * Returns the release function, which gives the Element its own height back.\n *\n * The caller owns the release; the fit owns the Element's `height` attribute\n * or height token until then, so nothing else should write it meanwhile.\n */\nexport function fitElementHeight(element: HTMLElement, box: HTMLElement | null = element.parentElement, options: ElementFitOptions = {}): () => void {\n const fit = options.fit ?? elementFitOf(element);\n const view = element.ownerDocument?.defaultView;\n const contain = options.contain === true;\n if ((!fit && !contain) || !box || !view || typeof view.ResizeObserver !== 'function') return () => {};\n const fitting = fit ? fittingOf(fit) : undefined;\n const initial = fitting ? fitting.read(element) : null;\n // What the Element's inline style had before a scale was written over it.\n const SCALED = ['width', 'height', 'transform', 'transform-origin'] as const;\n const own = SCALED.map(property => element.style.getPropertyValue(property));\n let written: number | undefined;\n let watched: HTMLElement | undefined;\n let frame = 0;\n let tries = 0;\n let scale = 1;\n let released = false;\n /**\n * Lay the Element out for a box `1 / next` times as wide and draw it `next` times as large: the box itself at 1.\n * Its height stays its own meanwhile, so that what it needs can be measured; {@link fill} sets it afterwards.\n */\n const setScale = (next: number, width: number) => {\n scale = next;\n SCALED.forEach((property, index) => { if (own[index]) element.style.setProperty(property, own[index]!); else element.style.removeProperty(property); });\n if (next >= 1) return;\n element.style.setProperty('width', `${width / next}px`);\n element.style.setProperty('transform-origin', '0 0');\n element.style.setProperty('transform', `scale(${next})`);\n };\n /** A scaled Element is as tall as the box it is drawn into, whatever height its own style gave it. */\n const fill = (height: number) => { if (scale < 1) element.style.setProperty('height', `${height / scale}px`); };\n /** What surrounds the drawing, and the least height the Element can be laid out at; `undefined` until it has drawn itself. */\n const measure = (): {content: HTMLElement | null; chrome: number; least: number} | undefined => {\n if (!fitting) return {content: null, chrome: 0, least: Math.max(element.offsetHeight, element.scrollHeight)};\n if (!fitting.parts) {\n // The Element's own height is the height it is given and whatever it draws round that: a frame, a row of tools.\n const chrome = written === undefined ? 0 : Math.max(0, Math.max(element.offsetHeight, element.scrollHeight) - written);\n return {content: null, chrome, least: chrome + fitting.least};\n }\n const {content, surface} = fitting.parts(element.shadowRoot ?? element);\n if (!content || (!surface && written === undefined)) return undefined;\n const chrome = content.offsetHeight - (surface ? surface.offsetHeight : written!);\n return {content, chrome, least: chrome + fitting.least};\n };\n const apply = () => {\n frame = 0;\n if (released) return;\n const boxWidth = box.clientWidth, boxHeight = box.clientHeight;\n if (boxHeight <= 0) return;\n if (contain && boxWidth > 0) {\n // Read in one turn, so nothing is painted in between. All of it shows at `at` when it is no wider than\n // the layout that scale gives it and no taller, at its least, than the box is in that layout.\n const shows = (at: number): boolean => {\n setScale(at, boxWidth);\n const needs = measure();\n return element.scrollWidth <= element.clientWidth + 1 && !(needs && needs.least > boxHeight / at + 0.5);\n };\n if (!shows(1)) {\n // Down to a scale that shows all of it: a wider layout needs less height, never more, so a few rounds reach one.\n let high = 1;\n for (let round = 0; round < 4; round++) {\n const needs = measure();\n let next = scale;\n if (needs && needs.least > boxHeight / scale + 0.5) next = Math.min(next, boxHeight / needs.least);\n if (element.scrollWidth > element.clientWidth + 1) next = Math.min(next, boxWidth / element.scrollWidth);\n if (!(next > 0) || next >= scale) break;\n high = scale;\n setScale(next, boxWidth);\n }\n // Then back up towards the largest that still does: rows that unwrapped in the wider layout left room.\n let low = scale;\n for (let round = 0; round < 4 && high - low > 0.01; round++) {\n const middle = (low + high) / 2;\n if (shows(middle)) low = middle; else high = middle;\n }\n if (scale !== low) setScale(low, boxWidth);\n }\n }\n if (!fitting) { fill(boxHeight); return; }\n const available = boxHeight / scale;\n let next: number;\n if (!fitting.parts) next = available - (measure()?.chrome ?? 0);\n else {\n const needs = measure();\n // The Element draws itself after it is connected, some only once they have data.\n if (!needs) {\n if (written === undefined) { written = Math.max(fitting.least, Math.round(available)); fitting.write(element, written); }\n if (tries++ < 120) schedule();\n fill(boxHeight);\n return;\n }\n // A readout that wraps or a tool row that appears changes what is left for the drawing.\n if (needs.content && needs.content !== watched) {\n if (watched) observer.unobserve(watched);\n observer.observe(needs.content);\n watched = needs.content;\n }\n next = available - needs.chrome;\n }\n next = Math.max(fitting.least, Math.round(next));\n fill(boxHeight);\n if (next === written) return;\n written = next;\n fitting.write(element, next);\n // What surrounds the drawing can change with its size, and an Element may draw a new height a moment later: measure once more.\n if (tries++ < 120) schedule();\n };\n const schedule = () => { if (!frame && !released) frame = view.requestAnimationFrame(apply); };\n const observer = new view.ResizeObserver(() => { tries = 0; schedule(); });\n observer.observe(box);\n // An Element with no fit is measured itself: what it holds may arrive after it is connected.\n if (!fitting) observer.observe(element);\n schedule();\n return () => {\n if (released) return;\n released = true;\n observer.disconnect();\n if (frame) view.cancelAnimationFrame(frame);\n if (scale < 1) setScale(1, 0);\n if (!fitting || !fit) return;\n const restored = options.restore ? options.restore(initial) : initial;\n if (written !== undefined || fit.kind === 'token' || restored !== fitting.read(element)) fitting.clear(element, restored);\n };\n}\n","// ============================================================================\n// SSR-safe custom-element base + attribute helpers shared by every element\n// module in both families. Extracted from @webscore/view's base.ts (the\n// superset of the six per-package copies).\n//\n// `HTMLElement` does not exist in Node, so `class X extends HTMLElement` at\n// module top level throws a ReferenceError the moment the module is imported\n// server-side. Extending `HTMLElementBase` instead keeps the modules importable\n// anywhere; the `define*` guards already prevent registration outside the\n// browser, and the class is never instantiated without a DOM.\n// ============================================================================\n\nimport {observeElementTarget, type ElementTargetState} from './element-target';\n\nexport const HTMLElementBase = (\n typeof HTMLElement !== \"undefined\" ? HTMLElement : (class {} as unknown)\n) as typeof HTMLElement;\n\nexport {\n provideModuleContext,\n requestModuleContext,\n observeModuleContext,\n getModuleContextState,\n hasModuleContextBoundary,\n notifyModuleContext,\n observeModuleTarget,\n observeModuleInput,\n observeCompanionInput,\n notifyModuleChange,\n observeElementModule,\n moduleOwner,\n type ModuleContextState,\n type ModuleInputState,\n type ObserveModuleInputOptions,\n type CompanionInput,\n type ObserveCompanionInputOptions,\n} from './element-module';\n\n/** Cleanup owned by one connected lifetime of a {@link WebMusicElement}. */\nexport type ElementCleanup = () => void;\n\ninterface ElementMountScope {\n generation: number;\n cleanups: ElementCleanup[];\n}\n\n/**\n * Minimal lifecycle base for WebMusic custom elements.\n *\n * It deliberately owns no Shadow DOM, UI profile, presenter, registration or\n * domain state. Subclasses mount those concerns in {@link onMount}, and either\n * return a cleanup or register several cleanups with {@link own}. Every\n * connection gets a fresh cleanup scope, so disconnect/reconnect is safe.\n */\nexport abstract class WebMusicElement extends HTMLElementBase {\n #mounted = false;\n #generation = 0;\n #cleanups: ElementCleanup[] = [];\n #mountScopes: ElementMountScope[] = [];\n\n /** Browser lifecycle entry point. Prefer overriding {@link onMount}. */\n connectedCallback(): void {\n if (this.#mounted) return;\n this.#mounted = true;\n const generation = ++this.#generation;\n const cleanups: ElementCleanup[] = [];\n const scope: ElementMountScope = { generation, cleanups };\n this.#cleanups = cleanups;\n this.#mountScopes.push(scope);\n\n try {\n const cleanup = this.onMount();\n if (cleanup !== undefined) {\n if (\n this.#mounted &&\n this.#generation === generation &&\n this.#cleanups === cleanups\n ) {\n cleanups.push(cleanup);\n } else {\n // onMount may synchronously disconnect/reconnect before returning.\n // Its returned cleanup belongs to that stale lifetime, never to the\n // newly connected one.\n // The surrounding catch reports a failed cleanup exactly once.\n cleanup();\n }\n }\n } catch (error) {\n const errors: unknown[] = [error];\n if (this.#generation === generation) {\n this.#mounted = false;\n this.#generation += 1;\n if (this.#cleanups === cleanups) this.#cleanups = [];\n }\n errors.push(...this.#drainCleanups(cleanups));\n this.#report(errors);\n } finally {\n const scopeIndex = this.#mountScopes.lastIndexOf(scope);\n if (scopeIndex >= 0) this.#mountScopes.splice(scopeIndex, 1);\n }\n }\n\n /** Browser lifecycle entry point. Prefer overriding {@link onUnmount}. */\n disconnectedCallback(): void {\n if (!this.#mounted) return;\n this.#mounted = false;\n this.#generation += 1;\n // Detach this lifetime's stack before invoking any user cleanup. A cleanup\n // may synchronously reconnect the element and register a fresh stack.\n const cleanups = this.#cleanups;\n this.#cleanups = [];\n\n const errors: unknown[] = [];\n try {\n this.onUnmount();\n } catch (error) {\n errors.push(error);\n }\n errors.push(...this.#drainCleanups(cleanups));\n this.#report(errors);\n }\n\n /** Mount UI and domain bindings for the current connected lifetime. */\n protected onMount(): ElementCleanup | void {}\n\n /** Run subclass-specific unmount work before owned cleanups are released. */\n protected onUnmount(): void {}\n\n /**\n * Own a cleanup for the current connected lifetime.\n *\n * Cleanups run once in reverse registration order. Registering outside an\n * active mount is rejected, preventing resources from silently leaking.\n */\n protected own<T extends ElementCleanup>(cleanup: T): T {\n const scope = this.#mountScopes[this.#mountScopes.length - 1];\n if (!scope && !this.#mounted) {\n throw new Error(\"WebMusicElement can only own cleanup while mounted\");\n }\n if (typeof cleanup !== \"function\") {\n throw new TypeError(\"WebMusicElement cleanup must be a function\");\n }\n if (scope) {\n if (\n this.#mounted &&\n this.#generation === scope.generation &&\n this.#cleanups === scope.cleanups\n ) {\n scope.cleanups.push(cleanup);\n } else {\n // A stale onMount can resume after it synchronously disconnected and a\n // nested connection installed a fresh cleanup scope. Release late\n // ownership immediately instead of attaching it to the new lifetime.\n cleanup();\n }\n return cleanup;\n }\n this.#cleanups.push(cleanup);\n return cleanup;\n }\n\n /**\n * Handle a mount, unmount or cleanup failure after rollback has completed.\n * Override to integrate an application's error reporting policy.\n */\n protected onLifecycleError(error: unknown): void {\n throw error;\n }\n\n #drainCleanups(cleanups: ElementCleanup[]): unknown[] {\n const errors: unknown[] = [];\n while (cleanups.length > 0) {\n const cleanup = cleanups.pop();\n try {\n cleanup?.();\n } catch (error) {\n errors.push(error);\n }\n }\n return errors;\n }\n\n #report(errors: readonly unknown[]): void {\n let reportingFailure: unknown;\n let reportingFailed = false;\n for (const error of errors) {\n try {\n this.onLifecycleError(error);\n } catch (failure) {\n if (!reportingFailed) {\n reportingFailed = true;\n reportingFailure = failure;\n }\n }\n }\n if (reportingFailed) throw reportingFailure;\n }\n}\n\n/**\n * Classic \"lazy properties\" upgrade fix: if a property was assigned on the\n * instance BEFORE the element was upgraded (e.g. `el.score = s` ran before\n * `customElements.define`), the plain own property shadows the class accessor.\n * Re-routing it through the (now installed) prototype setter makes the value\n * take effect. Call from `connectedCallback` for each public property.\n */\nexport function upgradeProperty(el: HTMLElement, prop: string): void {\n if (Object.prototype.hasOwnProperty.call(el, prop)) {\n const value = (el as unknown as Record<string, unknown>)[prop];\n delete (el as unknown as Record<string, unknown>)[prop];\n (el as unknown as Record<string, unknown>)[prop] = value;\n }\n}\n\n/** {@link upgradeProperty} for several properties at once. */\nexport function upgradeProperties(\n el: HTMLElement,\n props: readonly string[],\n): void {\n for (const prop of props) upgradeProperty(el, prop);\n}\n\n/**\n * Read a numeric attribute with a fallback and optional clamping. Unlike\n * `Number(this.getAttribute(...))`, an absent, empty or non-numeric value\n * (e.g. `pixels-per-second=\"abc\"` → NaN) falls back instead of poisoning\n * downstream maths (NaN widths, NaN lane heights, …).\n */\nexport function numAttr(\n el: Element,\n name: string,\n fallback: number,\n min?: number,\n max?: number,\n): number {\n const raw = el.getAttribute(name);\n let value = raw == null || raw.trim() === \"\" ? fallback : Number(raw);\n if (!Number.isFinite(value)) value = fallback;\n if (min !== undefined) value = Math.max(min, value);\n if (max !== undefined) value = Math.min(max, value);\n return value;\n}\n\n/**\n * Read a tri-state boolean attribute: absent → `fallback`; present reads\n * `false` / `0` / `no` / `off` (any case) as false and anything else —\n * including the bare attribute — as true.\n */\nexport function boolAttr(el: Element, name: string, fallback = false): boolean {\n const raw = el.getAttribute(name);\n if (raw == null) return fallback;\n return !/^(false|0|no|off)$/i.test(raw.trim());\n}\n\n/**\n * Interpret a size attribute as a CSS length: a bare number is pixels\n * (`width=\"640\"` → `640px`), anything else passes through untouched\n * (`width=\"100%\"`, `height=\"12rem\"`). Empty / absent → `undefined`.\n */\nexport function cssSizeAttr(el: Element, name: string): string | undefined {\n const raw = el.getAttribute(name)?.trim();\n if (!raw) return undefined;\n return /^-?\\d+(\\.\\d+)?$/.test(raw) ? `${raw}px` : raw;\n}\n\n/** Register `ctor` at `tag` once; a no-op outside the browser or if taken. */\nexport function defineOnce(tag: string, ctor: CustomElementConstructor): void {\n if (typeof customElements !== \"undefined\" && !customElements.get(tag))\n customElements.define(tag, ctor);\n}\n\nexport {observeElementTarget, type ElementTargetState} from './element-target';\nexport {adoptHostRule} from './host-rule';\nexport {elementFitOf, fitElementHeight, type ElementFitOptions, type ElementHeightFit} from './host-fit';\n\n/** A selected element may exist before its non-reflected source is available. */\nexport type ElementSourceState = ElementTargetState | 'unavailable';\n\nexport interface ElementSourceOptions<T> {\n /** An explicit value takes precedence. Only undefined enables selector lookup. */\n readonly source?: unknown;\n readonly selector?: string;\n readonly property: string;\n /** Domain validation belongs to the consumer; Kernel has no domain types. */\n readonly accepts: (value: unknown) => value is T;\n}\n\nexport interface ElementSourceResolution<T> {\n readonly state: ElementSourceState;\n readonly source?: T;\n readonly target?: Element;\n readonly error?: unknown;\n}\n\n/**\n * Resolve an explicit source or a selected element's public object property.\n * Captures one configuration; dispose and rebind when that configuration changes.\n * Does not subscribe to, own, or dispose the borrowed domain source. Source\n * changes on the same target use the existing webmusic:sourcechange protocol.\n */\nexport function observeElementSource<T>(\n host: Element,\n options: ElementSourceOptions<T>,\n listener: (resolution: ElementSourceResolution<T>) => void,\n): () => void {\n const read = (value: unknown, target?: Element): ElementSourceResolution<T> => {\n if (value === undefined) return {state: 'unavailable', target};\n try {\n return options.accepts(value)\n ? {state: 'ready', source: value, target}\n : {state: 'invalid', target, error: new TypeError(`Invalid ${options.property} source`)};\n } catch (error) { return {state: 'invalid', target, error}; }\n };\n if (options.source !== undefined) {\n listener(read(options.source));\n return () => {};\n }\n if (!options.selector) {\n listener({state: 'missing'});\n return () => {};\n }\n return observeElementTarget(host, options.selector, (target, state) => {\n if (!target || state !== 'ready') { listener({state, target}); return; }\n let resolution: ElementSourceResolution<T>;\n try { resolution = read((target as unknown as Record<string, unknown>)[options.property], target); }\n catch (error) { resolution = {state: 'invalid', target, error}; }\n listener(resolution);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGA,SAAS,kBAAkB,UAAiC,MAAc,SAAiC;AACzG,MAAI,WAAqC;AACzC,OAAK,SAAS,YAAY,IAAI,EAAE;AAAA,IAC9B,MAAM;AACJ,YAAM,QAAQ;AACd,iBAAW;AACX,cAAQ;AAAA,IACV;AAAA,IACA,MAAM;AAAE,iBAAW;AAAA,IAAW;AAAA,EAChC;AACA,SAAO,MAAM;AAAE,eAAW;AAAA,EAAW;AACvC;AASO,SAAS,qBACd,MACA,UACA,UACY;AACZ,QAAM,OAAO,KAAK,YAAY;AAC9B,MAAI,SAAS;AACb,MAAI;AACJ,MAAI;AACJ,QAAM,UAAU,oBAAI,IAAY;AAChC,QAAM,kBAAqC,CAAC;AAC5C,QAAM,WAAW,KAAK,eAAe,aAAa;AAClD,QAAM,UAAU,CAAC,QAAQ,UAAgB;AACvC,QAAI,CAAC,OAAQ;AACb,QAAI;AACJ,QAAI;AACJ,QAAI;AACF,YAAM,UAAU,OAAO,KAAK,qBAAqB,aAC7C,KAAK,iBAAiB,QAAQ,IAC9B,CAAC,KAAK,cAAc,QAAQ,CAAC,EAAE,OAAO,OAAO;AACjD,cAAQ,QAAQ,SAAS,IAAI,cAAc,QAAQ,WAAW,IAAI,UAAU;AAC5E,UAAI,UAAU,QAAS,UAAS,QAAQ,CAAC,KAAK;AAA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C,OAAO,OAAM,CAAC;AAAG;AAAA,IAAQ;AACvE,QAAI;AACJ,QAAI;AAAE,mBAAa,KAAM,OAA8C,QAAQ,QAAQ,GAAG,MAAM;AAAA,IAAG,SAC5F,OAAO;AAAE,mBAAa,EAAC,OAAO,WAAW,QAAQ,MAAK;AAAA,IAAG;AAChE,aAAS,UAAU;AAAA,EACrB,CAAC;AACH;","names":["chrome","next"]}
@@ -0,0 +1,120 @@
1
+ import {
2
+ __privateAdd,
3
+ __privateGet,
4
+ __privateMethod,
5
+ __privateSet
6
+ } from "./chunk-PXG64RU4.js";
7
+
8
+ // src/module/capability.ts
9
+ function createCapabilityKey(name) {
10
+ if (!name.trim()) throw new TypeError("Capability name must not be empty");
11
+ return Object.freeze({ name, identity: Symbol(name) });
12
+ }
13
+ var _values;
14
+ var _ModuleCapabilities = class _ModuleCapabilities {
15
+ constructor() {
16
+ __privateAdd(this, _values);
17
+ __privateSet(this, _values, /* @__PURE__ */ new Map());
18
+ }
19
+ get(key) {
20
+ return __privateGet(this, _values).get(key.identity);
21
+ }
22
+ has(key) {
23
+ return __privateGet(this, _values).has(key.identity);
24
+ }
25
+ with(key, value) {
26
+ const next = new _ModuleCapabilities();
27
+ const values = __privateGet(next, _values);
28
+ for (const [identity, item] of __privateGet(this, _values)) values.set(identity, item);
29
+ values.set(key.identity, value);
30
+ return next;
31
+ }
32
+ };
33
+ _values = new WeakMap();
34
+ var ModuleCapabilities = _ModuleCapabilities;
35
+
36
+ // src/module/port.ts
37
+ var PORT_FAMILIES = Object.freeze(["audio", "note", "control", "transport", "source", "message"]);
38
+ var directions = ["input", "output"];
39
+ var multiplicities = ["single", "sum"];
40
+ var readinessStates = ["unresolved", "preparing", "ready", "error", "detached"];
41
+ function assertPortInfo(port) {
42
+ if (!port || typeof port !== "object") throw new TypeError("Port must be an object");
43
+ if (typeof port.id !== "string" || !port.id.trim() || port.id !== port.id.trim()) {
44
+ throw new TypeError("Port ID must be a nonempty trimmed string");
45
+ }
46
+ if (!PORT_FAMILIES.includes(port.family)) throw new TypeError(`Unknown port family: ${String(port.family)}`);
47
+ if (!directions.includes(port.direction)) throw new TypeError(`Unknown port direction: ${String(port.direction)}`);
48
+ if (!multiplicities.includes(port.multiplicity)) throw new TypeError(`Unknown port multiplicity: ${String(port.multiplicity)}`);
49
+ if (!Number.isInteger(port.schemaVersion) || port.schemaVersion < 1) throw new TypeError("Port schemaVersion must be a positive integer");
50
+ if (!readinessStates.includes(port.readiness)) throw new TypeError(`Unknown port readiness: ${String(port.readiness)}`);
51
+ }
52
+ var _entries, _onError, _PortListeners_instances, report_fn;
53
+ var PortListeners = class {
54
+ constructor(onError) {
55
+ __privateAdd(this, _PortListeners_instances);
56
+ __privateAdd(this, _entries, /* @__PURE__ */ new Set());
57
+ __privateAdd(this, _onError);
58
+ __privateSet(this, _onError, onError);
59
+ }
60
+ get size() {
61
+ return __privateGet(this, _entries).size;
62
+ }
63
+ add(listener) {
64
+ if (typeof listener !== "function") throw new TypeError("Listener must be a function");
65
+ const entry = { listener };
66
+ __privateGet(this, _entries).add(entry);
67
+ return () => {
68
+ __privateGet(this, _entries).delete(entry);
69
+ };
70
+ }
71
+ emit(value) {
72
+ for (const entry of [...__privateGet(this, _entries)]) {
73
+ if (!__privateGet(this, _entries).has(entry)) continue;
74
+ try {
75
+ const result = entry.listener(value);
76
+ if (result && typeof result.then === "function") {
77
+ void Promise.resolve(result).catch((error) => __privateMethod(this, _PortListeners_instances, report_fn).call(this, error));
78
+ }
79
+ } catch (error) {
80
+ __privateMethod(this, _PortListeners_instances, report_fn).call(this, error);
81
+ }
82
+ }
83
+ }
84
+ clear() {
85
+ __privateGet(this, _entries).clear();
86
+ }
87
+ };
88
+ _entries = new WeakMap();
89
+ _onError = new WeakMap();
90
+ _PortListeners_instances = new WeakSet();
91
+ report_fn = function(error) {
92
+ var _a;
93
+ try {
94
+ (_a = __privateGet(this, _onError)) == null ? void 0 : _a.call(this, error);
95
+ } catch {
96
+ }
97
+ };
98
+
99
+ // src/module/project-types.ts
100
+ var ProjectModuleUnavailableError = class extends Error {
101
+ constructor(message, options) {
102
+ super(message);
103
+ this.name = "ProjectModuleUnavailableError";
104
+ if (options && "cause" in options) this.cause = options.cause;
105
+ }
106
+ };
107
+ function isProjectModuleUnavailable(error) {
108
+ return error instanceof ProjectModuleUnavailableError || error instanceof Error && error.name === "ProjectModuleUnavailableError";
109
+ }
110
+
111
+ export {
112
+ createCapabilityKey,
113
+ ModuleCapabilities,
114
+ PORT_FAMILIES,
115
+ assertPortInfo,
116
+ PortListeners,
117
+ ProjectModuleUnavailableError,
118
+ isProjectModuleUnavailable
119
+ };
120
+ //# sourceMappingURL=chunk-NT2BZ3QM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/module/capability.ts","../src/module/port.ts","../src/module/project-types.ts"],"sourcesContent":["/** Identity is the symbol token, not its diagnostic name. Types do not validate arbitrary inputs. */\nexport interface CapabilityKey<T> {\n readonly name: string;\n readonly identity: symbol;\n readonly type?: T;\n}\n\nexport function createCapabilityKey<T>(name: string): CapabilityKey<T> {\n if (!name.trim()) throw new TypeError('Capability name must not be empty');\n return Object.freeze({name, identity: Symbol(name)});\n}\n\n/** Immutable directory of borrowed capabilities; contained resources are never frozen or disposed. */\nexport class ModuleCapabilities {\n readonly #values: ReadonlyMap<symbol, unknown>;\n\n constructor() { this.#values = new Map(); }\n\n get<T>(key: CapabilityKey<T>): T | undefined {\n return this.#values.get(key.identity) as T | undefined;\n }\n\n has<T>(key: CapabilityKey<T>): boolean { return this.#values.has(key.identity); }\n\n with<T>(key: CapabilityKey<T>, value: T): ModuleCapabilities {\n const next = new ModuleCapabilities();\n const values = next.#values as Map<symbol, unknown>;\n for (const [identity, item] of this.#values) values.set(identity, item);\n values.set(key.identity, value);\n return next;\n }\n}\n","/** The signal families a module port can carry (DEC-068; `message` from DEC-075). */\nexport type PortFamily = 'audio' | 'note' | 'control' | 'transport' | 'source' | 'message';\nexport type PortDirection = 'input' | 'output';\n/** `single` accepts one producer (or, for an output, one main route); `sum` accepts several. */\nexport type PortMultiplicity = 'single' | 'sum';\n/** Observable resolution state. `detached` is terminal for a disposed or revoked port. */\nexport type PortReadiness = 'unresolved' | 'preparing' | 'ready' | 'error' | 'detached';\n\nexport const PORT_FAMILIES: readonly PortFamily[] = Object.freeze(['audio', 'note', 'control', 'transport', 'source', 'message']);\nconst directions: readonly PortDirection[] = ['input', 'output'];\nconst multiplicities: readonly PortMultiplicity[] = ['single', 'sum'];\nconst readinessStates: readonly PortReadiness[] = ['unresolved', 'preparing', 'ready', 'error', 'detached'];\n\n/** Fields every port declares, whatever its family. */\nexport interface ModulePortInfo {\n readonly id: string;\n readonly family: PortFamily;\n readonly direction: PortDirection;\n readonly multiplicity: PortMultiplicity;\n readonly schemaVersion: number;\n readonly readiness: PortReadiness;\n}\n\n/** Validate the common declaration fields; family-specific checks belong to each port type. */\nexport function assertPortInfo(port: ModulePortInfo): void {\n if (!port || typeof port !== 'object') throw new TypeError('Port must be an object');\n if (typeof port.id !== 'string' || !port.id.trim() || port.id !== port.id.trim()) {\n throw new TypeError('Port ID must be a nonempty trimmed string');\n }\n if (!PORT_FAMILIES.includes(port.family)) throw new TypeError(`Unknown port family: ${String(port.family)}`);\n if (!directions.includes(port.direction)) throw new TypeError(`Unknown port direction: ${String(port.direction)}`);\n if (!multiplicities.includes(port.multiplicity)) throw new TypeError(`Unknown port multiplicity: ${String(port.multiplicity)}`);\n if (!Number.isInteger(port.schemaVersion) || port.schemaVersion < 1) throw new TypeError('Port schemaVersion must be a positive integer');\n if (!readinessStates.includes(port.readiness)) throw new TypeError(`Unknown port readiness: ${String(port.readiness)}`);\n}\n\n/**\n * Ordered, reentrancy-safe listener set shared by the port families. A\n * listener removed during delivery is not called; one listener's failure is\n * reported and does not starve the others.\n */\nexport class PortListeners<T> {\n readonly #entries = new Set<{listener: (value: T) => void}>();\n readonly #onError?: (error: unknown) => void;\n\n constructor(onError?: (error: unknown) => void) { this.#onError = onError; }\n get size(): number { return this.#entries.size; }\n\n add(listener: (value: T) => void): () => void {\n if (typeof listener !== 'function') throw new TypeError('Listener must be a function');\n const entry = {listener};\n this.#entries.add(entry);\n return () => { this.#entries.delete(entry); };\n }\n\n emit(value: T): void {\n for (const entry of [...this.#entries]) {\n if (!this.#entries.has(entry)) continue;\n try {\n const result: unknown = entry.listener(value);\n if (result && typeof (result as PromiseLike<unknown>).then === 'function') {\n void Promise.resolve(result).catch(error => this.#report(error));\n }\n } catch (error) { this.#report(error); }\n }\n }\n\n clear(): void { this.#entries.clear(); }\n\n #report(error: unknown): void {\n try { this.#onError?.(error); } catch { /* Delivery continues after a diagnostic failure. */ }\n }\n}\n","import type {SessionTransport} from '../session';\nimport type {ModuleAudioEnvironment, ModuleContext} from './context';\nimport type {ConnectionLease} from './lease';\nimport type {ControlSignal} from './param-audio';\nimport type {ModuleHandle} from './registry';\n\nexport type ProjectJson = null | boolean | number | string | readonly ProjectJson[] | ProjectJsonObject;\nexport interface ProjectJsonObject { readonly [key: string]: ProjectJson }\nexport interface ProjectPluginReference { readonly id: string; readonly version: string }\nexport interface ProjectAssetReference {\n readonly id: string;\n readonly uri: string;\n readonly mediaType?: string;\n readonly integrity?: string;\n}\nexport interface ProjectContextRecord {\n readonly id: string;\n readonly parentId?: string;\n /** An owner in the direct parent context supplies the nested audio/admission bus. */\n readonly ownerModuleId?: string;\n}\nexport interface ProjectModuleRecord {\n readonly id: string;\n readonly plugin: ProjectPluginReference;\n readonly contextId: string;\n readonly label?: string;\n readonly config: ProjectJsonObject;\n /** Named asset roles point at project asset IDs; Kernel never fetches these URIs. */\n readonly assets?: Readonly<Record<string, string>>;\n readonly params?: Readonly<Record<string, number>>;\n}\nexport type ProjectSignalKind = 'audio' | 'control' | 'note' | 'transport' | 'source' | 'message';\nexport interface ProjectEndpoint { readonly moduleId: string; readonly port: string }\nexport interface ProjectParamEndpoint { readonly moduleId: string; readonly param: string }\nexport interface ProjectConnectionRecord {\n readonly id: string;\n readonly kind: ProjectSignalKind;\n readonly from: ProjectEndpoint;\n readonly to: ProjectEndpoint;\n readonly mode?: 'replace' | 'send' | 'tap';\n}\nexport interface ProjectModulationRecord {\n readonly id: string;\n readonly source: ProjectEndpoint;\n readonly target: ProjectParamEndpoint;\n readonly depth: number;\n readonly polarity?: 'bipolar' | 'unipolar';\n}\nexport interface ProjectMacroRecord {\n readonly id: string;\n readonly label?: string;\n readonly value: number;\n readonly targets: readonly (ProjectParamEndpoint & {readonly min: number; readonly max: number})[];\n}\nexport interface ProjectAutomationPoint {\n readonly type: 'set' | 'linear' | 'exponential';\n readonly value: number;\n readonly timeSeconds: number;\n}\nexport interface ProjectAutomationRecord {\n readonly id: string;\n readonly target: ProjectParamEndpoint;\n readonly points: readonly ProjectAutomationPoint[];\n readonly loop?: 'repeat' | 'once';\n /** A manual base edit can suspend a track without discarding its authored points. */\n readonly enabled?: boolean;\n /** Baseline before the first authored point; preserved independently of current base value. */\n readonly initialValue?: number;\n}\nexport interface ProjectModuleLayout {\n readonly moduleId: string;\n readonly x: number;\n readonly y: number;\n readonly collapsed?: boolean;\n /** The box's width and height in canvas pixels, when it was resized; absent means its natural size. */\n readonly width?: number;\n readonly height?: number;\n}\n/** A text note on the canvas of one context (DEC-076). */\nexport interface ProjectComment {\n readonly id: string;\n readonly contextId: string;\n readonly text: string;\n readonly x: number;\n readonly y: number;\n}\n/** Modules selected and moved together. */\nexport interface ProjectGroup { readonly id: string; readonly moduleIds: readonly string[] }\nexport interface ProjectLayout {\n readonly modules: readonly ProjectModuleLayout[];\n /**\n * The presentation view (DEC-076): the modules it shows and where. A module\n * without an entry is absent from presentation.\n */\n readonly presentation?: readonly ProjectModuleLayout[];\n readonly comments?: readonly ProjectComment[];\n readonly groups?: readonly ProjectGroup[];\n /**\n * Custom properties of the presentation as a whole (DEC-088): their names\n * and the CSS values they are given. Kernel only keeps them; a host that\n * shows the presentation decides which it applies.\n */\n readonly style?: Readonly<Record<string, string>>;\n /**\n * The page a host lays the presentation out in (DEC-092): a tree of its\n * own design that says where each shown module sits among whatever else\n * the page holds. Kernel keeps it as plain data, under the project's\n * limits; what it means, and what of it is safe to show, is the host's.\n */\n readonly page?: ProjectJsonObject;\n}\n/** What drives a mapped parameter: a MIDI controller, pitch bend, program change or a computer key. */\nexport type ProjectMappingSource =\n | {readonly kind: 'cc'; readonly controller: number; readonly channel?: number}\n | {readonly kind: 'pitchbend'; readonly channel?: number}\n | {readonly kind: 'program'; readonly channel?: number}\n | {readonly kind: 'pressure'; readonly channel?: number}\n | {readonly kind: 'key'; readonly key: string};\n/** One mapping from a control source to a parameter (DEC-076). */\nexport interface ProjectMappingRecord {\n readonly id: string;\n readonly source: ProjectMappingSource;\n readonly target: ProjectParamEndpoint;\n /** Target range the source's 0–1 maps onto; defaults to the parameter's display range. */\n readonly min?: number;\n readonly max?: number;\n}\nexport interface ProjectSessionState {\n /** Unwrapped Session seconds, preserving once-only automation and LFO phase across loop passes. */\n readonly positionSeconds: number;\n readonly rate: number;\n readonly loop?: Readonly<{startSeconds: number; endSeconds: number}> | null;\n /** Tempo and meter of the Session's musical time (DEC-077); 120 bpm in 4/4 when absent. */\n readonly tempo?: Readonly<{bpm: number; beatsPerBar: number; beatUnit: number}>;\n}\n/** Serializable project state. DSP objects, DOM, storage and undo history are deliberately absent. */\nexport interface ModuleProject {\n readonly schema: 'webmusic.module-project';\n readonly version: 1;\n readonly id: string;\n readonly contexts: readonly ProjectContextRecord[];\n readonly modules: readonly ProjectModuleRecord[];\n readonly assets: readonly ProjectAssetReference[];\n readonly connections: readonly ProjectConnectionRecord[];\n readonly modulations: readonly ProjectModulationRecord[];\n readonly macros: readonly ProjectMacroRecord[];\n readonly automation: readonly ProjectAutomationRecord[];\n readonly session: ProjectSessionState;\n readonly layout: ProjectLayout;\n /** Control mappings (DEC-076); absent means none. */\n readonly mappings?: readonly ProjectMappingRecord[];\n}\n\nexport interface ProjectPortDescriptor {\n readonly id: string;\n readonly label?: string;\n readonly kind: ProjectSignalKind;\n readonly direction: 'input' | 'output';\n}\nexport interface ProjectFactoryRequest {\n readonly record: ProjectModuleRecord;\n readonly context: ModuleContext;\n readonly signal: AbortSignal;\n asset(role: string): ProjectAssetReference | undefined;\n resolveAsset(role: string): Promise<unknown>;\n}\n/** Exclusively owned by one staged graph. Factories must respect context.destination and must not publish externally. */\nexport interface ProjectModuleInstance {\n readonly module: ModuleHandle;\n readonly ports?: readonly ProjectPortDescriptor[];\n getInput?(port: string): AudioNode | undefined;\n getControl?(port: string): ControlSignal | undefined;\n /** Enrich a fresh child scope; keep its ID, registry and shared AudioEnvironment. */\n childContext?(context: ModuleContext): ModuleContext;\n /**\n * The module a `source` cord from `port` carries (DEC-089). Without it, or\n * when it returns undefined, the cord carries this instance's module.\n */\n sourceOutput?(port: string): ModuleHandle | undefined;\n /**\n * Accept a `source` cord on `port`: follow `module` until the lease is\n * released (DEC-089). Return undefined to leave the cord to the runtime's\n * connector.\n */\n connectSource?(port: string, module: ModuleHandle): ConnectionLease | undefined;\n /** Capture live serializable configuration such as oscillator waveform. */\n exportConfig?(): ProjectJsonObject;\n /**\n * Called once after the graph holding this instance commits, before\n * observers hear of it; a candidate graph that never commits is disposed\n * without activation. Message modules start timers and send load-time output here.\n */\n activate?(): void;\n dispose(): void;\n}\n/**\n * Thrown by a plugin factory when its module cannot exist in this environment\n * (a capability, preparation or resource it needs is unavailable). Restoration\n * keeps the record unresolved with this message, exactly like a missing\n * plugin, instead of failing; any other error still fails the restore.\n */\nexport class ProjectModuleUnavailableError extends Error {\n /** The underlying failure, when there is one. */\n readonly cause?: unknown;\n constructor(message: string, options?: {cause?: unknown}) {\n super(message);\n this.name = 'ProjectModuleUnavailableError';\n if (options && 'cause' in options) this.cause = options.cause;\n }\n}\n\n/** True for {@link ProjectModuleUnavailableError}, also across duplicate package copies. */\nexport function isProjectModuleUnavailable(error: unknown): error is ProjectModuleUnavailableError {\n return error instanceof ProjectModuleUnavailableError || (error instanceof Error && error.name === 'ProjectModuleUnavailableError');\n}\n\nexport interface ProjectPluginFactory extends ProjectPluginReference {\n /**\n * Must return a fresh, exclusively owned instance, even when replacing the\n * same stable ID. Throw {@link ProjectModuleUnavailableError} to leave the\n * module unresolved.\n */\n create(request: ProjectFactoryRequest): ProjectModuleInstance | Promise<ProjectModuleInstance>;\n}\nexport interface ProjectConnectionRequest {\n readonly connection: ProjectConnectionRecord;\n readonly from: ProjectModuleInstance;\n readonly to: ProjectModuleInstance;\n readonly context: ModuleContext;\n readonly signal: AbortSignal;\n}\n/** Adapters explicitly opt in to domain signals; undefined means retained unresolved. */\nexport type ProjectConnector = (request: ProjectConnectionRequest) => ConnectionLease | undefined | Promise<ConnectionLease | undefined>;\nexport interface ProjectRuntimeOptions {\n /** Borrowed environment/context. Disposing a project never closes it. */\n readonly audio: ModuleAudioEnvironment;\n readonly plugins: ProjectPluginLookup;\n readonly destination?: () => AudioNode | undefined;\n readonly resolveAsset?: (asset: ProjectAssetReference, signal: AbortSignal) => unknown | Promise<unknown>;\n readonly connect?: ProjectConnector;\n readonly onCleanupError?: (error: unknown) => void;\n /**\n * Preload the active graph's Session as members join it (DEC-069,\n * DEC-094): the runtime owns that Session, so its players' sound,\n * parameters and inserts are real before the first play. `true`, or the\n * options of {@link keepProjectSessionPreloaded}.\n */\n readonly preload?: boolean | ProjectPreloadOptions;\n}\n/** How a runtime preloads its Session. */\nexport interface ProjectPreloadOptions {\n /** A failure that is a moment, not an error (a member not ready yet): the preload is asked again shortly, at most twenty times. */\n readonly transient?: (error: unknown) => boolean;\n /** Where a preload that failed is reported; by default the runtime's `onCleanupError`, else nowhere. */\n readonly onError?: (error: unknown) => void;\n}\nexport interface ProjectPluginLookup { get(id: string, version: string): ProjectPluginFactory | undefined }\nexport interface ProjectDiagnostic {\n readonly kind: 'module' | 'context' | 'connection' | 'modulation' | 'macro' | 'automation';\n readonly id: string;\n readonly reason: string;\n}\nexport interface ProjectRuntimeModule {\n readonly record: ProjectModuleRecord;\n readonly status: 'ready' | 'unresolved';\n readonly ports: readonly ProjectPortDescriptor[];\n /** Effective audio owner established by the context's destination/admission, inherited through organizational scopes. */\n readonly defaultOwnerModuleId?: string;\n readonly diagnostic?: string;\n}\nexport interface ProjectRuntimeSnapshot {\n readonly project?: ModuleProject;\n readonly revision: number;\n readonly restoring: boolean;\n readonly disposed: boolean;\n readonly modules: readonly ProjectRuntimeModule[];\n readonly unresolved: readonly ProjectDiagnostic[];\n}\nexport interface ProjectRestoreOptions {\n readonly signal?: AbortSignal;\n /** Restore remains paused by default; the caller owns any user-gesture resume policy. */\n readonly play?: boolean;\n}\nexport interface ProjectRestoreResult {\n readonly status: 'committed' | 'cancelled';\n readonly snapshot: ProjectRuntimeSnapshot;\n}\n/** Borrowed current resources; disposal stays with ModuleProjectRuntime. */\nexport interface ProjectRuntimeResources {\n readonly context: ModuleContext;\n readonly session: SessionTransport;\n module(id: string): ModuleHandle | undefined;\n}\n"],"mappings":";;;;;;;;AAOO,SAAS,oBAAuB,MAAgC;AACrE,MAAI,CAAC,KAAK,KAAK,EAAG,OAAM,IAAI,UAAU,mCAAmC;AACzE,SAAO,OAAO,OAAO,EAAC,MAAM,UAAU,OAAO,IAAI,EAAC,CAAC;AACrD;AAVA;AAaO,IAAM,sBAAN,MAAM,oBAAmB;AAAA,EAG9B,cAAc;AAFd,uBAAS;AAEO,uBAAK,SAAU,oBAAI,IAAI;AAAA,EAAG;AAAA,EAE1C,IAAO,KAAsC;AAC3C,WAAO,mBAAK,SAAQ,IAAI,IAAI,QAAQ;AAAA,EACtC;AAAA,EAEA,IAAO,KAAgC;AAAE,WAAO,mBAAK,SAAQ,IAAI,IAAI,QAAQ;AAAA,EAAG;AAAA,EAEhF,KAAQ,KAAuB,OAA8B;AAC3D,UAAM,OAAO,IAAI,oBAAmB;AACpC,UAAM,SAAS,mBAAK;AACpB,eAAW,CAAC,UAAU,IAAI,KAAK,mBAAK,SAAS,QAAO,IAAI,UAAU,IAAI;AACtE,WAAO,IAAI,IAAI,UAAU,KAAK;AAC9B,WAAO;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
9
+ // src/transition-insert-chain.ts
10
+ var sequence = 0;
11
+ var TransitionInsertChain = class {
12
+ constructor(context, options = {}) {
13
+ this.context = context;
14
+ this.options = options;
15
+ this.previous = [];
16
+ this.serial = 0;
17
+ this.graphRevision = 0;
18
+ this.ended = false;
19
+ this.editing = false;
20
+ this.id = options.id ?? `transition-insert-${++sequence}`;
21
+ if (!this.id) throw new Error("A TransitionInsertChain requires a nonempty id.");
22
+ this.maxRetiring = options.maxRetiring ?? 8;
23
+ if (!Number.isSafeInteger(this.maxRetiring) || this.maxRetiring < 1) {
24
+ throw new RangeError("maxRetiring must be a positive safe integer.");
25
+ }
26
+ this.input = context.createGain();
27
+ let output;
28
+ try {
29
+ this.output = output = context.createGain();
30
+ this.active = this.build([], 1);
31
+ } catch (error) {
32
+ try {
33
+ this.input.disconnect();
34
+ } catch (cleanupError) {
35
+ this.report(cleanupError);
36
+ }
37
+ try {
38
+ output?.disconnect();
39
+ } catch (cleanupError) {
40
+ this.report(cleanupError);
41
+ }
42
+ throw error;
43
+ }
44
+ }
45
+ get current() {
46
+ return this.active.chain;
47
+ }
48
+ get retiring() {
49
+ return Object.freeze(this.previous.map((generation) => Object.freeze({
50
+ chain: generation.chain,
51
+ retireAt: generation.retireAt
52
+ })));
53
+ }
54
+ get revision() {
55
+ return this.graphRevision;
56
+ }
57
+ get disposed() {
58
+ return this.ended;
59
+ }
60
+ replace(slots, options = {}) {
61
+ this.assertEditable();
62
+ const fade = duration(options.fadeSeconds ?? 0.02, "fadeSeconds");
63
+ const tail = duration(options.tailSeconds ?? 0, "tailSeconds");
64
+ let now = this.context.currentTime;
65
+ let retireAt;
66
+ if (!Number.isFinite(now) || !Number.isFinite(fade + tail)) throw new RangeError("Transition times must be finite.");
67
+ if (slots.some((slot) => slot.ownership === "borrowed")) {
68
+ throw new Error("Transition generations require fresh owned effect slots.");
69
+ }
70
+ this.collect();
71
+ this.assertEditable();
72
+ if (fade + tail > 0 && this.previous.length >= this.maxRetiring) {
73
+ throw new Error("The retiring effect generation limit has been reached.");
74
+ }
75
+ this.editing = true;
76
+ const old = this.active;
77
+ const changed = [];
78
+ let candidate;
79
+ try {
80
+ candidate = this.build(slots, 0);
81
+ this.assertAlive();
82
+ if (fade + tail > 0) {
83
+ this.ticker ?? (this.ticker = createTickSource(this.options.tick));
84
+ this.ticker.start(() => this.collect());
85
+ }
86
+ now = this.context.currentTime;
87
+ const fadeEnd = now + fade;
88
+ retireAt = fadeEnd + tail;
89
+ if (!Number.isFinite(now) || !Number.isFinite(retireAt)) throw new RangeError("Transition times must be finite.");
90
+ candidate.outputRamp = this.ramp(candidate.outlet.gain, candidate.outputRamp, now, now, fadeEnd, 1);
91
+ const outgoing = [old, ...this.previous.filter((generation) => !generation.drainingTail && generation.retireAt > now)];
92
+ for (const generation of outgoing) {
93
+ const { inputRamp: input, outputRamp: output } = generation;
94
+ changed.push({ generation, input, output });
95
+ if (tail > 0) {
96
+ generation.inputRamp = this.ramp(generation.inlet.gain, input, now, now, fadeEnd, 0);
97
+ generation.outputRamp = this.ramp(generation.outlet.gain, output, now, fadeEnd, retireAt, 0);
98
+ } else {
99
+ generation.outputRamp = this.ramp(generation.outlet.gain, output, now, now, fadeEnd, 0);
100
+ generation.inputRamp = this.ramp(generation.inlet.gain, input, now, fadeEnd, fadeEnd, 0);
101
+ }
102
+ }
103
+ this.assertAlive();
104
+ } catch (error) {
105
+ if (candidate) this.release(candidate);
106
+ if (!this.ended) {
107
+ for (const { generation, input, output } of changed) {
108
+ this.restore(generation.inlet.gain, input, now);
109
+ this.restore(generation.outlet.gain, output, now);
110
+ generation.inputRamp = input;
111
+ generation.outputRamp = output;
112
+ }
113
+ }
114
+ if (!this.previous.length) this.ticker?.stop();
115
+ this.editing = false;
116
+ throw error;
117
+ }
118
+ this.active = candidate;
119
+ for (const { generation } of changed) {
120
+ generation.retireAt = retireAt;
121
+ generation.drainingTail = tail > 0;
122
+ }
123
+ this.previous.push(old);
124
+ this.graphRevision++;
125
+ this.editing = false;
126
+ this.collect();
127
+ }
128
+ /** Release expired generations; useful after deterministic offline rendering. */
129
+ collect() {
130
+ if (this.ended || this.editing) return;
131
+ this.editing = true;
132
+ const due = this.previous.filter((generation) => generation.retireAt <= this.context.currentTime);
133
+ this.previous = this.previous.filter((generation) => !due.includes(generation));
134
+ for (const generation of due) this.release(generation);
135
+ this.editing = false;
136
+ if (!this.previous.length) this.ticker?.stop();
137
+ }
138
+ dispose() {
139
+ if (this.ended) return;
140
+ this.ended = true;
141
+ this.graphRevision++;
142
+ try {
143
+ this.ticker?.dispose();
144
+ } catch (error) {
145
+ this.report(error);
146
+ }
147
+ const generations = [this.active, ...this.previous];
148
+ this.previous = [];
149
+ for (const generation of generations) this.release(generation);
150
+ }
151
+ build(slots, level) {
152
+ const chain = new InsertChain(this.context, { id: `${this.id}/generation-${++this.serial}`, onCleanupError: this.options.onCleanupError });
153
+ let generation;
154
+ try {
155
+ generation = {
156
+ chain,
157
+ inlet: this.context.createGain(),
158
+ outlet: this.context.createGain(),
159
+ edges: [],
160
+ inputRamp: { start: this.context.currentTime, end: this.context.currentTime, from: 1, to: 1 },
161
+ outputRamp: { start: this.context.currentTime, end: this.context.currentTime, from: level, to: level }
162
+ };
163
+ const owner = generation;
164
+ effectGenerationGuards.set(chain, (nodes) => this.reserved(nodes, owner));
165
+ generation.inlet.gain.value = 1;
166
+ generation.outlet.gain.value = level;
167
+ chain.replace(slots);
168
+ this.assertAlive();
169
+ for (const edge of [
170
+ { source: this.input, destination: generation.inlet },
171
+ { source: generation.inlet, destination: chain.input },
172
+ { source: chain.output, destination: generation.outlet },
173
+ { source: generation.outlet, destination: this.output }
174
+ ]) {
175
+ generation.edges.push(edge);
176
+ edge.source.connect(edge.destination);
177
+ this.assertAlive();
178
+ }
179
+ return generation;
180
+ } catch (error) {
181
+ if (generation) this.release(generation);
182
+ else {
183
+ try {
184
+ chain.dispose();
185
+ } catch (cleanupError) {
186
+ this.report(cleanupError);
187
+ }
188
+ }
189
+ throw error;
190
+ }
191
+ }
192
+ reserved(nodes, owner) {
193
+ const touches = (node) => nodes.input === node || nodes.output === node;
194
+ if ([this.input, this.output, owner.inlet, owner.outlet].some(touches)) return true;
195
+ for (const generation of [this.active, ...this.previous]) {
196
+ if (!generation || generation === owner) continue;
197
+ if ([generation.inlet, generation.outlet, generation.chain.input, generation.chain.output].some(touches)) return true;
198
+ for (const instance of generation.chain.instances) {
199
+ if (touches(instance.nodes.input) || touches(instance.nodes.output)) return true;
200
+ const parameters = new Set(Object.values(instance.nodes.params ?? {}));
201
+ if (Object.values(nodes.params ?? {}).some((parameter) => parameters.has(parameter))) return true;
202
+ }
203
+ }
204
+ return false;
205
+ }
206
+ ramp(parameter, previous, now, start, end, to) {
207
+ const from = valueAt(previous, now);
208
+ hold(parameter, from, now);
209
+ if (start > now) parameter.setValueAtTime(from, start);
210
+ if (end > start) parameter.linearRampToValueAtTime(to, end);
211
+ else parameter.setValueAtTime(to, end);
212
+ return { start, end, from, to };
213
+ }
214
+ restore(parameter, previous, now) {
215
+ try {
216
+ hold(parameter, valueAt(previous, now), now);
217
+ if (previous.start > now) parameter.setValueAtTime(previous.from, previous.start);
218
+ if (previous.end > now) {
219
+ if (previous.end > previous.start) parameter.linearRampToValueAtTime(previous.to, previous.end);
220
+ else parameter.setValueAtTime(previous.to, previous.end);
221
+ }
222
+ } catch (error) {
223
+ this.report(error);
224
+ }
225
+ }
226
+ release(generation) {
227
+ effectGenerationGuards.delete(generation.chain);
228
+ for (const edge of [...generation.edges].reverse()) {
229
+ try {
230
+ edge.source.disconnect(edge.destination);
231
+ } catch (error) {
232
+ this.report(error);
233
+ }
234
+ }
235
+ generation.edges.length = 0;
236
+ try {
237
+ generation.chain.dispose();
238
+ } catch (error) {
239
+ this.report(error);
240
+ }
241
+ }
242
+ assertAlive() {
243
+ if (this.ended) throw new Error("TransitionInsertChain is disposed.");
244
+ }
245
+ assertEditable() {
246
+ this.assertAlive();
247
+ if (this.editing) throw new Error("TransitionInsertChain edits cannot re-enter graph construction or cleanup.");
248
+ }
249
+ report(error) {
250
+ try {
251
+ this.options.onCleanupError?.(error);
252
+ } catch {
253
+ }
254
+ }
255
+ };
256
+ function valueAt(ramp, time) {
257
+ if (time < ramp.start) return ramp.from;
258
+ if (time >= ramp.end) return ramp.to;
259
+ return ramp.from + (ramp.to - ramp.from) * (time - ramp.start) / (ramp.end - ramp.start);
260
+ }
261
+ function hold(parameter, value, time) {
262
+ if (typeof parameter.cancelAndHoldAtTime === "function") parameter.cancelAndHoldAtTime(time);
263
+ else {
264
+ parameter.cancelScheduledValues(time);
265
+ parameter.linearRampToValueAtTime(value, time);
266
+ }
267
+ parameter.setValueAtTime(value, time);
268
+ }
269
+ function duration(value, name) {
270
+ if (!Number.isFinite(value) || value < 0) throw new RangeError(`${name} must be finite and nonnegative.`);
271
+ return value;
272
+ }
273
+
274
+ export {
275
+ TransitionInsertChain
276
+ };
277
+ //# sourceMappingURL=chunk-O7SA5GLC.js.map