@lavitre/apps 1.49.0 → 1.49.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"MediaLink.js","sourceRoot":"","sources":["../../MediaLink/MediaLink.ts"],"names":[],"mappings":"AAiIA,8EAA8E;AAC9E,4EAA4E;AAC5E,uBAAuB;AACvB,8EAA8E;AAC9E,MAAM,MAAM,GAAG,YAAY,CAAA;AAC3B,MAAM,UAAU,GAAG,GAAG,MAAM,QAAQ,CAAA;AACpC,MAAM,eAAe,GAAG,GAAG,MAAM,YAAY,CAAA;AAC7C,MAAM,gBAAgB,GAAG,GAAG,MAAM,aAAa,CAAA;AAC/C,MAAM,WAAW,GAAG,GAAG,MAAM,SAAS,CAAA;AACtC;;;;;;GAMG;AACH,MAAM,eAAe,GAAG,GAAG,MAAM,YAAY,CAAA;AA8B7C;;;;;;GAMG;AACH,MAAM,aAAa,GAAmB,EAAE,CAAA;AAExC,gFAAgF;AAChF,MAAM,yBAAyB,GAAoB,EAAE,UAAU,EAAE,IAAI,EAAE,CAAA;AAsBvE,KAAK,UAAU,iBAAiB,CAAC,KAAqB;IACpD,IAAI,OAAO,GAAsB,EAAE,CAAA;IACnC,IAAI,CAAC;QACH,OAAO,GAAG,MAAM,OAAO,CAAC,IAAI,CAAoB;YAC9C,KAAK,CAAC,aAAa,EAAE;YACrB,IAAI,OAAO,CAAoB,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;SACjF,CAAC,CAAA;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,EAAE,CAAA;IACd,CAAC;IACD,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,EAA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AAK,QAAQ;QACtE,OAAQ,CAA6B,CAAC,WAAW,CAAC,KAAK,QAAQ,CAChE,CAAA;AACH,CAAC","sourcesContent":["import type { Frame } from '../Frame/Frame.js'\nimport type { CompanionFrame } from '../CompanionFrame/CompanionFrame.js'\nimport type { IceServerConfig } from '../Frame/Frame.Model.js'\nimport type { Connector } from '../Connector/Connector.js'\nimport type { OpenFrameOptions } from '../Common/index.js'\n\n// ---------------------------------------------------------------------------\n// MediaLink — SDK-owned app-level WebRTC establishment.\n//\n// Signalling travels over the frame's CRDT doc (frame.crdt.doc), exactly like\n// webrtcSignaling.ts in lavitre-app-camera-studio, which this module\n// generalises. The CRDT channel is the right transport because it is kept in\n// sync between a companion frame and its paired Vitre frame by the la Vitre\n// Yjs relay — unlike sendToVitreFrame / sendToLocalFrame which are local-only.\n//\n// ICE/TURN server authority: the VITRE is the source of truth. The answerer\n// (Vitre frame) resolves its full ICE server list — including TURN credentials\n// — and publishes it to the 'iceServers' CRDT map entry. The offerer (companion\n// frame) waits up to `vitreIceTimeoutMs` for this entry before building its\n// RTCPeerConnection, then falls back to its own getIceServers() result, then to\n// public STUN. This matches the security posture of the rest of the platform:\n// TURN credentials are short-lived tokens already delivered to companions via\n// WebRTCOffer messages; they are NOT long-lived secrets. The CRDT doc is scoped\n// to the (appId, frameConnectorId) peer set — the same peers that already hold\n// the media stream — so publishing them here does not widen the exposure surface.\n//\n// Retry uses ICE restart (createOffer{iceRestart:true}) re-published over the\n// CRDT, not a full renegotiation. The resolved ICE server list is stored on the\n// impl and reused for all restarts of the same session (no re-fetch). Voluntary\n// stop writes a session-tagged control entry BEFORE closing the PC so the other\n// side tears down without entering the retry path.\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type MediaLinkState = 'connecting' | 'connected' | 'reconnecting' | 'ended' | 'failed'\nexport type MediaLinkEndReason = 'user' | 'remote-user' | 'failure'\n\nexport type MediaLinkRetryOptions = {\n /** Grace period after 'disconnected' before starting ICE restart. Default 3000 ms. */\n graceMs?: number\n /** Maximum ICE restart attempts before giving up. Default 3. */\n attempts?: number\n /** Per-attempt backoff delays in ms. Default [2000, 4000, 8000]. */\n backoffMs?: number[]\n}\n\nexport type StartMediaLinkOptions = {\n /**\n * Communicated to the answerer frame; tells the Vitre how to display the\n * incoming stream (standard shared-video slot vs. an app-frame overlay).\n */\n receiverDisplay?: 'standard' | 'appFrame'\n /** Opaque app data delivered to the answerer along with the link. */\n metadata?: unknown\n retry?: MediaLinkRetryOptions\n /**\n * When true (default), the offerer sends a control message to the app's\n * Vitre main Connector via `frame.sendMessageToVitreConnector` requesting\n * that the answerer frame be opened.\n */\n requestAnswererFrame?: boolean\n /**\n * How long (ms) the offerer waits for the Vitre answerer to publish its ICE\n * server list before falling back to the companion-side `getIceServers()` or\n * public STUN. Default 8000 ms (accounts for frame-open latency + CRDT sync).\n *\n * The Vitre is the source of authority for TURN credentials; a longer timeout\n * yields better NAT traversal for peers behind symmetric NAT.\n */\n vitreIceTimeoutMs?: number\n /**\n * Attached to the link BEFORE the connection starts — unlike assigning\n * `link.onStateChange` after `startMediaLink` resolves, this cannot miss a\n * fast transition (e.g. an instant 'connected' on loopback / late-join).\n */\n onStateChange?: (state: MediaLinkState) => void\n /** Same early-attachment rationale as {@link onStateChange}. */\n onEnded?: (reason: MediaLinkEndReason) => void\n}\n\n/** Handle returned to the companion-frame (offerer) side. */\nexport interface MediaLink {\n readonly state: MediaLinkState\n readonly sessionId: string\n /**\n * Swap the video (and audio, if present) tracks on the existing senders\n * via `replaceTrack` — no renegotiation. The answerer keeps receiving on\n * the same transceiver; the remote track object is unchanged so\n * `AnsweredMediaLink.onStreamChanged` will NOT fire on the Vitre side.\n */\n replaceStream(stream: MediaStream): Promise<void>\n /**\n * Voluntary stop: writes a session-tagged `ended: 'user'` control entry to\n * the CRDT doc BEFORE closing the PC. The other side tears down immediately\n * with `onEnded('remote-user')` — no retry.\n */\n stop(): void\n onStateChange?: (state: MediaLinkState) => void\n onEnded?: (reason: MediaLinkEndReason) => void\n}\n\n/** Handle returned to the Vitre-frame (answerer) side. */\nexport interface AnsweredMediaLink {\n readonly sessionId: string\n /** Remote stream surfaced via `ontrack`. */\n readonly stream: MediaStream\n readonly receiverDisplay?: 'standard' | 'appFrame'\n readonly metadata?: unknown\n /**\n * Called after the offerer invokes `replaceStream`. NOTE: because\n * `replaceStream` uses `replaceTrack` (no renegotiation), the remote\n * `MediaStreamTrack` object is the SAME object — browsers do NOT fire a\n * new `ontrack` and the track's content simply switches. This callback\n * will therefore NOT fire in current browser implementations. It is\n * provided as a forward-compatibility hook and for documentation purposes.\n */\n onStreamChanged?: (stream: MediaStream) => void\n onStateChange?: (state: MediaLinkState) => void\n onEnded?: (reason: MediaLinkEndReason) => void\n /**\n * Vitre-side voluntary stop: writes `ended: 'user'` toward the offerer.\n * No retry on either side.\n */\n stop(): void\n}\n\n// ---------------------------------------------------------------------------\n// Internal CRDT key names — use a namespace prefix to avoid collisions with\n// app-level CRDT keys.\n// ---------------------------------------------------------------------------\nconst PREFIX = 'mediaLink:'\nconst KEY_SIGNAL = `${PREFIX}signal`\nconst KEY_ICE_OFFERER = `${PREFIX}iceOfferer`\nconst KEY_ICE_ANSWERER = `${PREFIX}iceAnswerer`\nconst KEY_CONTROL = `${PREFIX}control`\n/**\n * Answerer-owned map key holding the Vitre's full ICE server list (including\n * TURN credentials). Written by the answerer once per session, consumed by the\n * offerer before building its RTCPeerConnection. The key is a Yjs map so the\n * value is overwritten atomically per session; validation uses `entry.s ===\n * sessionId` so a stale entry from a previous session is never consumed.\n */\nconst KEY_ICE_SERVERS = `${PREFIX}iceServers`\n\n// The control message shape used by voluntary stop.\ntype ControlEntry = { sessionId: string; ended: MediaLinkEndReason }\n\n// ICE candidate tagged with the session so stale candidates from a previous\n// session are ignored rather than fed into the wrong peer connection.\ntype TaggedIce = { s: string; c: RTCIceCandidateInit }\n\n// Shape written into KEY_SIGNAL.\ntype SignalEntry = {\n sessionId: string\n offer?: string\n answer?: string\n receiverDisplay?: 'standard' | 'appFrame'\n metadata?: unknown\n}\n\n/**\n * Shape written by the answerer (Vitre frame) into the KEY_ICE_SERVERS map\n * under the key `'servers'`. Tagged with `s: sessionId` so the offerer can\n * reject a stale entry from a previous session.\n *\n * Security note: TURN credentials are short-lived tokens already exposed to\n * companions via WebRTCOffer messages; publishing them here does not widen the\n * exposure surface. The CRDT doc is scoped to (appId, frameConnectorId) peers\n * — the same set that already holds the media stream.\n */\ntype IceServersEntry = { s: string; servers: IceServerConfig[] }\n\n/**\n * Fallback when getIceServers() returns empty or times out. INTENTIONALLY EMPTY:\n * la Vitre must never depend on an external STUN/TURN (e.g. Google) — all ICE\n * servers come from getIceServers() (the la Vitre relay). An empty list means\n * host-candidates only; the real fix for \"no servers\" is server-side, not a public\n * STUN leak.\n */\nconst STUN_FALLBACK: RTCIceServer[] = []\n\n/** ICE restart config: re-offer with iceRestart to create a new ICE session. */\nconst ICE_RESTART_OFFER_OPTIONS: RTCOfferOptions = { iceRestart: true }\n\n// Control message JSON posted from the offerer frame to the Vitre main connector\n// to request that the answerer frame be opened.\nexport type MediaLinkOpenAnswererMessage = {\n type: 'lavitre-media-link'\n action: 'open-answerer' | 'close-answerer'\n frameConnectorId: string\n sessionId: string\n}\n\n// ---------------------------------------------------------------------------\n// ICE server resolution (same approach as webrtcSignaling.ts)\n// ---------------------------------------------------------------------------\n\n// The subset of the frame surface the shared CRDT/ICE helpers touch. Both the\n// Vitre `Frame` (answerer side) and the `CompanionFrame` (offerer side) satisfy\n// it, so the helpers stay agnostic to which side called them — the companion-\n// only `sendMessageToVitreConnector` is reached through the `CompanionFrame`\n// typed `frame` field of the offerer, not these helpers.\ntype MediaLinkFrame = Pick<Frame, 'crdt' | 'getIceServers'>\n\nasync function resolveIceServers(frame: MediaLinkFrame): Promise<RTCIceServer[]> {\n let servers: IceServerConfig[] = []\n try {\n servers = await Promise.race<IceServerConfig[]>([\n frame.getIceServers(),\n new Promise<IceServerConfig[]>((resolve) => setTimeout(() => resolve([]), 3000)),\n ])\n } catch {\n servers = []\n }\n const list = servers.length > 0 ? servers : STUN_FALLBACK.map((s) => ({\n urls: Array.isArray(s.urls) ? s.urls : [s.urls as string],\n }))\n return list.map((s) => ({\n urls: s.urls,\n username: (s as IceServerConfig).username,\n credential: (s as IceServerConfig).credential,\n }))\n}\n\n// ---------------------------------------------------------------------------\n// CRDT accessor helpers\n// ---------------------------------------------------------------------------\n\nfunction getDoc(frame: MediaLinkFrame) {\n return frame.crdt.doc\n}\n\nfunction getSignalMap(frame: MediaLinkFrame) {\n return getDoc(frame).getMap<string>(KEY_SIGNAL)\n}\n\nfunction getIceOffererArray(frame: MediaLinkFrame) {\n return getDoc(frame).getArray<string>(KEY_ICE_OFFERER)\n}\n\nfunction getIceAnswererArray(frame: MediaLinkFrame) {\n return getDoc(frame).getArray<string>(KEY_ICE_ANSWERER)\n}\n\nfunction getControlArray(frame: MediaLinkFrame) {\n return getDoc(frame).getArray<string>(KEY_CONTROL)\n}\n\nfunction getIceServersMap(frame: MediaLinkFrame) {\n return getDoc(frame).getMap<string>(KEY_ICE_SERVERS)\n}\n\n// Iterate new ICE entries from `from`, return updated count.\nfunction drainIce(\n arr: ReturnType<typeof getIceOffererArray>,\n from: number,\n sessionId: string,\n onCandidate: (c: RTCIceCandidateInit) => void,\n): number {\n const len = arr.length\n for (let i = from; i < len; i++) {\n try {\n const entry = JSON.parse(arr.get(i)) as TaggedIce\n if (entry.s === sessionId) onCandidate(entry.c)\n } catch {\n /* ignore malformed entry */\n }\n }\n return len\n}\n\n// Check the control array for a voluntary-stop entry for this session.\nfunction checkVoluntaryStop(\n frame: MediaLinkFrame,\n sessionId: string,\n): MediaLinkEndReason | null {\n const arr = getControlArray(frame)\n for (let i = 0; i < arr.length; i++) {\n try {\n const e = JSON.parse(arr.get(i)) as ControlEntry\n if (e.sessionId === sessionId) return e.ended\n } catch {\n /* ignore */\n }\n }\n return null\n}\n\n// Write a voluntary-stop entry.\nfunction writeControlStop(frame: MediaLinkFrame, sessionId: string, reason: MediaLinkEndReason): void {\n const entry: ControlEntry = { sessionId, ended: reason }\n getControlArray(frame).push([JSON.stringify(entry)])\n}\n\n// ---------------------------------------------------------------------------\n// Offerer implementation\n// ---------------------------------------------------------------------------\n\nclass MediaLinkImpl implements MediaLink {\n public state: MediaLinkState = 'connecting'\n public onStateChange?: (state: MediaLinkState) => void\n public onEnded?: (reason: MediaLinkEndReason) => void\n\n private pc: RTCPeerConnection | null = null\n private senders: RTCRtpSender[] = []\n private remoteSet = false\n private pendingRemote: RTCIceCandidateInit[] = []\n private processedIce = 0\n private stopped = false\n // FIX 3: separate flag so teardown() cleanup runs exactly once regardless\n // of whether the call came from stop() (after stopped=true) or externally.\n private tornDown = false\n\n // Retry state\n private retryCount = 0\n private graceTimer: ReturnType<typeof setTimeout> | null = null\n private retryTimer: ReturnType<typeof setTimeout> | null = null\n\n // CRDT observer references so we can unobserve\n private signalObserver: (() => void) | null = null\n private iceObserver: (() => void) | null = null\n private controlObserver: (() => void) | null = null\n\n private pagehideHandler: (() => void) | null = null\n\n /**\n * Resolved ICE server list shared across all ICE restarts of this session.\n * Set once during start() (after waiting for the Vitre-published list) and\n * reused by every subsequent initPeerConnection(iceRestart=true) call.\n */\n private resolvedIceServers: RTCIceServer[] | null = null\n\n constructor(\n public readonly sessionId: string,\n // Companion side: the offerer originates the link from a companion frame and\n // signals the Vitre connector via `frame.sendMessageToVitreConnector`.\n private readonly frame: CompanionFrame,\n private stream: MediaStream,\n private readonly options: Required<MediaLinkRetryOptions>,\n private readonly openAnswererFrame: boolean,\n private readonly receiverDisplay: 'standard' | 'appFrame' | undefined,\n private readonly metadata: unknown,\n private readonly vitreIceTimeoutMs: number,\n ) {}\n\n async start(): Promise<void> {\n // Register pagehide handler (best-effort voluntary signal on tab close).\n this.pagehideHandler = () => { this.stop() }\n window.addEventListener('pagehide', this.pagehideHandler)\n\n // IMPROVEMENT 7: prune stale CRDT entries from any previous session.\n // The design is single-active-session per frame doc: only one 'session'\n // key in the signal map, and growing ICE/control arrays. At the start of\n // each new offerer session we delete all entries in both ICE arrays and\n // the control array whose sessionId differs from our new sessionId. This\n // bounds CRDT growth to O(1 session) rather than O(lifetime of the frame).\n // Also clear a stale 'iceServers' map entry from a previous session so the\n // offerer cannot accidentally consume it (the answerer overwrites per session\n // anyway, but an extra guard here makes stale-entry reasoning explicit).\n const doc = this.frame.crdt.doc\n doc.transact(() => {\n const iceOfferer = getIceOffererArray(this.frame)\n const iceAnswerer = getIceAnswererArray(this.frame)\n const controlArr = getControlArray(this.frame)\n const iceServersMap = getIceServersMap(this.frame)\n // Delete indices in reverse so removal does not shift subsequent indices.\n const pruneArray = (arr: ReturnType<typeof getIceOffererArray>) => {\n const toDelete: number[] = []\n for (let i = 0; i < arr.length; i++) {\n try {\n const e = JSON.parse(arr.get(i)) as { s?: string }\n if (e.s !== this.sessionId) toDelete.push(i)\n } catch { toDelete.push(i) }\n }\n for (let i = toDelete.length - 1; i >= 0; i--) {\n arr.delete(toDelete[i]!, 1)\n }\n }\n pruneArray(iceOfferer)\n pruneArray(iceAnswerer)\n pruneArray(controlArr)\n // Clear a stale iceServers entry from a prior session.\n const rawIce = iceServersMap.get('servers')\n if (rawIce) {\n try {\n const existing = JSON.parse(rawIce) as IceServersEntry\n if (existing.s !== this.sessionId) iceServersMap.delete('servers')\n } catch { iceServersMap.delete('servers') }\n }\n })\n\n // Step 1: publish a session-request (no offer yet) so a late-joining\n // answerer frame sees this session after CRDT sync and can start resolving\n // its ICE servers immediately.\n const sessionRequest: SignalEntry = {\n sessionId: this.sessionId,\n receiverDisplay: this.receiverDisplay,\n metadata: this.metadata,\n // offer is intentionally absent — this is a session-request only.\n }\n doc.transact(() => {\n getSignalMap(this.frame).set('session', JSON.stringify(sessionRequest))\n })\n\n // Step 2: send the open-answerer message AFTER writing the session-request\n // so the answerer frame (if it opens late) finds the session-request in the\n // CRDT on first sync.\n if (this.openAnswererFrame) {\n const msg: MediaLinkOpenAnswererMessage = {\n type: 'lavitre-media-link',\n action: 'open-answerer',\n frameConnectorId: this.frame.id,\n sessionId: this.sessionId,\n }\n this.frame.sendMessageToVitreConnector(JSON.stringify(msg))\n }\n\n // Step 3: race the vitre ICE list against the companion fallback and the\n // timeout. Start the companion-side resolve immediately in parallel.\n const companionIcePromise = resolveIceServers(this.frame)\n\n const vitreIcePromise = new Promise<IceServerConfig[] | null>((resolve) => {\n const iceServersMap = getIceServersMap(this.frame)\n const timeout = setTimeout(() => {\n iceServersMap.unobserve(observer)\n resolve(null)\n }, this.vitreIceTimeoutMs)\n\n const tryRead = (): boolean => {\n const raw = iceServersMap.get('servers')\n if (!raw) return false\n try {\n const entry = JSON.parse(raw) as IceServersEntry\n if (entry.s !== this.sessionId) return false\n if (!Array.isArray(entry.servers) || entry.servers.length === 0) return false\n clearTimeout(timeout)\n iceServersMap.unobserve(observer)\n resolve(entry.servers)\n return true\n } catch { return false }\n }\n\n const observer = () => { tryRead() }\n iceServersMap.observe(observer)\n // Check for an entry that was already present before we subscribed.\n tryRead()\n })\n\n // Pick the best available ICE servers: vitre > companion > public STUN.\n const vitreServers = await vitreIcePromise\n let iceServers: RTCIceServer[]\n if (vitreServers !== null && vitreServers.length > 0) {\n iceServers = vitreServers.map((s) => ({\n urls: s.urls,\n username: s.username,\n credential: s.credential,\n }))\n } else {\n // Fall back to companion-side result (already resolving in parallel).\n iceServers = await companionIcePromise\n }\n\n // stop() may have torn the link down while we awaited the ICE servers\n // (up to vitreIceTimeoutMs) — do not build a PC that nobody would close.\n if (this.tornDown) return\n\n // Store for reuse across ICE restarts of this session.\n this.resolvedIceServers = iceServers\n\n await this.initPeerConnection()\n }\n\n private async initPeerConnection(iceRestart = false): Promise<void> {\n // Reuse the ICE server list resolved during start() for all restarts of\n // this session. On the first call (iceRestart=false) resolvedIceServers is\n // already set by start(); on subsequent calls it is the stored value.\n const iceServers = this.resolvedIceServers ?? STUN_FALLBACK\n const pc = new RTCPeerConnection({ iceServers })\n this.pc = pc\n // --- ICE/TURN diagnostics (offerer). Reveals whether TURN servers were handed\n // out, ICE negotiation progress, and TURN auth failures (errorCode 401/403 =\n // expired/invalid credentials — the classic cause of an intermittent black frame).\n const turnCount = iceServers.filter((s) => {\n const urls = Array.isArray(s.urls) ? s.urls : [s.urls]\n return urls.some((u) => typeof u === 'string' && u.startsWith('turn'))\n }).length\n console.log('[lavitre-apps][MediaLink] pc-init offerer ' + JSON.stringify({ servers: iceServers.length, turn: turnCount, iceRestart }))\n pc.oniceconnectionstatechange = () => {\n if (this.pc === pc) console.log('[lavitre-apps][MediaLink] iceState offerer', pc.iceConnectionState)\n }\n pc.onicecandidateerror = (ev) => {\n console.warn('[lavitre-apps][MediaLink] ice-error offerer ' + JSON.stringify({ code: ev.errorCode, url: ev.url, text: ev.errorText }))\n }\n this.senders = []\n this.remoteSet = false\n this.pendingRemote = []\n // Keep the ice processed index across ICE restarts so we don't re-add old\n // candidates. For a full new session (first call) it starts at 0; for a\n // restart the CRDT arrays keep growing, so we advance from the current tip.\n if (!iceRestart) {\n this.processedIce = 0\n }\n\n for (const track of this.stream.getTracks()) {\n this.senders.push(pc.addTrack(track, this.stream))\n }\n\n pc.onicecandidate = (e) => {\n if (e.candidate && this.pc === pc) {\n const tagged: TaggedIce = { s: this.sessionId, c: e.candidate.toJSON() }\n getIceOffererArray(this.frame).push([JSON.stringify(tagged)])\n }\n }\n\n pc.onconnectionstatechange = () => {\n if (this.stopped || this.pc !== pc) return\n const cs = pc.connectionState\n console.log('[lavitre-apps][MediaLink] connState offerer', cs)\n if (cs === 'connected') {\n this.clearTimers()\n this.retryCount = 0\n this.setState('connected')\n } else if (cs === 'disconnected') {\n this.setState('reconnecting')\n this.graceTimer = setTimeout(() => {\n this.graceTimer = null\n if (!this.stopped && this.pc === pc) this.attemptRestart()\n }, this.options.graceMs)\n } else if (cs === 'failed') {\n this.clearTimers()\n this.attemptRestart()\n }\n }\n\n const signalMap = getSignalMap(this.frame)\n const vitreIce = getIceAnswererArray(this.frame)\n const controlArr = getControlArray(this.frame)\n\n // Drain remote ICE from the answerer array.\n const drainRemote = () => {\n if (!this.pc || this.pc !== pc) return\n this.processedIce = drainIce(vitreIce, this.processedIce, this.sessionId, (c) => {\n if (this.remoteSet) void pc.addIceCandidate(c).catch(() => {})\n else this.pendingRemote.push(c)\n })\n }\n\n // Handle the answer arriving in the signal map.\n const onSignal = () => {\n if (this.remoteSet || !this.pc || this.pc !== pc) return\n const raw = signalMap.get('session')\n if (!raw) return\n let entry: SignalEntry\n try { entry = JSON.parse(raw) } catch { return }\n if (entry.sessionId !== this.sessionId) return\n const answer = entry.answer\n if (!answer) return\n void pc.setRemoteDescription({ type: 'answer', sdp: answer })\n .then(() => {\n if (this.pc !== pc) return\n this.remoteSet = true\n for (const c of this.pendingRemote.splice(0)) {\n void pc.addIceCandidate(c).catch(() => {})\n }\n drainRemote()\n })\n .catch((err) => console.error('[lavitre-apps] MediaLink setRemoteDescription(answer)', err))\n }\n\n // Watch for voluntary stop from the answerer side.\n const onControl = () => {\n if (this.stopped) return\n const reason = checkVoluntaryStop(this.frame, this.sessionId)\n if (reason != null) this.teardown('remote-user')\n }\n\n if (this.signalObserver) signalMap.unobserve(this.signalObserver)\n if (this.iceObserver) vitreIce.unobserve(this.iceObserver)\n if (this.controlObserver) controlArr.unobserve(this.controlObserver)\n\n this.signalObserver = onSignal\n this.iceObserver = drainRemote\n this.controlObserver = onControl\n\n signalMap.observe(onSignal)\n vitreIce.observe(drainRemote)\n controlArr.observe(onControl)\n\n // Create and publish the offer, merging into the existing session-request\n // entry (written by start()) to preserve sessionId/receiverDisplay/metadata.\n const offerOptions = iceRestart ? ICE_RESTART_OFFER_OPTIONS : undefined\n const offer = await pc.createOffer(offerOptions)\n await pc.setLocalDescription(offer)\n\n const doc = this.frame.crdt.doc\n doc.transact(() => {\n const existing = (() => {\n const raw = signalMap.get('session')\n if (!raw) return null\n try { return JSON.parse(raw) as SignalEntry } catch { return null }\n })()\n const entry: SignalEntry = {\n ...(existing ?? {}),\n sessionId: this.sessionId,\n offer: offer.sdp ?? '',\n receiverDisplay: this.receiverDisplay,\n metadata: this.metadata,\n }\n signalMap.set('session', JSON.stringify(entry))\n })\n\n // Catch state that synced before observers attached.\n onSignal()\n drainRemote()\n onControl()\n }\n\n private async attemptRestart(): Promise<void> {\n if (this.stopped) return\n if (this.retryCount >= this.options.attempts) {\n this.teardown('failure')\n return\n }\n\n const delayMs = this.options.backoffMs[\n Math.min(this.retryCount, this.options.backoffMs.length - 1)\n ] ?? 0\n this.retryCount++\n this.setState('reconnecting')\n\n this.retryTimer = setTimeout(async () => {\n this.retryTimer = null\n if (this.stopped) return\n // Close old PC before creating new one.\n const oldPc = this.pc\n this.pc = null\n if (oldPc) {\n oldPc.onicecandidate = null\n oldPc.onconnectionstatechange = null\n oldPc.close()\n }\n try {\n await this.initPeerConnection(true)\n } catch (err) {\n console.error('[lavitre-apps] MediaLink ICE restart failed', err)\n this.attemptRestart()\n }\n }, delayMs)\n }\n\n async replaceStream(stream: MediaStream): Promise<void> {\n // FIX 4: no-op if torn down or PC is gone.\n if (this.tornDown || !this.pc) return\n this.stream = stream\n const tracks = stream.getTracks()\n const replacePromises: Promise<void>[] = []\n for (const sender of this.senders) {\n // FIX 4: skip senders whose track is null (e.g. ended track removed by browser).\n if (!sender.track) continue\n const newTrack = tracks.find((t) => t.kind === sender.track?.kind)\n if (newTrack) replacePromises.push(sender.replaceTrack(newTrack))\n }\n await Promise.all(replacePromises)\n }\n\n stop(): void {\n if (this.stopped) return\n // FIX 3: set stopped=true BEFORE writing the control entry. The CRDT write\n // triggers the local onControl observer synchronously, which calls\n // teardown('remote-user'). With stopped=true set, that re-entrant call hits\n // the tornDown guard and returns early; then teardown('user') below runs\n // the actual cleanup.\n this.stopped = true\n writeControlStop(this.frame, this.sessionId, 'user')\n // Reliable close signal to the Vitre answerer via the host channel — more\n // likely to flush on companion-frame unmount/back than the P2P CRDT control,\n // so the answerer frame closes promptly. Mirrors the open-answerer send.\n if (this.openAnswererFrame) {\n try {\n const closeMsg: MediaLinkOpenAnswererMessage = {\n type: 'lavitre-media-link',\n action: 'close-answerer',\n frameConnectorId: this.frame.id,\n sessionId: this.sessionId,\n }\n this.frame.sendMessageToVitreConnector(JSON.stringify(closeMsg))\n } catch {\n /* best-effort */\n }\n }\n this.teardown('user')\n }\n\n /** Internal teardown. Guards on tornDown so the cleanup body runs exactly once. */\n private teardown(reason: MediaLinkEndReason): void {\n // FIX 3: guard on tornDown (not stopped) — stop() sets stopped=true before\n // writing the control entry, whose synchronous observer fires teardown\n // ('remote-user'); that hits this guard and exits; then stop() calls\n // teardown('user') which performs the cleanup exactly once.\n if (this.tornDown) return\n this.tornDown = true\n this.stopped = true\n\n // Remove pagehide listener.\n if (this.pagehideHandler) {\n window.removeEventListener('pagehide', this.pagehideHandler)\n this.pagehideHandler = null\n }\n\n this.clearTimers()\n\n // Unsubscribe CRDT observers.\n const signalMap = getSignalMap(this.frame)\n const vitreIce = getIceAnswererArray(this.frame)\n const controlArr = getControlArray(this.frame)\n if (this.signalObserver) { signalMap.unobserve(this.signalObserver); this.signalObserver = null }\n if (this.iceObserver) { vitreIce.unobserve(this.iceObserver); this.iceObserver = null }\n if (this.controlObserver) { controlArr.unobserve(this.controlObserver); this.controlObserver = null }\n\n // Close the PC.\n if (this.pc) {\n this.pc.onicecandidate = null\n this.pc.onconnectionstatechange = null\n this.pc.close()\n this.pc = null\n }\n\n this.setState('ended')\n this.onEnded?.(reason)\n }\n\n private setState(s: MediaLinkState): void {\n if (this.state === s) return\n ;(this as { state: MediaLinkState }).state = s\n this.onStateChange?.(s)\n }\n\n private clearTimers(): void {\n if (this.graceTimer != null) { clearTimeout(this.graceTimer); this.graceTimer = null }\n if (this.retryTimer != null) { clearTimeout(this.retryTimer); this.retryTimer = null }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Answerer implementation\n// ---------------------------------------------------------------------------\n\n// The answerer does not drive ICE recovery (the offerer does). If the offerer\n// vanishes WITHOUT a clean control-stop (e.g. the companion frame is closed and\n// its CRDT 'ended' write never flushes), the connection goes disconnected/failed\n// and nothing would ever end the session — so closeOnEnd and the app's onEnded\n// would hang forever. After this grace window with no recovery, the answerer\n// ends the session itself. Longer than the offerer's ICE-restart cycle so a real\n// reconnection wins first.\nconst ANSWERER_DISCONNECT_GRACE_MS = 10000\n\nclass AnsweredMediaLinkImpl implements AnsweredMediaLink {\n public onStreamChanged?: (stream: MediaStream) => void\n public onStateChange?: (state: MediaLinkState) => void\n public onEnded?: (reason: MediaLinkEndReason) => void\n\n private pc: RTCPeerConnection | null = null\n private _stream: MediaStream | null = null\n private remoteSet = false\n private pendingRemote: RTCIceCandidateInit[] = []\n private processedIce = 0\n private stopped = false\n // Separate flag used by teardown so that teardown()'s cleanup body runs\n // exactly once regardless of the call path (stop() vs. external teardown()).\n private tornDown = false\n // FIX 2: track the last offer SDP we processed to avoid re-triggering\n // handleOffer when the answerer itself writes its answer into the session\n // entry (the CRDT observer fires again with the same offer still present).\n private lastProcessedOfferSdp: string | null = null\n // Backstop timer: armed on a sustained disconnect with no offerer recovery,\n // it ends the session so closeOnEnd / onEnded don't hang (see the const above).\n private endTimer: ReturnType<typeof setTimeout> | null = null\n\n // CRDT observer references\n private signalObserver: (() => void) | null = null\n private iceObserver: (() => void) | null = null\n private controlObserver: (() => void) | null = null\n\n constructor(\n public readonly sessionId: string,\n private readonly frame: Frame,\n public readonly receiverDisplay: 'standard' | 'appFrame' | undefined,\n public readonly metadata: unknown,\n private readonly onStreamReady: (link: AnsweredMediaLink) => void,\n ) {}\n\n get stream(): MediaStream {\n if (!this._stream) throw new Error('[lavitre-apps] AnsweredMediaLink: stream not yet available')\n return this._stream\n }\n\n async initiate(offerSdp: string, currentIceOffererTip: number): Promise<void> {\n const iceServers = await resolveIceServers(this.frame)\n const pc = new RTCPeerConnection({ iceServers })\n this.pc = pc\n // --- ICE/TURN diagnostics (answerer = the Vitre that reshares). Same signals as\n // the offerer: TURN handed out?, ICE progress, TURN auth failures (401/403).\n const turnCount = iceServers.filter((s) => {\n const urls = Array.isArray(s.urls) ? s.urls : [s.urls]\n return urls.some((u) => typeof u === 'string' && u.startsWith('turn'))\n }).length\n console.log('[lavitre-apps][MediaLink] pc-init answerer ' + JSON.stringify({ servers: iceServers.length, turn: turnCount }))\n pc.oniceconnectionstatechange = () => {\n if (this.pc === pc) console.log('[lavitre-apps][MediaLink] iceState answerer', pc.iceConnectionState)\n }\n pc.onicecandidateerror = (ev) => {\n console.warn('[lavitre-apps][MediaLink] ice-error answerer ' + JSON.stringify({ code: ev.errorCode, url: ev.url, text: ev.errorText }))\n }\n this.remoteSet = false\n this.pendingRemote = []\n this.processedIce = currentIceOffererTip\n\n pc.ontrack = (e) => {\n if (this.pc !== pc) return\n const incoming = e.streams[0] ?? new MediaStream([e.track])\n if (!this._stream) {\n this._stream = incoming\n // Notify the handler: the link is ready for the app.\n this.onStreamReady(this)\n } else {\n // Subsequent tracks (e.g. audio added after video).\n this._stream = incoming\n this.onStreamChanged?.(this._stream)\n }\n }\n\n // FIX 1: answerer trickle ICE — publish answerer candidates so the offerer\n // can drain them from getIceAnswererArray. Guard this.pc === pc to discard\n // stale events after an ICE restart replaces the peer connection.\n pc.onicecandidate = (e) => {\n if (e.candidate && this.pc === pc) {\n const tagged: TaggedIce = { s: this.sessionId, c: e.candidate.toJSON() }\n getIceAnswererArray(this.frame).push([JSON.stringify(tagged)])\n }\n }\n\n pc.onconnectionstatechange = () => {\n if (this.stopped || this.pc !== pc) return\n const cs = pc.connectionState\n console.log('[lavitre-apps][MediaLink] connState answerer', cs)\n if (cs === 'connected') {\n if (this.endTimer) { clearTimeout(this.endTimer); this.endTimer = null }\n this.emitState('connected')\n } else if (cs === 'failed' || cs === 'disconnected') {\n // Answerer does not retry; recovery is offerer-driven (ICE restart).\n // Reflect 'reconnecting' so the app can react. A clean stop still ends\n // the session sooner via the control observer. But if the offerer is\n // GONE (e.g. companion frame closed without flushing its 'ended' write),\n // no restart will come — so arm a grace timer to end the session\n // ourselves; otherwise the answerer (and closeOnEnd) would hang forever.\n this.emitState('reconnecting')\n if (!this.endTimer) {\n this.endTimer = setTimeout(() => {\n this.endTimer = null\n if (!this.stopped && this.pc === pc && pc.connectionState !== 'connected') {\n this.teardown('failure')\n }\n }, ANSWERER_DISCONNECT_GRACE_MS)\n }\n }\n }\n\n const offererIce = getIceOffererArray(this.frame)\n const signalMap = getSignalMap(this.frame)\n const controlArr = getControlArray(this.frame)\n\n const drainOffererIce = () => {\n if (!this.pc || this.pc !== pc) return\n this.processedIce = drainIce(offererIce, this.processedIce, this.sessionId, (c) => {\n if (this.remoteSet) void pc.addIceCandidate(c).catch(() => {})\n else this.pendingRemote.push(c)\n })\n }\n\n // Watch for a re-offer (ICE restart from the offerer side).\n // FIX 2: guard against the answerer's own answer-write re-triggering this\n // handler. When the answerer writes its answer into the 'session' entry the\n // CRDT observer fires again — the entry still carries .offer so without\n // the guard handleOffer would run again on a stable PC, creating an\n // unbounded loop. We skip if the offer SDP has not changed since we last\n // processed it; ICE-restart offers carry a different SDP and still pass.\n const onSignal = () => {\n if (!this.pc || this.pc !== pc || this.stopped) return\n const raw = signalMap.get('session')\n if (!raw) return\n let entry: SignalEntry\n try { entry = JSON.parse(raw) } catch { return }\n if (entry.sessionId !== this.sessionId || !entry.offer) return\n if (entry.offer === this.lastProcessedOfferSdp) return\n // Re-offer arrived: re-answer (ICE restart or first answer).\n void this.handleOffer(entry.offer)\n }\n\n const onControl = () => {\n if (this.stopped) return\n const reason = checkVoluntaryStop(this.frame, this.sessionId)\n if (reason != null) this.teardown('remote-user')\n }\n\n if (this.signalObserver) signalMap.unobserve(this.signalObserver)\n if (this.iceObserver) offererIce.unobserve(this.iceObserver)\n if (this.controlObserver) controlArr.unobserve(this.controlObserver)\n\n this.signalObserver = onSignal\n this.iceObserver = drainOffererIce\n this.controlObserver = onControl\n\n signalMap.observe(onSignal)\n offererIce.observe(drainOffererIce)\n controlArr.observe(onControl)\n\n // FIX 2: record the initial offer SDP before processing so that the CRDT\n // observer fired by our own answer-write below sees it and returns early.\n this.lastProcessedOfferSdp = offerSdp\n await pc.setRemoteDescription({ type: 'offer', sdp: offerSdp })\n this.remoteSet = true\n for (const c of this.pendingRemote.splice(0)) {\n void pc.addIceCandidate(c).catch(() => {})\n }\n\n const answer = await pc.createAnswer()\n await pc.setLocalDescription(answer)\n\n // Publish the answer into the existing session entry.\n const raw = signalMap.get('session')\n if (raw) {\n try {\n const existing = JSON.parse(raw) as SignalEntry\n const updated: SignalEntry = { ...existing, answer: answer.sdp ?? '' }\n signalMap.set('session', JSON.stringify(updated))\n } catch {\n signalMap.set('session', JSON.stringify({ sessionId: this.sessionId, answer: answer.sdp ?? '' }))\n }\n }\n\n drainOffererIce()\n onControl()\n }\n\n /** Handle a re-offer (ICE restart) from the offerer. */\n private async handleOffer(offerSdp: string): Promise<void> {\n if (!this.pc || this.stopped) return\n // FIX 2: record the SDP we are about to process BEFORE any async work so\n // that the synchronous CRDT observer fired by our own answer-write below\n // sees it and returns early (same SDP = already handled).\n this.lastProcessedOfferSdp = offerSdp\n const pc = this.pc\n try {\n await pc.setRemoteDescription({ type: 'offer', sdp: offerSdp })\n this.remoteSet = true\n const answer = await pc.createAnswer()\n await pc.setLocalDescription(answer)\n\n const signalMap = getSignalMap(this.frame)\n const raw = signalMap.get('session')\n if (raw) {\n try {\n const existing = JSON.parse(raw) as SignalEntry\n const updated: SignalEntry = { ...existing, answer: answer.sdp ?? '' }\n signalMap.set('session', JSON.stringify(updated))\n } catch {\n signalMap.set('session', JSON.stringify({ sessionId: this.sessionId, answer: answer.sdp ?? '' }))\n }\n }\n } catch (err) {\n console.error('[lavitre-apps] AnsweredMediaLink handleOffer', err)\n }\n }\n\n stop(): void {\n if (this.stopped) return\n // FIX 3: set stopped=true BEFORE writing the control entry. The CRDT write\n // triggers the local onControl observer synchronously, which calls\n // teardown('remote-user'). With stopped=true already set, that call is a\n // no-op on the stopped guard, but teardown('user') below must still run\n // the cleanup — so teardown guards on the separate tornDown flag, not on\n // stopped.\n this.stopped = true\n writeControlStop(this.frame, this.sessionId, 'user')\n this.teardown('user')\n }\n\n teardown(reason: MediaLinkEndReason): void {\n // FIX 3: guard on tornDown (not stopped) so that the cleanup body runs\n // exactly once regardless of path — stop() sets stopped=true before writing\n // the control entry, which fires onControl→teardown('remote-user')\n // synchronously; that call hits this guard and returns early; then\n // stop() continues and calls teardown('user') which runs the cleanup.\n if (this.tornDown) return\n this.tornDown = true\n this.stopped = true\n if (this.endTimer) { clearTimeout(this.endTimer); this.endTimer = null }\n // FIX 2: reset lastProcessedOfferSdp on teardown.\n this.lastProcessedOfferSdp = null\n\n const signalMap = getSignalMap(this.frame)\n const offererIce = getIceOffererArray(this.frame)\n const controlArr = getControlArray(this.frame)\n if (this.signalObserver) { signalMap.unobserve(this.signalObserver); this.signalObserver = null }\n if (this.iceObserver) { offererIce.unobserve(this.iceObserver); this.iceObserver = null }\n if (this.controlObserver) { controlArr.unobserve(this.controlObserver); this.controlObserver = null }\n\n if (this.pc) {\n this.pc.ontrack = null\n this.pc.onicecandidate = null\n this.pc.onconnectionstatechange = null\n this.pc.close()\n this.pc = null\n }\n\n this.emitState('ended')\n this.onEnded?.(reason)\n }\n\n private emitState(s: MediaLinkState): void {\n this.onStateChange?.(s)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Companion-frame side — the offerer.\n *\n * Acquires ICE servers, creates an `RTCPeerConnection` with the given stream,\n * publishes the offer over the frame CRDT doc, and optionally requests that\n * the answerer frame be opened on the Vitre via\n * `frame.sendMessageToVitreConnector`. Resolves with a {@link MediaLink}\n * handle once the local description is set (i.e. signalling is in flight).\n *\n * Call `connector.openFrame(frameConnectorId, ...)` on the Vitre side (or use\n * {@link enableMediaLinkAnswerer}) BEFORE calling this so the answerer frame\n * is ready to receive the offer when the CRDT syncs. If `requestAnswererFrame`\n * is true (default) the SDK sends the control message automatically.\n *\n * @param frame The companion frame (`CompanionFrame`, from `initializeCompanionFrame`).\n * @param stream The `MediaStream` to send to the Vitre frame.\n * @param options Optional configuration (retry, metadata, display mode…).\n */\nexport async function startMediaLink(\n frame: CompanionFrame,\n stream: MediaStream,\n options?: StartMediaLinkOptions,\n): Promise<MediaLink> {\n const sessionId = crypto.randomUUID()\n const retryOpts: Required<MediaLinkRetryOptions> = {\n graceMs: options?.retry?.graceMs ?? 3000,\n attempts: options?.retry?.attempts ?? 3,\n backoffMs: options?.retry?.backoffMs ?? [2000, 4000, 8000],\n }\n const link = new MediaLinkImpl(\n sessionId,\n frame,\n stream,\n retryOpts,\n options?.requestAnswererFrame !== false,\n options?.receiverDisplay,\n options?.metadata,\n options?.vitreIceTimeoutMs ?? 8000,\n )\n // Attach the callbacks BEFORE start() so no state transition can be missed\n // (start() awaits ICE resolution; a fast answer could otherwise fire\n // 'connected' before the caller had a chance to assign the handlers).\n if (options?.onStateChange) link.onStateChange = options.onStateChange\n if (options?.onEnded) link.onEnded = options.onEnded\n await link.start()\n return link\n}\n\n/**\n * Vitre-frame side — subscribe to incoming media link sessions.\n *\n * The handler fires once per session (including sessions already present in\n * the CRDT doc at the time of subscription — late-join). Each invocation\n * provides an {@link AnsweredMediaLink} with the remote stream and teardown\n * handle. The caller is responsible for calling `frame.shareStream(link.stream)`\n * (or equivalent) to route the stream to the space.\n *\n * Returns an unsubscribe function that stops watching for new sessions. Existing\n * {@link AnsweredMediaLink} handles are NOT torn down by unsubscribing — each\n * must be ended explicitly via `link.stop()` or via the offerer's `stop()`.\n *\n * @param frame The Vitre-side frame (`Frame`).\n * @param handler Called for every new (or already-present) incoming session.\n * @returns Unsubscribe function.\n */\nexport function onMediaLink(\n frame: Frame,\n handler: (link: AnsweredMediaLink) => void,\n): () => void {\n const signalMap = getSignalMap(frame)\n // Track sessions already handled so the CRDT observer doesn't re-fire them.\n const seen = new Set<string>()\n // Track sessions for which we have published our ICE servers but the offer\n // has not yet arrived — prevents re-publishing on every CRDT tick.\n const icePublished = new Set<string>()\n // Cleared by the unsubscribe function: stops in-flight async ICE publishes\n // from writing to the CRDT after the caller unsubscribed, and lets a later\n // re-subscribe publish again for fresh sessions.\n let active = true\n\n const processSignal = () => {\n const raw = signalMap.get('session')\n if (!raw) return\n let entry: SignalEntry\n try { entry = JSON.parse(raw) } catch { return }\n const { sessionId, offer, receiverDisplay, metadata } = entry\n if (!sessionId) return\n\n if (!seen.has(sessionId)) {\n // A new session (with or without an offer) has appeared. The answerer\n // must resolve the Vitre's ICE servers and publish them exactly once for\n // this session so the offerer can consume them before building its PC.\n if (!icePublished.has(sessionId)) {\n icePublished.add(sessionId)\n void (async () => {\n let servers: IceServerConfig[] = []\n try { servers = await frame.getIceServers() } catch { servers = [] }\n if (!active) return // unsubscribed while resolving — do not write\n if (!servers.length) return // nothing useful to publish; offerer falls back naturally\n const iceEntry: IceServersEntry = { s: sessionId, servers }\n getIceServersMap(frame).set('servers', JSON.stringify(iceEntry))\n })()\n }\n }\n\n // Wait until the offer arrives before creating the answerer impl.\n if (!offer) return\n if (seen.has(sessionId)) return\n seen.add(sessionId)\n\n // Snapshot the current tip of the offerer ICE array so the answerer\n // doesn't try to process offerer candidates that were published before\n // this session's offer.\n const iceOffererTip = getIceOffererArray(frame).length\n\n const link = new AnsweredMediaLinkImpl(\n sessionId,\n frame,\n receiverDisplay,\n metadata,\n handler,\n )\n void link.initiate(offer, iceOffererTip).catch((err) => {\n console.error('[lavitre-apps] AnsweredMediaLink initiate', err)\n })\n }\n\n signalMap.observe(processSignal)\n // Catch a session that was already in the CRDT when this observer attached.\n processSignal()\n\n return () => {\n active = false\n signalMap.unobserve(processSignal)\n }\n}\n\n/**\n * Vitre CONNECTOR helper — automatically opens the answerer frame when a\n * companion frame requests it via the `lavitre-media-link` control message,\n * and closes it again when the last link of that frame ends (configurable).\n *\n * Wire this in the Connector's `onMessageFromCompanionFrame` on the Vitre side:\n * ```ts\n * const unsub = enableMediaLinkAnswerer(connector, {\n * url: 'https://my-app.apps.lavit.re/frame.html',\n * name: 'My App',\n * })\n * // Later:\n * unsub()\n * ```\n *\n * **Frame id matching**: the companion mints a per-session id of the form\n * `<appId>-<uuid>` and sends it in the `open-answerer` message. This helper\n * matches incoming messages by prefix:\n * - exact match: `msgFrameConnectorId === prefix`\n * - prefix match: `msgFrameConnectorId.startsWith(prefix + '-')`\n *\n * `frameConnectorId` (optional): the match prefix. Defaults to `connector.appId`\n * so apps that omit it work without any configuration. An app can still pass a\n * fixed string for backward compatibility — it matches via the `===` arm.\n *\n * The answerer frame is opened with the **companion-minted id** received in the\n * message (not a fixed constant), so re-share / concurrent sessions each get a\n * distinct frame and SharedContentId — stale state never leaks across sessions.\n *\n * `closeOnEnd` (default `true`): when the last active session for this frame\n * ends, the connector calls `connector.closeFrame(currentFrameId)`.\n *\n * @returns Unsubscribe function.\n */\nexport function enableMediaLinkAnswerer(\n connector: Connector,\n opts: {\n /** Match prefix. Defaults to `connector.appId`. */\n frameConnectorId?: string\n url: string\n name?: string\n closeOnEnd?: boolean\n size?: { width: number; height: number }\n },\n): () => void {\n const { url, name, closeOnEnd = true, size } = opts\n // Default the match prefix to the connector's appId so callers that omit\n // frameConnectorId work without any extra configuration.\n const prefix = opts.frameConnectorId ?? connector.appId\n let isOpen = false\n let activeSessions = 0\n // The companion-minted frame id of the currently-open answerer frame.\n // Set on the first matching open-answerer; reset to null on frame unload.\n let currentFrameId: string | null = null\n // Sessions whose open-answerer arrived before the answerer frame finished\n // loading (getFrameConnector returns undefined until then). Drained when\n // openFrame resolves; cleared on frame unload.\n const pendingSessions = new Set<string>()\n\n // IMPROVEMENT 6: per-session CRDT control observers, keyed by sessionId.\n // Kept here (outside the message handler) so that the frameUnloaded handler\n // installed ONCE below can unobserve all of them on frame close.\n const sessionControlObservers = new Map<string, { arr: ReturnType<typeof getControlArray>; obs: () => void }>()\n\n const previousHandler = connector.onMessageFromCompanionFrame\n const previousUnloadedHandler = connector.onFrameUnloaded\n\n // IMPROVEMENT 6: register onFrameUnloaded ONCE at setup time (not per session).\n // Capture the previous handler and call it first (same chain pattern used for\n // onMessageFromCompanionFrame). Restore-on-unsubscribe only if our closure is\n // still installed.\n const unloadedHandler = (unloadedId: string) => {\n previousUnloadedHandler?.(unloadedId)\n if (unloadedId === currentFrameId) {\n isOpen = false\n activeSessions = 0\n pendingSessions.clear()\n currentFrameId = null\n // Unobserve all per-session CRDT observers accumulated so far.\n for (const { arr, obs } of sessionControlObservers.values()) {\n arr.unobserve(obs)\n }\n sessionControlObservers.clear()\n }\n }\n connector.onFrameUnloaded = unloadedHandler\n\n const handler = (\n fromCompanionId: string,\n msgFrameConnectorId: string,\n message: string,\n ) => {\n // Forward to any previously-registered handler first.\n previousHandler?.(fromCompanionId, msgFrameConnectorId, message)\n\n // Accept messages whose frame id matches the prefix exactly (backward-compat\n // with a fixed id) OR starts with `<prefix>-` (UUID-suffixed per-session id).\n if (msgFrameConnectorId !== prefix && !msgFrameConnectorId.startsWith(prefix + '-')) return\n\n let parsed: unknown\n try { parsed = JSON.parse(message) } catch { return }\n if (!isMediaLinkOpenAnswererMessage(parsed)) return\n\n // Explicit close from the companion frame (sent on its stop/unmount). This is\n // the reliable, prompt close path — it does not depend on the P2P CRDT control\n // flushing during teardown. Drop that session and close the frame if it was\n // the last one.\n if (parsed.action === 'close-answerer') {\n const sid = parsed.sessionId\n const entry = sessionControlObservers.get(sid)\n if (entry) {\n entry.arr.unobserve(entry.obs)\n sessionControlObservers.delete(sid)\n }\n pendingSessions.delete(sid)\n activeSessions = Math.max(0, activeSessions - 1)\n if (activeSessions === 0 && isOpen && currentFrameId) {\n const frameToClose = currentFrameId\n isOpen = false\n currentFrameId = null\n connector.closeFrame(frameToClose)\n }\n return\n }\n\n if (parsed.action !== 'open-answerer') return\n\n activeSessions++\n\n const sessionId = (parsed as MediaLinkOpenAnswererMessage).sessionId\n\n // Register the per-session CRDT control observer that detects a voluntary\n // stop. `getFrameConnector` only returns once the answerer frame is LOADED,\n // so if it isn't yet — the first session triggers openFrame, or another\n // session arrives during that load — the sessionId is queued (see\n // pendingSessions) and wired when openFrame resolves below. The observer is\n // stored in sessionControlObservers (keyed by sessionId) so the single\n // onFrameUnloaded handler above can clean them all up on frame close.\n const registerSessionObserver = (sid: string) => {\n if (!closeOnEnd) return\n if (sessionControlObservers.has(sid)) return\n if (!currentFrameId) {\n pendingSessions.add(sid)\n return\n }\n const frameConnector = connector.getFrameConnector(currentFrameId)\n if (!frameConnector) {\n pendingSessions.add(sid)\n return\n }\n const controlArr = getControlArray(frameConnector)\n const onControl = () => {\n if (!currentFrameId) return\n const reason = checkVoluntaryStop(frameConnector, sid)\n if (reason != null) {\n controlArr.unobserve(onControl)\n sessionControlObservers.delete(sid)\n activeSessions = Math.max(0, activeSessions - 1)\n if (activeSessions === 0 && isOpen && currentFrameId) {\n const frameToClose = currentFrameId\n isOpen = false\n currentFrameId = null\n connector.closeFrame(frameToClose)\n }\n }\n }\n controlArr.observe(onControl)\n sessionControlObservers.set(sid, { arr: controlArr, obs: onControl })\n }\n\n if (!isOpen) {\n isOpen = true\n // The answerer frame is opened with the companion-minted id so each\n // re-share / concurrent session gets a distinct frame and SharedContentId.\n currentFrameId = msgFrameConnectorId\n const frameOptions: OpenFrameOptions = {\n frameConnectorId: currentFrameId,\n url,\n name: name ?? 'MediaLink',\n ...(size ? { size } : {}),\n }\n // openFrame resolves when the frame connector is LOADED — only then can\n // getFrameConnector return it, so wire any queued sessions on resolution.\n connector\n .openFrame(frameOptions)\n .then(() => {\n for (const sid of pendingSessions) registerSessionObserver(sid)\n pendingSessions.clear()\n })\n .catch((err) => {\n console.error('[lavitre-apps] enableMediaLinkAnswerer openFrame', err)\n })\n }\n\n // Register now if the frame is already loaded; otherwise this queues the\n // sessionId for the openFrame resolution above.\n registerSessionObserver(sessionId)\n }\n\n connector.onMessageFromCompanionFrame = handler\n\n return () => {\n if (connector.onMessageFromCompanionFrame === handler) {\n connector.onMessageFromCompanionFrame = previousHandler\n }\n // Restore onFrameUnloaded only if our closure is still installed.\n if (connector.onFrameUnloaded === unloadedHandler) {\n connector.onFrameUnloaded = previousUnloadedHandler\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Type guard\n// ---------------------------------------------------------------------------\n\nfunction isMediaLinkOpenAnswererMessage(v: unknown): v is MediaLinkOpenAnswererMessage {\n return (\n typeof v === 'object' &&\n v !== null &&\n (v as Record<string, unknown>)['type'] === 'lavitre-media-link' &&\n typeof (v as Record<string, unknown>)['action'] === 'string' &&\n typeof (v as Record<string, unknown>)['frameConnectorId'] === 'string' &&\n typeof (v as Record<string, unknown>)['sessionId'] === 'string'\n )\n}\n"]}
1
+ {"version":3,"file":"MediaLink.js","sourceRoot":"","sources":["../../MediaLink/MediaLink.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAiI9C,8EAA8E;AAC9E,4EAA4E;AAC5E,uBAAuB;AACvB,8EAA8E;AAC9E,MAAM,MAAM,GAAG,YAAY,CAAA;AAC3B,MAAM,UAAU,GAAG,GAAG,MAAM,QAAQ,CAAA;AACpC,MAAM,eAAe,GAAG,GAAG,MAAM,YAAY,CAAA;AAC7C,MAAM,gBAAgB,GAAG,GAAG,MAAM,aAAa,CAAA;AAC/C,MAAM,WAAW,GAAG,GAAG,MAAM,SAAS,CAAA;AACtC;;;;;;GAMG;AACH,MAAM,eAAe,GAAG,GAAG,MAAM,YAAY,CAAA;AA8B7C;;;;;;GAMG;AACH,MAAM,aAAa,GAAmB,EAAE,CAAA;AAExC,gFAAgF;AAChF,MAAM,yBAAyB,GAAoB,EAAE,UAAU,EAAE,IAAI,EAAE,CAAA;AAsBvE,KAAK,UAAU,iBAAiB,CAAC,KAAqB;IACpD,IAAI,OAAO,GAAsB,EAAE,CAAA;IACnC,IAAI,CAAC;QACH,OAAO,GAAG,MAAM,OAAO,CAAC,IAAI,CAAoB;YAC9C,KAAK,CAAC,aAAa,EAAE;YACrB,IAAI,OAAO,C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AAA;QACrD,CAAC;IACH,CAAC,CAAA;AACH,CAAC;AAED,8EAA8E;AAC9E,aAAa;AACb,8EAA8E;AAE9E,SAAS,8BAA8B,CAAC,CAAU;IAChD,OAAO,CACL,OAAO,CAAC,KAAK,QAAQ;QACrB,CAAC,KAAK,IAAI;QACT,CAA6B,CAAC,MAAM,CAAC,KAAK,oBAAoB;QAC/D,OAAQ,CAA6B,CAAC,QAAQ,CAAC,KAAK,QAAQ;QAC5D,OAAQ,CAA6B,CAAC,kBAAkB,CAAC,KAAK,QAAQ;QACtE,OAAQ,CAA6B,CAAC,WAAW,CAAC,KAAK,QAAQ,CAChE,CAAA;AACH,CAAC","sourcesContent":["import type { Frame } from '../Frame/Frame.js'\nimport { randomUuid } from '../Common/Uuid.js'\nimport type { CompanionFrame } from '../CompanionFrame/CompanionFrame.js'\nimport type { IceServerConfig } from '../Frame/Frame.Model.js'\nimport type { Connector } from '../Connector/Connector.js'\nimport type { OpenFrameOptions } from '../Common/index.js'\n\n// ---------------------------------------------------------------------------\n// MediaLink — SDK-owned app-level WebRTC establishment.\n//\n// Signalling travels over the frame's CRDT doc (frame.crdt.doc), exactly like\n// webrtcSignaling.ts in lavitre-app-camera-studio, which this module\n// generalises. The CRDT channel is the right transport because it is kept in\n// sync between a companion frame and its paired Vitre frame by the la Vitre\n// Yjs relay — unlike sendToVitreFrame / sendToLocalFrame which are local-only.\n//\n// ICE/TURN server authority: the VITRE is the source of truth. The answerer\n// (Vitre frame) resolves its full ICE server list — including TURN credentials\n// — and publishes it to the 'iceServers' CRDT map entry. The offerer (companion\n// frame) waits up to `vitreIceTimeoutMs` for this entry before building its\n// RTCPeerConnection, then falls back to its own getIceServers() result, then to\n// public STUN. This matches the security posture of the rest of the platform:\n// TURN credentials are short-lived tokens already delivered to companions via\n// WebRTCOffer messages; they are NOT long-lived secrets. The CRDT doc is scoped\n// to the (appId, frameConnectorId) peer set — the same peers that already hold\n// the media stream — so publishing them here does not widen the exposure surface.\n//\n// Retry uses ICE restart (createOffer{iceRestart:true}) re-published over the\n// CRDT, not a full renegotiation. The resolved ICE server list is stored on the\n// impl and reused for all restarts of the same session (no re-fetch). Voluntary\n// stop writes a session-tagged control entry BEFORE closing the PC so the other\n// side tears down without entering the retry path.\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type MediaLinkState = 'connecting' | 'connected' | 'reconnecting' | 'ended' | 'failed'\nexport type MediaLinkEndReason = 'user' | 'remote-user' | 'failure'\n\nexport type MediaLinkRetryOptions = {\n /** Grace period after 'disconnected' before starting ICE restart. Default 3000 ms. */\n graceMs?: number\n /** Maximum ICE restart attempts before giving up. Default 3. */\n attempts?: number\n /** Per-attempt backoff delays in ms. Default [2000, 4000, 8000]. */\n backoffMs?: number[]\n}\n\nexport type StartMediaLinkOptions = {\n /**\n * Communicated to the answerer frame; tells the Vitre how to display the\n * incoming stream (standard shared-video slot vs. an app-frame overlay).\n */\n receiverDisplay?: 'standard' | 'appFrame'\n /** Opaque app data delivered to the answerer along with the link. */\n metadata?: unknown\n retry?: MediaLinkRetryOptions\n /**\n * When true (default), the offerer sends a control message to the app's\n * Vitre main Connector via `frame.sendMessageToVitreConnector` requesting\n * that the answerer frame be opened.\n */\n requestAnswererFrame?: boolean\n /**\n * How long (ms) the offerer waits for the Vitre answerer to publish its ICE\n * server list before falling back to the companion-side `getIceServers()` or\n * public STUN. Default 8000 ms (accounts for frame-open latency + CRDT sync).\n *\n * The Vitre is the source of authority for TURN credentials; a longer timeout\n * yields better NAT traversal for peers behind symmetric NAT.\n */\n vitreIceTimeoutMs?: number\n /**\n * Attached to the link BEFORE the connection starts — unlike assigning\n * `link.onStateChange` after `startMediaLink` resolves, this cannot miss a\n * fast transition (e.g. an instant 'connected' on loopback / late-join).\n */\n onStateChange?: (state: MediaLinkState) => void\n /** Same early-attachment rationale as {@link onStateChange}. */\n onEnded?: (reason: MediaLinkEndReason) => void\n}\n\n/** Handle returned to the companion-frame (offerer) side. */\nexport interface MediaLink {\n readonly state: MediaLinkState\n readonly sessionId: string\n /**\n * Swap the video (and audio, if present) tracks on the existing senders\n * via `replaceTrack` — no renegotiation. The answerer keeps receiving on\n * the same transceiver; the remote track object is unchanged so\n * `AnsweredMediaLink.onStreamChanged` will NOT fire on the Vitre side.\n */\n replaceStream(stream: MediaStream): Promise<void>\n /**\n * Voluntary stop: writes a session-tagged `ended: 'user'` control entry to\n * the CRDT doc BEFORE closing the PC. The other side tears down immediately\n * with `onEnded('remote-user')` — no retry.\n */\n stop(): void\n onStateChange?: (state: MediaLinkState) => void\n onEnded?: (reason: MediaLinkEndReason) => void\n}\n\n/** Handle returned to the Vitre-frame (answerer) side. */\nexport interface AnsweredMediaLink {\n readonly sessionId: string\n /** Remote stream surfaced via `ontrack`. */\n readonly stream: MediaStream\n readonly receiverDisplay?: 'standard' | 'appFrame'\n readonly metadata?: unknown\n /**\n * Called after the offerer invokes `replaceStream`. NOTE: because\n * `replaceStream` uses `replaceTrack` (no renegotiation), the remote\n * `MediaStreamTrack` object is the SAME object — browsers do NOT fire a\n * new `ontrack` and the track's content simply switches. This callback\n * will therefore NOT fire in current browser implementations. It is\n * provided as a forward-compatibility hook and for documentation purposes.\n */\n onStreamChanged?: (stream: MediaStream) => void\n onStateChange?: (state: MediaLinkState) => void\n onEnded?: (reason: MediaLinkEndReason) => void\n /**\n * Vitre-side voluntary stop: writes `ended: 'user'` toward the offerer.\n * No retry on either side.\n */\n stop(): void\n}\n\n// ---------------------------------------------------------------------------\n// Internal CRDT key names — use a namespace prefix to avoid collisions with\n// app-level CRDT keys.\n// ---------------------------------------------------------------------------\nconst PREFIX = 'mediaLink:'\nconst KEY_SIGNAL = `${PREFIX}signal`\nconst KEY_ICE_OFFERER = `${PREFIX}iceOfferer`\nconst KEY_ICE_ANSWERER = `${PREFIX}iceAnswerer`\nconst KEY_CONTROL = `${PREFIX}control`\n/**\n * Answerer-owned map key holding the Vitre's full ICE server list (including\n * TURN credentials). Written by the answerer once per session, consumed by the\n * offerer before building its RTCPeerConnection. The key is a Yjs map so the\n * value is overwritten atomically per session; validation uses `entry.s ===\n * sessionId` so a stale entry from a previous session is never consumed.\n */\nconst KEY_ICE_SERVERS = `${PREFIX}iceServers`\n\n// The control message shape used by voluntary stop.\ntype ControlEntry = { sessionId: string; ended: MediaLinkEndReason }\n\n// ICE candidate tagged with the session so stale candidates from a previous\n// session are ignored rather than fed into the wrong peer connection.\ntype TaggedIce = { s: string; c: RTCIceCandidateInit }\n\n// Shape written into KEY_SIGNAL.\ntype SignalEntry = {\n sessionId: string\n offer?: string\n answer?: string\n receiverDisplay?: 'standard' | 'appFrame'\n metadata?: unknown\n}\n\n/**\n * Shape written by the answerer (Vitre frame) into the KEY_ICE_SERVERS map\n * under the key `'servers'`. Tagged with `s: sessionId` so the offerer can\n * reject a stale entry from a previous session.\n *\n * Security note: TURN credentials are short-lived tokens already exposed to\n * companions via WebRTCOffer messages; publishing them here does not widen the\n * exposure surface. The CRDT doc is scoped to (appId, frameConnectorId) peers\n * — the same set that already holds the media stream.\n */\ntype IceServersEntry = { s: string; servers: IceServerConfig[] }\n\n/**\n * Fallback when getIceServers() returns empty or times out. INTENTIONALLY EMPTY:\n * la Vitre must never depend on an external STUN/TURN (e.g. Google) — all ICE\n * servers come from getIceServers() (the la Vitre relay). An empty list means\n * host-candidates only; the real fix for \"no servers\" is server-side, not a public\n * STUN leak.\n */\nconst STUN_FALLBACK: RTCIceServer[] = []\n\n/** ICE restart config: re-offer with iceRestart to create a new ICE session. */\nconst ICE_RESTART_OFFER_OPTIONS: RTCOfferOptions = { iceRestart: true }\n\n// Control message JSON posted from the offerer frame to the Vitre main connector\n// to request that the answerer frame be opened.\nexport type MediaLinkOpenAnswererMessage = {\n type: 'lavitre-media-link'\n action: 'open-answerer' | 'close-answerer'\n frameConnectorId: string\n sessionId: string\n}\n\n// ---------------------------------------------------------------------------\n// ICE server resolution (same approach as webrtcSignaling.ts)\n// ---------------------------------------------------------------------------\n\n// The subset of the frame surface the shared CRDT/ICE helpers touch. Both the\n// Vitre `Frame` (answerer side) and the `CompanionFrame` (offerer side) satisfy\n// it, so the helpers stay agnostic to which side called them — the companion-\n// only `sendMessageToVitreConnector` is reached through the `CompanionFrame`\n// typed `frame` field of the offerer, not these helpers.\ntype MediaLinkFrame = Pick<Frame, 'crdt' | 'getIceServers'>\n\nasync function resolveIceServers(frame: MediaLinkFrame): Promise<RTCIceServer[]> {\n let servers: IceServerConfig[] = []\n try {\n servers = await Promise.race<IceServerConfig[]>([\n frame.getIceServers(),\n new Promise<IceServerConfig[]>((resolve) => setTimeout(() => resolve([]), 3000)),\n ])\n } catch {\n servers = []\n }\n const list = servers.length > 0 ? servers : STUN_FALLBACK.map((s) => ({\n urls: Array.isArray(s.urls) ? s.urls : [s.urls as string],\n }))\n return list.map((s) => ({\n urls: s.urls,\n username: (s as IceServerConfig).username,\n credential: (s as IceServerConfig).credential,\n }))\n}\n\n// ---------------------------------------------------------------------------\n// CRDT accessor helpers\n// ---------------------------------------------------------------------------\n\nfunction getDoc(frame: MediaLinkFrame) {\n return frame.crdt.doc\n}\n\nfunction getSignalMap(frame: MediaLinkFrame) {\n return getDoc(frame).getMap<string>(KEY_SIGNAL)\n}\n\nfunction getIceOffererArray(frame: MediaLinkFrame) {\n return getDoc(frame).getArray<string>(KEY_ICE_OFFERER)\n}\n\nfunction getIceAnswererArray(frame: MediaLinkFrame) {\n return getDoc(frame).getArray<string>(KEY_ICE_ANSWERER)\n}\n\nfunction getControlArray(frame: MediaLinkFrame) {\n return getDoc(frame).getArray<string>(KEY_CONTROL)\n}\n\nfunction getIceServersMap(frame: MediaLinkFrame) {\n return getDoc(frame).getMap<string>(KEY_ICE_SERVERS)\n}\n\n// Iterate new ICE entries from `from`, return updated count.\nfunction drainIce(\n arr: ReturnType<typeof getIceOffererArray>,\n from: number,\n sessionId: string,\n onCandidate: (c: RTCIceCandidateInit) => void,\n): number {\n const len = arr.length\n for (let i = from; i < len; i++) {\n try {\n const entry = JSON.parse(arr.get(i)) as TaggedIce\n if (entry.s === sessionId) onCandidate(entry.c)\n } catch {\n /* ignore malformed entry */\n }\n }\n return len\n}\n\n// Check the control array for a voluntary-stop entry for this session.\nfunction checkVoluntaryStop(\n frame: MediaLinkFrame,\n sessionId: string,\n): MediaLinkEndReason | null {\n const arr = getControlArray(frame)\n for (let i = 0; i < arr.length; i++) {\n try {\n const e = JSON.parse(arr.get(i)) as ControlEntry\n if (e.sessionId === sessionId) return e.ended\n } catch {\n /* ignore */\n }\n }\n return null\n}\n\n// Write a voluntary-stop entry.\nfunction writeControlStop(frame: MediaLinkFrame, sessionId: string, reason: MediaLinkEndReason): void {\n const entry: ControlEntry = { sessionId, ended: reason }\n getControlArray(frame).push([JSON.stringify(entry)])\n}\n\n// ---------------------------------------------------------------------------\n// Offerer implementation\n// ---------------------------------------------------------------------------\n\nclass MediaLinkImpl implements MediaLink {\n public state: MediaLinkState = 'connecting'\n public onStateChange?: (state: MediaLinkState) => void\n public onEnded?: (reason: MediaLinkEndReason) => void\n\n private pc: RTCPeerConnection | null = null\n private senders: RTCRtpSender[] = []\n private remoteSet = false\n private pendingRemote: RTCIceCandidateInit[] = []\n private processedIce = 0\n private stopped = false\n // FIX 3: separate flag so teardown() cleanup runs exactly once regardless\n // of whether the call came from stop() (after stopped=true) or externally.\n private tornDown = false\n\n // Retry state\n private retryCount = 0\n private graceTimer: ReturnType<typeof setTimeout> | null = null\n private retryTimer: ReturnType<typeof setTimeout> | null = null\n\n // CRDT observer references so we can unobserve\n private signalObserver: (() => void) | null = null\n private iceObserver: (() => void) | null = null\n private controlObserver: (() => void) | null = null\n\n private pagehideHandler: (() => void) | null = null\n\n /**\n * Resolved ICE server list shared across all ICE restarts of this session.\n * Set once during start() (after waiting for the Vitre-published list) and\n * reused by every subsequent initPeerConnection(iceRestart=true) call.\n */\n private resolvedIceServers: RTCIceServer[] | null = null\n\n constructor(\n public readonly sessionId: string,\n // Companion side: the offerer originates the link from a companion frame and\n // signals the Vitre connector via `frame.sendMessageToVitreConnector`.\n private readonly frame: CompanionFrame,\n private stream: MediaStream,\n private readonly options: Required<MediaLinkRetryOptions>,\n private readonly openAnswererFrame: boolean,\n private readonly receiverDisplay: 'standard' | 'appFrame' | undefined,\n private readonly metadata: unknown,\n private readonly vitreIceTimeoutMs: number,\n ) {}\n\n async start(): Promise<void> {\n // Register pagehide handler (best-effort voluntary signal on tab close).\n this.pagehideHandler = () => { this.stop() }\n window.addEventListener('pagehide', this.pagehideHandler)\n\n // IMPROVEMENT 7: prune stale CRDT entries from any previous session.\n // The design is single-active-session per frame doc: only one 'session'\n // key in the signal map, and growing ICE/control arrays. At the start of\n // each new offerer session we delete all entries in both ICE arrays and\n // the control array whose sessionId differs from our new sessionId. This\n // bounds CRDT growth to O(1 session) rather than O(lifetime of the frame).\n // Also clear a stale 'iceServers' map entry from a previous session so the\n // offerer cannot accidentally consume it (the answerer overwrites per session\n // anyway, but an extra guard here makes stale-entry reasoning explicit).\n const doc = this.frame.crdt.doc\n doc.transact(() => {\n const iceOfferer = getIceOffererArray(this.frame)\n const iceAnswerer = getIceAnswererArray(this.frame)\n const controlArr = getControlArray(this.frame)\n const iceServersMap = getIceServersMap(this.frame)\n // Delete indices in reverse so removal does not shift subsequent indices.\n const pruneArray = (arr: ReturnType<typeof getIceOffererArray>) => {\n const toDelete: number[] = []\n for (let i = 0; i < arr.length; i++) {\n try {\n const e = JSON.parse(arr.get(i)) as { s?: string }\n if (e.s !== this.sessionId) toDelete.push(i)\n } catch { toDelete.push(i) }\n }\n for (let i = toDelete.length - 1; i >= 0; i--) {\n arr.delete(toDelete[i]!, 1)\n }\n }\n pruneArray(iceOfferer)\n pruneArray(iceAnswerer)\n pruneArray(controlArr)\n // Clear a stale iceServers entry from a prior session.\n const rawIce = iceServersMap.get('servers')\n if (rawIce) {\n try {\n const existing = JSON.parse(rawIce) as IceServersEntry\n if (existing.s !== this.sessionId) iceServersMap.delete('servers')\n } catch { iceServersMap.delete('servers') }\n }\n })\n\n // Step 1: publish a session-request (no offer yet) so a late-joining\n // answerer frame sees this session after CRDT sync and can start resolving\n // its ICE servers immediately.\n const sessionRequest: SignalEntry = {\n sessionId: this.sessionId,\n receiverDisplay: this.receiverDisplay,\n metadata: this.metadata,\n // offer is intentionally absent — this is a session-request only.\n }\n doc.transact(() => {\n getSignalMap(this.frame).set('session', JSON.stringify(sessionRequest))\n })\n\n // Step 2: send the open-answerer message AFTER writing the session-request\n // so the answerer frame (if it opens late) finds the session-request in the\n // CRDT on first sync.\n if (this.openAnswererFrame) {\n const msg: MediaLinkOpenAnswererMessage = {\n type: 'lavitre-media-link',\n action: 'open-answerer',\n frameConnectorId: this.frame.id,\n sessionId: this.sessionId,\n }\n this.frame.sendMessageToVitreConnector(JSON.stringify(msg))\n }\n\n // Step 3: race the vitre ICE list against the companion fallback and the\n // timeout. Start the companion-side resolve immediately in parallel.\n const companionIcePromise = resolveIceServers(this.frame)\n\n const vitreIcePromise = new Promise<IceServerConfig[] | null>((resolve) => {\n const iceServersMap = getIceServersMap(this.frame)\n const timeout = setTimeout(() => {\n iceServersMap.unobserve(observer)\n resolve(null)\n }, this.vitreIceTimeoutMs)\n\n const tryRead = (): boolean => {\n const raw = iceServersMap.get('servers')\n if (!raw) return false\n try {\n const entry = JSON.parse(raw) as IceServersEntry\n if (entry.s !== this.sessionId) return false\n if (!Array.isArray(entry.servers) || entry.servers.length === 0) return false\n clearTimeout(timeout)\n iceServersMap.unobserve(observer)\n resolve(entry.servers)\n return true\n } catch { return false }\n }\n\n const observer = () => { tryRead() }\n iceServersMap.observe(observer)\n // Check for an entry that was already present before we subscribed.\n tryRead()\n })\n\n // Pick the best available ICE servers: vitre > companion > public STUN.\n const vitreServers = await vitreIcePromise\n let iceServers: RTCIceServer[]\n if (vitreServers !== null && vitreServers.length > 0) {\n iceServers = vitreServers.map((s) => ({\n urls: s.urls,\n username: s.username,\n credential: s.credential,\n }))\n } else {\n // Fall back to companion-side result (already resolving in parallel).\n iceServers = await companionIcePromise\n }\n\n // stop() may have torn the link down while we awaited the ICE servers\n // (up to vitreIceTimeoutMs) — do not build a PC that nobody would close.\n if (this.tornDown) return\n\n // Store for reuse across ICE restarts of this session.\n this.resolvedIceServers = iceServers\n\n await this.initPeerConnection()\n }\n\n private async initPeerConnection(iceRestart = false): Promise<void> {\n // Reuse the ICE server list resolved during start() for all restarts of\n // this session. On the first call (iceRestart=false) resolvedIceServers is\n // already set by start(); on subsequent calls it is the stored value.\n const iceServers = this.resolvedIceServers ?? STUN_FALLBACK\n const pc = new RTCPeerConnection({ iceServers })\n this.pc = pc\n // --- ICE/TURN diagnostics (offerer). Reveals whether TURN servers were handed\n // out, ICE negotiation progress, and TURN auth failures (errorCode 401/403 =\n // expired/invalid credentials — the classic cause of an intermittent black frame).\n const turnCount = iceServers.filter((s) => {\n const urls = Array.isArray(s.urls) ? s.urls : [s.urls]\n return urls.some((u) => typeof u === 'string' && u.startsWith('turn'))\n }).length\n console.log('[lavitre-apps][MediaLink] pc-init offerer ' + JSON.stringify({ servers: iceServers.length, turn: turnCount, iceRestart }))\n pc.oniceconnectionstatechange = () => {\n if (this.pc === pc) console.log('[lavitre-apps][MediaLink] iceState offerer', pc.iceConnectionState)\n }\n pc.onicecandidateerror = (ev) => {\n console.warn('[lavitre-apps][MediaLink] ice-error offerer ' + JSON.stringify({ code: ev.errorCode, url: ev.url, text: ev.errorText }))\n }\n this.senders = []\n this.remoteSet = false\n this.pendingRemote = []\n // Keep the ice processed index across ICE restarts so we don't re-add old\n // candidates. For a full new session (first call) it starts at 0; for a\n // restart the CRDT arrays keep growing, so we advance from the current tip.\n if (!iceRestart) {\n this.processedIce = 0\n }\n\n for (const track of this.stream.getTracks()) {\n this.senders.push(pc.addTrack(track, this.stream))\n }\n\n pc.onicecandidate = (e) => {\n if (e.candidate && this.pc === pc) {\n const tagged: TaggedIce = { s: this.sessionId, c: e.candidate.toJSON() }\n getIceOffererArray(this.frame).push([JSON.stringify(tagged)])\n }\n }\n\n pc.onconnectionstatechange = () => {\n if (this.stopped || this.pc !== pc) return\n const cs = pc.connectionState\n console.log('[lavitre-apps][MediaLink] connState offerer', cs)\n if (cs === 'connected') {\n this.clearTimers()\n this.retryCount = 0\n this.setState('connected')\n } else if (cs === 'disconnected') {\n this.setState('reconnecting')\n this.graceTimer = setTimeout(() => {\n this.graceTimer = null\n if (!this.stopped && this.pc === pc) this.attemptRestart()\n }, this.options.graceMs)\n } else if (cs === 'failed') {\n this.clearTimers()\n this.attemptRestart()\n }\n }\n\n const signalMap = getSignalMap(this.frame)\n const vitreIce = getIceAnswererArray(this.frame)\n const controlArr = getControlArray(this.frame)\n\n // Drain remote ICE from the answerer array.\n const drainRemote = () => {\n if (!this.pc || this.pc !== pc) return\n this.processedIce = drainIce(vitreIce, this.processedIce, this.sessionId, (c) => {\n if (this.remoteSet) void pc.addIceCandidate(c).catch(() => {})\n else this.pendingRemote.push(c)\n })\n }\n\n // Handle the answer arriving in the signal map.\n const onSignal = () => {\n if (this.remoteSet || !this.pc || this.pc !== pc) return\n const raw = signalMap.get('session')\n if (!raw) return\n let entry: SignalEntry\n try { entry = JSON.parse(raw) } catch { return }\n if (entry.sessionId !== this.sessionId) return\n const answer = entry.answer\n if (!answer) return\n void pc.setRemoteDescription({ type: 'answer', sdp: answer })\n .then(() => {\n if (this.pc !== pc) return\n this.remoteSet = true\n for (const c of this.pendingRemote.splice(0)) {\n void pc.addIceCandidate(c).catch(() => {})\n }\n drainRemote()\n })\n .catch((err) => console.error('[lavitre-apps] MediaLink setRemoteDescription(answer)', err))\n }\n\n // Watch for voluntary stop from the answerer side.\n const onControl = () => {\n if (this.stopped) return\n const reason = checkVoluntaryStop(this.frame, this.sessionId)\n if (reason != null) this.teardown('remote-user')\n }\n\n if (this.signalObserver) signalMap.unobserve(this.signalObserver)\n if (this.iceObserver) vitreIce.unobserve(this.iceObserver)\n if (this.controlObserver) controlArr.unobserve(this.controlObserver)\n\n this.signalObserver = onSignal\n this.iceObserver = drainRemote\n this.controlObserver = onControl\n\n signalMap.observe(onSignal)\n vitreIce.observe(drainRemote)\n controlArr.observe(onControl)\n\n // Create and publish the offer, merging into the existing session-request\n // entry (written by start()) to preserve sessionId/receiverDisplay/metadata.\n const offerOptions = iceRestart ? ICE_RESTART_OFFER_OPTIONS : undefined\n const offer = await pc.createOffer(offerOptions)\n await pc.setLocalDescription(offer)\n\n const doc = this.frame.crdt.doc\n doc.transact(() => {\n const existing = (() => {\n const raw = signalMap.get('session')\n if (!raw) return null\n try { return JSON.parse(raw) as SignalEntry } catch { return null }\n })()\n const entry: SignalEntry = {\n ...(existing ?? {}),\n sessionId: this.sessionId,\n offer: offer.sdp ?? '',\n receiverDisplay: this.receiverDisplay,\n metadata: this.metadata,\n }\n signalMap.set('session', JSON.stringify(entry))\n })\n\n // Catch state that synced before observers attached.\n onSignal()\n drainRemote()\n onControl()\n }\n\n private async attemptRestart(): Promise<void> {\n if (this.stopped) return\n if (this.retryCount >= this.options.attempts) {\n this.teardown('failure')\n return\n }\n\n const delayMs = this.options.backoffMs[\n Math.min(this.retryCount, this.options.backoffMs.length - 1)\n ] ?? 0\n this.retryCount++\n this.setState('reconnecting')\n\n this.retryTimer = setTimeout(async () => {\n this.retryTimer = null\n if (this.stopped) return\n // Close old PC before creating new one.\n const oldPc = this.pc\n this.pc = null\n if (oldPc) {\n oldPc.onicecandidate = null\n oldPc.onconnectionstatechange = null\n oldPc.close()\n }\n try {\n await this.initPeerConnection(true)\n } catch (err) {\n console.error('[lavitre-apps] MediaLink ICE restart failed', err)\n this.attemptRestart()\n }\n }, delayMs)\n }\n\n async replaceStream(stream: MediaStream): Promise<void> {\n // FIX 4: no-op if torn down or PC is gone.\n if (this.tornDown || !this.pc) return\n this.stream = stream\n const tracks = stream.getTracks()\n const replacePromises: Promise<void>[] = []\n for (const sender of this.senders) {\n // FIX 4: skip senders whose track is null (e.g. ended track removed by browser).\n if (!sender.track) continue\n const newTrack = tracks.find((t) => t.kind === sender.track?.kind)\n if (newTrack) replacePromises.push(sender.replaceTrack(newTrack))\n }\n await Promise.all(replacePromises)\n }\n\n stop(): void {\n if (this.stopped) return\n // FIX 3: set stopped=true BEFORE writing the control entry. The CRDT write\n // triggers the local onControl observer synchronously, which calls\n // teardown('remote-user'). With stopped=true set, that re-entrant call hits\n // the tornDown guard and returns early; then teardown('user') below runs\n // the actual cleanup.\n this.stopped = true\n writeControlStop(this.frame, this.sessionId, 'user')\n // Reliable close signal to the Vitre answerer via the host channel — more\n // likely to flush on companion-frame unmount/back than the P2P CRDT control,\n // so the answerer frame closes promptly. Mirrors the open-answerer send.\n if (this.openAnswererFrame) {\n try {\n const closeMsg: MediaLinkOpenAnswererMessage = {\n type: 'lavitre-media-link',\n action: 'close-answerer',\n frameConnectorId: this.frame.id,\n sessionId: this.sessionId,\n }\n this.frame.sendMessageToVitreConnector(JSON.stringify(closeMsg))\n } catch {\n /* best-effort */\n }\n }\n this.teardown('user')\n }\n\n /** Internal teardown. Guards on tornDown so the cleanup body runs exactly once. */\n private teardown(reason: MediaLinkEndReason): void {\n // FIX 3: guard on tornDown (not stopped) — stop() sets stopped=true before\n // writing the control entry, whose synchronous observer fires teardown\n // ('remote-user'); that hits this guard and exits; then stop() calls\n // teardown('user') which performs the cleanup exactly once.\n if (this.tornDown) return\n this.tornDown = true\n this.stopped = true\n\n // Remove pagehide listener.\n if (this.pagehideHandler) {\n window.removeEventListener('pagehide', this.pagehideHandler)\n this.pagehideHandler = null\n }\n\n this.clearTimers()\n\n // Unsubscribe CRDT observers.\n const signalMap = getSignalMap(this.frame)\n const vitreIce = getIceAnswererArray(this.frame)\n const controlArr = getControlArray(this.frame)\n if (this.signalObserver) { signalMap.unobserve(this.signalObserver); this.signalObserver = null }\n if (this.iceObserver) { vitreIce.unobserve(this.iceObserver); this.iceObserver = null }\n if (this.controlObserver) { controlArr.unobserve(this.controlObserver); this.controlObserver = null }\n\n // Close the PC.\n if (this.pc) {\n this.pc.onicecandidate = null\n this.pc.onconnectionstatechange = null\n this.pc.close()\n this.pc = null\n }\n\n this.setState('ended')\n this.onEnded?.(reason)\n }\n\n private setState(s: MediaLinkState): void {\n if (this.state === s) return\n ;(this as { state: MediaLinkState }).state = s\n this.onStateChange?.(s)\n }\n\n private clearTimers(): void {\n if (this.graceTimer != null) { clearTimeout(this.graceTimer); this.graceTimer = null }\n if (this.retryTimer != null) { clearTimeout(this.retryTimer); this.retryTimer = null }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Answerer implementation\n// ---------------------------------------------------------------------------\n\n// The answerer does not drive ICE recovery (the offerer does). If the offerer\n// vanishes WITHOUT a clean control-stop (e.g. the companion frame is closed and\n// its CRDT 'ended' write never flushes), the connection goes disconnected/failed\n// and nothing would ever end the session — so closeOnEnd and the app's onEnded\n// would hang forever. After this grace window with no recovery, the answerer\n// ends the session itself. Longer than the offerer's ICE-restart cycle so a real\n// reconnection wins first.\nconst ANSWERER_DISCONNECT_GRACE_MS = 10000\n\nclass AnsweredMediaLinkImpl implements AnsweredMediaLink {\n public onStreamChanged?: (stream: MediaStream) => void\n public onStateChange?: (state: MediaLinkState) => void\n public onEnded?: (reason: MediaLinkEndReason) => void\n\n private pc: RTCPeerConnection | null = null\n private _stream: MediaStream | null = null\n private remoteSet = false\n private pendingRemote: RTCIceCandidateInit[] = []\n private processedIce = 0\n private stopped = false\n // Separate flag used by teardown so that teardown()'s cleanup body runs\n // exactly once regardless of the call path (stop() vs. external teardown()).\n private tornDown = false\n // FIX 2: track the last offer SDP we processed to avoid re-triggering\n // handleOffer when the answerer itself writes its answer into the session\n // entry (the CRDT observer fires again with the same offer still present).\n private lastProcessedOfferSdp: string | null = null\n // Backstop timer: armed on a sustained disconnect with no offerer recovery,\n // it ends the session so closeOnEnd / onEnded don't hang (see the const above).\n private endTimer: ReturnType<typeof setTimeout> | null = null\n\n // CRDT observer references\n private signalObserver: (() => void) | null = null\n private iceObserver: (() => void) | null = null\n private controlObserver: (() => void) | null = null\n\n constructor(\n public readonly sessionId: string,\n private readonly frame: Frame,\n public readonly receiverDisplay: 'standard' | 'appFrame' | undefined,\n public readonly metadata: unknown,\n private readonly onStreamReady: (link: AnsweredMediaLink) => void,\n ) {}\n\n get stream(): MediaStream {\n if (!this._stream) throw new Error('[lavitre-apps] AnsweredMediaLink: stream not yet available')\n return this._stream\n }\n\n async initiate(offerSdp: string, currentIceOffererTip: number): Promise<void> {\n const iceServers = await resolveIceServers(this.frame)\n const pc = new RTCPeerConnection({ iceServers })\n this.pc = pc\n // --- ICE/TURN diagnostics (answerer = the Vitre that reshares). Same signals as\n // the offerer: TURN handed out?, ICE progress, TURN auth failures (401/403).\n const turnCount = iceServers.filter((s) => {\n const urls = Array.isArray(s.urls) ? s.urls : [s.urls]\n return urls.some((u) => typeof u === 'string' && u.startsWith('turn'))\n }).length\n console.log('[lavitre-apps][MediaLink] pc-init answerer ' + JSON.stringify({ servers: iceServers.length, turn: turnCount }))\n pc.oniceconnectionstatechange = () => {\n if (this.pc === pc) console.log('[lavitre-apps][MediaLink] iceState answerer', pc.iceConnectionState)\n }\n pc.onicecandidateerror = (ev) => {\n console.warn('[lavitre-apps][MediaLink] ice-error answerer ' + JSON.stringify({ code: ev.errorCode, url: ev.url, text: ev.errorText }))\n }\n this.remoteSet = false\n this.pendingRemote = []\n this.processedIce = currentIceOffererTip\n\n pc.ontrack = (e) => {\n if (this.pc !== pc) return\n const incoming = e.streams[0] ?? new MediaStream([e.track])\n if (!this._stream) {\n this._stream = incoming\n // Notify the handler: the link is ready for the app.\n this.onStreamReady(this)\n } else {\n // Subsequent tracks (e.g. audio added after video).\n this._stream = incoming\n this.onStreamChanged?.(this._stream)\n }\n }\n\n // FIX 1: answerer trickle ICE — publish answerer candidates so the offerer\n // can drain them from getIceAnswererArray. Guard this.pc === pc to discard\n // stale events after an ICE restart replaces the peer connection.\n pc.onicecandidate = (e) => {\n if (e.candidate && this.pc === pc) {\n const tagged: TaggedIce = { s: this.sessionId, c: e.candidate.toJSON() }\n getIceAnswererArray(this.frame).push([JSON.stringify(tagged)])\n }\n }\n\n pc.onconnectionstatechange = () => {\n if (this.stopped || this.pc !== pc) return\n const cs = pc.connectionState\n console.log('[lavitre-apps][MediaLink] connState answerer', cs)\n if (cs === 'connected') {\n if (this.endTimer) { clearTimeout(this.endTimer); this.endTimer = null }\n this.emitState('connected')\n } else if (cs === 'failed' || cs === 'disconnected') {\n // Answerer does not retry; recovery is offerer-driven (ICE restart).\n // Reflect 'reconnecting' so the app can react. A clean stop still ends\n // the session sooner via the control observer. But if the offerer is\n // GONE (e.g. companion frame closed without flushing its 'ended' write),\n // no restart will come — so arm a grace timer to end the session\n // ourselves; otherwise the answerer (and closeOnEnd) would hang forever.\n this.emitState('reconnecting')\n if (!this.endTimer) {\n this.endTimer = setTimeout(() => {\n this.endTimer = null\n if (!this.stopped && this.pc === pc && pc.connectionState !== 'connected') {\n this.teardown('failure')\n }\n }, ANSWERER_DISCONNECT_GRACE_MS)\n }\n }\n }\n\n const offererIce = getIceOffererArray(this.frame)\n const signalMap = getSignalMap(this.frame)\n const controlArr = getControlArray(this.frame)\n\n const drainOffererIce = () => {\n if (!this.pc || this.pc !== pc) return\n this.processedIce = drainIce(offererIce, this.processedIce, this.sessionId, (c) => {\n if (this.remoteSet) void pc.addIceCandidate(c).catch(() => {})\n else this.pendingRemote.push(c)\n })\n }\n\n // Watch for a re-offer (ICE restart from the offerer side).\n // FIX 2: guard against the answerer's own answer-write re-triggering this\n // handler. When the answerer writes its answer into the 'session' entry the\n // CRDT observer fires again — the entry still carries .offer so without\n // the guard handleOffer would run again on a stable PC, creating an\n // unbounded loop. We skip if the offer SDP has not changed since we last\n // processed it; ICE-restart offers carry a different SDP and still pass.\n const onSignal = () => {\n if (!this.pc || this.pc !== pc || this.stopped) return\n const raw = signalMap.get('session')\n if (!raw) return\n let entry: SignalEntry\n try { entry = JSON.parse(raw) } catch { return }\n if (entry.sessionId !== this.sessionId || !entry.offer) return\n if (entry.offer === this.lastProcessedOfferSdp) return\n // Re-offer arrived: re-answer (ICE restart or first answer).\n void this.handleOffer(entry.offer)\n }\n\n const onControl = () => {\n if (this.stopped) return\n const reason = checkVoluntaryStop(this.frame, this.sessionId)\n if (reason != null) this.teardown('remote-user')\n }\n\n if (this.signalObserver) signalMap.unobserve(this.signalObserver)\n if (this.iceObserver) offererIce.unobserve(this.iceObserver)\n if (this.controlObserver) controlArr.unobserve(this.controlObserver)\n\n this.signalObserver = onSignal\n this.iceObserver = drainOffererIce\n this.controlObserver = onControl\n\n signalMap.observe(onSignal)\n offererIce.observe(drainOffererIce)\n controlArr.observe(onControl)\n\n // FIX 2: record the initial offer SDP before processing so that the CRDT\n // observer fired by our own answer-write below sees it and returns early.\n this.lastProcessedOfferSdp = offerSdp\n await pc.setRemoteDescription({ type: 'offer', sdp: offerSdp })\n this.remoteSet = true\n for (const c of this.pendingRemote.splice(0)) {\n void pc.addIceCandidate(c).catch(() => {})\n }\n\n const answer = await pc.createAnswer()\n await pc.setLocalDescription(answer)\n\n // Publish the answer into the existing session entry.\n const raw = signalMap.get('session')\n if (raw) {\n try {\n const existing = JSON.parse(raw) as SignalEntry\n const updated: SignalEntry = { ...existing, answer: answer.sdp ?? '' }\n signalMap.set('session', JSON.stringify(updated))\n } catch {\n signalMap.set('session', JSON.stringify({ sessionId: this.sessionId, answer: answer.sdp ?? '' }))\n }\n }\n\n drainOffererIce()\n onControl()\n }\n\n /** Handle a re-offer (ICE restart) from the offerer. */\n private async handleOffer(offerSdp: string): Promise<void> {\n if (!this.pc || this.stopped) return\n // FIX 2: record the SDP we are about to process BEFORE any async work so\n // that the synchronous CRDT observer fired by our own answer-write below\n // sees it and returns early (same SDP = already handled).\n this.lastProcessedOfferSdp = offerSdp\n const pc = this.pc\n try {\n await pc.setRemoteDescription({ type: 'offer', sdp: offerSdp })\n this.remoteSet = true\n const answer = await pc.createAnswer()\n await pc.setLocalDescription(answer)\n\n const signalMap = getSignalMap(this.frame)\n const raw = signalMap.get('session')\n if (raw) {\n try {\n const existing = JSON.parse(raw) as SignalEntry\n const updated: SignalEntry = { ...existing, answer: answer.sdp ?? '' }\n signalMap.set('session', JSON.stringify(updated))\n } catch {\n signalMap.set('session', JSON.stringify({ sessionId: this.sessionId, answer: answer.sdp ?? '' }))\n }\n }\n } catch (err) {\n console.error('[lavitre-apps] AnsweredMediaLink handleOffer', err)\n }\n }\n\n stop(): void {\n if (this.stopped) return\n // FIX 3: set stopped=true BEFORE writing the control entry. The CRDT write\n // triggers the local onControl observer synchronously, which calls\n // teardown('remote-user'). With stopped=true already set, that call is a\n // no-op on the stopped guard, but teardown('user') below must still run\n // the cleanup — so teardown guards on the separate tornDown flag, not on\n // stopped.\n this.stopped = true\n writeControlStop(this.frame, this.sessionId, 'user')\n this.teardown('user')\n }\n\n teardown(reason: MediaLinkEndReason): void {\n // FIX 3: guard on tornDown (not stopped) so that the cleanup body runs\n // exactly once regardless of path — stop() sets stopped=true before writing\n // the control entry, which fires onControl→teardown('remote-user')\n // synchronously; that call hits this guard and returns early; then\n // stop() continues and calls teardown('user') which runs the cleanup.\n if (this.tornDown) return\n this.tornDown = true\n this.stopped = true\n if (this.endTimer) { clearTimeout(this.endTimer); this.endTimer = null }\n // FIX 2: reset lastProcessedOfferSdp on teardown.\n this.lastProcessedOfferSdp = null\n\n const signalMap = getSignalMap(this.frame)\n const offererIce = getIceOffererArray(this.frame)\n const controlArr = getControlArray(this.frame)\n if (this.signalObserver) { signalMap.unobserve(this.signalObserver); this.signalObserver = null }\n if (this.iceObserver) { offererIce.unobserve(this.iceObserver); this.iceObserver = null }\n if (this.controlObserver) { controlArr.unobserve(this.controlObserver); this.controlObserver = null }\n\n if (this.pc) {\n this.pc.ontrack = null\n this.pc.onicecandidate = null\n this.pc.onconnectionstatechange = null\n this.pc.close()\n this.pc = null\n }\n\n this.emitState('ended')\n this.onEnded?.(reason)\n }\n\n private emitState(s: MediaLinkState): void {\n this.onStateChange?.(s)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API entry points\n// ---------------------------------------------------------------------------\n\n/**\n * Companion-frame side — the offerer.\n *\n * Acquires ICE servers, creates an `RTCPeerConnection` with the given stream,\n * publishes the offer over the frame CRDT doc, and optionally requests that\n * the answerer frame be opened on the Vitre via\n * `frame.sendMessageToVitreConnector`. Resolves with a {@link MediaLink}\n * handle once the local description is set (i.e. signalling is in flight).\n *\n * Call `connector.openFrame(frameConnectorId, ...)` on the Vitre side (or use\n * {@link enableMediaLinkAnswerer}) BEFORE calling this so the answerer frame\n * is ready to receive the offer when the CRDT syncs. If `requestAnswererFrame`\n * is true (default) the SDK sends the control message automatically.\n *\n * @param frame The companion frame (`CompanionFrame`, from `initializeCompanionFrame`).\n * @param stream The `MediaStream` to send to the Vitre frame.\n * @param options Optional configuration (retry, metadata, display mode…).\n */\nexport async function startMediaLink(\n frame: CompanionFrame,\n stream: MediaStream,\n options?: StartMediaLinkOptions,\n): Promise<MediaLink> {\n const sessionId = randomUuid()\n const retryOpts: Required<MediaLinkRetryOptions> = {\n graceMs: options?.retry?.graceMs ?? 3000,\n attempts: options?.retry?.attempts ?? 3,\n backoffMs: options?.retry?.backoffMs ?? [2000, 4000, 8000],\n }\n const link = new MediaLinkImpl(\n sessionId,\n frame,\n stream,\n retryOpts,\n options?.requestAnswererFrame !== false,\n options?.receiverDisplay,\n options?.metadata,\n options?.vitreIceTimeoutMs ?? 8000,\n )\n // Attach the callbacks BEFORE start() so no state transition can be missed\n // (start() awaits ICE resolution; a fast answer could otherwise fire\n // 'connected' before the caller had a chance to assign the handlers).\n if (options?.onStateChange) link.onStateChange = options.onStateChange\n if (options?.onEnded) link.onEnded = options.onEnded\n await link.start()\n return link\n}\n\n/**\n * Vitre-frame side — subscribe to incoming media link sessions.\n *\n * The handler fires once per session (including sessions already present in\n * the CRDT doc at the time of subscription — late-join). Each invocation\n * provides an {@link AnsweredMediaLink} with the remote stream and teardown\n * handle. The caller is responsible for calling `frame.shareStream(link.stream)`\n * (or equivalent) to route the stream to the space.\n *\n * Returns an unsubscribe function that stops watching for new sessions. Existing\n * {@link AnsweredMediaLink} handles are NOT torn down by unsubscribing — each\n * must be ended explicitly via `link.stop()` or via the offerer's `stop()`.\n *\n * @param frame The Vitre-side frame (`Frame`).\n * @param handler Called for every new (or already-present) incoming session.\n * @returns Unsubscribe function.\n */\nexport function onMediaLink(\n frame: Frame,\n handler: (link: AnsweredMediaLink) => void,\n): () => void {\n const signalMap = getSignalMap(frame)\n // Track sessions already handled so the CRDT observer doesn't re-fire them.\n const seen = new Set<string>()\n // Track sessions for which we have published our ICE servers but the offer\n // has not yet arrived — prevents re-publishing on every CRDT tick.\n const icePublished = new Set<string>()\n // Cleared by the unsubscribe function: stops in-flight async ICE publishes\n // from writing to the CRDT after the caller unsubscribed, and lets a later\n // re-subscribe publish again for fresh sessions.\n let active = true\n\n const processSignal = () => {\n const raw = signalMap.get('session')\n if (!raw) return\n let entry: SignalEntry\n try { entry = JSON.parse(raw) } catch { return }\n const { sessionId, offer, receiverDisplay, metadata } = entry\n if (!sessionId) return\n\n if (!seen.has(sessionId)) {\n // A new session (with or without an offer) has appeared. The answerer\n // must resolve the Vitre's ICE servers and publish them exactly once for\n // this session so the offerer can consume them before building its PC.\n if (!icePublished.has(sessionId)) {\n icePublished.add(sessionId)\n void (async () => {\n let servers: IceServerConfig[] = []\n try { servers = await frame.getIceServers() } catch { servers = [] }\n if (!active) return // unsubscribed while resolving — do not write\n if (!servers.length) return // nothing useful to publish; offerer falls back naturally\n const iceEntry: IceServersEntry = { s: sessionId, servers }\n getIceServersMap(frame).set('servers', JSON.stringify(iceEntry))\n })()\n }\n }\n\n // Wait until the offer arrives before creating the answerer impl.\n if (!offer) return\n if (seen.has(sessionId)) return\n seen.add(sessionId)\n\n // Snapshot the current tip of the offerer ICE array so the answerer\n // doesn't try to process offerer candidates that were published before\n // this session's offer.\n const iceOffererTip = getIceOffererArray(frame).length\n\n const link = new AnsweredMediaLinkImpl(\n sessionId,\n frame,\n receiverDisplay,\n metadata,\n handler,\n )\n void link.initiate(offer, iceOffererTip).catch((err) => {\n console.error('[lavitre-apps] AnsweredMediaLink initiate', err)\n })\n }\n\n signalMap.observe(processSignal)\n // Catch a session that was already in the CRDT when this observer attached.\n processSignal()\n\n return () => {\n active = false\n signalMap.unobserve(processSignal)\n }\n}\n\n/**\n * Vitre CONNECTOR helper — automatically opens the answerer frame when a\n * companion frame requests it via the `lavitre-media-link` control message,\n * and closes it again when the last link of that frame ends (configurable).\n *\n * Wire this in the Connector's `onMessageFromCompanionFrame` on the Vitre side:\n * ```ts\n * const unsub = enableMediaLinkAnswerer(connector, {\n * url: 'https://my-app.apps.lavit.re/frame.html',\n * name: 'My App',\n * })\n * // Later:\n * unsub()\n * ```\n *\n * **Frame id matching**: the companion mints a per-session id of the form\n * `<appId>-<uuid>` and sends it in the `open-answerer` message. This helper\n * matches incoming messages by prefix:\n * - exact match: `msgFrameConnectorId === prefix`\n * - prefix match: `msgFrameConnectorId.startsWith(prefix + '-')`\n *\n * `frameConnectorId` (optional): the match prefix. Defaults to `connector.appId`\n * so apps that omit it work without any configuration. An app can still pass a\n * fixed string for backward compatibility — it matches via the `===` arm.\n *\n * The answerer frame is opened with the **companion-minted id** received in the\n * message (not a fixed constant), so re-share / concurrent sessions each get a\n * distinct frame and SharedContentId — stale state never leaks across sessions.\n *\n * `closeOnEnd` (default `true`): when the last active session for this frame\n * ends, the connector calls `connector.closeFrame(currentFrameId)`.\n *\n * @returns Unsubscribe function.\n */\nexport function enableMediaLinkAnswerer(\n connector: Connector,\n opts: {\n /** Match prefix. Defaults to `connector.appId`. */\n frameConnectorId?: string\n url: string\n name?: string\n closeOnEnd?: boolean\n size?: { width: number; height: number }\n },\n): () => void {\n const { url, name, closeOnEnd = true, size } = opts\n // Default the match prefix to the connector's appId so callers that omit\n // frameConnectorId work without any extra configuration.\n const prefix = opts.frameConnectorId ?? connector.appId\n let isOpen = false\n let activeSessions = 0\n // The companion-minted frame id of the currently-open answerer frame.\n // Set on the first matching open-answerer; reset to null on frame unload.\n let currentFrameId: string | null = null\n // Sessions whose open-answerer arrived before the answerer frame finished\n // loading (getFrameConnector returns undefined until then). Drained when\n // openFrame resolves; cleared on frame unload.\n const pendingSessions = new Set<string>()\n\n // IMPROVEMENT 6: per-session CRDT control observers, keyed by sessionId.\n // Kept here (outside the message handler) so that the frameUnloaded handler\n // installed ONCE below can unobserve all of them on frame close.\n const sessionControlObservers = new Map<string, { arr: ReturnType<typeof getControlArray>; obs: () => void }>()\n\n const previousHandler = connector.onMessageFromCompanionFrame\n const previousUnloadedHandler = connector.onFrameUnloaded\n\n // IMPROVEMENT 6: register onFrameUnloaded ONCE at setup time (not per session).\n // Capture the previous handler and call it first (same chain pattern used for\n // onMessageFromCompanionFrame). Restore-on-unsubscribe only if our closure is\n // still installed.\n const unloadedHandler = (unloadedId: string) => {\n previousUnloadedHandler?.(unloadedId)\n if (unloadedId === currentFrameId) {\n isOpen = false\n activeSessions = 0\n pendingSessions.clear()\n currentFrameId = null\n // Unobserve all per-session CRDT observers accumulated so far.\n for (const { arr, obs } of sessionControlObservers.values()) {\n arr.unobserve(obs)\n }\n sessionControlObservers.clear()\n }\n }\n connector.onFrameUnloaded = unloadedHandler\n\n const handler = (\n fromCompanionId: string,\n msgFrameConnectorId: string,\n message: string,\n ) => {\n // Forward to any previously-registered handler first.\n previousHandler?.(fromCompanionId, msgFrameConnectorId, message)\n\n // Accept messages whose frame id matches the prefix exactly (backward-compat\n // with a fixed id) OR starts with `<prefix>-` (UUID-suffixed per-session id).\n if (msgFrameConnectorId !== prefix && !msgFrameConnectorId.startsWith(prefix + '-')) return\n\n let parsed: unknown\n try { parsed = JSON.parse(message) } catch { return }\n if (!isMediaLinkOpenAnswererMessage(parsed)) return\n\n // Explicit close from the companion frame (sent on its stop/unmount). This is\n // the reliable, prompt close path — it does not depend on the P2P CRDT control\n // flushing during teardown. Drop that session and close the frame if it was\n // the last one.\n if (parsed.action === 'close-answerer') {\n const sid = parsed.sessionId\n const entry = sessionControlObservers.get(sid)\n if (entry) {\n entry.arr.unobserve(entry.obs)\n sessionControlObservers.delete(sid)\n }\n pendingSessions.delete(sid)\n activeSessions = Math.max(0, activeSessions - 1)\n if (activeSessions === 0 && isOpen && currentFrameId) {\n const frameToClose = currentFrameId\n isOpen = false\n currentFrameId = null\n connector.closeFrame(frameToClose)\n }\n return\n }\n\n if (parsed.action !== 'open-answerer') return\n\n activeSessions++\n\n const sessionId = (parsed as MediaLinkOpenAnswererMessage).sessionId\n\n // Register the per-session CRDT control observer that detects a voluntary\n // stop. `getFrameConnector` only returns once the answerer frame is LOADED,\n // so if it isn't yet — the first session triggers openFrame, or another\n // session arrives during that load — the sessionId is queued (see\n // pendingSessions) and wired when openFrame resolves below. The observer is\n // stored in sessionControlObservers (keyed by sessionId) so the single\n // onFrameUnloaded handler above can clean them all up on frame close.\n const registerSessionObserver = (sid: string) => {\n if (!closeOnEnd) return\n if (sessionControlObservers.has(sid)) return\n if (!currentFrameId) {\n pendingSessions.add(sid)\n return\n }\n const frameConnector = connector.getFrameConnector(currentFrameId)\n if (!frameConnector) {\n pendingSessions.add(sid)\n return\n }\n const controlArr = getControlArray(frameConnector)\n const onControl = () => {\n if (!currentFrameId) return\n const reason = checkVoluntaryStop(frameConnector, sid)\n if (reason != null) {\n controlArr.unobserve(onControl)\n sessionControlObservers.delete(sid)\n activeSessions = Math.max(0, activeSessions - 1)\n if (activeSessions === 0 && isOpen && currentFrameId) {\n const frameToClose = currentFrameId\n isOpen = false\n currentFrameId = null\n connector.closeFrame(frameToClose)\n }\n }\n }\n controlArr.observe(onControl)\n sessionControlObservers.set(sid, { arr: controlArr, obs: onControl })\n }\n\n if (!isOpen) {\n isOpen = true\n // The answerer frame is opened with the companion-minted id so each\n // re-share / concurrent session gets a distinct frame and SharedContentId.\n currentFrameId = msgFrameConnectorId\n const frameOptions: OpenFrameOptions = {\n frameConnectorId: currentFrameId,\n url,\n name: name ?? 'MediaLink',\n ...(size ? { size } : {}),\n }\n // openFrame resolves when the frame connector is LOADED — only then can\n // getFrameConnector return it, so wire any queued sessions on resolution.\n connector\n .openFrame(frameOptions)\n .then(() => {\n for (const sid of pendingSessions) registerSessionObserver(sid)\n pendingSessions.clear()\n })\n .catch((err) => {\n console.error('[lavitre-apps] enableMediaLinkAnswerer openFrame', err)\n })\n }\n\n // Register now if the frame is already loaded; otherwise this queues the\n // sessionId for the openFrame resolution above.\n registerSessionObserver(sessionId)\n }\n\n connector.onMessageFromCompanionFrame = handler\n\n return () => {\n if (connector.onMessageFromCompanionFrame === handler) {\n connector.onMessageFromCompanionFrame = previousHandler\n }\n // Restore onFrameUnloaded only if our closure is still installed.\n if (connector.onFrameUnloaded === unloadedHandler) {\n connector.onFrameUnloaded = previousUnloadedHandler\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Type guard\n// ---------------------------------------------------------------------------\n\nfunction isMediaLinkOpenAnswererMessage(v: unknown): v is MediaLinkOpenAnswererMessage {\n return (\n typeof v === 'object' &&\n v !== null &&\n (v as Record<string, unknown>)['type'] === 'lavitre-media-link' &&\n typeof (v as Record<string, unknown>)['action'] === 'string' &&\n typeof (v as Record<string, unknown>)['frameConnectorId'] === 'string' &&\n typeof (v as Record<string, unknown>)['sessionId'] === 'string'\n )\n}\n"]}
package/dist/Version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const apiVersion = "1.49.0";
1
+ export declare const apiVersion = "1.49.2";
package/dist/Version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const apiVersion = '1.49.0';
1
+ export const apiVersion = '1.49.2';
2
2
  //# sourceMappingURL=Version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Version.js","sourceRoot":"","sources":["../Version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,UAAU,GAAG,QAAQ,CAAA","sourcesContent":["export const apiVersion = '1.49.0'"]}
1
+ {"version":3,"file":"Version.js","sourceRoot":"","sources":["../Version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,UAAU,GAAG,QAAQ,CAAA","sourcesContent":["export const apiVersion = '1.49.2'"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lavitre/apps",
3
- "version": "1.49.0",
3
+ "version": "1.49.2",
4
4
  "description": "TypeScript SDK for building la Vitre apps (connector, frames, companion, CRDT sync)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -63,8 +63,6 @@
63
63
  "lint": "eslint --fix ."
64
64
  },
65
65
  "dependencies": {
66
- "events": "^3.3.0",
67
- "uuid": "^14.0.0",
68
66
  "y-protocols": "^1.0.6",
69
67
  "yjs": "^13.6.31"
70
68
  },