openrtc 1.0.8 → 1.0.10
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.
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a as a$2,c as c$3,b as b$3,d as d$2}from'./chunk-DI5IPRPM.js';import {w,c as c$1,B,D,o,q as q$1,b as b$1,d as d$1,e as e$1,f as f$2,k as k$2,g,h,i as i$1,j as j$1,n as n$1,m as m$1,l as l$1}from'./chunk-YTUWXCRO.js';import {b,e,c as c$2,f as f$1,g as g$2}from'./chunk-QT2ASNI3.js';import {w as w$1,x,u,G,f,p,q,r,b as b$2,j,i,k as k$1,l,n,m,a as a$1,E,d as d$3,e as e$2,t,h as h$1,g as g$1,y,z,B as B$1,A as A$1,C,D as D$1}from'./chunk-HVTYSEU7.js';import {c,a,d}from'./chunk-C7YN5MSV.js';import {x25519}from'@noble/curves/ed25519.js';import {hkdf}from'@noble/hashes/hkdf.js';import {sha256}from'@noble/hashes/sha2.js';import {getFirestore,collection,onSnapshot,query,limit}from'firebase/firestore';import*as kt from'@moq/net';var Gn=3e4,he=class he{constructor(){this.name="webrtc";this.pc=null;this.dc=null;this.state="disconnected";this.pendingCandidates=[];this.connectTimeoutId=null;this.iceDisconnectedGraceTimer=null;this.iceRestartAttempted=false;this.localNodeId="";this.remoteNodeId="";this.candidatesGathered=0;this.sdpOfferSent=false;this.sdpAnswerReceived=false;this._terminalFailure=false;this.activeAttemptId=0;this.negotiationId=null;this.disconnectedGraceExtensions=0;this.offerInFlight=false;this.messageListeners=[];this.stateListeners=[];this.internalSignalSender=null;}get isReady(){return this.state==="connected"}isTerminalFailure(){return this._terminalFailure}getNegotiationId(){return this.negotiationId}getDataChannelReadyState(){return this.dc?.readyState??null}getNativeTransport(){return this.pc}setSignalSender(e){this.internalSignalSender=e;}async init(e,t,n){this.closePeerResources();let i=++this.activeAttemptId;this.localNodeId=e,this.remoteNodeId=t,this.candidatesGathered=0,this.sdpOfferSent=false,this.sdpAnswerReceived=false,this._terminalFailure=false,this.offerInFlight=false,this.pendingCandidates=[],this.disconnectedGraceExtensions=0,this.negotiationId=typeof n?.negotiationId=="string"&&n.negotiationId.trim().length>0?n.negotiationId.trim():this.createNegotiationId(),this.setState("connecting"),this.startConnectTimeout(i);let o=n.rtcConfig||{},s=typeof n?.forceRole=="string"&&(n.forceRole==="initiator"||n.forceRole==="responder")?n.forceRole:null,a=s?s==="initiator":e>t;d$1(`[WebRTCTransport] init \u2014 role=${a?"initiator":"responder"}`,{local:e.slice(0,12),remote:t.slice(0,12),negotiationId:this.negotiationId,forcedRole:s});try{d$1("[WebRTCTransport] Creating RTCPeerConnection",{iceServers:o.iceServers?.length??0}),this.pc=new RTCPeerConnection(o);}catch(l){console.error("[WebRTCTransport] RTCPeerConnection constructor failed",l),this.setState("failed");return}let c=this.pc.createDataChannel("pluto-dc",{negotiated:true,id:0});this.setupDataChannel(c,i),this.setupPCHandlers(a,i),a&&queueMicrotask(()=>{this.createAndSendOffer(i,"initial-initiator");});}setupDataChannel(e,t){this.dc=e,e.onopen=()=>{this.isCurrentAttempt(t,e)&&(d$1("[WebRTCTransport] DataChannel opened \u2014 upgrade complete"),this.promoteConnectedIfReady("datachannel-open"));},e.onmessage=n=>{if(!this.isCurrentAttempt(t,e))return;let i=typeof n.data=="string"?new TextEncoder().encode(n.data):new Uint8Array(n.data);this.messageListeners.forEach(o=>o(i));},e.onclose=()=>{this.isCurrentAttempt(t,e)&&(d$1("[WebRTCTransport] DataChannel closed"),(this.state==="connected"||this.state==="connecting")&&this.setState("disconnected"));},e.onerror=n=>{if(!this.isCurrentAttempt(t,e))return;console.warn("[WebRTCTransport] DataChannel error",n);let i=n?.error?.message??"";if((i.includes("User-Initiated Abort")||i.includes("Close called"))&&this.state==="connected"&&e.readyState!=="open"){console.warn("[WebRTCTransport] DataChannel aborted post-connect; forcing disconnected state",{readyState:e.readyState,connectionState:this.pc?.connectionState,iceConnectionState:this.pc?.iceConnectionState}),this.setState("disconnected");return}this.state==="connecting"&&this.setState("failed");};}setupPCHandlers(e,t){let n=this.pc;n&&(n.onicecandidate=i=>{this.isCurrentAttempt(t,void 0,n)&&(i.candidate?(this.candidatesGathered++,d$1(`[WebRTCTransport] ICE candidate #${this.candidatesGathered}: ${i.candidate.type} ${i.candidate.protocol} ${i.candidate.address??"?"}:${i.candidate.port}`),this.internalSignalSender?this.internalSignalSender({transport:"webrtc",type:"candidate",candidate:i.candidate,negotiationId:this.negotiationId??void 0}).catch(o=>{console.warn("[WebRTCTransport] Failed sending local ICE candidate signal",{error:o,gatheringState:n?.iceGatheringState,iceConnectionState:n?.iceConnectionState});}):console.warn("[WebRTCTransport] ICE candidate dropped \u2014 no signal sender!")):this.candidatesGathered===0?(console.warn("[WebRTCTransport] ICE gathering complete with 0 candidates \u2014 failing immediately.","If both peers are on the same page, WebRTC requires separate tabs or devices.",{local:this.localNodeId.slice(0,12),remote:this.remoteNodeId.slice(0,12)}),this._terminalFailure=true,this.setState("failed")):d$1(`[WebRTCTransport] ICE gathering complete \u2014 ${this.candidatesGathered} candidate(s)`));},n.onnegotiationneeded=async()=>{e&&await this.createAndSendOffer(t,"negotiationneeded");},n.onconnectionstatechange=()=>{if(!this.isCurrentAttempt(t,void 0,n))return;let i=n.connectionState;if(d$1(`[WebRTCTransport] Connection state: ${i}`),i==="connected")this.promoteConnectedIfReady("pc-connected");else if(i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] pc.connectionState=failed during grace window \u2014 deferring to grace timer",{iceState:n.iceConnectionState,iceRestartAttempted:this.iceRestartAttempted});return}console.error("[WebRTCTransport] Connection failed",{iceState:n.iceConnectionState,gatheringState:n.iceGatheringState,signalingState:n.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived}),this.clearIceDisconnectedGrace("pc-failed"),this.setState("failed");}else i==="closed"?(this.clearIceDisconnectedGrace("pc-closed"),this.setState("disconnected")):i==="disconnected"&&(d$1("[WebRTCTransport] pc.connectionState=disconnected, deferring to ICE grace period"),this.startIceDisconnectedGrace(t,n,e,"pc-disconnected"));},n.oniceconnectionstatechange=()=>{if(!this.isCurrentAttempt(t,void 0,n))return;let i=n.iceConnectionState;if(d$1(`[WebRTCTransport] ICE connection state: ${i}`,{gatheringState:n.iceGatheringState,signalingState:n.signalingState,candidatesGathered:this.candidatesGathered,hasSdpOffer:this.sdpOfferSent,hasSdpAnswer:this.sdpAnswerReceived,hasRemoteDescription:!!n.remoteDescription,hasLocalDescription:!!n.localDescription}),i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] ice failed during grace window \u2014 deferring to grace timer");return}console.error("[WebRTCTransport] ICE failed \u2014 likely NAT traversal issue or no matching candidates",{gatheringState:n.iceGatheringState,signalingState:n.signalingState,candidatesGathered:this.candidatesGathered}),this.clearIceDisconnectedGrace("ice-failed"),this.setState("failed");}else i==="disconnected"?this.startIceDisconnectedGrace(t,n,e,"ice-disconnected"):(i==="connected"||i==="completed")&&(this.iceDisconnectedGraceTimer&&d$1("[WebRTCTransport] ice-recovered \u2014 cancelling grace timer"),this.clearIceDisconnectedGrace("ice-recovered"),this.iceRestartAttempted=false,this.promoteConnectedIfReady("ice-connected"));},n.onicegatheringstatechange=()=>{this.isCurrentAttempt(t,void 0,n)&&d$1(`[WebRTCTransport] ICE gathering state: ${n.iceGatheringState}`,{iceConnectionState:n.iceConnectionState,signalingState:n.signalingState,hasLocalDesc:!!n.localDescription,hasRemoteDesc:!!n.remoteDescription});});}async createAndSendOffer(e,t){let n=this.pc;if(!(!n||!this.isCurrentAttempt(e,void 0,n))&&n.signalingState==="stable"&&!(this.sdpOfferSent&&n.localDescription?.type==="offer")&&!this.offerInFlight){d$1(`[WebRTCTransport] Creating offer (${t})`),this.offerInFlight=true;try{let i=await n.createOffer();if(await n.setLocalDescription(i),!this.isCurrentAttempt(e,void 0,n))return;if(this.sdpOfferSent=!0,this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:i,negotiationId:this.negotiationId??void 0});}catch(o){console.warn("[WebRTCTransport] Offer signaling failed (non-fatal)",{error:o,negotiationId:this.negotiationId,signalingState:n.signalingState,iceConnectionState:n.iceConnectionState});}else console.warn("[WebRTCTransport] No signal sender \u2014 offer not transmitted");}catch(i){console.error("[WebRTCTransport] Offer creation failed",i),this.closePeerResources(),this.setState("failed");}finally{this.isCurrentAttempt(e,void 0,n)&&(this.offerInFlight=false);}}}handleSignalingMessage(e){if(!this.pc||e.transport!=="webrtc")return;let t=this.normalizeNegotiationId(e?.negotiationId);if(t&&this.negotiationId&&t!==this.negotiationId){c$1("[WebRTCTransport] Ignoring stale signaling message for a different negotiation",{signalType:e?.type??null,signalNegotiationId:t,activeNegotiationId:this.negotiationId});return}if(e.type==="candidate"){let n=e.candidate;d$1("[WebRTCTransport] Received remote ICE candidate",{hasRemoteDesc:!!this.pc.remoteDescription,type:n?.type,protocol:n?.protocol,address:n?.address}),this.pc.remoteDescription?this.pc.addIceCandidate(n).catch(i=>{console.warn("[WebRTCTransport] addIceCandidate failed",i);}):(this.pendingCandidates.push(n),d$1(`[WebRTCTransport] Buffered remote candidate \u2014 ${this.pendingCandidates.length} pending`));}else if(e.type==="sdp"){let n=e.sdp,i=n.type==="offer",o=n.type==="answer";if(o&&this.pc.signalingState!=="have-local-offer"){c$1("[WebRTCTransport] Ignoring SDP answer because no local offer is pending",{signalingState:this.pc.signalingState,iceConnectionState:this.pc.iceConnectionState,signalNegotiationId:t,activeNegotiationId:this.negotiationId,hasLocalDescription:!!this.pc.localDescription,hasRemoteDescription:!!this.pc.remoteDescription});return}d$1(`[WebRTCTransport] Received SDP ${n.type} \u2014 applying remote description`),o&&(this.sdpAnswerReceived=true),this.pc.setRemoteDescription(n).then(async()=>{if(o&&(d$1("[WebRTCTransport] Remote SDP answer applied",{signalingState:this.pc?.signalingState,iceConnectionState:this.pc?.iceConnectionState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),this.promoteConnectedIfReady("sdp-answer-applied")),this.pendingCandidates.length&&(d$1(`[WebRTCTransport] Flushing ${this.pendingCandidates.length} buffered candidate(s)`),this.pendingCandidates.forEach(s=>this.pc?.addIceCandidate(s)),this.pendingCandidates=[]),i){d$1("[WebRTCTransport] Creating answer (responder)");let s=await this.pc.createAnswer();if(await this.pc.setLocalDescription(s),d$1("[WebRTCTransport] Answer sent"),this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:s,negotiationId:t??this.negotiationId??void 0});}catch(a){throw console.warn("[WebRTCTransport] Failed sending SDP answer signal",{error:a,signalingState:this.pc?.signalingState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),a}else console.warn("[WebRTCTransport] No signal sender \u2014 answer not transmitted");}}).catch(s=>{console.error(`[WebRTCTransport] setRemoteDescription (${n.type}) failed`,s),this.setState("failed");});}}async send(e){if(this.dc&&this.dc.readyState==="open"){let t=new Uint8Array(e);this.dc.send(t);}else throw new Error("WebRTC DataChannel not open")}getBufferedAmount(){return this.dc?.bufferedAmount??0}async waitForDrain(e){!this.dc||this.dc.bufferedAmount<=e||await new Promise(t=>{let n=this.dc;if(!n){t();return}n.bufferedAmountLowThreshold=e,n.onbufferedamountlow=()=>{n.onbufferedamountlow=null,t();};});}close(){this.closePeerResources(),this.setState("disconnected");}onMessage(e){this.messageListeners.push(e);}onStateChange(e){this.stateListeners.push(e);}setState(e){this.state!==e&&(this.state=e,(e==="connected"||e==="failed"||e==="disconnected")&&this.clearConnectTimeout(),this.stateListeners.forEach(t=>t(e)));}startConnectTimeout(e){this.clearConnectTimeout(),this.connectTimeoutId=setTimeout(()=>{this.activeAttemptId===e&&this.state==="connecting"&&(console.warn(`[WebRTCTransport] Timed out after ${he.ICE_CONNECT_TIMEOUT_MS}ms`,{iceState:this.pc?.iceConnectionState,gatheringState:this.pc?.iceGatheringState,signalingState:this.pc?.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived,hasRemoteDescription:!!this.pc?.remoteDescription,hasLocalDescription:!!this.pc?.localDescription}),this.setState("failed"));},he.ICE_CONNECT_TIMEOUT_MS);}clearConnectTimeout(){this.connectTimeoutId&&(clearTimeout(this.connectTimeoutId),this.connectTimeoutId=null);}startIceDisconnectedGrace(e,t,n,i){if(!this.iceDisconnectedGraceTimer){if(this.iceRestartAttempted)d$1("[WebRTCTransport] ice-disconnected grace (restart already attempted)",{reason:i});else if(this.iceRestartAttempted=true,n){try{d$1("[WebRTCTransport] ice-restart-attempted",{reason:i,isInitiator:n}),t.restartIce();}catch(o){console.warn("[WebRTCTransport] restartIce threw",o);}this.sendIceRestartOffer(e,t);}else d$1("[WebRTCTransport] ice-restart deferred to initiator",{reason:i});this.iceDisconnectedGraceTimer=setTimeout(()=>{if(this.iceDisconnectedGraceTimer=null,this.activeAttemptId!==e||this.pc!==t)return;let o=t.iceConnectionState,s=t.connectionState,a=this.dc?.readyState??"missing";if(o==="connected"||o==="completed"||s==="connected"||a==="open"){d$1("[WebRTCTransport] ice-grace expired \u2014 recovered",{ice:o,conn:s,dcReadyState:a});return}if(this.disconnectedGraceExtensions<1){this.disconnectedGraceExtensions+=1,console.warn("[WebRTCTransport] ice-grace expired \u2014 extending once before fail",{ice:o,conn:s,dcReadyState:a,extension:this.disconnectedGraceExtensions}),this.startIceDisconnectedGrace(e,t,n,`${i}:extended`);return}console.warn("[WebRTCTransport] ice-grace expired \u2014 marking failed",{ice:o,conn:s}),this.setState("failed");},he.ICE_DISCONNECTED_GRACE_MS);}}async sendIceRestartOffer(e,t){try{let n=await t.createOffer({iceRestart:!0});if(!this.isCurrentAttempt(e,void 0,t)||(await t.setLocalDescription(n),!this.isCurrentAttempt(e,void 0,t)))return;this.internalSignalSender?(await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:n,negotiationId:this.negotiationId??void 0}),d$1("[WebRTCTransport] ice-restart re-offer sent",{negotiationId:this.negotiationId})):console.warn("[WebRTCTransport] ice-restart re-offer dropped \u2014 no signal sender");}catch(n){console.warn("[WebRTCTransport] ice-restart re-offer failed",n);}}clearIceDisconnectedGrace(e){this.iceDisconnectedGraceTimer&&(clearTimeout(this.iceDisconnectedGraceTimer),this.iceDisconnectedGraceTimer=null);}promoteConnectedIfReady(e){let t=this.dc?.readyState??"missing";if(t!=="open"){d$1("[WebRTCTransport] Deferring connected state until DataChannel is open",{reason:e,dcReadyState:t,iceConnectionState:this.pc?.iceConnectionState,connectionState:this.pc?.connectionState});return}this.clearIceDisconnectedGrace(`connected:${e}`),this.disconnectedGraceExtensions=0,this.setState("connected");}closePeerResources(){this.activeAttemptId+=1,this.clearConnectTimeout(),this.clearIceDisconnectedGrace("close"),this.iceRestartAttempted=false,this.pendingCandidates=[],this._terminalFailure=false,this.negotiationId=null,this.disconnectedGraceExtensions=0,this.offerInFlight=false,this.dc&&(this.dc.onopen=null,this.dc.onmessage=null,this.dc.onclose=null,this.dc.onerror=null,this.dc.readyState!=="closed"&&this.dc.close(),this.dc=null),this.pc&&(this.pc.onicecandidate=null,this.pc.onnegotiationneeded=null,this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.connectionState!=="closed"&&this.pc.close(),this.pc=null);}isCurrentAttempt(e,t,n){return !(this.activeAttemptId!==e||t&&this.dc!==t||n&&this.pc!==n)}createNegotiationId(){return `ts-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}normalizeNegotiationId(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}};he.ICE_CONNECT_TIMEOUT_MS=Gn,he.ICE_DISCONNECTED_GRACE_MS=3e4;var tt=he;var ss={iroh:{available:false,reason:"iroh is constructed by the OpenRTC runtime, not the legacy ITransport factory."},"iroh-quic":{available:false,reason:"iroh-quic is a path label, not a standalone transport."},"iroh-relay":{available:false,reason:"iroh-relay is a path label, not a standalone transport."},"iroh-lan":{available:false,reason:"iroh-lan is a path label, not a standalone transport."},ble:{available:false,reason:"ble requires a separately licensed native host companion and current physical-device evidence."},webrtc:{available:true},"webrtc-lan":{available:false,reason:"webrtc-lan is a path label, not a standalone transport."},"webrtc-turn":{available:false,reason:"webrtc-turn is a path label, not a standalone transport."},moq:{available:false,reason:"MoQ is constructed by the route lifecycle, not the legacy ITransport factory."}};function as(r){return r.implementation==="route-adapter"?"plugin":r.implementation==="core"?"native":"path-label"}function cs(){return Object.fromEntries(a.map(r=>[r.id,{...r,routeImplementation:r.implementation,implementation:as(r),protocol:r.id,preferredRank:d[r.id],...ss[r.id]}]))}var ce=class{static createTransport(e){if(this.assertProtocolAvailable(e),e==="webrtc")return new tt;throw new Error(`[TransportFactory] '${e}' is not implemented as an ITransport plugin.`)}static getProtocolCapability(e){return {...this.capabilityMap[e]}}static getProtocolCapabilities(){return Object.fromEntries(a.map(e=>[e.id,this.getProtocolCapability(e.id)]))}static getPreferredProtocolOrder(e={}){let t=e.runtime??"any",n=e.includePathLabels??true;return a.filter(i=>n||i.implementation!=="path-label").filter(i=>t==="browser"?i.browser:t==="native"?i.native:i.browser||i.native).sort((i,o)=>d[i.id]-d[o.id]).map(i=>i.id)}static assertProtocolAvailable(e){let t=this.capabilityMap[e];if(!t.available||t.maturity==="unsupported"){let n=t.reason?` ${t.reason}`:"";throw new Error(`[TransportFactory] Protocol '${e}' is unsupported.${n}`)}}};ce.capabilityMap=cs();function Aa(r){return ce.getPreferredProtocolOrder(r)}var nt=32,no="openrtc:x25519-hkdf:v1",Kn=new TextEncoder().encode("openrtc:application-crypto:v1");function it(r,e){if(!(e instanceof Uint8Array)||e.byteLength!==nt)throw new Error(`[OpenRTC] ${r} must be ${nt} bytes`)}function ds(r,e){let[t,n]=r<=e?[r,e]:[e,r],i=new TextEncoder().encode(t),o=new TextEncoder().encode(n),s=new Uint8Array(Kn.byteLength+1+i.byteLength+1+o.byteLength),a=0;return s.set(Kn,a),a+=Kn.byteLength,s[a]=0,a+=1,s.set(i,a),a+=i.byteLength,s[a]=0,a+=1,s.set(o,a),s}function io(r=e=>{let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),t}){let e=r(nt);return it("key agreement secret",e),{publicKey:x25519.getPublicKey(e),secretKey:e}}function oo(r,e,t,n){it("key agreement local secret",r),it("key agreement remote public key",e);let i=x25519.getSharedSecret(r,e);return hkdf(sha256,i,void 0,ds(t,n),32)}function xe(r){return Array.from(sha256(r).slice(0,6),e=>e.toString(16).padStart(2,"0")).join("")}function ro(r){it("key agreement public key",r);let e="";for(let n=0;n<r.byteLength;n+=1)e+=String.fromCharCode(r[n]);let t=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return {algorithm:no,publicKey:t}}function so(r){if(!r||r.algorithm!==no)return null;let e=typeof r.publicKey=="string"?r.publicKey.trim():"";if(!e)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4===0?t:t+"=".repeat(4-t.length%4),i=Uint8Array.from(atob(n),o=>o.charCodeAt(0));return i.byteLength!==nt?null:i}var ot=class{constructor(e,t){this._disposed=false;this.cleanups=[];this.runtime=e,this.scope=t.scope,this.allowAllPeers=t.allowAllPeers??false,this.allowedPeerIds=new Set(t.allowPeers??[]);}get disposed(){return this._disposed}matchesPeer(e){if(this.allowAllPeers||e.scopes?.includes(this.scope))return true;if(this.allowedPeerIds.size>0){let t=[e.peerId,e.deviceId,e.deviceIdHint,e.connectionId];for(let n of t)if(n&&this.allowedPeerIds.has(n))return true}return false}matchesConnectionState(e){if(this.allowAllPeers)return true;let t=e.scopes;if(Array.isArray(t)&&t.includes(this.scope))return true;if(this.allowedPeerIds.size>0){let n=[e.connectionId,e.deviceId,e.deviceIdHint,e.remoteNodeId];for(let i of n)if(i&&this.allowedPeerIds.has(i))return true}return false}matchesStream(e){if(this.allowAllPeers)return true;let t=e.scopes;return !!(Array.isArray(t)&&t.includes(this.scope)||this.allowedPeerIds.size>0&&this.allowedPeerIds.has(e.remoteNodeId))}watchPeerStates(e){this.assertNotDisposed();let t=this.runtime.watchPeerStates(n=>{if(this._disposed)return;let i=this.allowAllPeers?n:n.filter(o=>this.matchesPeer(o));e(i);});return this.cleanups.push(t),t}onConnectionStateChange(e){this.assertNotDisposed();let t=o=>{this._disposed||this.matchesConnectionState(o)&&e(o);},n=this.runtime.onConnectionStateChange(t);return typeof n=="function"?(this.cleanups.push(n),n):n.then(o=>this._disposed?(o(),()=>{}):(this.cleanups.push(o),o))}listConnectedPeers(){this.assertNotDisposed();let e=this.runtime.listConnectedPeers();return this.allowAllPeers?e:e.filter(t=>this.matchesPeer(t))}async getPeerReadiness(e){return this.assertNotDisposed(),this.runtime.getPeerReadiness(e)}connectPeer(e){return this.assertNotDisposed(),this.runtime.connectPeer({...e,scope:e.scope??this.scope})}async disconnectPeer(e){return this.assertNotDisposed(),this.runtime.disconnectPeer(e,this.scope)}onIncomingStream(e){this.assertNotDisposed();let t=this.runtime.onIncomingStream(n=>{this._disposed||this.matchesStream(n)&&e(n);});return this.cleanups.push(t),t}dispose(){if(!this._disposed){this._disposed=true;for(let e of this.cleanups)try{e();}catch{}this.cleanups.length=0,this.releaseScopedPeersOnDispose();}}releaseScopedPeersOnDispose(){let e;try{e=this.runtime.listConnectedPeers();}catch{return}for(let t of e){if(!t.scopes?.includes(this.scope))continue;let n=t.peerId||t.connectionId||t.deviceId||t.deviceIdHint;n&&this.runtime.disconnectPeer(n,this.scope).catch(()=>{});}}assertNotDisposed(){if(this._disposed)throw new Error(`[Session] Session '${this.scope}' has been disposed.`)}};var rt=class{constructor(e,t,n=()=>{}){this.client=e;this.backend=t;this.onLifecycleMutation=n;}async connectToDevice(e){let t=this.backend;if(!t||typeof t.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return e.deviceId&&(this.clearManualDisconnectProjection(e.deviceId),await t.setAutoConnectExcluded?.(e.deviceId,false).catch(()=>{})),t.connectToDevice(e)}async connectRaw(e){return this.client.connectRaw(e.ticket,e.timeoutMs)}async openBi(e){return this.client.openBi(e)}async openUni(e){return this.client.openUni(e)}async isConnected(e){return this.client.isConnected(e)}async disconnectNode(e){try{await this.client.disconnectNode(e);}finally{this.onLifecycleMutation();}}async disconnectDevice(e){let t=this.backend;await t?.setAutoConnectExcluded?.(e,true).catch(()=>{});try{try{t&&typeof t.disconnectDevice=="function"&&await t.disconnectDevice(e);}finally{await this.client.forceDisconnectPeer(e);}}finally{this.onLifecycleMutation();}}async setAutoConnectExcluded(e,t){let n=this.backend;n&&typeof n.setAutoConnectExcluded=="function"&&await n.setAutoConnectExcluded(e,t),t||this.clearManualDisconnectProjection(e);}async disconnectPeer(e,t){try{await this.client.disconnectPeer(e,t);}finally{this.onLifecycleMutation();}}async forceDisconnectPeer(e){try{await this.client.forceDisconnectPeer(e);}finally{this.onLifecycleMutation();}}clearManualDisconnectProjection(e){let t=this.client.clearManualDisconnectProjection;typeof t=="function"&&t.call(this.client,e);}};var co={classifyScope(r){return r.startsWith("drive-grant:")?{sessionKind:"drive-grant-guest",grantId:r.slice(12),scope:r}:r==="user-device"?{sessionKind:"app-user-device",scope:r}:{scope:r}}},ps=[["sessionKind","session_kind"],["grantId","grant_id"],["scope","scope"],["peerNodeId","peer_node_id"],["connectionId","connection_id"],["transportEpoch","transport_epoch"],["channel","channel"],["tokenFp","token_fp"]];function us(r){let e=[];for(let[t,n]of ps){let i=r[t];i==null||i===""||e.push(`${n}=${i}`);}return e.join(" ")}function gs(r,e,t=co){let n=t.classifyScope(r);return {...{sessionKind:n.sessionKind,grantId:n.grantId,scope:n.scope??r},...e??{}}}function _e(r,e){return gs(r,e,co)}function $(r,e,t,...n){let i=us(e),o=hs(t,n);console.log(i&&o?`${r} ${i} ${o}`:i?`${r} ${i}`:o?`${r} ${o}`:r);}function hs(r,e){if(!r)return "";if(e.length===0)return r;if(/\{\}/.test(r)){let n=0;return r.replace(/\{\}/g,()=>{let i=n<e.length?e[n]:"";return n+=1,ao(i)})}return [r,...e.map(ao)].join(" ")}function ao(r){if(r==null)return String(r);if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);try{return JSON.stringify(r)}catch{return String(r)}}var X=class extends Error{constructor(e,t){super(t),this.kind=e,this.name="DriveGrantActorError";}};function zn(r,e){return {scope:r,peerNodeId:e}}function qn(r){return `${r.scope}@${r.peerNodeId}`}var Fe=class{constructor(e){this.state="idle";this.inFlight=null;this.key=e.key,this.dial=e.dial,this.close=e.close??(async()=>{});}isReady(){return this.state==="base-ready"||this.state==="protocol-ready"}isClosed(){return this.state==="closed"}getState(){return this.state}getPreferredTransport(){return this.state==="closed"||this.state==="idle"||this.state==="dialing"?"none":"base"}markProtocolReady(){this.state!=="closed"&&(this.state="protocol-ready",$("[drive-grant-actor][state]",this.correlation(),"state=protocol-ready"));}markDegraded(){this.state!=="closed"&&(this.state="degraded",$("[drive-grant-actor][state]",this.correlation(),"state=degraded"));}correlation(e){return _e(this.key.scope,{peerNodeId:this.key.peerNodeId,...e??{}})}async ensureReady(){if(this.state==="closed")throw new X("shutdown","drive-grant actor: already shut down");if(!this.isReady())return this.inFlight?this.inFlight:(this.state="dialing",$("[drive-grant-actor][dial]",this.correlation(),"begin"),this.inFlight=this.dial(this.key).then(()=>{this.state!=="closed"&&(this.state="base-ready",this.inFlight=null,$("[drive-grant-actor][dial]",this.correlation(),"ready_first"));},e=>{this.state!=="closed"&&(this.state="idle"),this.inFlight=null;let t=e instanceof Error?e.message:String(e);throw $("[drive-grant-actor][dial]",this.correlation(),"failed error={}",t),e instanceof X?e:new X("dial-failed",`drive-grant actor: dial failed: ${t}`)}),this.inFlight)}async openLogicalChannel(e){if(this.state==="closed")throw new X("shutdown","drive-grant actor: already shut down");if(!this.isReady())throw new X("not-ready","drive-grant actor: ensureReady() must resolve before openLogicalChannel");return $("[drive-grant-actor][channel]",this.correlation({channel:e}),"open"),{label:e}}async openLogicalChannelTestStub(e){if(this.state==="closed")throw new X("shutdown","drive-grant actor: already shut down");if(!this.isReady())throw new X("not-ready","drive-grant actor: ensureReady() must resolve before openLogicalChannel");return {label:e}}async shutdown(){if(this.state!=="closed"){this.state="closed",this.inFlight=null,$("[drive-grant-actor][shutdown]",this.correlation(),"begin");try{await this.close(this.key);}catch{}$("[drive-grant-actor][shutdown]",this.correlation(),"complete");}}},Be=class{constructor(e){this.actors=new Map;this.factory=e;}getOrSpawn(e,t){let n=qn(e),i=this.actors.get(n);if(i&&!i.isClosed())return i;let o=(t??this.factory)(e);return this.actors.set(n,o),o}get(e){return this.actors.get(qn(e))??null}async shutdownAll(){let e=[...this.actors.values()];this.actors.clear(),await Promise.all(e.map(t=>t.shutdown()));}size(){return this.actors.size}};var ms=new TextEncoder,fs=new TextDecoder;function Qn(r){let e=new Uint8Array(4+r.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,r.byteLength,false),e.set(r,4),e}function ys(r){let e=new Uint8Array(0);return t=>{for(e=$n(e,t);e.byteLength>=4;){let n=Vn(e,0);if(e.byteLength<4+n)break;r(e.slice(4,4+n)),e=e.slice(4+n);}}}function vs(r){return ms.encode(JSON.stringify(r))}function Cs(r){return JSON.parse(fs.decode(r))}function Ha(r){return Qn(vs(r))}function Ua(r,e={}){return ys(t=>{try{r(Cs(t),t);}catch(n){if(e.onInvalidJson){e.onInvalidJson(n,t);return}throw n}})}function $n(r,e){return w$1([r,e])}function Vn(r,e){return (r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}var me=class{constructor(e,t){this.appTag=b$2(e),this.backend=t;}get tag(){return this.appTag}async waitForAuth(){return this.backend.waitForAuth()}get currentUser(){return this.backend.currentUser}getRtdbPresence(){let e=this.backend;return typeof e.getRtdbPresence=="function"?e.getRtdbPresence():e.rtdbPresence??null}onAuthChange(e){return this.backend.onAuthChange(e)}async signInAnonymously(){await this.backend.signInAnonymously();}async signInWithPluto(){if(typeof this.backend.signInWithPluto=="function"){await this.backend.signInWithPluto();return}await G().signInWithPluto();}async signOut(){await this.backend.signOut();}async stopAuthScopedActivity(){typeof this.backend.stopAuthScopedActivity=="function"&&await this.backend.stopAuthScopedActivity();}getRuntimeCapabilities(){return this.backend.getRuntimeCapabilities?.()}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n=true,i=300*1e3,o){await this.backend.updatePresence(e,t,n,i,o);}async setOffline(e){await this.backend.setOffline(e);}async cleanupStaleDevices(){await this.backend.cleanupStaleDevices();}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}async subscribeSessions(e,t){let i=(await this.backend.subscribeSessions(e)).getReader(),o=false;return (async()=>{try{for(;!o;){let{done:a,value:c}=await i.read();if(a)break;if(c)for(let l of c)"session"in l&&l.session&&await t(l.session);}}catch(a){o||console.error("[Signaling] Session stream error:",a);}})(),()=>{o=true,i.cancel();}}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async searchDevices(e){return this.backend.searchDevices(e)}async updateDevice(e,t){await this.backend.updateDevice(e,t);}async deleteDevice(e){await this.backend.deleteDevice(e);}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}notifyDisconnectRequested(e){typeof this.backend.notifyDisconnectRequested=="function"&&this.backend.notifyDisconnectRequested(e);}startPresenceLoop(e,t,n,i,o){this.backend.startPresenceLoop(e,t,n,i,o);}forceReconnectSnapshot(){this.backend.forceReconnectSnapshot();}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates=="function"?this.backend.getConnectionStates():[]}onConnectionStateChange(e){return typeof this.backend.onConnectionStateChange=="function"?this.backend.onConnectionStateChange(e):()=>{}}supportsRustPeerLifecycleProjection(){return typeof this.backend.listPeerSessions=="function"||typeof this.backend.getPeerSession=="function"||typeof this.backend.waitForSettledPeer=="function"||typeof this.backend.getConnectionStates=="function"}setWasmClient(e){let t=this.backend;t&&typeof t.setWasmClient=="function"&&t.setWasmClient(e);}};var Ts=6e5,As=250,ws=20,ks=100,st=class{constructor(e){this.options=e;this.rtdbPresence=null;this.firestore=getFirestore(e.app);}setRtdbPresence(e){this.rtdbPresence=e;}watchMembers(e,t,n){let i=collection(this.firestore,`${this.getNamespaceRoot()}/rooms/${e}/members`);return this.rtdbPresence?this.watchMembersWithRtdb(e,t,i,n):this.watchMembersSnapshot(i,o=>{let s=Date.now(),a=o.docs.map(c=>this.toRoomMember(c)).filter(c=>!!c).filter(c=>c.nodeId!==t).filter(c=>!this.isExpired(c,s)).sort((c,l)=>c.joinedAt!==l.joinedAt?c.joinedAt-l.joinedAt:c.nodeId.localeCompare(l.nodeId));n(a);})}watchMembersWithRtdb(e,t,n,i){let o=this.rtdbPresence,s=this.getAppTag(),a=[],c={},l=()=>{let u=Date.now(),f=a.filter(h=>h.nodeId!==t).filter(h=>!this.isExpired(h,u)).filter(h=>{let m=c[h.nodeId];return !(m&&!m.online)}).sort((h,m)=>h.joinedAt!==m.joinedAt?h.joinedAt-m.joinedAt:h.nodeId.localeCompare(m.nodeId));i(f);},d=this.watchMembersSnapshot(n,u=>{a=u.docs.map(f=>this.toRoomMember(f)).filter(f=>!!f),l();}),p=o.onRoomPresenceChange(s,e,u=>{c=u,l();});return ()=>{d(),p();}}watchMembersSnapshot(e,t){let n=false,i=0,o=null,s=null,a=()=>{n||(s=onSnapshot(query(e,limit(ks)),c=>{i=0,t(c);},c=>{if(s=null,this.isTransientPermissionError(c)&&i<ws){i+=1,o=setTimeout(a,As);return}console.warn("[BrowserFirestoreRooms] room watch failed:",c);}));};return a(),()=>{n=true,o&&(clearTimeout(o),o=null),s?.(),s=null;}}isTransientPermissionError(e){if(e?.code==="permission-denied")return true;let n=e instanceof Error?e.message:String(e);return /permission-denied|missing or insufficient permissions/i.test(n)}getNamespaceRoot(){let e=this.options.getRoomBackendTag().trim();if(!e)throw new Error("Room backend tag is required for browser room watches");return e.startsWith("space::")?`spaces/${e.slice(7)}`:`apps/${e}`}getAppTag(){return this.options.getRoomBackendTag().trim()}toRoomMember(e){let t=e.data(),n=typeof t.nodeId=="string"&&t.nodeId.trim().length>0?t.nodeId.trim():e.id,i=typeof t.ticket=="string"?t.ticket:"";return {nodeId:n,userId:typeof t.userId=="string"?t.userId:"",ticket:i,joinedAt:this.toMillis(t.joinedAt)??0,lastSeenAt:this.toMillis(t.lastSeenAt)??0,expiresAt:this.toMillis(t.expiresAt)}}isExpired(e,t){if(typeof e.expiresAt=="number")return e.expiresAt<=t;let n=e.lastSeenAt||e.joinedAt||0;return n>0&&n+Ts<=t}toMillis(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Number(e);if(Number.isFinite(t))return t;let n=Date.parse(e);return Number.isNaN(n)?void 0:n}if(e instanceof Date)return e.getTime();if(e&&typeof e=="object"&&typeof e.toMillis=="function")try{return e.toMillis()}catch{return}}};function lo(r){return {get wasmClient(){return r.wasmClient},get roomCreationMode(){return r.roomCreationMode},get appLimits(){return r.appLimits},ensureAuthenticated:e=>r.ensureAuthenticated(e),getTicketWithToken:(e,t)=>r.getTicketWithToken(e,t),getNodeId:()=>r.getNodeId(),connect:(e,t)=>r.connect(e,t),refreshHostedAppSettings:e=>r.refreshHostedAppSettings(e),usesDirectRoomBackend:()=>r.usesDirectRoomBackend(),getRoomBackendTag:()=>r.getRoomBackendTag()}}var Ie=class{constructor(e,t){this.heartbeatStops=new Map;this.browserRooms=null;this.rtdbPresence=null;this.client=e,this.signaling=t;}getBrowserRooms(){return this.browserRooms||(this.browserRooms=new st({app:G().getApp(),getRoomBackendTag:()=>this.client.getRoomBackendTag()})),this.rtdbPresence&&this.browserRooms&&this.browserRooms.setRtdbPresence(this.rtdbPresence),this.browserRooms}setRtdbPresence(e){this.rtdbPresence=e,this.browserRooms&&this.browserRooms.setRtdbPresence(e);}syncRtdbPresenceFromSignaling(){if(this.rtdbPresence)return;let e=this.signaling.getRtdbPresence();if(e){this.setRtdbPresence(e);return}try{this.setRtdbPresence(new e$1(G().getApp()));}catch{}}usesDirectRoomBackend(){return this.client.usesDirectRoomBackend()}get roomBackendTag(){return this.client.getRoomBackendTag()}resolveRoomUserId(e){return G().getCurrentUser?.()?.uid??this.signaling.currentUser?.id??e??"anonymous"}get appTag(){return this.signaling.tag}async invokeRoomCallable(e,t){let{getFunctions:n,httpsCallable:i}=await import('firebase/functions'),o=n(G().getApp());return (await i(o,e)(t)).data}isAlreadyExistsError(e){if(!e||typeof e!="object")return false;let t="code"in e&&typeof e.code=="string"?e.code:"",n="message"in e&&typeof e.message=="string"?e.message:"";return t.includes("already-exists")||n.toLowerCase().includes("already exists")}normalizeRoomId(e){return e.trim().toUpperCase()}async getMembersInternal(e,t){if(!this.client.wasmClient)throw new Error("WASM Client not loaded");let n=t??await this.client.getNodeId(),i=await this.client.wasmClient.get_members(e,n,this.roomBackendTag);return this.parseMemberDocuments(i)}parseMemberDocuments(e){return JSON.parse(e).map(n=>this.parseRoomMemberDocument(n))}parseRoomMemberDocument(e){let t=e.fields;return {nodeId:t.nodeId?.stringValue||e.name.split("/").pop(),userId:t.userId?.stringValue,ticket:t.ticket?.stringValue,joinedAt:t.joinedAt?.integerValue?parseInt(t.joinedAt.integerValue):void 0,lastSeenAt:t.lastSeenAt?.integerValue?parseInt(t.lastSeenAt.integerValue):void 0,expiresAt:t.expiresAt?.integerValue?parseInt(t.expiresAt.integerValue):void 0}}async createRoom(e){if(await this.client.ensureAuthenticated("room-op"),!this.client.wasmClient)throw new Error("WASM Client not loaded");this.syncRtdbPresenceFromSignaling();let t=await this.client.getNodeId(),n=this.resolveRoomUserId(t);if(!this.usesDirectRoomBackend()){if(await this.client.refreshHostedAppSettings(),this.client.roomCreationMode==="server-only")throw new Error("This app uses server-only room creation. Create the room on your backend with your sk_live_... key, then call joinRoom(roomId) on the client.");let c="",l=false,d=typeof e=="string"&&e.trim().length>0?e.trim().toUpperCase():"",p=d?1:3;for(let u=0;u<p;u+=1){if(d)c=d;else {let h=new Uint8Array(6);crypto.getRandomValues(h),c=Array.from(h,m=>m.toString(36).padStart(2,"0")).join("").substring(0,6).toUpperCase();}let f=await this.client.getTicketWithToken(`room:${c}`,0);try{await this.invokeRoomCallable("createClientRoom",{appTag:this.appTag,roomId:c,nodeId:t,ticket:f}),l=!0;break}catch(h){if(this.isAlreadyExistsError(h)){if(d)throw h;continue}throw h}}if(!l)throw new Error(d?`Failed to create requested room "${d}".`:"Failed to create room after multiple attempts (ID collisions).");return await this.registerRtdbRoomMember(c,t),c}let i="",o=false,s=typeof e=="string"&&e.trim().length>0?e.trim().toUpperCase():"",a=s?1:3;for(let c=0;c<a;c++){if(s)i=s;else {let p=new Uint8Array(6);crypto.getRandomValues(p),i=Array.from(p,u=>u.toString(36).padStart(2,"0")).join("").substring(0,6).toUpperCase();}let l=await this.client.getTicketWithToken(`room:${i}`,0);await this.client.refreshHostedAppSettings();let d=this.client.appLimits.maxMembersPerRoom>=0?this.client.appLimits.maxMembersPerRoom:50;if(o=await this.client.wasmClient.create_room(i,n,l,t,this.roomBackendTag,d),o){console.log(`Room created: ${i}`);break}else {if(s)throw new Error(`Room "${i}" already exists.`);console.log(`Collision for roomId ${i}, retrying...`);}}if(!o)throw new Error(s?`Failed to create requested room "${s}".`:"Failed to create room after multiple attempts (ID collisions).");return await this.registerRtdbRoomMember(i,t),i}async joinRoom(e,t={}){if(await this.client.ensureAuthenticated("room-op"),!this.client.wasmClient)throw new Error("WASM Client not loaded");if(this.syncRtdbPresenceFromSignaling(),typeof e!="string"||e.length===0||e.length>64)throw new Error("roomId must be a non-empty string of at most 64 characters");if(e!=="demo"&&!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error("roomId must contain only alphanumeric characters, hyphens, or underscores");let n=await this.client.getNodeId(),i=this.resolveRoomUserId(n),o=this.normalizeRoomId(e),s=await this.client.getTicketWithToken(`room:${o}`,0);console.log("[RoomManager] joinRoom request",{roomId:e,normalizedId:o,targetRoomId:o,tag:this.roomBackendTag,userId:i,myNodeId:n,hasTicket:!!s,ticketLength:s?.length||0});try{this.usesDirectRoomBackend()?await this.client.wasmClient.join_room(o,i,s,n,this.roomBackendTag):(await this.client.refreshHostedAppSettings(),await this.invokeRoomCallable("joinClientRoom",{appTag:this.appTag,roomId:o,nodeId:n,ticket:s})),console.log(`Joined room: ${o}`);}catch(c){throw c$1("[RoomManager] joinRoom failed",c),c}let a=[];if(t.bootstrapPeers!==false){let l=(await this.getMembersInternal(o,n)).map(async p=>{let u=false,f=Date.now();if(p.expiresAt)p.expiresAt<f&&(u=true);else {let h=p.lastSeenAt||p.joinedAt||0;f-h>300*1e3&&(u=true);}if(u)return null;if(p.ticket)try{console.log(`Bootstrapping: Connecting to peer ${p.nodeId}...`);let h=await this.client.connect(p.ticket,5e3);return h.send({type:"chat",text:`Use ${i} joined the room.`}).catch(m=>{c$1("[RoomManager] join notification send skipped",{roomId:o,peerNodeId:p.nodeId,error:m});}),h}catch(h){return console.warn(`Failed to connect to peer ${p.nodeId}:`,h),null}return null});(await Promise.allSettled(l)).forEach(p=>{p.status==="fulfilled"&&p.value&&a.push(p.value);});}return await this.registerRtdbRoomMember(o,n),a}async leaveRoom(e){this.usesDirectRoomBackend()||await this.client.ensureAuthenticated("room-op");let t=await this.client.getNodeId();if(!t)return;console.log(`Leaving room ${e}...`),await this.markRtdbRoomMemberOffline(e,t),this.stopHeartbeat(e);let n=this.normalizeRoomId(e);try{this.usesDirectRoomBackend()?await this.client.wasmClient.leave_room(n,t,this.roomBackendTag):await this.invokeRoomCallable("leaveClientRoom",{appTag:this.appTag,roomId:n,nodeId:t}),console.log(`Left room: ${n}`);}catch(i){throw console.warn("Leave room failed:",i),i}}async getRoomMembers(e){await this.client.ensureAuthenticated("room-op");let t=this.normalizeRoomId(e);return this.getMembersInternal(t)}watchRoom(e,t){let n=false,i=null;return (async()=>{try{if(await this.client.ensureAuthenticated("room-op"),n)return;let o=this.normalizeRoomId(e),s=await this.client.getNodeId();if(n)return;i=this.getBrowserRooms().watchMembers(o,s,t),n&&(i(),i=null);}catch(o){n||console.warn("[RoomManager] watchRoom listener failed:",o);}})(),()=>{n=true,i?.(),i=null;}}async registerRtdbRoomMember(e,t){if(this.stopHeartbeat(e),this.rtdbPresence){let n=this.roomBackendTag;try{await this.rtdbPresence.registerRoomMember(n,e,t);}catch(i){throw new Error(`[RoomManager] RTDB room member register failed for ${e}: ${i instanceof Error?i.message:String(i)}`)}this.heartbeatStops.set(e,()=>{this.markRtdbRoomMemberOffline(e,t);});}else throw new Error(`[RoomManager] RTDB presence is required for room liveness (${e}); legacy Firestore heartbeat is disabled`)}async markRtdbRoomMemberOffline(e,t){if(!this.rtdbPresence)return;let n=this.roomBackendTag;try{await this.rtdbPresence.markRoomMemberOffline(n,e,t);}catch(i){console.warn("[RoomManager] RTDB markRoomMemberOffline failed:",i);}}stopHeartbeat(e){if(typeof e=="string"){let t=this.heartbeatStops.get(e);t&&(t(),this.heartbeatStops.delete(e),console.log(`Heartbeat stopped for room ${e}.`));return}for(let[t,n]of this.heartbeatStops.entries())n(),console.log(`Heartbeat stopped for room ${t}.`);this.heartbeatStops.clear();}};function Ns(r,e){let t=r.trim();if(!t)throw new Error("Channel envelope requires a non-empty channel id.");let n=new TextEncoder,i=n.encode(t),o=e?n.encode(JSON.stringify(e)):new Uint8Array(0),s=new Uint8Array(6+i.byteLength+o.byteLength),a=new DataView(s.buffer);return s[0]=127,s[1]=1,a.setUint16(2,i.byteLength,false),a.setUint16(4,o.byteLength,false),s.set(i,6),s.set(o,6+i.byteLength),s}function po(r,e,t){let n=Ns(e,t),i=r.getWriter(),o=false,s=async()=>{o||(o=true,await i.write(n));};return new WritableStream({write:async a=>{await s(),await i.write(a);},close:async()=>{await s();try{await i.close();}finally{i.releaseLock();}},abort:async a=>{try{await i.abort(a);}finally{i.releaseLock();}}})}var Yn=[0,300,600,1e3,1500,2e3,2500,3e3,3500,3500,3500,3500,3500,3500,3500],uo=2e3,at=0,ct="main",lt=64,go=4*1024*1024,ho=1,mo="openrtc:native-main-message",fo=15e3,yo=16,vo=3e4,Co=250,So=250,Io=2e3,bo=600,Ro=2e3,Po=120,To=1e3,Ao=6e4,Jn="system/peer-default",Ds="share/explicit-file",Ms="share/explicit-control",wo=[{id:Jn,kind:"system",ownership:"shared",peerModel:"device-first",routing:"session-default",readiness:"settled-peer",promotionPolicy:"eligible",signalingPolicy:"hosted",description:"Default trusted device/runtime traffic"},{id:Ds,kind:"share",ownership:"shared",peerModel:"anonymous-ticket",routing:"stream-envelope",readiness:"transport-only",promotionPolicy:"never",signalingPolicy:"ticket-only",description:"Explicit file transfer channel for share/ticket traffic"},{id:Ms,kind:"share",ownership:"shared",peerModel:"anonymous-ticket",routing:"stream-envelope",readiness:"transport-only",promotionPolicy:"never",signalingPolicy:"ticket-only",description:"Explicit control channel for share/ticket traffic"}];function ko(r){return {get registry(){return r.getRegistry()},get wasmClient(){return r.getWasmClient()},get node(){return r.getNode()},get discoveryMode(){return r.getDiscoveryMode()},get localNodeId(){return r.getLocalNodeId()},get deviceId(){return r.getDeviceId()},registerDisposer:e=>r.registerDisposer(e)}}var No="openrtc:endpoint-ticket:v1";function Y(r){let e=r.lastIndexOf(".");return {irohTicket:e>=0?r.slice(0,e):r,tokenSuffix:e>=0?r.slice(e+1):null}}function Do(){return Mo(24)}function dt(r,e,t,n,i){return `${r}.${Es(r,e,t,n,i)}`}function ne(r,e){let t=Ls(e);return !t||!xs(r,t)?null:t}function Es(r,e,t,n,i){return btoa(JSON.stringify({t:e,s:t,m:n,h:Eo(r),...typeof i=="number"?{e:i}:{},a:No,n:_s()})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ls(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return JSON.parse(atob(e+"=".repeat(t)))}catch{return null}}function xs(r,e){return !(typeof e.h=="string"&&e.h!==Eo(r)||typeof e.e=="number"&&Number.isFinite(e.e)&&e.e<=Date.now()||typeof e.a=="string"&&e.a!==No||typeof e.n=="string"&&!Fs(e.n))}function _s(){return Mo(16)}function Mo(r){let e=new Uint8Array(r);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Fs(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return atob(e+"=".repeat(t)).length===16}catch{return false}}function Z(r,e){return r>>>e|r<<32-e}var Bs=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Eo(r){let e=new TextEncoder().encode(r),t=e.length*8,n=e.length+1;for(;n%64!==56;)n+=1;let i=new Uint8Array(n+8);i.set(e),i[e.length]=128;let o=new DataView(i.buffer);o.setUint32(n,Math.floor(t/4294967296),false),o.setUint32(n+4,t>>>0,false);let s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],a=new Array(64);for(let c=0;c<i.length;c+=64){for(let v=0;v<16;v+=1)a[v]=o.getUint32(c+v*4,false);for(let v=16;v<64;v+=1){let P=Z(a[v-15],7)^Z(a[v-15],18)^a[v-15]>>>3,I=Z(a[v-2],17)^Z(a[v-2],19)^a[v-2]>>>10;a[v]=a[v-16]+P+a[v-7]+I>>>0;}let[l,d,p,u,f,h,m,y]=s;for(let v=0;v<64;v+=1){let P=Z(f,6)^Z(f,11)^Z(f,25),I=f&h^~f&m,T=y+P+I+Bs[v]+a[v]>>>0,C=Z(l,2)^Z(l,13)^Z(l,22),N=l&d^l&p^d&p,b=C+N>>>0;y=m,m=h,h=f,f=u+T>>>0,u=p,p=d,d=l,l=T+b>>>0;}s[0]=s[0]+l>>>0,s[1]=s[1]+d>>>0,s[2]=s[2]+p>>>0,s[3]=s[3]+u>>>0,s[4]=s[4]+f>>>0,s[5]=s[5]+h>>>0,s[6]=s[6]+m>>>0,s[7]=s[7]+y>>>0;}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var pt=class{constructor(e,t,n){this.ctx=e;this.options=t;this.deps=n;this.appliedAuthSessionToken=null;this.authSyncUnsubscribe=null;this.authRefreshInterval=null;this.publicAuthChangeUnsubscribes=new Set;this.lastWasmAuthSyncUserId=null;this.lastWasmAuthSyncToken=null;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(this.disposed)return;this.disposed=true;let e=this.authSyncUnsubscribe;if(this.authSyncUnsubscribe=null,e)try{e();}catch(n){console.warn("[Client][WASM-AUTH] auth-change unsubscribe failed",n);}let t=this.authRefreshInterval;this.authRefreshInterval=null,t&&clearInterval(t);for(let n of Array.from(this.publicAuthChangeUnsubscribes))try{n();}catch(i){console.warn("[Client][AUTH] public auth-change unsubscribe failed",i);}this.publicAuthChangeUnsubscribes.clear();}assertActive(){if(this.disposed)throw new Error("[Client][AUTH] Auth coordinator is disposed")}isSpaceWithSpaceKey(){let e=this.options.spaceKey??this.options.space;return (this.options.discoveryMode===void 0||this.options.discoveryMode==="space")&&typeof e=="string"&&e.trim().length>0}async ensureAuthenticated(e){if(this.assertActive(),this.deps.usesTicketOnlySignalingMode())return;let t=this.options.authMode??"anonymous",n=e!=="discovery";if(this.isSpaceWithSpaceKey()){let l=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",d=this.options.spaceKey??this.options.space,p=typeof d=="string"?d.trim():"",u=l&&p?await a$1(l,p).catch(()=>null):null;if(this.assertActive(),G().getCurrentUser()){let P=await G().getIdToken({forceRefresh:false}).catch(()=>null);this.assertActive();let I=a$2(P);if(u&&c$3(I,u)){await E(this.deps.waitForAuth(),5e3),this.assertActive(),n&&d$1(`[Client][AUTH] Space scoped token already authenticated (${e})`);return}n&&d$1("[Client][AUTH] Existing Firebase user is not scoped to this space; minting scoped token",{reason:e,expectedNamespaceId:u?.slice(0,12)??null,actualNamespaceId:b$3(I,"namespaceId")?.slice(0,12)??null});}let h=this.options.spaceTokenProvider;if(!h)throw new Error("[Client][AUTH] space discovery requires spaceTokenProvider (use spaceToken for static sites)");let m=await h(),y=typeof m?.customToken=="string"?m.customToken.trim():"";if(!y)throw new Error("[Client][AUTH] spaceTokenProvider returned no customToken");this.assertActive(),await G().signInWithCustomTokenValue(y),this.assertActive(),await E(this.deps.waitForAuth(),5e3),this.assertActive();let v=await G().getIdToken({forceRefresh:true}).catch(()=>null);this.assertActive(),this.setWasmAuthToken(v??y,v?"space-id-token":"space-token"),this.assertActive(),n&&d$1(`[Client][AUTH] Space scoped token authenticated (${e})`);return}let o=typeof this.options.sessionToken=="string"?this.options.sessionToken.trim():"";if(o&&this.appliedAuthSessionToken!==o){this.assertActive(),await G().signInWithCustomTokenValue(o),this.assertActive(),this.appliedAuthSessionToken=o,await E(this.deps.waitForAuth(),5e3),this.assertActive(),n&&d$1(`[Client][AUTH] Session token authenticated (${e})`);return}try{await E(this.deps.waitForAuth(),5e3);}catch(l){this.assertActive(),n&&console.warn(`[Client][AUTH] waitForAuth timed out (${e})`,l);}this.assertActive();let s=this.deps.getCurrentUser(),a=s?.id??s?.uid??null,c=this.options.discoveryMode==="user-scoped"&&typeof a=="string"&&a.startsWith("space_");if(s&&!c){n&&d$1(`[Client][AUTH] Authenticated (${e}) as ${a??"current-user"}`);return}if(c&&n&&d$1("[Client][AUTH] Ignoring space-scoped user for anonymous user-scoped discovery"),t==="external"||t==="required")throw new Error(`[Client][AUTH] ${t} auth mode requires host-provided auth before ${e}`);n&&d$1(`[Client][AUTH] No user (${e}); attempting anonymous sign-in...`),await E(this.deps.signInAnonymously(),8e3),this.assertActive();try{await E(this.deps.waitForAuth(),5e3);}catch{}if(this.assertActive(),!this.deps.getCurrentUser())throw new Error("[Client][AUTH] Anonymous sign-in did not produce an authenticated user");n&&d$1(`[Client][AUTH] Anonymous sign-in success (${e})`);}setWasmAuthToken(e,t){let n=this.ctx.wasmClient;if(!n||typeof n.set_auth_token!="function"){console.warn("[Client][WASM-AUTH] WasmClient.set_auth_token is unavailable");return}let i=e?"token":null;this.lastWasmAuthSyncUserId===i&&this.lastWasmAuthSyncToken===e||(this.lastWasmAuthSyncUserId=i,this.lastWasmAuthSyncToken=e,d$1(`[Client][WASM-AUTH] Sync token (${t}) hasToken=${!!e} tokenLen=${e?.length??0}`),n.set_auth_token(e));}installAuthTokenSync(){if(this.disposed||this.isSpaceWithSpaceKey()||this.authSyncUnsubscribe)return;let e=this.deps.onAuthChange(()=>{this.disposed||this.syncAuthTokenToWasm("auth-change").catch(t=>{this.disposed||console.warn("[Client][WASM-AUTH] Failed syncing auth token on auth change:",t);});});this.authSyncUnsubscribe=e,this.authRefreshInterval||(this.authRefreshInterval=setInterval(()=>{this.disposed||this.syncAuthTokenToWasm("periodic-refresh",true).catch(t=>{this.disposed||console.warn("[Client][WASM-AUTH] Periodic auth refresh sync failed:",t);});},600*1e3));}async syncAuthTokenToWasm(e,t=false){if(this.disposed||this.isSpaceWithSpaceKey())return;let n=this.deps.getCurrentUser(),i=n&&n.getToken?await n.getToken(t):null;if(this.disposed)return;let o=!!i,s=i?.length||0,a=n?.id||null;this.lastWasmAuthSyncUserId===a&&this.lastWasmAuthSyncToken===i||(d$1(`[Client][WASM-AUTH] Sync token (${e}) hasToken=${o} tokenLen=${s} uid=${a||"none"} forceRefresh=${t}`),!this.disposed&&this.setWasmAuthToken(i,e));}async refreshRuntimeAuthToken(e="runtime-start"){this.disposed||this.deps.usesTicketOnlySignalingMode()||(await this.ensureAuthenticated("discovery"),!this.disposed&&(this.isSpaceWithSpaceKey()||await this.syncAuthTokenToWasm("auth-change",e==="managed-session")));}get currentUser(){return this.deps.getCurrentUser()}onAuthChange(e){if(this.disposed)return ()=>{};let t=true,n=this.deps.onAuthChange(o=>{!t||this.disposed||e(o);}),i=()=>{if(t){t=false;try{n();}finally{this.publicAuthChangeUnsubscribes.delete(i);}}};return this.publicAuthChangeUnsubscribes.add(i),i}async signInAnonymously(){return this.assertActive(),this.deps.signInAnonymously()}async signInWithPluto(){return this.assertActive(),this.deps.signInWithPluto()}async signOut(){if(!this.disposed&&(this.deps.beforeSignOut(),await this.deps.stopAuthScopedActivity(),!this.disposed))return this.deps.signOut()}};var ut=class{constructor(e,t){this.ctx=e;this.deps=t;this.devicesById=new Map;this.deviceIdsByNodeId=new Map;this.activeScanningStops=new Set;this.activeSubscriptionStops=new Set;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(!this.disposed){this.disposed=true;for(let e of Array.from(this.activeScanningStops))try{e();}catch(t){console.warn("[Client] active device scanning unsubscribe failed",t);}this.activeScanningStops.clear();for(let e of Array.from(this.activeSubscriptionStops))try{e();}catch(t){console.warn("[Client] device directory subscription unsubscribe failed",t);}this.activeSubscriptionStops.clear();}}get byIdMap(){return this.devicesById}set byIdMap(e){this.devicesById=e instanceof Map?e:new Map;}get byNodeIdMap(){return this.deviceIdsByNodeId}set byNodeIdMap(e){this.deviceIdsByNodeId=e instanceof Map?e:new Map;}remember(e){if(!this.disposed&&e?.deviceId){if(this.devicesById.set(e.deviceId,e),typeof e.nodeId=="string"&&e.nodeId.trim()){let t=e.nodeId.trim();this.deviceIdsByNodeId.set(t,e.deviceId);}this.deps.onDeviceRemembered(e);}}getKnownDevice(e,t){let n=typeof e=="string"?e.trim():"";if(n){let o=this.devicesById.get(n);if(o)return o}let i=typeof t=="string"?t.trim():"";if(i){let o=this.deviceIdsByNodeId.get(i);if(o)return this.devicesById.get(o)??null}return null}getKnownDeviceIdForNode(e){let t=typeof e=="string"?e.trim():"";return t?this.deviceIdsByNodeId.get(t)??null:null}getKnownDeviceNodeId(e){let t=typeof e=="string"?e.trim():"";return t&&this.devicesById.get(t)?.nodeId?.trim()||null}rememberKnownDeviceForNode(e,t){if(this.disposed)return;let n=e.trim(),i=t.trim();!n||!i||this.deviceIdsByNodeId.set(n,i);}getKnownDevicePlatform(e,t){let n=this.getKnownDevice(e,t),i=typeof n?.platformType=="string"?n.platformType:typeof n?.platform_type=="string"?n.platform_type:null;return i?String(i).trim().toLowerCase():null}async refreshKnownDeviceCache(){if(this.disposed||!this.deps.requiresManagedTransportTrust())return;let e=await this.searchDevices().catch(()=>[]);this.disposed||e.forEach(t=>this.remember(t));}async searchDevices(){if(this.disposed)return [];if(await this.deps.ensureSignalingReadyForDiscovery("search"),this.disposed)return [];let e=await this.deps.searchDevices();return this.disposed?[]:(e.forEach(t=>{this.remember(t),this.deps.applyDiscoveredDevice(t);}),e)}async updateDevice(e,t){this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("search"),!this.disposed&&await this.deps.updateDevice(e,t));}async deleteDevice(e){this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("search"),!this.disposed&&await this.deps.deleteDevice(e));}async cleanupStaleDevices(){this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("search"),!this.disposed&&await this.deps.cleanupStaleDevices());}onDevicesChange(e){if(this.disposed)return ()=>{};let t=true,n=null,i=()=>{if(!(!t&&!n)){if(t=false,n)try{n();}finally{n=null;}this.activeSubscriptionStops.delete(i);}};return this.activeSubscriptionStops.add(i),(async()=>{await this.deps.ensureSignalingReadyForDiscovery("watch"),!(!t||this.disposed)&&(n=this.deps.onDevicesChange(o=>{!t||this.disposed||(o.forEach(s=>{this.remember(s),this.deps.applyDiscoveredDevice(s);}),e(o));}),(!t||this.disposed)&&i());})().catch(o=>{if(!(!t||this.disposed)){console.warn("[Client] Failed to initialize onDevicesChange listener:",o);try{e([]);}finally{i();}}}),i}async subscribeSessions(e,t){if(this.disposed)return ()=>{};if(await this.deps.ensureSignalingReadyForDiscovery("sessions"),this.disposed)return ()=>{};let n=true,i=await this.deps.subscribeSessions(e,s=>{if(n&&!this.disposed)return t(s)});if(this.disposed)return i(),()=>{};let o=()=>{if(n){n=false;try{i();}finally{this.activeSubscriptionStops.delete(o);}}};return this.activeSubscriptionStops.add(o),o}async startScanningLoop(e){if(this.disposed)return {stop:()=>{}};let t=new Set,n=false,i=null,o=null,s=e.localDeviceId;try{let c=await this.deps.getLocalDeviceId();if(this.disposed)return {stop:()=>{}};c&&(s=c);}catch{}i=this.onDevicesChange(c=>{n||this.disposed||e.onDevices?.(c);});let a=()=>{n=true,i&&(i(),i=null),o&&(o(),o=null),this.activeScanningStops.delete(a);};this.activeScanningStops.add(a);try{(e.onIncomingSession||e.acceptIncomingSession)&&(o=await this.subscribeSessions(s,async c=>{if(n||this.disposed)return;let l=c.sessionId||c.connectionId;if(!(!l||t.has(l))&&c.targetDeviceId===s&&c.initiatorDeviceId!==s&&!(c.state==="connected"||c.state==="closed"||c.state==="failed")){t.add(l);try{if(this.disposed)return;if(e.onIncomingSession){await e.onIncomingSession(c);return}(this.deps.getPeerStatus(c.initiatorDeviceId)==="connected"||e.isConnected?.(c.initiatorDeviceId))&&(this.deps.hasPeerScopes(c.initiatorDeviceId)||(e.hasProtectedConnectionIntent?.(c.initiatorDeviceId)??!1)||await this.deps.forceDisconnectPeer(c.initiatorDeviceId).catch(async()=>{await e.cleanupStaleConnection?.(c.initiatorDeviceId);})),c.initiatorNodeId&&await e.allowIncomingNodeId?.(c.initiatorNodeId);let p=await e.acceptIncomingSession?.(l,c.initiatorDeviceId);if(!p?.success)throw new Error(p?.error||"Failed to accept incoming signaling session");await e.onIncomingSessionAccepted?.(c);}catch(d){throw t.delete(l),d}}}));}catch(c){throw a(),c}return {stop:a}}};var gt=class{constructor(e,t,n){this.ctx=e;this.options=t;this.deps=n;this.managedPresenceGrant=null;this.disposed=false;this.activePresenceDescriptor=null;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(this.disposed)return;this.disposed=true,this.managedPresenceGrant=null;let e=this.activePresenceDescriptor;this.activePresenceDescriptor=null,!(!e||!this.ctx.localNodeId)&&this.markOfflineDuringDispose(this.ctx.localNodeId);}markOfflineDuringDispose(e){let t=n=>{console.warn("[Client][PRESENCE] failed to mark offline during dispose",n);};try{Promise.resolve(this.deps.setOffline(e)).catch(t);}catch(n){t(n);}}assertActive(){if(this.disposed)throw new Error("[Client][PRESENCE] Presence controller is disposed")}resolvePresenceUserId(){let e=(this.options.discoveryMode===void 0||this.options.discoveryMode==="space")&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0;return this.deps.getCurrentUser()?.id??(e?this.ctx.localNodeId:null)}startSignalingPresenceLoop(e){if(this.disposed)return;let t=this.activePresenceDescriptor,n=(t?.metadata??"")===(e.metadata??"");t&&t.userId===e.userId&&t.nodeId===e.nodeId&&t.deviceName===e.deviceName&&t.ticket===e.ticket&&n||(this.deps.startPresenceLoop(e.userId,e.nodeId,e.deviceName,e.ticket,e.metadata),this.activePresenceDescriptor=e);}notifySignalingBackendChanged(){this.activePresenceDescriptor=null;}setManagedPresenceTicket(e){if(this.disposed)return;let t=e?.trim()||"";if(!t){this.managedPresenceGrant=null;return}let{irohTicket:n,tokenSuffix:i}=this.deps.splitCompoundTicket(t),o=i?this.deps.decodeCompoundTicketPayload(n,i):null;if(!o?.t||!o?.s)throw new Error("Managed presence ticket must be a compound ticket with an embedded token payload");this.managedPresenceGrant={scope:o.s,token:o.t,maxConnections:typeof o.m=="number"?o.m:0,compoundTicket:t,irohTicket:n};let s=this.ctx.wasmClient;s&&typeof s.register_session_token=="function"&&s.register_session_token(o.t,o.s,typeof o.m=="number"?o.m:0);}clearManagedPresenceTicket(){this.managedPresenceGrant=null;}async resolvePresenceTicket(e){this.assertActive();let t=e?.trim();if(t)return t;if(this.managedPresenceGrant)return this.refreshManagedPresenceTicketIfNeeded();let n=this.options.ticket?.trim();return n||this.deps.getTicket()}async refreshManagedPresenceTicketIfNeeded(){let e=this.managedPresenceGrant;if(!e)return this.deps.getTicket();let t=e.irohTicket;try{t=await this.deps.getTicket();}catch{return e.compoundTicket}if(t===e.irohTicket)return e.compoundTicket;let n=this.ctx.wasmClient;if(n&&typeof n.endpoint_ticket_with_token=="function"){let i=n.endpoint_ticket_with_token.bind(n),o=await d$2(()=>i(e.scope,e.maxConnections),{isActive:()=>!this.disposed}),{irohTicket:s,tokenSuffix:a}=this.deps.splitCompoundTicket(o),c=a?this.deps.decodeCompoundTicketPayload(s,a):null;return e.irohTicket=s,e.compoundTicket=o,c?.t&&c?.s&&(e.token=c.t,e.scope=c.s,e.maxConnections=typeof c.m=="number"?c.m:0),c$1("[Client][PRESENCE] reminted managed compound ticket through Rust",{grantScope:e.scope}),e.compoundTicket}if(e.scope==="user-device")throw new Error("Managed user-device presence refresh requires Rust/WASM endpoint_ticket_with_token support.");return e.irohTicket=t,e.compoundTicket=this.deps.buildCompoundTicketWithPayload(t,e.token,e.scope,e.maxConnections),c$1("[Client][PRESENCE] rebuilt managed compound ticket after endpoint change",{grantScope:e.scope}),e.compoundTicket}async startPresenceLoop(e){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let t=this.ctx.localNodeId;if(!t)throw new Error("startPresenceLoop requires an initialized node");let n=this.resolvePresenceUserId();if(!n)throw new Error("startPresenceLoop requires an authenticated user");let i=await this.resolvePresenceTicket(e?.ticket);if(this.assertActive(),!i||!i.trim())throw new Error("startPresenceLoop requires a valid endpoint ticket");this.startSignalingPresenceLoop({userId:n,nodeId:t,deviceName:e?.deviceName||this.options.deviceName||"Unknown Device",ticket:i,metadata:e?.metadata}),this.deps.syncRoomRtdbPresence();}async startPresenceLoopForListen(){if(this.disposed)return;let e=this.ctx.localNodeId,t=this.resolvePresenceUserId();if(!t||!e)return;let n=await this.resolvePresenceTicket();this.disposed||this.startSignalingPresenceLoop({userId:t,nodeId:e,deviceName:this.options.deviceName||"Unknown Device",ticket:n,metadata:""});}async setOffline(){this.disposed||(this.activePresenceDescriptor=null,this.ctx.localNodeId&&await this.deps.setOffline(this.ctx.localNodeId));}async updatePresence(e=true,t=3e5,n,i){if(this.disposed||!this.ctx.wasmClient)return;let o=(this.options.discoveryMode===void 0||this.options.discoveryMode==="space")&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0;if(o&&(await this.deps.ensureAuthenticated("discovery"),this.disposed)||!this.deps.getCurrentUser()?.id&&!o)return;let a=this.ctx.localNodeId;if(!a)return;let c=await this.resolvePresenceTicket(i);if(this.disposed)return;if(!c||!c.trim())throw new Error("updatePresence requires a valid endpoint ticket");let l=n,d=await this.deps.getLocalDeviceId()||this.ctx.deviceId;if(this.disposed)return;if(!d)throw new Error("updatePresence requires a stable local device ID");try{let u=n?JSON.parse(n):{};u.deviceId||(u.deviceId=d,l=JSON.stringify(u));}catch{l=JSON.stringify({deviceId:d,rawMetadata:n});}let p=await j$1(l);await this.deps.updatePresence(a,c,e,t,p);}};var ht=class{constructor(e,t){this.ctx=e;this.deps=t;this.hostedAppSettingsLoaded=false;this.backendConnectionStateUnsubscribe=null;this.signalingBackend=null;this.subscriptionGeneration=0;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}async refreshHostedAppSettings(e=false){if(!(this.disposed||this.deps.usesTicketOnlySignalingMode())&&!(this.hostedAppSettingsLoaded&&!e))try{let{getFunctions:t,httpsCallable:n}=await import('firebase/functions');if(this.disposed)return;let i=t(G().getApp()),s=await n(i,"validateApiKey")({apiKey:this.deps.getApiKey()});if(this.disposed)return;let a=s.data;a.warning&&console.warn("[pluto-rtc]",a.warning),this.deps.setAppLimits(a.limits),a.discoveryMode&&this.deps.setDiscoveryMode(a.discoveryMode),this.deps.setRoomCreationMode(a.roomCreationMode??((this.deps.getOptions().discoveryMode??"space")==="space"?"client-open":"client-auth")),this.hostedAppSettingsLoaded=!0;}catch(t){if(this.disposed)return;console.warn("[pluto-rtc] Could not fetch hosted app settings, using local defaults.",t);}}setSignalingBackend(e){if(this.disposed)return;this.disposeBackendConnectionSubscription();let t=this.subscriptionGeneration,n=this.deps.getCurrentSignaling();this.deps.stopRoomLiveness(),this.stopAuthScopedActivityBestEffort(n);let i=this.deps.createSignaling(e);this.signalingBackend=e,this.deps.installBackend(i,e),this.deps.onSignalingBackendChanged(),this.syncRoomRtdbPresenceFromBackend();let o=e.setCoreClient;typeof o=="function"&&o.call(e,this.deps.getCoreClientHost());try{e.checkForSSOToken();}catch(a){console.warn("[Client] backend SSO token check failed:",a);}b$1("[Client] subscribing to backend connection state changes",{backendType:e?.constructor?.name??"unknown",hasGetConnectionStates:typeof e.getConnectionStates=="function",hasOnConnectionStateChange:typeof e.onConnectionStateChange=="function"});let s;try{s=i.onConnectionStateChange(a=>{this.disposed||t!==this.subscriptionGeneration||(this.deps.onBackendConnectionState(a),this.schedulePeerReconciliationBestEffort("backend-state"));});}catch(a){if(this.disposed||t!==this.subscriptionGeneration)return;console.warn("[Client] Failed to subscribe to backend connection state changes:",a);return}if(typeof s=="function"){let a=s;if(this.disposed||t!==this.subscriptionGeneration){this.callBackendConnectionStateUnsubscribe(a);return}this.backendConnectionStateUnsubscribe=a,b$1("[Client] backend connection state subscription established synchronously");}else s&&typeof s.then=="function"&&s.then(a=>{if(this.disposed||t!==this.subscriptionGeneration){this.callBackendConnectionStateUnsubscribe(a);return}this.backendConnectionStateUnsubscribe=a,b$1("[Client] backend connection state subscription established asynchronously");}).catch(a=>{this.disposed||t!==this.subscriptionGeneration||console.warn("[Client] Failed to subscribe to backend connection state changes:",a);});}syncRoomRtdbPresenceFromBackend(){if(this.disposed)return;let e=this.signalingBackend?.rtdbPresence;e&&this.deps.setRoomRtdbPresence(e);}async getLocalDeviceId(){return this.disposed?null:this.deps.getCurrentSignaling().getLocalDeviceId()}async getTurnCredentials(){return this.disposed?null:this.deps.getCurrentSignaling().getTurnCredentials()}setWasmClient(e){this.disposed||this.deps.getCurrentSignaling().setWasmClient(e);}getCurrentUser(){return this.disposed?null:this.deps.getCurrentSignaling().currentUser}async waitForAuth(){this.disposed||await this.deps.getCurrentSignaling().waitForAuth();}onAuthChange(e){return this.disposed?()=>{}:this.deps.getCurrentSignaling().onAuthChange(e)}async signInAnonymously(){if(!this.disposed)return this.deps.getCurrentSignaling().signInAnonymously()}async signInWithPluto(){if(!this.disposed)return this.deps.getCurrentSignaling().signInWithPluto()}async signOut(){if(!this.disposed)return this.deps.getCurrentSignaling().signOut()}getRuntimeCapabilities(){if(!this.disposed)return this.deps.getCurrentSignaling().getRuntimeCapabilities?.()}startAutoConnect(e,t){this.disposed||this.deps.getCurrentSignaling().startAutoConnect(e,t);}async isConnected(e){return this.disposed?false:this.deps.getCurrentSignaling().isConnected(e)}notifyDisconnectRequested(e){this.disposed||this.deps.getCurrentSignaling().notifyDisconnectRequested(e);}forceReconnectSnapshot(){this.disposed||this.deps.getCurrentSignaling().forceReconnectSnapshot();}startPresenceLoop(e,t,n,i,o){this.disposed||this.deps.getCurrentSignaling().startPresenceLoop(e,t,n,i,o);}async setOffline(e){this.disposed||await this.deps.getCurrentSignaling().setOffline(e);}async updatePresence(e,t,n,i,o){this.disposed||await this.deps.getCurrentSignaling().updatePresence(e,t,n,i,o);}async searchDevices(){return this.disposed?[]:this.deps.getCurrentSignaling().searchDevices()}async updateDevice(e,t){this.disposed||await this.deps.getCurrentSignaling().updateDevice(e,t);}async deleteDevice(e){this.disposed||await this.deps.getCurrentSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.disposed||await this.deps.getCurrentSignaling().cleanupStaleDevices();}onDevicesChange(e){return this.disposed?()=>{}:this.deps.getCurrentSignaling().onDevicesChange(e)}async subscribeSessions(e,t){return this.disposed?()=>{}:this.deps.getCurrentSignaling().subscribeSessions(e,t)}async stopAuthScopedActivity(){this.disposed||(this.deps.stopRoomLiveness(),await this.stopAuthScopedActivityFor(this.deps.getCurrentSignaling()));}dispose(){if(this.disposed)return;this.disposed=true,this.disposeBackendConnectionSubscription(),this.deps.stopRoomLiveness();let e=this.deps.getCurrentSignaling();this.stopAuthScopedActivityBestEffort(e);}async stopAuthScopedActivityFor(e){if(e&&typeof e.stopAuthScopedActivity=="function")try{await e.stopAuthScopedActivity();}catch(t){if(this.disposed)return;console.warn("[Client] signaling auth-scoped teardown failed",t);}}stopAuthScopedActivityBestEffort(e){try{this.stopAuthScopedActivityFor(e);}catch{}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}disposeBackendConnectionSubscription(){this.subscriptionGeneration+=1,this.callBackendConnectionStateUnsubscribe(this.backendConnectionStateUnsubscribe),this.backendConnectionStateUnsubscribe=null;}callBackendConnectionStateUnsubscribe(e){if(e)try{e();}catch(t){console.warn("[Client] backend connection-state unsubscribe failed",t);}}};function Lo(r){return new Xn({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getApiKey:()=>r.options.apiKey,getCurrentSignaling:()=>r.signaling,createSignaling:e=>new me(q(r.options),e),stopRoomLiveness:()=>r.rooms.stopHeartbeat(),installBackend:e=>{r.setSignaling(e),r.setRooms(new Ie(r.roomClientHost,e));},setRoomRtdbPresence:e=>{r.rooms.setRtdbPresence(e);},setAppLimits:e=>{r.setAppLimits(e);},setDiscoveryMode:e=>{r.options.discoveryMode=e;},setRoomCreationMode:e=>{r.setRoomCreationMode(e);},getCoreClientHost:()=>({connect:(e,t,n,i,o)=>r.connectionDialer.connect(e,t,n,i,o),ensureManagedApplicationRoute:e=>r.ensureManagedApplicationRoute(e),waitForApplicationCryptoForPeer:(e,t)=>r.waitForApplicationCryptoForPeer(e,t),hasApplicationRouteForPeer:(e,t)=>r.hasApplicationRouteForPeer(e,t),rememberRouteRepairTokenFromTicket:e=>r.sessionTokens.rememberRouteRepairTokenFromTicket(e)}),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),onBackendConnectionState:e=>{if(e.transportState!=="connected"||e.replacementInProgress===true)return;let t=r.registry.get(e.connectionId);if(!t||t.isClosed||e.remoteNodeId&&e.remoteNodeId.trim()!==t.remoteNodeId)return;let n=e.activeTransportStableId,i=()=>{t.handleBaseTransportAvailable("rust-backend-state",{transportState:e.transportState??e.state,transportGeneration:e.transportGeneration,transportStableId:n});};if(!Number.isSafeInteger(n)||Number(n)<=0){i();return}r.managedTransportDialer.repairAdmissionForTransportGeneration(t.remoteNodeId,Number(n)).catch(o=>{c$1("[Client][AUTH] current-generation admission repair deferred",{connectionId:t.id,remoteNodeId:t.remoteNodeId,transportStableId:n,error:o instanceof Error?o.message:String(o)});}).finally(i);},beforeSignOut:()=>r.prepareStreamListenForSignOutIfExists(),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),getTicket:()=>r.runtimeIdentity.getTicket(),ensureSignalingReadyForDiscovery:e=>r.runtimeReadiness.ensureSignalingReadyForDiscovery(e),requiresManagedTransportTrust:()=>r.runtimeStatus.requiresManagedTransportTrust(r.discoveryMode),onDeviceRemembered:e=>{r.applicationCrypto.reindexDevice(e);},applyDiscoveredDevice:e=>{r.peerServices.applyDiscoveredDevice(e);},getPeerStatus:e=>r.peerServices.getPeerStatus(e),hasPeerScopes:e=>r.peerServices.hasPeerScopes(e),forceDisconnectPeer:e=>r.peerServices.forceDisconnectPeer(e)})}var Xn=class{constructor(e){this.host=e;}get auth(){return this._auth||(this._auth=new pt(this.host.getContext(),this.host.getOptions(),{usesTicketOnlySignalingMode:()=>this.host.usesTicketOnlySignalingMode(),getCurrentUser:()=>this.backend.getCurrentUser(),waitForAuth:()=>this.backend.waitForAuth(),onAuthChange:e=>this.backend.onAuthChange(e),signInAnonymously:()=>this.backend.signInAnonymously(),signInWithPluto:()=>this.backend.signInWithPluto(),signOut:()=>this.backend.signOut(),beforeSignOut:()=>this.host.beforeSignOut(),stopAuthScopedActivity:()=>this.backend.stopAuthScopedActivity()})),this._auth}get backend(){return this._backend||(this._backend=new ht(this.host.getContext(),{getOptions:()=>this.host.getOptions(),getApiKey:()=>this.host.getApiKey(),usesTicketOnlySignalingMode:()=>this.host.usesTicketOnlySignalingMode(),getCurrentSignaling:()=>this.host.getCurrentSignaling(),createSignaling:e=>this.host.createSignaling(e),stopRoomLiveness:()=>this.host.stopRoomLiveness(),installBackend:(e,t)=>this.host.installBackend(e,t),setRoomRtdbPresence:e=>this.host.setRoomRtdbPresence(e),setAppLimits:e=>this.host.setAppLimits(e),setDiscoveryMode:e=>this.host.setDiscoveryMode(e),setRoomCreationMode:e=>this.host.setRoomCreationMode(e),getCoreClientHost:()=>this.host.getCoreClientHost(),onBackendConnectionState:e=>this.host.onBackendConnectionState(e),schedulePeerReconciliation:e=>this.host.schedulePeerReconciliation(e),onSignalingBackendChanged:()=>{this._presence?.notifySignalingBackendChanged();}})),this._backend}get presence(){return this._presence||(this._presence=new gt(this.host.getContext(),this.host.getOptions(),{ensureWasmRuntimeForP2P:()=>this.host.ensureWasmRuntimeForP2P(),ensureAuthenticated:e=>this.auth.ensureAuthenticated(e),getTicket:()=>this.host.getTicket(),getLocalDeviceId:()=>this.backend.getLocalDeviceId(),getCurrentUser:()=>this.backend.getCurrentUser(),startPresenceLoop:(e,t,n,i,o)=>this.backend.startPresenceLoop(e,t,n,i,o),setOffline:e=>this.backend.setOffline(e),updatePresence:(e,t,n,i,o)=>this.backend.updatePresence(e,t,n,i,o),syncRoomRtdbPresence:()=>this.backend.syncRoomRtdbPresenceFromBackend(),splitCompoundTicket:e=>Y(e),decodeCompoundTicketPayload:(e,t)=>ne(e,t),buildCompoundTicketWithPayload:(e,t,n,i)=>dt(e,t,n,i)})),this._presence}get devices(){return this._devices||(this._devices=new ut(this.host.getContext(),{ensureSignalingReadyForDiscovery:e=>this.host.ensureSignalingReadyForDiscovery(e),searchDevices:()=>this.backend.searchDevices(),updateDevice:(e,t)=>this.backend.updateDevice(e,t),deleteDevice:e=>this.backend.deleteDevice(e),cleanupStaleDevices:()=>this.backend.cleanupStaleDevices(),onDevicesChange:e=>this.backend.onDevicesChange(e),subscribeSessions:(e,t)=>this.backend.subscribeSessions(e,t),requiresManagedTransportTrust:()=>this.host.requiresManagedTransportTrust(),onDeviceRemembered:e=>this.host.onDeviceRemembered(e),applyDiscoveredDevice:e=>this.host.applyDiscoveredDevice(e),getPeerStatus:e=>this.host.getPeerStatus(e),hasPeerScopes:e=>this.host.hasPeerScopes(e),forceDisconnectPeer:e=>this.host.forceDisconnectPeer(e),getLocalDeviceId:()=>this.backend.getLocalDeviceId()})),this._devices}clearManagedPresenceTicketIfExists(){this._presence?.clearManagedPresenceTicket();}};var mt=class{constructor(e){this.localTerminalConnectionIds=new Set;this.connections=e??new Map;}get(e){return this.connections.get(e)}has(e){return this.connections.has(e)}set(e,t){this.connections.set(e,t);}delete(e){return this.connections.delete(e)}values(){return this.connections.values()}forEach(e){this.connections.forEach(e);}[Symbol.iterator](){return this.connections[Symbol.iterator]()}get size(){return this.connections.size}all(){return Array.from(this.connections.values())}applicationReady(e={}){return this.all().filter(t=>typeof t.isReadyForApplicationPayload=="function"?t.isReadyForApplicationPayload(e):!t.isClosed)}get backingMap(){return this.connections}set backingMap(e){this.connections=e instanceof Map?e:new Map;}getForPeer(e,t){for(let n of this.connections.values())if(e&&n.id===e||t&&(n.remoteNodeId===t||n.deviceId===t))return n;return null}markLocalTerminalClose(e){this.localTerminalConnectionIds.add(e);}clearLocalTerminalClose(e){this.localTerminalConnectionIds.delete(e);}hasLocalTerminalClose(e){return !!e&&this.localTerminalConnectionIds.has(e)&&!this.connections.has(e)}};function We(){return BigInt(Date.now())}function ft(r,e){let t=new ArrayBuffer(17),n=new DataView(t);return n.setUint8(0,3),n.setBigUint64(1,r,false),n.setBigInt64(9,e,false),new Uint8Array(t)}function xo(r,e){let t=new ArrayBuffer(25),n=new DataView(t);return n.setUint8(0,4),n.setBigUint64(1,r.seq,false),n.setBigInt64(9,r.senderUnixMs,false),n.setBigInt64(17,e,false),new Uint8Array(t)}function _o(r){if(r.byteLength<17||r[0]!==3)return null;let e=new DataView(r.buffer,r.byteOffset,r.byteLength);return {seq:e.getBigUint64(1,false),senderUnixMs:e.getBigInt64(9,false)}}function Fo(r){if(r.byteLength<25||r[0]!==4)return null;let e=new DataView(r.buffer,r.byteOffset,r.byteLength);return {seq:e.getBigUint64(1,false),senderUnixMs:e.getBigInt64(9,false),recvUnixMs:e.getBigInt64(17,false)}}function Zn(r,e){let t=import.meta.env??{};if(!(String(t.VITE_E2E??"").toLowerCase()==="true"))return e;let i=r==="VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_TICK_MS"?t.VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_TICK_MS:r==="VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_SUSPECT_MS"?t.VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_SUSPECT_MS:r==="VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_STALE_MS"?t.VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_STALE_MS:void 0,o=Number(i);return Number.isFinite(o)&&o>0?o:e}var Oe={tickIntervalMs:Zn("VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_TICK_MS",5e3),suspectAfterMs:Zn("VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_SUSPECT_MS",1e4),staleAfterMs:Zn("VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_STALE_MS",3e4)},yt=class{constructor(e,t,n=Oe){this.seq=0n;this.pendingPings=new Map;this.lastPongAtMs=null;this.firstPingSentAtMs=null;this.currentHealth="unknown";this.lastLatencyMs=null;this.tickTimer=null;this.stopped=false;this.probeWaiters=new Map;this.probeLatencyWaiters=new Map;this.probeTimers=new Map;this.probeLatencyTimers=new Map;this.sendFn=e,this.onHealthChange=t,this.config=n;}start(){this.tickTimer!==null||this.stopped||(this.tickTimer=setInterval(()=>{this.tick();},this.config.tickIntervalMs),this.tick());}stop(){this.stopped=true,this.tickTimer!==null&&(clearInterval(this.tickTimer),this.tickTimer=null);for(let e of this.probeWaiters.values())e(false);this.probeWaiters.clear();for(let e of this.probeTimers.values())clearTimeout(e);this.probeTimers.clear();for(let e of this.probeLatencyWaiters.values())e(null);this.probeLatencyWaiters.clear();for(let e of this.probeLatencyTimers.values())clearTimeout(e);this.probeLatencyTimers.clear(),this.pendingPings.clear();}handleIncoming(e){if(!e||e.byteLength===0)return false;let t=e[0];if(t===3){let n=_o(e);if(n){c$1("[TransportHeartbeat] ping received from peer, sending pong",{seq:n.seq.toString()});let i=xo(n,We());this.sendFn(i).catch(o=>console.warn("[TransportHeartbeat] pong send failed",o));}else console.warn("[TransportHeartbeat] ping decode failed",{byteLength:e.byteLength});return true}if(t===4){let n=Fo(e);if(n){let i=this.pendingPings.get(n.seq),o=i!==void 0,s=null;c$1("[TransportHeartbeat] pong received",{seq:n.seq.toString(),wasPending:o,pendingCount:this.pendingPings.size}),o&&(this.pendingPings.delete(n.seq),this.lastPongAtMs=Date.now(),s=Math.max(0,this.lastPongAtMs-i),this.lastLatencyMs=s,this.evaluateHealth());let a=this.probeWaiters.get(n.seq);a&&(this.probeWaiters.delete(n.seq),a(true));let c=this.probeLatencyWaiters.get(n.seq);c&&(this.probeLatencyWaiters.delete(n.seq),c(s));}else console.warn("[TransportHeartbeat] pong decode failed",{byteLength:e.byteLength});return true}return false}async tick(){if(this.stopped)return;let e=Date.now(),t=e-this.config.staleAfterMs;for(let[o,s]of this.pendingPings)s<=t&&this.pendingPings.delete(o);this.seq++;let n=this.seq,i=ft(n,We());try{await this.sendFn(i),this.firstPingSentAtMs===null&&(this.firstPingSentAtMs=e),this.pendingPings.set(n,e),c$1("[TransportHeartbeat] ping sent",{seq:n.toString(),pendingCount:this.pendingPings.size,lastPongAtMs:this.lastPongAtMs,silenceSinceLastPongMs:this.lastPongAtMs?e-this.lastPongAtMs:null});}catch(o){console.warn("[TransportHeartbeat] ping send failed",{seq:n.toString(),error:o});}this.evaluateHealth();}evaluateHealth(){let e=this.computeHealth();if(e!==this.currentHealth){c$1("[TransportHeartbeat] health transition",{from:this.currentHealth,to:e,lastPongAtMs:this.lastPongAtMs,firstPingSentAtMs:this.firstPingSentAtMs,silenceMs:this.lastPongAtMs?Date.now()-this.lastPongAtMs:this.firstPingSentAtMs?Date.now()-this.firstPingSentAtMs:null,pendingCount:this.pendingPings.size}),this.currentHealth=e;try{this.onHealthChange(e);}catch{}}}computeHealth(){let e=Date.now();if(this.firstPingSentAtMs===null)return "unknown";if(this.lastPongAtMs!==null){let n=e-this.lastPongAtMs;return n>=this.config.staleAfterMs?"stale":n>=this.config.suspectAfterMs?"suspect":"healthy"}let t=e-this.firstPingSentAtMs;return t>=this.config.staleAfterMs?"stale":t>=this.config.suspectAfterMs?"suspect":"unknown"}get health(){return this.currentHealth}get latencyMs(){return this.lastLatencyMs}async probe(e){if(this.stopped)return false;this.seq++;let t=this.seq,n=ft(t,We()),i=Date.now();return this.pendingPings.set(t,i),this.firstPingSentAtMs===null&&(this.firstPingSentAtMs=i),await new Promise(o=>{let s=setTimeout(()=>{this.probeTimers.delete(t),this.probeWaiters.delete(t)&&(this.pendingPings.delete(t),o(false));},e);this.probeTimers.set(t,s),this.probeWaiters.set(t,a=>{let c=this.probeTimers.get(t);c&&(clearTimeout(c),this.probeTimers.delete(t)),o(a);}),this.sendFn(n).catch(()=>{let a=this.probeTimers.get(t);a&&(clearTimeout(a),this.probeTimers.delete(t)),this.pendingPings.delete(t),this.probeWaiters.delete(t)&&o(false);});})}async probeLatency(e){if(this.stopped)return null;this.seq++;let t=this.seq,n=ft(t,We()),i=Date.now();return this.pendingPings.set(t,i),this.firstPingSentAtMs===null&&(this.firstPingSentAtMs=i),await new Promise(o=>{let s=setTimeout(()=>{this.probeLatencyTimers.delete(t),this.probeLatencyWaiters.delete(t)&&(this.pendingPings.delete(t),o(null));},e);this.probeLatencyTimers.set(t,s),this.probeLatencyWaiters.set(t,a=>{let c=this.probeLatencyTimers.get(t);c&&(clearTimeout(c),this.probeLatencyTimers.delete(t)),o(a);}),this.sendFn(n).catch(()=>{let a=this.probeLatencyTimers.get(t);a&&(clearTimeout(a),this.probeLatencyTimers.delete(t)),this.pendingPings.delete(t),this.probeLatencyWaiters.delete(t)&&o(null);});})}};var k=class k{constructor(e,t,n,i,o,s={}){this.listeners=[];this.pendingMessages=[];this.pendingEncryptedApplicationPayloads=[];this.lastApplicationPayloadTransport=null;this.webrtcBinaryHandlers=[];this.closeListeners=[];this.upgradeStateListeners=[];this.writer=null;this.reader=null;this._isClosed=false;this.receiveBuffer=new Uint8Array(0);this.writeMutex=Promise.resolve();this.applicationCryptoWaiters=[];this.applicationKeyAgreementObservationEpoch=0;this.nativeSignalSender=null;this.webrtcTransport=null;this.webRtcApplicationRouteReadyTransport=null;this.webRtcApplicationRouteReadyNegotiationId=null;this.upgradeState="none";this.upgradeRequested=false;this.negotiationSwitchCount=0;this.upgradeAttemptActive=false;this.upgradeRetryCount=0;this.lastBaseTransportGeneration=null;this.lastBaseTransportStableId=null;this.upgradeReDriveCount=0;this.upgradeReDriveTimer=null;this.upgradeRetryTimer=null;this.upgradeAttemptTimeoutTimer=null;this.lastReportedTransportStatus=null;this.pendingTransportStatusReport=null;this.transportStatusReportInFlight=false;this.applicationRouteMissingNotified=false;this.upgradeTerminalFailure=false;this.pendingSignals=[];this.activeNegotiationId=null;this.pendingAvailabilityHint=null;this.webrtcHeartbeat=null;this.webRtcHeartbeatProbeInFlight=false;this.webRtcApplicationRouteProbeInFlight=false;this.pendingWebRtcApplicationRouteProof=null;this.webRtcHeartbeatConsecutiveProbeFailures=0;this.irohHealthListeners=[];this.webrtcHealthListeners=[];this.lastWebRtcHeartbeatOkAt=null;this.lastWebRtcDataChannelOpenAt=null;this.lastApplicationRouteReadyReportAt=null;this.lastForegroundAt=null;this.webRtcDisconnectedGraceTimer=null;this.preferredWebRtcRole=null;this.lastWebRtcLocalCandidateType=null;this.lastWebRtcRemoteCandidateType=null;this._peerMoQReady=false;this._remoteSupportsWebRTC=false;this.mediaListeners=[];this.trackListeners=[];this.warnedSrtpApplicationCryptoBoundary=false;this.id=e,this.localNodeId=t,this.remoteNodeId=n,this.deviceId=n,this.writer=i,this.reader=o,this.options=s,this.readLoop(),this.options.rtcConfig?.lanMode&&this.options.rtcConfig&&queueMicrotask(()=>this.requestWebRTCUpgrade("lan-mode"));}get isClosed(){return this._isClosed}setApplicationCrypto(e){this.options={...this.options,applicationCrypto:e},e?(this.applicationRouteMissingNotified=false,this.resolveApplicationCryptoWaiters(),this.flushPendingEncryptedApplicationPayloads(),!this.isCurrentWebRtcTransportApplicationRouteReady()&&this.webrtcTransport&&this.upgradeState==="upgraded"&&this.startWebRtcApplicationRouteProbe(this.webrtcTransport,"application-crypto-ready"),this.options.transportContext?.requestMoQApplicationRouteProof?.()):this.options.transportContext?.clearMoQApplicationRouteProof?.();}markApplicationKeyAgreementObserved(){return this.applicationKeyAgreementObservationEpoch+=1,this.applicationKeyAgreementObservationEpoch}getApplicationKeyAgreementObservationEpoch(){return this.applicationKeyAgreementObservationEpoch}requireApplicationCrypto(){this.options={...this.options,requireApplicationCrypto:true};}isApplicationCryptoRequired(){return this.options.requireApplicationCrypto===true}isReadyForApplicationPayload(e={}){if(this.isClosed||!this.hasRequiredApplicationCrypto())return false;let t=e.preferredTransports??[],n=this.getTransportStatus().activeTransport;return t.length===0?this.isTransportAvailableForApplicationPayload(n):t.includes(n)||f$1(n)&&t.includes("webrtc")?this.isTransportAvailableForApplicationPayload(n):e.allowFallbackAfterPreferredTransportFailure===true&&this.upgradeState==="failed"&&this.isTransportAvailableForApplicationPayload(n)}getApplicationPayloadTransports(e={}){if(!this.isReadyForApplicationPayload(e))return [];let t=this.getTransportStatus(),n=[t.activeTransport];return e.includeFallbackTransports===true&&t.parallelTransport&&t.parallelTransport!==t.activeTransport&&this.isTransportAvailableForApplicationPayload(t.parallelTransport)&&n.push(t.parallelTransport),n}isTransportAvailableForApplicationPayload(e){return this._isClosed||!this.hasRequiredApplicationCrypto()?false:f$1(e)?this.isWebRtcApplicationRouteReady():e==="moq"?this.isMoQApplicationRouteReady():e==="iroh"||e==="iroh-relay"||e==="iroh-quic"||e==="iroh-lan"||e==="ble"?this.hasBaseApplicationRoute():false}resolveApplicationCryptoWaiters(){let e=this.applicationCryptoWaiters.splice(0);for(let t of e)t.timer&&clearTimeout(t.timer),t.resolve();}rejectApplicationCryptoWaiters(e){let t=this.applicationCryptoWaiters.splice(0);for(let n of t)n.timer&&clearTimeout(n.timer),n.reject(e);}async waitForRequiredApplicationCrypto(){if(!this.options.requireApplicationCrypto||this.options.applicationCrypto)return;if(this.isClosed)throw new Error("[Connection] Application crypto is required but the connection is closed.");let e=this.options.applicationCryptoWaitMs??k.DEFAULT_APPLICATION_CRYPTO_WAIT_MS;if(e<=0)throw new Error("[Connection] Application crypto is required before sending app payloads.");await new Promise((t,n)=>{let i={resolve:t,reject:n,timer:null};i.timer=setTimeout(()=>{this.applicationCryptoWaiters=this.applicationCryptoWaiters.filter(o=>o!==i),n(new Error("[Connection] Application crypto negotiation timed out before sending app payloads."));},e),this.applicationCryptoWaiters.push(i);});}requestWebRTCUpgrade(e="peer-capable"){if(!this.options.rtcConfig){this.traceLifecycle("webrtc-request-skipped",{reason:e,skipReason:"missing-rtc-config"});return}let t=this.getDeterministicWebRtcRole();this.upgradeState==="upgrading"&&this.preferredWebRtcRole==="responder"||(this.preferredWebRtcRole=t);let n=this.getControlFrameMode()==="native-main"&&!this.isWebRtcApplicationRouteReady();this.traceLifecycle("webrtc-requested",{reason:e,requestedRole:t,forceRenegotiate:n}),this.beginWebRtcRecovery(e,{forceRenegotiate:n,replaceExisting:n&&!!this.webrtcTransport,resetRetryBudget:true,skipIfAlreadyUpgrading:true});}isWebRtcRouteHeartbeatLive(){if(!this.isWebRtcDataChannelOpen())return false;let e=this.lastWebRtcHeartbeatOkAt===null?null:Date.now()-this.lastWebRtcHeartbeatOkAt;if(e!==null&&e<=k.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS)return true;let t=this.lastWebRtcDataChannelOpenAt===null?null:Date.now()-this.lastWebRtcDataChannelOpenAt;return t!==null&&t<=k.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS}requestTransportRecovery(e,t={}){!this.options.rtcConfig||this._isClosed||this.beginWebRtcRecovery(e,{forceRenegotiate:!!t.forceRenegotiate,replaceExisting:!!t.replaceExisting,resetRetryBudget:false,skipIfAlreadyUpgrading:false});}handleAppForeground(){if(this.lastForegroundAt=Date.now(),this._isClosed||!this.options.rtcConfig||!this.upgradeRequested||!this.hasRecoverableBasePath())return;if(this.upgradeState==="upgrading"&&this.upgradeAttemptActive&&this.activeNegotiationId){this.pendingAvailabilityHint={negotiationId:this.activeNegotiationId,source:"app-foreground"},this.traceLifecycle("webrtc-availability-hint-deferred",{negotiationId:this.activeNegotiationId});return}let e=this.webrtcTransport,t=e?.getNativeTransport?.(),n=e?.getDataChannelReadyState?.()??null,i=typeof t?.connectionState=="string"?t.connectionState:null,o=typeof t?.iceConnectionState=="string"?t.iceConnectionState:null;if(this.upgradeState!=="upgraded"||n!=="open"||i==="failed"||i==="disconnected"||o==="failed"||o==="disconnected"){this.requestTransportRecovery("app-foreground",{forceRenegotiate:true,replaceExisting:!!e||this.upgradeState==="failed"||this.upgradeState==="upgraded"});return}let a=this.webrtcHeartbeat,c=this.lastWebRtcHeartbeatOkAt===null?null:Date.now()-this.lastWebRtcHeartbeatOkAt;!(c!==null&&c>=Oe.suspectAfterMs)||!a||a.probe(k.FOREGROUND_PROBE_TIMEOUT_MS).then(d=>{d||this._isClosed||this.webrtcTransport===e&&this.requestTransportRecovery("app-foreground-probe-failed",{forceRenegotiate:true,replaceExisting:true});});}handleBaseTransportAvailable(e,t){if(t?.transportState&&t.transportState!=="connected")return;let n=Number.isSafeInteger(t?.transportGeneration)?Number(t?.transportGeneration):null,i=Number.isSafeInteger(t?.transportStableId)?Number(t?.transportStableId):null,o=false;if(n!==null){if(this.lastBaseTransportGeneration!==null&&n<this.lastBaseTransportGeneration||n===this.lastBaseTransportGeneration)return;o=this.lastBaseTransportGeneration!==null,this.lastBaseTransportGeneration=n,this.lastBaseTransportStableId=i;}this._isClosed||!this.options.rtcConfig||!this.upgradeRequested||this.upgradeState==="upgrading"&&!o||(this.traceLifecycle("base-transport-available",{source:e,transportGeneration:n,transportStableId:i,replacedBaseTransport:o}),this.beginWebRtcRecovery(`base-transport-available:${e}`,{forceRenegotiate:true,replaceExisting:!!this.webrtcTransport,resetRetryBudget:true,skipIfAlreadyUpgrading:!o}));}beginWebRtcRecovery(e,t){if(!this.options.rtcConfig||this._isClosed)return;let n=t.forceRenegotiate,i=t.replaceExisting,o=t.resetRetryBudget;if(t.skipIfAlreadyUpgrading&&(this.upgradeState==="upgrading"||this.upgradeState==="upgraded")){let s=this.isWebRtcApplicationRouteReady();if(!(this.upgradeState==="upgraded"&&!s&&!this.isWebRtcRouteHeartbeatLive()&&this.getDeterministicWebRtcRole()==="initiator")){c$1("[Connection] WebRTC recovery request ignored: attempt already active",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,currentState:this.upgradeState,routeAlreadyProven:s});return}c$1("[Connection] WebRTC recovery replacing a stale upgraded route (heartbeat not live)",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e}),this.stopWebRtcHeartbeat(),this.pendingSignals=[],this.teardownWebRTCTransport(`recovery-replace-stale:${e}`),this.setUpgradeState("none");}c$1("[Connection] beginWebRtcRecovery called",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,replaceExisting:i,forceRenegotiate:n,resetRetryBudget:o,currentState:this.upgradeState,caller:new Error().stack?.split(`
|
|
2
|
+
`).slice(1,4).join(" | ")}),this.upgradeRequested=true,this.upgradeAttemptActive=false,this.upgradeTerminalFailure=false,this.clearUpgradeRetryTimer(),this.clearUpgradeReDriveTimer(),this.clearUpgradeAttemptTimeoutTimer(),o&&(this.upgradeRetryCount=0,this.upgradeReDriveCount=0),i&&(this.stopWebRtcHeartbeat(),this.pendingSignals=[],this.teardownWebRTCTransport(`recovery-replace-existing:${e}`)),this.attemptUpgrade({forceRenegotiate:n,replaceExisting:i});}getUpgradeState(){return this.upgradeState}updateRTCConfig(e){this.options.rtcConfig=e;}onUpgradeStateChange(e){this.upgradeStateListeners.push(e);}async getTransportDiagnostics(){return this.collectTransportDiagnostics(false)}async collectTransportDiagnostics(e){let{activeTransport:t,parallelTransport:n}=this.getTransportStatus(),i={activeTransport:t,parallelTransport:n,usesRelay:null,relaySource:null,webrtc:null},o=this.webrtcTransport,s=o?.getNativeTransport?.();if(!o||!s)return i;try{let a=typeof s.getStats=="function"?await s.getStats():null,c=null;typeof a?.forEach=="function"&&(a.forEach(L=>{if(c||L?.type!=="transport")return;let _=L?.selectedCandidatePairId;!_||typeof a.get!="function"||(c=a.get(_)??null);}),c||a.forEach(L=>{c||L?.type==="candidate-pair"&&L?.selected===!0&&(c=L);}));let l=c?.localCandidateId&&typeof a?.get=="function"?a.get(c.localCandidateId):null,d=c?.remoteCandidateId&&typeof a?.get=="function"?a.get(c.remoteCandidateId):null,p=s?.sctp?.transport?.iceTransport,u=null;try{u=typeof p?.getSelectedCandidatePair=="function"?p.getSelectedCandidatePair():null;}catch{}let f=u?.local??l??null,h=u?.remote??d??null,m=typeof f?.candidateType=="string"?f.candidateType:typeof f?.type=="string"?f.type:null,y=typeof h?.candidateType=="string"?h.candidateType:typeof h?.type=="string"?h.type:null,v=typeof f?.protocol=="string"?f.protocol:null,P=typeof h?.protocol=="string"?h.protocol:null,I=!!(m&&y),T=I?m==="relay"||y==="relay":null,C=I?`${m??"unknown"}<->${y??"unknown"}`:null;if(this._isClosed||this.webrtcTransport!==o||this.upgradeState!=="upgraded")return {...i,relaySource:"webrtc-stats-stale"};let N=this.webRtcTransportLabel();e&&I&&(this.lastWebRtcLocalCandidateType=m,this.lastWebRtcRemoteCandidateType=y);let b=this.getTransportStatus();return e&&N!==this.webRtcTransportLabel()&&this.isWebRtcApplicationRouteReadyForTransport(o)&&this.reportTransportStatusIfChanged(),{...i,...b,usesRelay:T,relaySource:T==null?null:T?"webrtc-candidate-relay":"webrtc-candidate-direct",webrtc:{iceConnectionState:typeof s.iceConnectionState=="string"?s.iceConnectionState:null,iceGatheringState:typeof s.iceGatheringState=="string"?s.iceGatheringState:null,localCandidateType:m,remoteCandidateType:y,localProtocol:v,remoteProtocol:P,candidateTypeSummary:C}}}catch{return {...i,relaySource:"webrtc-stats-unavailable"}}}refreshWebRtcCandidatePairObservation(e){this._isClosed||this.webrtcTransport!==e||this.collectTransportDiagnostics(true).catch(t=>{c$1("[Connection] WebRTC selected candidate-pair observation failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:e.getNegotiationId?.()??null,error:t});});}clearWebRtcCandidatePairObservation(){this.lastWebRtcLocalCandidateType=null,this.lastWebRtcRemoteCandidateType=null;}webRtcTransportLabel(){let e=this.options.rtcConfig,t=e?.lanMode===true&&e.useDefaultIceServers===false&&Array.isArray(e.iceServers)&&e.iceServers.length===0;return g$2(this.lastWebRtcLocalCandidateType,this.lastWebRtcRemoteCandidateType,t)}get transportType(){return this.isWebRtcApplicationRouteReady()?this.webRtcTransportLabel():this.isMoQApplicationRouteReady()?"moq":"iroh-relay"}get peerMoQReady(){return this._peerMoQReady}set peerMoQReady(e){this._peerMoQReady!==e&&(this._peerMoQReady=e,e?this.options.transportContext?.requestMoQApplicationRouteProof?.():this.options.transportContext?.clearMoQApplicationRouteProof?.(),this.reportTransportStatusIfChanged());}get remoteSupportsWebRTC(){return this._remoteSupportsWebRTC}set remoteSupportsWebRTC(e){this._remoteSupportsWebRTC=e;}async send(e,t={}){return this.sendTyped(0,e,{requireApplicationCrypto:true,useApplicationPayloadRoute:true,routeOptions:t})}async sendMedia(e,t){let n=e==="video"?1:2;return this.sendTyped(n,t,{requireApplicationCrypto:true})}async sendOnTransport(e,t){return this.sendTypedOnTransport(e,0,t,{requireApplicationCrypto:true})}getLastApplicationPayloadTransport(){return this.lastApplicationPayloadTransport}async sendControl(e){return this.sendTyped(0,e,{requireApplicationCrypto:false,protectApplicationPayload:false})}async sendRawIrohFrame(e){if(this.isClosed||!this.writer)throw new Error("[Connection] Requested transport unavailable: iroh");let t=this.writeMutex,n;this.writeMutex=new Promise(i=>{n=i;});try{if(await t,!this.writer)throw new Error("[Connection] Requested transport unavailable: iroh");await this.writer.write(e);}catch(i){throw this.preserveWebRtcConnectionAfterBaseTransportLoss(`Iroh Send Error: ${i}`)||(console.error("[Connection] Iroh Send error:",i),this.close(`Send Error: ${i}`)),i}finally{n();}}getAvailableTransports(){let e=[],{activeTransport:t,parallelTransport:n}=this.getTransportStatus();this.isWebRtcApplicationRouteReady()&&e.push(this.webRtcTransportLabel());this.options.transportContext;if(this.isMoQApplicationRouteReady()&&e.push("moq"),this.hasBaseApplicationRoute()){let o=t==="iroh-lan"||t==="iroh-quic"||t==="iroh-relay"||t==="ble"?t:n;e.push(o??"iroh-relay");}return e}onWebRTCBinaryMessage(e){this.webrtcBinaryHandlers.push(e);}dispatchWebRtcBinaryHandlers(e){for(let t of this.webrtcBinaryHandlers)if(t(e))return true;return false}getWebRTCTransport(){return this.isWebRtcApplicationRouteReady()?this.webrtcTransport:null}async sendOnWebRTC(e){if(!this.webrtcTransport||!this.isWebRtcApplicationRouteReady())throw new Error("[Connection] WebRTC transport unavailable");await this.waitForRequiredApplicationCrypto(),await this.webrtcTransport.send(this.protectApplicationPayload(0,e));}encodePayload(e){return typeof e=="string"?new TextEncoder().encode(e):e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new TextEncoder().encode(JSON.stringify(e))}protectApplicationPayload(e,t){return this.options.applicationCrypto?.protectPayload(e,t)??t}protectRequiredApplicationPayload(e,t){let n=this.options.applicationCrypto;return n?n.protectPayload(e,t):null}openApplicationPayload(e,t){let n=this.options.applicationCrypto;return n?n.openPayload(e,t):l$1(t)?(this.queueEncryptedApplicationPayload(e,t),null):this.options.requireApplicationCrypto===true&&!this.isPlaintextBootstrapPayload(t)?null:t}openUntypedApplicationPayload(e){if(!l$1(e))return this.options.requireApplicationCrypto===true?null:e;let t=this.options.applicationCrypto;return t?t.openPayload(0,e)??t.openPayload(3,e):(this.queueEncryptedApplicationPayload("untyped",e),null)}isPlaintextBootstrapPayload(e){try{return JSON.parse(k.textDecoder.decode(e))?.type==="handshake"}catch{return false}}queueEncryptedApplicationPayload(e,t){this._isClosed||(this.pendingEncryptedApplicationPayloads.push({typeId:e,payload:new Uint8Array(t)}),this.pendingEncryptedApplicationPayloads.length>k.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS&&this.pendingEncryptedApplicationPayloads.splice(0,this.pendingEncryptedApplicationPayloads.length-k.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS));}flushPendingEncryptedApplicationPayloads(){let e=this.options.applicationCrypto;if(!e||this.pendingEncryptedApplicationPayloads.length===0)return;let t=this.pendingEncryptedApplicationPayloads.splice(0),n=[];for(let i of t){let o=i.typeId==="untyped"?e.openPayload(0,i.payload)??e.openPayload(3,i.payload):e.openPayload(i.typeId,i.payload);if(o){i.typeId===1?this.emitMedia("video",o):i.typeId===2?this.emitMedia("audio",o):this.processDataPayload(o);continue}l$1(i.payload)&&n.push(i);}n.length>k.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS&&n.splice(0,n.length-k.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS),this.pendingEncryptedApplicationPayloads=n;}buildFrame(e,t){let n=5+t.length,i=new Uint8Array(n);return new DataView(i.buffer).setUint32(0,1+t.length,false),i[4]=e,i.set(t,5),i}async sendOverIroh(e,t,n){let i=this.options.transportContext;if(i?.disableIrohFallback&&e!==0)return console.warn(`[Connection] Iroh disabled for ${n}; dropping packet.`),false;if(this.isClosed)return false;if(!this.writer&&i?.sendIrohApplicationFrame)return await i.sendIrohApplicationFrame(t),true;if(!this.writer)return false;let o=this.writeMutex,s;this.writeMutex=new Promise(a=>{s=a;});try{return await o,this.writer?(await this.writer.write(t),!0):!1}catch(a){if(this.preserveWebRtcConnectionAfterBaseTransportLoss(`Iroh Send Error: ${a}`))return false;throw console.error("[Connection] Iroh Send error:",a),this.close(`Send Error: ${a}`),a}finally{s();}}async sendUsingTransport(e,t,n,i,o,s){let a=this.options.transportContext;return e==="webrtc-lan"||e==="webrtc-turn"?this.transportType!==e||!this.webrtcTransport||!this.isWebRtcApplicationRouteReady()||t!==0?false:(await this.webrtcTransport.send(o),this.reportApplicationRouteReady("webrtc-application-send"),true):e==="webrtc"?!this.webrtcTransport||!this.isWebRtcApplicationRouteReady()||t!==0?false:(await this.webrtcTransport.send(o),this.reportApplicationRouteReady("webrtc-application-send"),true):e==="moq"?a&&a.isMoQReady()&&this.peerMoQReady&&this.isMoQDataRouteReady(a)?(await a.sendMoQ(s,{alreadyProtected:true}),true):false:e==="iroh-lan"||e==="ble"?this.transportType!==e?false:this.sendOverIroh(t,s,"explicit transport send"):e==="iroh"||e==="iroh-relay"||e==="iroh-quic"?this.sendOverIroh(t,s,"explicit transport send"):false}async sendTypedOnTransport(e,t,n,i={}){i.requireApplicationCrypto&&await this.waitForRequiredApplicationCrypto();let o=this.encodePayload(n),s=i.protectApplicationPayload===false?o:this.protectApplicationPayload(t,o),a=this.buildFrame(t,o),c=this.buildFrame(t,s);if(!await this.sendUsingTransport(e,t,n,a,s,c))throw new Error(`[Connection] Requested transport unavailable: ${e}`);this.lastApplicationPayloadTransport=e;}async sendTyped(e,t,n={}){this.options.transportContext;n.requireApplicationCrypto&&await this.waitForRequiredApplicationCrypto();let o=this.encodePayload(t),s=n.protectApplicationPayload===false?o:this.protectApplicationPayload(e,o),a=this.buildFrame(e,o),c=this.buildFrame(e,s),l=n.useApplicationPayloadRoute&&e===0?this.getApplicationPayloadTransports(n.routeOptions??{}):this.getSendTransportPriorities(n);if(l.length===0)throw new Error("[Connection] Application payload route is not ready.");let d=null;for(let u of l)try{if(await this.sendUsingTransport(u,e,t,a,s,c)){this.lastApplicationPayloadTransport=u;return}}catch(f){d=f,console.warn(`[Connection] ${u} Send Failed:`,f);}let p=l.join(", ");throw d instanceof Error?new Error(`[Connection] Failed to send app payload on route(s): ${p}. Last error: ${d.message}`):new Error(`[Connection] Failed to send app payload on route(s): ${p}.`)}getSendTransportPriorities(e){let t=["webrtc","moq","iroh"],n=this.options.transportContext?.priorities??t,i=n.length>0?n:t,o=this.options.transportContext?.rankRoutes?.(i)??i;return e.requireApplicationCrypto===false||e.protectApplicationPayload===false?["iroh",...o.filter(a=>a!=="iroh"&&a!=="iroh-relay"&&a!=="iroh-quic"&&a!=="iroh-lan")]:o}async disconnect(){this.close("Explicit Disconnect");}onMessage(e){if(this.listeners.push(e),this.pendingMessages.length!==0)for(let t of this.pendingMessages)e(t);}onMedia(e){this.mediaListeners.push(e);}onDisconnect(e){this.closeListeners.push(e);}close(e){if(this._isClosed)return;if(this._isClosed=true,this.upgradeRequested=false,this.upgradeAttemptActive=false,this.activeNegotiationId=null,this.pendingAvailabilityHint=null,this.pendingSignals=[],this.clearUpgradeRetryTimer(),this.clearUpgradeReDriveTimer(),this.clearUpgradeAttemptTimeoutTimer(),this.clearWebRtcDisconnectedGraceTimer(),this.teardownWebRTCTransport(`connection-close:${e??"unspecified"}`),this.setUpgradeState("none"),this.rejectApplicationCryptoWaiters(new Error("[Connection] Application crypto negotiation stopped because the connection closed.")),this.pendingEncryptedApplicationPayloads=[],this.writer?.close().catch(()=>{}),(this.options.transportContext?.readerCloseStrategy??"cancel")==="release-lock")try{this.reader?.releaseLock();}catch{}else this.reader?.cancel().catch(()=>{});this.writer=null,this.reader=null,this.closeListeners.forEach(n=>n());}preserveWebRtcConnectionAfterBaseTransportLoss(e){let t=this.getControlFrameMode()==="native-main"&&!!this.nativeSignalSender,n=!!this.webrtcTransport&&(this.upgradeState==="upgraded"||this.upgradeState==="upgrading"&&!!this.nativeSignalSender);if(!t&&!n)return false;c$1("[Connection] Base transport closed while a control/WebRTC route remains usable; preserving connection",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,transportStatus:this.getTransportStatus(),upgradeState:this.upgradeState}),this.clearUpgradeRetryTimer();try{this.reader?.releaseLock();}catch{}try{this.writer?.releaseLock();}catch{}return this.reader=null,this.writer=null,this.reportApplicationRouteReady("base-transport-loss-preserved"),this.reportTransportStatusIfChanged(),true}async readLoop(){if(this.reader)try{for(;!this.isClosed;){let{done:e,value:t}=await this.reader.read();if(e){if(this.preserveWebRtcConnectionAfterBaseTransportLoss("Read Done (Remote Closed)"))break;this.close("Read Done (Remote Closed)");break}t&&this.handleData(t);}}catch(e){let t=`Read Error: ${e}`;if(this.preserveWebRtcConnectionAfterBaseTransportLoss(t))return;console.error("[Connection] Read loop error:",e),this.close(t);}}injectData(e){this.handleData(e);}handleData(e){let t=new Uint8Array(this.receiveBuffer.length+e.length);for(t.set(this.receiveBuffer),t.set(e,this.receiveBuffer.length),this.receiveBuffer=t;!(this.receiveBuffer.length<4);){let i=new DataView(this.receiveBuffer.buffer,this.receiveBuffer.byteOffset,this.receiveBuffer.byteLength).getUint32(0,false);if(this.receiveBuffer.length<4+i)break;let o=this.receiveBuffer.slice(4,4+i);this.receiveFrameBody(o),this.receiveBuffer=this.receiveBuffer.slice(4+i);}}receiveFrameBody(e){if(e.length===0)return;let t=e[0],n=e.slice(1);if(k.isUntypedDataFrame(e)){let i=this.openUntypedApplicationPayload(e);i&&this.processDataPayload(i);}else if(t===3)this.sendIrohHeartbeatPong(n);else if(t===4)this.irohHealthListeners.forEach(i=>i("healthy"));else if(t===1){let i=this.openApplicationPayload(t,n);i&&this.emitMedia("video",i);}else if(t===2){let i=this.openApplicationPayload(t,n);i&&this.emitMedia("audio",i);}else {if(t===0&&this.tryHandlePlaintextNativeSignal(n))return;let i=this.openApplicationPayload(t,n);i&&this.processDataPayload(i);}}tryHandlePlaintextNativeSignal(e){let t;try{t=JSON.parse(k.textDecoder.decode(e));}catch{return false}return !t||typeof t!="object"||t.type!=="#pluto-signal"?false:(this.handleInternalSignal(t),true)}static isUntypedDataFrame(e){let t=e[0];return t===123||t===91||l$1(e)?true:e.length>=4&&e[0]===68&&e[1]===86&&e[2]===67&&e[3]===72}processDataPayload(e){if(l$1(e)){let t=this.openUntypedApplicationPayload(e);t&&t!==e&&this.processDataPayload(t);return}try{let t=k.textDecoder.decode(e);if(!this.isLikelyTextPayload(e,t)){this.emitMessage(e);return}let n=JSON.parse(t);if(this.tryHandleWebRtcApplicationRouteProofPayload(n,null))return;if(n&&typeof n=="object"&&n.type==="#pluto-signal"){this.handleInternalSignal(n);return}typeof n=="object"&&n!==null?this.emitMessage(n):this.emitMessage(t);}catch{try{let t=k.textDecoder.decode(e);if(this.isLikelyTextPayload(e,t)){this.emitMessage(t);return}}catch{}this.emitMessage(e);}}isLikelyTextPayload(e,t){try{for(let i=0;i<t.length;i+=1){let o=t.charCodeAt(i);if(o<32&&o!==9&&o!==10&&o!==13)return !1}let n=k.textEncoder.encode(t);if(n.byteLength!==e.byteLength)return !1;for(let i=0;i<n.byteLength;i+=1)if(n[i]!==e[i])return !1;return !0}catch{return false}}emitMedia(e,t){this.mediaListeners.forEach(n=>n(e,t));}emitMessage(e){this.pendingMessages.push(e),this.pendingMessages.length>k.MAX_PENDING_MESSAGES&&this.pendingMessages.splice(0,this.pendingMessages.length-k.MAX_PENDING_MESSAGES),this.listeners.length!==0&&this.listeners.forEach(t=>t(e));}receiveMessage(e){this.emitMessage(e);}receiveDataPayload(e){this.processDataPayload(e);}warnSrtpApplicationCryptoBoundary(e){!this.options.applicationCrypto||this.warnedSrtpApplicationCryptoBoundary||(this.warnedSrtpApplicationCryptoBoundary=true,console.warn(`[Connection] ${e} uses WebRTC DTLS-SRTP media encryption, not the ORTCE1 applicationCrypto envelope. Use sendMedia() for ORTCE1-protected app-encoded media chunks.`));}addTrack(e){let t=this.webrtcTransport?.getNativeTransport?.();return t&&typeof t.addTrack=="function"?(this.warnSrtpApplicationCryptoBoundary("addTrack"),t.addTrack(e)):null}addTransceiver(e,t){let n=this.webrtcTransport?.getNativeTransport?.();return n&&typeof n.addTransceiver=="function"?(this.warnSrtpApplicationCryptoBoundary("addTransceiver"),n.addTransceiver(e,t)):null}onTrack(e){this.trackListeners.push(e);}hasRecoverableBasePath(){return !!this.nativeSignalSender||this.hasBaseApplicationRoute()}hasBaseApplicationRoute(){return this.options.hasBaseApplicationStream===false?false:!!this.writer||this.getControlFrameMode()==="native-main"&&!!this.nativeSignalSender&&typeof this.options.transportContext?.sendIrohApplicationFrame=="function"}isWebRtcDataChannelOpen(){return this.upgradeState==="upgraded"&&!!this.webrtcTransport&&this.webrtcTransport.getDataChannelReadyState?.()==="open"}clearWebRtcDisconnectedGraceTimer(){this.webRtcDisconnectedGraceTimer&&(clearTimeout(this.webRtcDisconnectedGraceTimer),this.webRtcDisconnectedGraceTimer=null);}transportStillLikelyAlive(e){let t=e.getDataChannelReadyState?.()??null,n=e.getNativeTransport?.()??null,i=typeof n?.connectionState=="string"?n.connectionState:null,o=typeof n?.iceConnectionState=="string"?n.iceConnectionState:null;return t==="closed"||t==="closing"?false:t==="open"?true:i==="connected"||i==="connecting"||o==="connected"||o==="completed"||o==="checking"}handleUnhealthyWebRtcTransportStateWithGrace(e,t){let n=e.getDataChannelReadyState?.()??null;if(n==="closed"||n==="closing"){if(c$1("[Connection] WebRTC unhealthy with closed DataChannel; failing upgraded transport immediately",{connectionId:this.id,remoteNodeId:this.remoteNodeId,state:t,dcReadyState:n}),!this.hasBaseApplicationRoute()&&!this.isMoQApplicationRouteReady()){this.close(`all-application-routes-closed:${t}`);return}this.stopWebRtcHeartbeat(),this.handleUpgradeFailure(`transport-state-${t}-dc-closed`);return}this.webRtcDisconnectedGraceTimer||(c$1("[Connection] WebRTC transport reported unhealthy; applying grace window before fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,state:t}),this.webRtcDisconnectedGraceTimer=setTimeout(()=>{if(this.webRtcDisconnectedGraceTimer=null,!(this._isClosed||this.webrtcTransport!==e)){if(this.transportStillLikelyAlive(e)){c$1("[Connection] WebRTC unhealthy grace expired but transport appears alive; suppressing fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,state:t});return}this.stopWebRtcHeartbeat(),this.handleUpgradeFailure(`transport-state-${t}-grace-expired`);}},k.WEBRTC_DISCONNECTED_GRACE_MS));}async attemptUpgrade(e){if(this._isClosed||!this.upgradeRequested||!this.options.rtcConfig)return;let t=typeof e=="object"&&e!==null?e:{preferredNegotiationId:e??null},n=t.preferredNegotiationId,i=!!t.forceRenegotiate;if(!!!t.replaceExisting&&(this.upgradeAttemptActive||this.upgradeState==="upgraded"))return;this.upgradeAttemptActive=true,this.teardownWebRTCTransport("upgrade-attempt-replacement"),this.clearWebRtcCandidatePairObservation(),this.applicationRouteMissingNotified=false;let s=this.normalizeNegotiationId(n)??this.createNegotiationId();this.activeNegotiationId=s,this.setUpgradeState("upgrading"),this.startUpgradeAttemptTimeout(s),(i||this.upgradeRetryCount>0)&&this.sendInternalSignal({transport:"webrtc",type:"renegotiate",negotiationId:s}).catch(()=>{});try{this.webrtcTransport=ce.createTransport("webrtc");}catch(d){this.upgradeAttemptActive=false,c$1("[Connection] WebRTC upgrade unavailable",d),this.handleUpgradeFailure("transport-create-error");return}let a=this.webrtcTransport;typeof a.setSignalSender=="function"&&a.setSignalSender(d=>this.sendInternalSignal(d)),a.onMessage(d=>{if(d instanceof Uint8Array&&d.byteLength>0){if(this.webrtcHeartbeat?.handleIncoming(d)){d[0]===4&&this.refreshWebRtcCandidatePairObservation(a);return}let u=l$1(d),f=this.openApplicationPayload(0,d);if(!f||u&&this.tryHandleWebRtcApplicationRouteProofBytes(a,f)||this.dispatchWebRtcBinaryHandlers(f))return;this.processDataPayload(f);return}let p=this.openApplicationPayload(0,d);p&&this.processDataPayload(p);}),a.onStateChange(d=>{if(!(this._isClosed||this.webrtcTransport!==a)){if(d$1(`[Connection] WebRTC transport state changed: ${d}`),d==="connected"){this.pendingAvailabilityHint=null,this.clearWebRtcDisconnectedGraceTimer(),this.clearUpgradeAttemptTimeoutTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.clearUpgradeRetryTimer(),this.lastWebRtcDataChannelOpenAt=Date.now(),this.setUpgradeState("upgraded"),this.startWebRtcHeartbeat(a),this.startWebRtcApplicationRouteProbe(a,"transport-connected");return}if(d==="failed"||d==="disconnected"){if(this.clearUpgradeAttemptTimeoutTimer(),this.upgradeAttemptActive=false,this.upgradeState==="upgraded"&&(d==="disconnected"||this.isWebRtcApplicationRouteReadyForTransport(a))){this.handleUnhealthyWebRtcTransportStateWithGrace(a,d);return}if(this.clearWebRtcDisconnectedGraceTimer(),a.isTerminalFailure?.()){let p=this.pendingAvailabilityHint,u=!!p&&p.negotiationId===this.activeNegotiationId;this.pendingAvailabilityHint=null,this.upgradeTerminalFailure=!u,u&&this.traceLifecycle("webrtc-terminal-failure-retry-after-availability",{negotiationId:this.activeNegotiationId,source:p?.source??null});}this.stopWebRtcHeartbeat(),this.handleUpgradeFailure(`transport-state-${d}`);}}});try{await a.init(this.localNodeId,this.deviceId,{rtcConfig:this.options.rtcConfig,negotiationId:s,forceRole:this.preferredWebRtcRole??void 0});}catch(d){this.upgradeAttemptActive=false,this.clearUpgradeAttemptTimeoutTimer(),c$1("[Connection] WebRTC init failed",d),this.handleUpgradeFailure("init-error");return}if(this.webrtcTransport!==a){this.upgradeAttemptActive=false;return}let c=a.getNegotiationId?.();if(c&&(this.activeNegotiationId=this.normalizeNegotiationId(c)??s),this.pendingSignals.length>0){let d=this.pendingSignals.splice(0);for(let p of d)a.handleSignalingMessage?.(p);}let l=a.getNativeTransport?.();l&&l.ontrack!==void 0&&(l.ontrack=d=>{d$1(`[Connection] Peer track received: ${d.track.kind}`),this.trackListeners.forEach(p=>p(d));});}setUpgradeState(e){this.upgradeState!==e&&(this.upgradeState=e,this.reportTransportStatusIfChanged(),this.upgradeStateListeners.forEach(t=>{try{t(e);}catch(n){c$1("[Connection] Upgrade state listener failed",n);}}));}handleUpgradeFailure(e){if(this._isClosed||!this.upgradeRequested)return;this.clearUpgradeAttemptTimeoutTimer();let t=this.upgradeTerminalFailure,n=!t&&this.shouldRetryUpgrade();this.upgradeAttemptActive=false,this.setUpgradeState("failed");let i={connectionId:this.id,remoteNodeId:this.remoteNodeId,retryCount:this.upgradeRetryCount,maxRetries:k.MAX_UPGRADE_RETRIES,terminal:t,willRetry:n};if(n?c$1(`[Connection] WebRTC upgrade retry scheduled after failure: ${e}`,i):console.warn(`[Connection] WebRTC upgrade failed: ${e}`,i),t&&console.warn("[Connection] WebRTC upgrade is terminal \u2014 not retrying. Both peers may be on the same page (same-context loopback)."),c$1(`[Connection] WebRTC upgrade fallback: ${e}`),n){this.scheduleUpgradeRetry();return}this.clearUpgradeRetryTimer(),this.teardownWebRTCTransport(`upgrade-failed:${e}`),!t&&this.upgradeRequested&&!this._isClosed&&this.upgradeRetryCount>=k.MAX_UPGRADE_RETRIES&&this.hasRecoverableBasePath()&&this.scheduleUpgradeReDrive();}scheduleUpgradeReDrive(){this.clearUpgradeReDriveTimer(),this.upgradeReDriveCount=Math.min(this.upgradeReDriveCount+1,Number.MAX_SAFE_INTEGER);let e=this.upgradeReDriveCount,t=Math.min(e-1,k.UPGRADE_REDRIVE_DELAYS_MS.length-1),n=k.UPGRADE_REDRIVE_DELAYS_MS[t];this.upgradeReDriveTimer=setTimeout(()=>{this.upgradeReDriveTimer=null,!(this._isClosed||!this.upgradeRequested||this.upgradeAttemptActive)&&(this.isWebRtcApplicationRouteReady()||!this.hasRecoverableBasePath()||(this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,d$1(`[Connection] Re-driving WebRTC upgrade round ${e} after ${n}ms because the retry budget was exhausted on a healthy base route`),this.attemptUpgrade({forceRenegotiate:true})));},n);}clearUpgradeReDriveTimer(){this.upgradeReDriveTimer&&(clearTimeout(this.upgradeReDriveTimer),this.upgradeReDriveTimer=null);}shouldRetryUpgrade(){return !(this._isClosed||!this.upgradeRequested||this.upgradeTerminalFailure||!this.options.rtcConfig||!this.hasRecoverableBasePath()||this.upgradeRetryCount>=k.MAX_UPGRADE_RETRIES)}scheduleUpgradeRetry(){this.clearUpgradeRetryTimer(),this.upgradeRetryCount+=1;let e=this.upgradeRetryCount;this.upgradeRetryTimer=setTimeout(()=>{this.upgradeRetryTimer=null,!(this._isClosed||!this.upgradeRequested||this.upgradeAttemptActive)&&(d$1(`[Connection] Retrying WebRTC upgrade ${e}/${k.MAX_UPGRADE_RETRIES}`),this.attemptUpgrade());},k.UPGRADE_RETRY_DELAY_MS);}clearUpgradeRetryTimer(){this.upgradeRetryTimer&&(clearTimeout(this.upgradeRetryTimer),this.upgradeRetryTimer=null);}startUpgradeAttemptTimeout(e){this.clearUpgradeAttemptTimeoutTimer(),this.upgradeAttemptTimeoutTimer=setTimeout(()=>{this.upgradeAttemptTimeoutTimer=null,!(this._isClosed||!this.upgradeRequested)&&this.upgradeState==="upgrading"&&this.activeNegotiationId===e&&(this.upgradeAttemptActive=false,c$1("[Connection] WebRTC upgrade attempt timed out",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:e}),this.handleUpgradeFailure("upgrade-attempt-timeout"));},k.WEBRTC_UPGRADE_ATTEMPT_TIMEOUT_MS);}clearUpgradeAttemptTimeoutTimer(){this.upgradeAttemptTimeoutTimer&&(clearTimeout(this.upgradeAttemptTimeoutTimer),this.upgradeAttemptTimeoutTimer=null);}teardownWebRTCTransport(e){this.pendingAvailabilityHint=null,this.clearWebRtcDisconnectedGraceTimer(),this.clearUpgradeAttemptTimeoutTimer(),this.clearWebRtcCandidatePairObservation();let t=this.webrtcTransport;if(!t)return;let n=t.getNativeTransport?.();this.traceLifecycle("webrtc-transport-teardown",{reason:e,negotiationId:this.activeNegotiationId,dataChannelReadyState:t.getDataChannelReadyState?.()??null,peerConnectionState:n?.connectionState??null,iceConnectionState:n?.iceConnectionState??null}),this.webrtcTransport=null,this.clearWebRtcApplicationRouteReady(),this.cancelWebRtcApplicationRouteProofForTransport(t,`teardown:${e}`),this.applicationRouteMissingNotified=false,this.stopWebRtcHeartbeat();try{t.close();}catch(i){c$1("[Connection] WebRTC transport close failed",i);}this.reportTransportStatusIfChanged();}startWebRtcHeartbeat(e){this.stopWebRtcHeartbeat();let t=Date.now();c$1("[Connection] WebRTC heartbeat starting",{connectionId:this.id,startedAt:t,config:Oe});let n=new yt(async i=>{c$1("[Connection] WebRTC heartbeat send",{connectionId:this.id,byteLength:i.byteLength,typeId:i[0]}),await e.send(i);},i=>{let o=Date.now()-t;if(c$1("[Connection] WebRTC heartbeat health callback",{connectionId:this.id,health:i,elapsedSinceStartMs:o}),i==="healthy"&&(this.lastWebRtcHeartbeatOkAt=Date.now(),this.webRtcHeartbeatConsecutiveProbeFailures=0,this.isWebRtcApplicationRouteReadyForTransport(e)?this.reportApplicationRouteReady("webrtc-heartbeat-healthy"):this.hasRequiredApplicationCrypto()?this.webrtcTransport===e?this.startWebRtcApplicationRouteProbe(e,"webrtc-heartbeat-healthy"):this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-transport",negotiationId:e.getNegotiationId?.()??null,activeNegotiationId:this.activeNegotiationId}):this.notifyWebRtcApplicationRouteMissing("webrtc-heartbeat-before-crypto")),this.webrtcHealthListeners.forEach(s=>s(i)),i==="stale"){if(this.webRtcHeartbeatProbeInFlight)return;this.webRtcHeartbeatProbeInFlight=true,d$1("[Connection] WebRTC heartbeat stale \u2014 probing transport before fallback"),n.probe(4e3).then(s=>{if(this._isClosed||this.webrtcTransport!==e)return;if(s){this.lastWebRtcHeartbeatOkAt=Date.now(),this.webRtcHeartbeatConsecutiveProbeFailures=0,d$1("[Connection] WebRTC heartbeat probe succeeded \u2014 keeping upgraded transport");return}if(this.webRtcHeartbeatConsecutiveProbeFailures+=1,this.transportStillLikelyAlive(e)){this.lastWebRtcHeartbeatOkAt=Date.now(),d$1("[Connection] WebRTC heartbeat probe failed but transport appears alive \u2014 suppressing fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,consecutiveFailures:this.webRtcHeartbeatConsecutiveProbeFailures});return}if(this.webRtcHeartbeatConsecutiveProbeFailures<2){d$1("[Connection] WebRTC heartbeat probe failed \u2014 awaiting one more failure before fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,consecutiveFailures:this.webRtcHeartbeatConsecutiveProbeFailures});return}if(!this.hasRecoverableBasePath()){this.lastWebRtcHeartbeatOkAt=Date.now(),d$1("[Connection] WebRTC heartbeat probe failed but no base recovery path exists \u2014 keeping transport",{connectionId:this.id,remoteNodeId:this.remoteNodeId});return}d$1("[Connection] WebRTC heartbeat probe failed consecutively \u2014 triggering upgrade fallback"),this.stopWebRtcHeartbeat(),this.handleUpgradeFailure("heartbeat-stale-probe-failed");}).finally(()=>{this.webRtcHeartbeatProbeInFlight=false;});}},Oe);this.webrtcHeartbeat=n,n.start();}stopWebRtcHeartbeat(){this.webRtcHeartbeatProbeInFlight=false,this.webRtcHeartbeatConsecutiveProbeFailures=0,this.webrtcHeartbeat&&(this.webrtcHeartbeat.stop(),this.webrtcHeartbeat=null);}notifyWebRtcApplicationRouteMissing(e){this.applicationRouteMissingNotified||(this.applicationRouteMissingNotified=true,this.traceLifecycle("webrtc-route-proved-application-crypto-missing",{negotiationId:this.activeNegotiationId,reason:e}),this.options.onApplicationRouteMissing?.({connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,negotiationId:this.activeNegotiationId}));}currentWebRtcNegotiationId(e){return this.normalizeNegotiationId(e.getNegotiationId?.())??this.normalizeNegotiationId(this.activeNegotiationId)}createWebRtcApplicationRouteProofId(){let e=new Uint8Array(8);try{globalThis.crypto?.getRandomValues?.(e);}catch{for(let n=0;n<e.byteLength;n+=1)e[n]=Math.floor(Math.random()*256);}let t=Array.from(e).map(n=>n.toString(16).padStart(2,"0")).join("");return `${Date.now().toString(36)}-${t}`}isCurrentWebRtcApplicationRouteProof(e){return !e.cancelled&&this.pendingWebRtcApplicationRouteProof===e&&!this._isClosed&&this.webrtcTransport===e.transport&&this.upgradeState==="upgraded"&&this.currentWebRtcNegotiationId(e.transport)===e.negotiationId}cancelWebRtcApplicationRouteProofForTransport(e,t){let n=this.pendingWebRtcApplicationRouteProof;n?.transport===e&&this.cancelWebRtcApplicationRouteProof(n,t);}cancelWebRtcApplicationRouteProof(e,t){!e||e.cancelled||(e.cancelled=true,e.timer&&(clearTimeout(e.timer),e.timer=null),this.pendingWebRtcApplicationRouteProof===e&&(this.pendingWebRtcApplicationRouteProof=null,this.webRtcApplicationRouteProbeInFlight=false),this.traceLifecycle("webrtc-application-route-proof-cancelled",{reason:t,negotiationId:e.negotiationId,probeId:e.probeId}));}completeWebRtcApplicationRouteProofAck(e){if(!this.isCurrentWebRtcApplicationRouteProof(e)){this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-proof",negotiationId:e.negotiationId,probeId:e.probeId,activeNegotiationId:this.activeNegotiationId});return}this.cancelWebRtcApplicationRouteProof(e,"ack-received"),this.markWebRtcApplicationRouteReady(e.transport);}async sendWebRtcApplicationRouteProofFrame(e,t,n={}){if(this._isClosed||this.webrtcTransport!==e||this.upgradeState!=="upgraded"||n.requireLocalNegotiation===true&&this.currentWebRtcNegotiationId(e)!==t.negotiationId)throw new Error("[Connection] WebRTC route proof cannot be sent on a stale transport");let i=k.textEncoder.encode(JSON.stringify(t)),o=this.protectRequiredApplicationPayload(0,i);if(!o)throw new Error("[Connection] WebRTC route proof requires application crypto");await e.send(o);}tryHandleWebRtcApplicationRouteProofBytes(e,t){try{let n=JSON.parse(k.textDecoder.decode(t));return this.tryHandleWebRtcApplicationRouteProofPayload(n,e)}catch{return false}}tryHandleWebRtcApplicationRouteProofPayload(e,t){if(!this.isWebRtcApplicationRouteProofFrame(e))return false;if(!t)return this.traceLifecycle("webrtc-route-proof-ignored",{reason:"missing-webrtc-transport-context",negotiationId:e.negotiationId,probeId:e.probeId,role:e.role}),true;if(this._isClosed||this.webrtcTransport!==t||this.upgradeState!=="upgraded")return this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-transport",negotiationId:e.negotiationId,probeId:e.probeId,role:e.role,activeNegotiationId:this.activeNegotiationId}),true;if(e.role==="probe")return this.sendWebRtcApplicationRouteProofFrame(t,{type:"#openrtc-webrtc-route-proof",version:1,role:"ack",negotiationId:e.negotiationId,probeId:e.probeId}).catch(i=>{c$1("[Connection] WebRTC application route proof ACK failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:e.negotiationId,probeId:e.probeId,error:i});}),true;if(this.currentWebRtcNegotiationId(t)!==e.negotiationId)return this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-negotiation",negotiationId:e.negotiationId,probeId:e.probeId,role:e.role,activeNegotiationId:this.activeNegotiationId}),true;let n=this.pendingWebRtcApplicationRouteProof;return n&&n.transport===t&&n.negotiationId===e.negotiationId&&n.probeId===e.probeId?(this.completeWebRtcApplicationRouteProofAck(n),true):(this.traceLifecycle("webrtc-route-proof-ignored",{reason:"unexpected-ack",negotiationId:e.negotiationId,probeId:e.probeId,activeNegotiationId:this.activeNegotiationId,expectedProbeId:n?.probeId??null}),true)}isWebRtcApplicationRouteProofFrame(e){if(!e||typeof e!="object")return false;let t=e;return t.type==="#openrtc-webrtc-route-proof"&&t.version===1&&(t.role==="probe"||t.role==="ack")&&typeof t.probeId=="string"&&t.probeId.length>0&&t.probeId.length<=k.WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH&&typeof t.negotiationId=="string"&&t.negotiationId.length>0&&t.negotiationId.length<=k.WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH}startWebRtcApplicationRouteProbe(e,t){if(this.webRtcApplicationRouteProbeInFlight||this._isClosed||this.webrtcTransport!==e||this.upgradeState!=="upgraded"||this.isWebRtcApplicationRouteReadyForTransport(e))return;let n=this.currentWebRtcNegotiationId(e);if(!n){this.traceLifecycle("webrtc-application-route-probe-deferred",{reason:t,skipReason:"missing-negotiation-id"});return}if(!this.options.applicationCrypto){this.notifyWebRtcApplicationRouteMissing("webrtc-heartbeat-before-crypto");return}let i=this.createWebRtcApplicationRouteProofId(),o={transport:e,negotiationId:n,probeId:i,reason:t,timer:null,cancelled:false};o.timer=setTimeout(()=>{this.cancelWebRtcApplicationRouteProof(o,"timeout"),this.traceLifecycle("webrtc-application-route-probe-deferred",{reason:t,negotiationId:n,probeId:i,skipReason:"ack-timeout"});},k.WEBRTC_APPLICATION_ROUTE_PROOF_TIMEOUT_MS),this.pendingWebRtcApplicationRouteProof=o,this.webRtcApplicationRouteProbeInFlight=true,this.traceLifecycle("webrtc-application-route-probe-start",{reason:t,negotiationId:n,probeId:i}),(async()=>{for(let s of k.WEBRTC_APPLICATION_ROUTE_PROOF_DELAYS_MS){if(!this.isCurrentWebRtcApplicationRouteProof(o)||this.isWebRtcApplicationRouteReadyForTransport(e)||s>0&&(await u(s),!this.isCurrentWebRtcApplicationRouteProof(o)||this.isWebRtcApplicationRouteReadyForTransport(e)))return;try{await this.sendWebRtcApplicationRouteProofFrame(e,{type:"#openrtc-webrtc-route-proof",version:1,role:"probe",negotiationId:n,probeId:i},{requireLocalNegotiation:!0});}catch(a){if(!this.isCurrentWebRtcApplicationRouteProof(o))return;c$1("[Connection] WebRTC application route proof send failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:n,probeId:i,error:a});}}})().finally(()=>{this.pendingWebRtcApplicationRouteProof===o&&(this.webRtcApplicationRouteProbeInFlight=false);});}async sendIrohHeartbeatPong(e){if(e.byteLength<16||!this.writer)return;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getBigUint64(0,false),i=t.getBigInt64(8,false),o=BigInt(Date.now()),s=new ArrayBuffer(29),a=new DataView(s);a.setUint32(0,25,false),a.setUint8(4,4),a.setBigUint64(5,n,false),a.setBigInt64(13,i,false),a.setBigInt64(21,o,false);let c=this.writeMutex,l;this.writeMutex=new Promise(d=>{l=d;});try{await c,this.writer&&await this.writer.write(new Uint8Array(s));}catch{}finally{l();}}onWebRtcHeartbeatHealth(e){this.webrtcHealthListeners.push(e);}onIrohHeartbeatHealth(e){this.irohHealthListeners.push(e);}reportTransportStatusIfChanged(){if(this._isClosed)return;let{activeTransport:e,parallelTransport:t}=this.getTransportStatus(),n=`${e}:${t??""}`;this.lastReportedTransportStatus!==n&&this.pendingTransportStatusReport?.fingerprint!==n&&(this.pendingTransportStatusReport={fingerprint:n,status:{activeTransport:e,parallelTransport:t??null},retryCount:0},this.drainTransportStatusReports());}drainTransportStatusReports(){this.transportStatusReportInFlight||this._isClosed||(this.transportStatusReportInFlight=true,(async()=>{for(;!this._isClosed&&this.pendingTransportStatusReport;){let e=this.pendingTransportStatusReport;if(this.pendingTransportStatusReport=null,this.lastReportedTransportStatus===e.fingerprint)continue;let t=true;try{t=await this.options.onTransportStatusChange?.(e.status)!==!1;}catch(o){t=false,c$1("[Connection] Transport status projection failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,...e.status,error:o});}if(this._isClosed)return;if(t){this.lastReportedTransportStatus=e.fingerprint;continue}let n=this.getTransportStatus(),i=`${n.activeTransport}:${n.parallelTransport??""}`;i===e.fingerprint&&!this.pendingTransportStatusReport&&e.retryCount<1&&(this.pendingTransportStatusReport={fingerprint:i,status:{activeTransport:n.activeTransport,parallelTransport:n.parallelTransport??null},retryCount:e.retryCount+1},await Promise.resolve());}})().finally(()=>{this.transportStatusReportInFlight=false,!this._isClosed&&this.pendingTransportStatusReport&&this.drainTransportStatusReports();}));}reportApplicationRouteReady(e){if(this._isClosed||!this.isWebRtcApplicationRouteReady())return;let t=Date.now();if(e!=="webrtc-route-ready"&&this.lastApplicationRouteReadyReportAt!==null&&t-this.lastApplicationRouteReadyReportAt<1e3)return;this.lastApplicationRouteReadyReportAt=t;let{activeTransport:n,parallelTransport:i}=this.getTransportStatus();this.options.onApplicationRouteReady?.({connectionId:this.id,remoteNodeId:this.remoteNodeId,activeTransport:n,parallelTransport:i,reason:e});}getTransportStatus(){let e=this.transportType;return {activeTransport:e,parallelTransport:this.resolveParallelTransport(e)}}getTransportLatencySnapshot(){let e=this.webrtcHeartbeat?.latencyMs??null;if(e===null)return {};let t={},{activeTransport:n,parallelTransport:i}=this.getTransportStatus();for(let o of [n,i])o==="webrtc-lan"?t.webrtcLan=e:o==="webrtc-turn"?t.webrtcTurn=e:o==="webrtc"&&(t.webrtc=e);return t}resolveParallelTransport(e){if(this._isClosed)return null;let t=c$2(e);return !t&&this.writer||!t&&f$1(e)&&this.hasRecoverableBasePath()?"iroh-relay":t&&this.isWebRtcDataChannelOpen()?this.webRtcTransportLabel():null}setNativeSignalSender(e){this.nativeSignalSender=e;}traceLifecycle(e,t={}){let n={event:e,connectionId:this.id,localNodeId:this.localNodeId,remoteNodeId:this.remoteNodeId,upgradeState:this.upgradeState,upgradeRequested:this.upgradeRequested,upgradeAttemptActive:this.upgradeAttemptActive,upgradeRetryCount:this.upgradeRetryCount,activeNegotiationId:this.activeNegotiationId,preferredWebRtcRole:this.preferredWebRtcRole,hasWriter:!!this.writer,hasNativeSignalSender:!!this.nativeSignalSender,isClosed:this._isClosed,...t};c$1("[OpenRTC][lifecycle]",n);try{c$1(`[OpenRTC][lifecycle-json] ${JSON.stringify(n)}`);}catch{}}getControlFrameMode(){return this.options.controlFrameMode??"typed"}async sendNativeControlEnvelope(e){return this.getControlFrameMode()!=="native-main"||!this.nativeSignalSender?false:(await this.nativeSignalSender(e),true)}promoteToNativeMainControlRoute(e){this.options={...this.options,controlFrameMode:"native-main"},this.nativeSignalSender=e,this.traceLifecycle("native-main-control-route-promoted");}hasRequiredApplicationCrypto(){return this.options.requireApplicationCrypto!==true||!!this.options.applicationCrypto}clearWebRtcApplicationRouteReady(){this.webRtcApplicationRouteReadyTransport=null,this.webRtcApplicationRouteReadyNegotiationId=null;}isCurrentWebRtcTransportApplicationRouteReady(){return !!this.webrtcTransport&&this.isWebRtcApplicationRouteReadyForTransport(this.webrtcTransport)}isWebRtcApplicationRouteReadyForTransport(e){return this.webRtcApplicationRouteReadyTransport===e&&this.webRtcApplicationRouteReadyNegotiationId===(e.getNegotiationId?.()??this.activeNegotiationId)}markWebRtcApplicationRouteReady(e){if(this.isWebRtcApplicationRouteReadyForTransport(e)||!this.hasRequiredApplicationCrypto()){this.hasRequiredApplicationCrypto()||this.traceLifecycle("webrtc-route-promotion-skipped",{reason:"missing-application-crypto",negotiationId:e.getNegotiationId?.()??this.activeNegotiationId});return}if(this.webrtcTransport!==e){this.traceLifecycle("webrtc-route-promotion-skipped",{reason:"stale-transport",negotiationId:e.getNegotiationId?.()??null,activeNegotiationId:this.activeNegotiationId});return}this.webRtcApplicationRouteReadyTransport=e,this.webRtcApplicationRouteReadyNegotiationId=e.getNegotiationId?.()??this.activeNegotiationId,this.negotiationSwitchCount=0,this.upgradeReDriveCount=0,this.clearUpgradeReDriveTimer(),this.traceLifecycle("webrtc-application-route-ready",{negotiationId:this.webRtcApplicationRouteReadyNegotiationId}),this.reportTransportStatusIfChanged(),this.refreshWebRtcCandidatePairObservation(e),this.reportApplicationRouteReady("webrtc-route-ready");}isWebRtcApplicationRouteReady(){return this.isCurrentWebRtcTransportApplicationRouteReady()&&this.upgradeState==="upgraded"&&!!this.webrtcTransport&&this.hasRequiredApplicationCrypto()}isMoQApplicationRouteReady(){let e=this.options.transportContext;return !this._isClosed&&!!e&&e.isMoQReady()&&this.peerMoQReady&&this.isMoQDataRouteReady(e)&&e.isMoQApplicationRouteProven?.()===true&&this.hasRequiredApplicationCrypto()}isMoQDataRouteReady(e){return typeof e.isMoQDataReady=="function"?e.isMoQDataReady():true}async sendInternalSignal(e){let t=e&&(e.transport==="webrtc"||!e.transport)?{...e,transport:"webrtc",negotiationId:this.normalizeNegotiationId(e.negotiationId)??this.activeNegotiationId??void 0}:e,n={type:"#pluto-signal",content:t};if(this.getControlFrameMode()==="native-main"){if(this.nativeSignalSender)try{await this.nativeSignalSender(n),d$1("[Connection] Sent internal signal via native sender",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});return}catch(i){console.warn("[Connection] Native signal sender failed, falling back to own native-main stream",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null,error:i});}if(this.writer&&typeof this.sendRawIrohFrame=="function")try{let i=new TextEncoder().encode(JSON.stringify(n)),o=new Uint8Array(1+i.byteLength);o[0]=0,o.set(i,1);let s=new ArrayBuffer(4+o.byteLength),a=new DataView(s),c=new Uint8Array(s);a.setUint32(0,o.byteLength,!1),c.set(o,4),await this.sendRawIrohFrame(c),d$1("[Connection] Sent internal signal over own native-main stream",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});return}catch(i){console.warn("[Connection] Own native-main stream signal send failed; falling back to typed iroh",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null,error:i});}}try{if((t?.type==="sdp"||t?.type==="candidate"||t?.type==="renegotiate")&&c$1("[Connection][WebRTC][signal][send]",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:t?.negotiationId??null,signalType:t?.type??null,sdpType:t?.sdp?.type??null,hasSdp:!!t?.sdp?.sdp,hasCandidate:!!t?.candidate}),this.writer&&typeof this.sendRawIrohFrame=="function"){let i=new TextEncoder().encode(JSON.stringify(n)),o=new Uint8Array(1+i.byteLength);o[0]=0,o.set(i,1);let s=new ArrayBuffer(4+o.byteLength),a=new DataView(s),c=new Uint8Array(s);a.setUint32(0,o.byteLength,!1),c.set(o,4),await this.sendRawIrohFrame(c),d$1("[Connection] Sent internal signal over native-main iroh frame",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});return}await this.sendTypedOnTransport("iroh",0,n,{requireApplicationCrypto:!1}),d$1("[Connection] Sent internal signal over iroh (typed-frame fallback)",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});}catch(i){throw console.warn("[Connection] Failed to send internal signal over iroh",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null,error:i}),i}}receiveInternalSignal(e){this._isClosed||!e||typeof e!="object"||this.handleInternalSignal({type:"#pluto-signal",content:e});}handleInternalSignal(e){if(!(e.content&&(e.content.transport==="webrtc"||!e.content.transport)))return;let n=e.content,i=typeof n?.type=="string"?n.type:null,o=n?.sdp&&typeof n.sdp=="object"&&typeof n.sdp.type=="string"?n.sdp.type:null,s=i==="sdp"&&o==="offer",a=this.normalizeNegotiationId(n?.negotiationId);if((i==="sdp"||i==="candidate"||i==="renegotiate")&&c$1("[Connection][WebRTC][signal][recv]",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:a??null,signalType:i,sdpType:o,hasSdp:!!n?.sdp?.sdp,hasCandidate:!!n?.candidate,upgradeState:this.upgradeState}),i==="renegotiate"){let y=this.lastWebRtcHeartbeatOkAt===null?null:Date.now()-this.lastWebRtcHeartbeatOkAt,v=this.lastWebRtcDataChannelOpenAt===null?null:Date.now()-this.lastWebRtcDataChannelOpenAt,P=y!==null&&y<=k.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS||this.isWebRtcDataChannelOpen()&&v!==null&&v<=k.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS;if(this.isWebRtcDataChannelOpen()||this.upgradeState==="upgraded"){let C=!!a&&a!==this.activeNegotiationId&&a.startsWith("conn-")&&!a.startsWith(`conn-${this.id}-`)&&this.getDeterministicWebRtcRole()==="responder";if(P&&!C){c$1("[Connection] Ignoring WebRTC renegotiate request; route is provably live",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,heartbeatSilenceMs:y,dataChannelOpenForMs:v});return}c$1("[Connection] Honoring WebRTC renegotiate by tearing down the current route",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,priorState:this.upgradeState,heartbeatSilenceMs:y,dataChannelOpenForMs:v,reason:C?"fresh-remote-generation":"stale-route"}),this.clearUpgradeRetryTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,this.pendingSignals=[],this.stopWebRtcHeartbeat(),this.teardownWebRTCTransport(C?"inbound-renegotiate-fresh-generation":"inbound-renegotiate-stale-route"),this.setUpgradeState("none");}else if(this.upgradeState==="upgrading"&&this.webrtcTransport)if(!!a&&a!==this.activeNegotiationId&&a.startsWith("native-"))c$1("[Connection] Honoring fresh native WebRTC renegotiate during in-flight upgrade",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId}),this.clearUpgradeRetryTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,this.pendingSignals=[],this.stopWebRtcHeartbeat(),this.teardownWebRTCTransport("inbound-native-renegotiate-while-upgrading"),this.setUpgradeState("none"),this.preferredWebRtcRole=this.getDeterministicWebRtcRole();else {c$1("[Connection] Ignoring WebRTC renegotiate request while an upgrade is already in flight",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}}let c=!!a&&!!this.activeNegotiationId&&a!==this.activeNegotiationId;if(c&&(i==="sdp"||i==="candidate")&&(this.isWebRtcDataChannelOpen()||this.upgradeState==="upgraded")){c$1("[Connection] Ignoring delayed WebRTC signal for a non-active generation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:i,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let l=i==="sdp"&&s||i==="renegotiate"&&this.upgradeState!=="upgrading"&&this.upgradeState!=="upgraded";if(c&&!l){c$1("[Connection] Ignoring stale WebRTC signal from a previous negotiation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:i,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let d=!!this.activeNegotiationId?.startsWith("native-"),p=!!a?.startsWith("native-"),u=s&&!!a?.startsWith(`conn-${this.id}-`);if(c&&l&&this.upgradeState==="upgrading"&&this.preferredWebRtcRole==="responder"&&d&&u){c$1("[Connection] Ignoring reflected WebRTC offer during active native negotiation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let f=s&&!!a?.startsWith(`conn-${this.id}-`);if(c&&l&&f&&!d&&this.getDeterministicWebRtcRole()==="initiator"&&(this.upgradeState==="upgrading"||this.upgradeAttemptActive)){c$1("[Connection] Ignoring competing inbound WebRTC offer as glare-impolite initiator",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let h=f&&!p;if(c&&l&&h&&this.negotiationSwitchCount>=k.MAX_NEGOTIATION_SWITCHES){console.warn("[Connection] Ignoring competing inbound WebRTC offer: negotiation switch budget exhausted",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,switchBudget:k.MAX_NEGOTIATION_SWITCHES});return}c&&l&&(h&&(this.negotiationSwitchCount+=1),c$1("[Connection] Switching to a fresh inbound WebRTC negotiation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,priorNegotiationId:this.activeNegotiationId,nextNegotiationId:a,priorState:this.upgradeState,signalType:i,switchCount:this.negotiationSwitchCount,budgetedNegotiationSwitch:h}),this.clearUpgradeRetryTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,this.pendingSignals=[],this.stopWebRtcHeartbeat(),this.teardownWebRTCTransport("inbound-negotiation-switch")),a&&(!this.activeNegotiationId||c)&&(this.activeNegotiationId=a);let m=!this.webrtcTransport||this.upgradeState==="failed"||c&&this.upgradeState!=="upgrading";if(l&&m&&this.options.rtcConfig&&!this._isClosed){c$1("[Connection] Auto-requesting WebRTC upgrade from incoming signal",{connectionId:this.id,remoteNodeId:this.remoteNodeId,currentState:this.upgradeState,signalType:i,sdpType:o,signalNegotiationId:a,preferredRole:s?"responder":this.preferredWebRtcRole}),s?this.preferredWebRtcRole="responder":i==="renegotiate"&&a?.startsWith("native-")&&(this.preferredWebRtcRole=this.getDeterministicWebRtcRole()),this.upgradeRequested=true,this.upgradeTerminalFailure=false,this.pendingSignals=[n],this.attemptUpgrade(a);return}n.transport||(n.transport="webrtc"),this.webrtcTransport?.handleSignalingMessage?this.webrtcTransport.handleSignalingMessage(n):(!a||!this.activeNegotiationId||a===this.activeNegotiationId)&&this.pendingSignals.push(n);}createNegotiationId(){return `conn-${this.id}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}getDeterministicWebRtcRole(){return this.localNodeId>this.remoteNodeId?"initiator":"responder"}normalizeNegotiationId(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}};k.textDecoder=new TextDecoder("utf-8",{fatal:true}),k.textEncoder=new TextEncoder,k.UPGRADE_RETRY_DELAY_MS=1e3,k.MAX_UPGRADE_RETRIES=5,k.UPGRADE_REDRIVE_DELAYS_MS=[5e3,1e4,15e3],k.WEBRTC_DISCONNECTED_GRACE_MS=4e3,k.MAX_PENDING_MESSAGES=256,k.DEFAULT_APPLICATION_CRYPTO_WAIT_MS=1e4,k.WEBRTC_UPGRADE_ATTEMPT_TIMEOUT_MS=Gn+3e3,k.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS=256,k.WEBRTC_APPLICATION_ROUTE_PROOF_TIMEOUT_MS=6500,k.WEBRTC_APPLICATION_ROUTE_PROOF_DELAYS_MS=[0,250,750,1500,3e3],k.WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH=256,k.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS=12e3,k.MAX_NEGOTIATION_SWITCHES=6,k.FOREGROUND_PROBE_TIMEOUT_MS=2e3;var ee=k;async function ie(r,e,t){await B$1(r,e)&&c$1("[Client][CONNECT] Closed unused bi stream after adopting existing connection",{remoteNodeId:t??null,reason:e});}async function Wo(r){try{await r.refreshApplicationRouteHandshake(r.connection,r.reason,{forceReciprocal:!0});return}catch(e){let t=r.wasmClient.remote_session_admission_ready_for_ticket;if(!r.hasCompoundTicketToken||typeof t!="function")throw e;let n;try{n=await t.call(r.wasmClient,r.ticket),r.assertActive();}catch{throw e}if(n)throw e;c$1("[Client][AUTH] repairing admission after physical replacement",{nodeId:r.nodeId,connectionId:r.connection.id,reason:r.reason}),await r.representTicket(`${r.reason}:current-generation-admission-repair`),r.assertActive(),await r.refreshApplicationRouteHandshake(r.connection,`${r.reason}:after-current-generation-admission-repair`,{forceReciprocal:true});}}function be(){return new Error("Transport-only ticket-only channels do not expose a main message stream.")}var ei=class extends ee{constructor(t){let n=new WritableStream({write(){throw be()}}).getWriter(),i=new ReadableStream().getReader();super(t.connectionId,t.localNodeId,t.remoteNodeId,n,i,{...t.options,controlFrameMode:"native-main",hasBaseApplicationStream:false});this.input=t;this.transportDisconnectStarted=false;}async send(){throw be()}async sendMedia(){throw be()}async sendControl(){throw be()}async sendOnTransport(t,n){throw be()}async sendRawIrohFrame(){throw be()}async disconnect(){await super.disconnect(),!this.transportDisconnectStarted&&(this.transportDisconnectStarted=true,await this.disconnectNodeTransportBestEffort());}async disconnectForMainStreamReplacement(){await super.disconnect();}async disconnectNodeTransportBestEffort(){try{await this.input.disconnectNodeTransport(this.remoteNodeId);}catch{}}};function Oo(r){return new ei(r)}var Ct=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}async connect(e,t=2e4,n,i,o){if(this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive(),!e||!e.trim())throw new Error("connect requires a non-empty endpoint ticket");let s=e.trim(),{irohTicket:a,tokenSuffix:c}=Y(s),l=this.deps.getWasmClient(),d;try{d=await l.endpoint_id_from_ticket(a);}catch(w){throw new Error(`connect requires a valid endpoint ticket: ${w?.message||w}`)}this.assertActive();let p=null;if(c){let w=ne(a,c);typeof w?.t=="string"&&(p=w.t,this.deps.rememberRouteRepairTokenForNode(d,w.t,c));}let u=this.deps.getDeterministicConnectionId(d),f=this.deps.getRegisteredChannel(i??null),h=this.deps.isTransportOnlyChannel(i);c$1("[Client][CONNECT] resolved ticket target",{nodeId:d,connectionId:u,channelId:i??null,registeredChannel:f?{id:f.id,readiness:f.readiness,promotionPolicy:f.promotionPolicy,signalingPolicy:f.signalingPolicy}:null,transportOnlyChannel:h,hasCompoundTicketToken:!!p});let m=this.ctx.registry.get(u);if(m&&!p){let w=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,o?.approvedScope??null,p,m);return w&&this.deps.initializeConnectionTrust(m,w),await this.deps.refreshApplicationRouteHandshake(m,"connect-existing"),this.assertActive(),m}let y=c?ne(a,c):null,v=o?.approvedScope??null;!v&&typeof y?.s=="string"&&y.s.trim()&&(v=y.s.trim());let P=async w=>{d$1(`Initiating managed transport dial to ${d} (${w})...`);let D=await this.deps.ensureWasmManagedTransport(s,n??null,{skipIfConnected:o?.admissionAlreadyPresented===true,admissionAlreadyPresented:o?.admissionAlreadyPresented===true,timeoutMs:t});if(this.assertActive(),D.approvedScope)v=D.approvedScope,this.deps.setSessionTokenApprovedScope(u,D.approvedScope);else if(p&&!v){await this.schedulePeerReconciliationBestEffort("managed-dial-scope-lookup"),this.assertActive();let E=this.deps.getSessionTokenApprovedScope(u);if(typeof E=="string"&&E.trim())v=E.trim();else {let z=this.deps.getPeerState(n??d)?.scopes?.[0];typeof z=="string"&&z.trim()&&(v=z.trim());}}},I=async(w,D)=>Wo({connection:w,reason:D,nodeId:d,ticket:s,hasCompoundTicketToken:!!p,wasmClient:l,assertActive:()=>this.assertActive(),refreshApplicationRouteHandshake:(E,O,z)=>this.deps.refreshApplicationRouteHandshake(E,O,z),representTicket:P});try{await P("initial");}catch(w){if(this.deps.isLocalIrohRuntimeNotInitializedError(w)){let D=await this.deps.recoverLocalIrohRuntime("connect-managed-dial");if(this.assertActive(),!D)throw new Error(`Failed to initiate managed transport dial to ${d}: ${w?.message||w}`);try{await P("after-local-runtime-recovery");}catch(E){throw new Error(`Failed to initiate managed transport dial to ${d} after local Iroh runtime recovery: ${E?.message||E}`)}}else throw w}if(this.assertActive(),p){let w=v??o?.approvedScope??null,D=this.ctx.registry.get(u);if(D&&!D.isClosed){let E=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,w,p,D);this.deps.assignConnectionChannel(D,i),this.deps.initializeConnectionTrust(D,E),E&&this.deps.bindConnectionDeviceIdInRust(D,E),this.deps.approveSessionTokenNode(d),this.deps.approveSessionTokenConnection(D.id),this.deps.applySessionTokenTrustApproval(D,w,"dialer-compound-ticket-existing-connection"),this.deps.announceConnectionWhenStable(D),c$1("[Client][AUTH] adopted token-approved existing connection",{nodeId:d,connectionId:D.id,localNodeId:D.localNodeId,remoteNodeId:D.remoteNodeId,approvalScope:v||null});let O=D.disconnectForMainStreamReplacement;if(!h&&typeof O=="function")this.deps.cleanupReplacedConnection(D.id),await O.call(D),this.assertActive();else return await I(D,"dialer-compound-ticket-existing-connection"),this.assertActive(),D}}if(h){let w;w=Oo({connectionId:u,localNodeId:this.ctx.localNodeId,remoteNodeId:d,options:{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(d),applicationCrypto:this.deps.getOptions()?.applicationCrypto,requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),onTransportStatusChange:O=>this.deps.handleConnectionTransportStatus(w,O.activeTransport,O.parallelTransport),onApplicationRouteReady:O=>{this.deps.handleConnectionApplicationRouteReady(w,O);},onApplicationRouteMissing:O=>{this.deps.handleConnectionApplicationRouteMissing(u,O);}},disconnectNodeTransport:O=>this.deps.disconnectNodeTransport(O)});let D=v??o?.approvedScope??null,E=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,D,p,w);return this.deps.assignConnectionChannel(w,i),this.deps.initializeConnectionTrust(w,E),this.deps.registerConnection(w),E&&this.deps.bindConnectionDeviceIdInRust(w,E),p&&(this.deps.approveSessionTokenNode(d),this.deps.approveSessionTokenConnection(w.id),this.deps.applySessionTokenTrustApproval(w,D,"dialer-compound-ticket-transport-only")),this.deps.announceConnectionWhenStable(w),c$1("[Client][AUTH] using transport-only channel connection",{nodeId:d,connectionId:w.id,channelId:i??null,signalingMode:this.deps.getOptions().signalingMode??"hosted",hasCompoundTicketToken:!!p}),w}let T=await this.openMainBiStream(d,t);this.disposed&&(await ie(T,"dial-coordinator-disposed-after-open",d),this.assertActive());let C=this.ctx.registry.get(u);if(C&&!C.isClosed){let w=v??o?.approvedScope??null,D=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,w,p,C);return await ie(T,"late-dial-adopted-existing-connection",d),this.deps.assignConnectionChannel(C,i),this.deps.initializeConnectionTrust(C,D),D&&this.deps.bindConnectionDeviceIdInRust(C,D),p&&(this.deps.approveSessionTokenNode(d),this.deps.approveSessionTokenConnection(C.id),this.deps.applySessionTokenTrustApproval(C,w,"dialer-compound-ticket-late-existing-connection")),this.deps.announceConnectionWhenStable(C),c$1("[Client][CONNECT] adopted existing connection after async dial completed",{nodeId:d,connectionId:C.id,channelId:i??null,approvalScope:v||null,upgradeState:typeof C.getUpgradeState=="function"?C.getUpgradeState():null}),await I(C,"late-dial-adopted-existing-connection"),this.assertActive(),C}let N=this.deps.shouldUseNativeMainFramingForPeer(d,this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,v??o?.approvedScope??null,p,null),!!p);N&&(await E(this.deps.writeNativeMainLabelHeaderOnBiStream(T,d),4e3,"writeNativeMainLabelHeaderOnBiStream"),this.disposed&&(await ie(T,"dial-coordinator-disposed-after-native-label",d),this.assertActive()));let b=this.createConnection({connId:u,nodeId:d,biStream:T,useNativeMainFraming:N});this.deps.assignConnectionChannel(b,i);let L=v??o?.approvedScope??null,_=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,L,p,b);if(this.deps.initializeConnectionTrust(b,_),this.disposed&&(await this.disconnectConnectionBestEffort(b),this.assertActive()),this.deps.registerConnection(b),_&&this.deps.bindConnectionDeviceIdInRust(b,_),p){await this.schedulePeerReconciliationBestEffort("compound-ticket-connect"),this.assertActive();let w=this.deps.getPeerState(b.id)??this.deps.getPeerState(d),D=this.deps.consumePendingSessionTokenTrustApproval(b.id);D.approved?this.deps.applySessionTokenTrustApproval(b,D.scope??L,"dialer-compound-ticket-pending"):w?.admissionState==="admitted"&&this.deps.applySessionTokenTrustApproval(b,L,"dialer-compound-ticket-rust-admitted"),c$1("[Client][AUTH] token-approved connection registered locally",{nodeId:d,connectionId:b.id,localNodeId:b.localNodeId,remoteNodeId:b.remoteNodeId,rustAdmissionState:w?.admissionState??null,pendingApproval:D.approved});}return this.deps.announceConnectionWhenStable(b),c$1("[Client][HANDSHAKE] sending hello (dial path)",{connectionId:b.id,remoteNodeId:b.remoteNodeId}),this.sendDialHelloInBackground(b),b}async connectPeer(e){this.assertActive();let t=e.scope??"persistent";if(!e.ticket)throw new Error("connectPeer requires a ticket.");c$1("[Client][connectPeer] starting",{scope:t,channelId:e.channelId??null,hasDeviceId:!!e.deviceId,ticketLength:e.ticket.length});let n=Y(e.ticket).tokenSuffix!==null;if(!n&&!this.deps.sessionTokenScopeAllowsDeviceBinding(t))throw new Error(`connectPeer requires a compound ticket with a session token for restricted scope '${t}'.`);if(e.respectManualDisconnect&&this.hasManualDisconnectProjection(e.deviceId))throw new Error(`connectPeer suppressed by manual disconnect for device ${e.deviceId}`);e.deviceId&&!n&&!e.respectManualDisconnect&&this.deps.clearManualDisconnectProjection(e.deviceId);let i=await this.connect(e.ticket,Math.max(1,e.timeoutMs??2e4),e.deviceId,e.channelId);this.assertActive();let o=this.deps.getSessionTokenApprovedScope(i.id),s=[...o?[o]:[],...this.deps.getPeerScopes(i.id)].filter((u,f,h)=>h.indexOf(u)===f),a=s.length>0?s:[t],l=s.length===0||a.some(u=>this.deps.sessionTokenScopeAllowsDeviceBinding(u))?e.deviceId:void 0,d=this.deps.resolvePromotionEligibility({connectionId:i.id,nodeId:i.remoteNodeId,deviceId:l??void 0}),p=l||i.remoteNodeId||i.deviceId||i.id;l&&n&&this.deps.clearManualDisconnectProjection(l),this.deps.hasRustPeerLifecycleProjection()?this.schedulePeerReconciliationInBackground("connect-peer"):this.deps.dispatchLiveConnectionProjection(i,{trustProjection:null,promotionEligible:d,peerId:p,deviceId:l,ticket:e.ticket,scopes:a,applicationRouteReady:this.deps.hasApplicationRouteForConnection(i),webRtcApplicationRouteReady:this.deps.isWebRtcApplicationRouteReadyForConnection(i)});for(let u of a)this.deps.addPeerScope(p,u);return i}hasManualDisconnectProjection(e){let t=typeof e=="string"?e.trim():"";if(!t)return false;let n=this.deps.getWasmClient();if(n&&typeof n.is_auto_connect_excluded=="function"&&n.is_auto_connect_excluded(t)===true)return true;let i=this.deps.getPeerState(t);if(!i)return false;if(i.manualDisconnect===true)return true;let o=i,s=[i.error,o.lastDisconnectReason].filter(a=>typeof a=="string"&&a.length>0).join(" ");return /manual disconnect/i.test(s)}async openMainBiStream(e,t){this.assertActive();let n=null,i=0,o=500,s=Math.ceil(t/o),a=this.deps.getWasmClient(),c=a.open_native_main_control_bi;if(typeof c!="function")throw new Error("[Client][NATIVE-MAIN] open_native_main_control_bi is unavailable on this WASM build; the admission and key-agreement control plane cannot use a protected application stream. Rebuild the OpenRTC WASM runtime.");for(;i<s;){this.assertActive();try{n=await E(c.call(a,e),2500,"wasmClient.open_native_main_control_bi"),this.disposed&&(await ie(n,"dial-coordinator-disposed-during-open",e),this.assertActive());break}catch(l){if(this.disposed)throw l;i++,await u(o);}}if(!n)throw new Error(`Failed to establish connection to ${e} after ${t} ms`);return n}assertActive(){if(this.disposed)throw new Error("Connection dial cancelled because the client was disposed.")}createConnection(e){let{connId:t,nodeId:n,biStream:i,useNativeMainFraming:o}=e,s;if(s=new ee(t,this.deps.getLocalNodeId(),n,i.send.getWriter(),i.recv.getReader(),{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(n),applicationCrypto:this.deps.getOptions()?.applicationCrypto,requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),controlFrameMode:o?"native-main":"typed",onTransportStatusChange:a=>this.deps.handleConnectionTransportStatus(s,a.activeTransport,a.parallelTransport),onApplicationRouteReady:a=>{this.deps.handleConnectionApplicationRouteReady(s,a);},onApplicationRouteMissing:a=>{this.deps.handleConnectionApplicationRouteMissing(t,a);}}),o&&this.deps.getWasmClient()){let a=this.deps.getWasmClient();s.setNativeSignalSender(async c=>{await this.deps.sendNativeSignalEnvelope(s,n,c,a);}),c$1("[Client][NATIVE-MAIN] Attached native signal sender to dial-path connection",{connectionId:s.id,remoteNodeId:n});}return s}sendDialHelloInBackground(e){let t=n=>{this.disposed||console.warn("[Client][TRUST] Failed to send outgoing handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:n});};try{Promise.resolve(this.deps.sendTransportHandshake(e,"hello")).then(()=>{this.disposed||this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,"protected-hello:dial");}).catch(t);}catch(n){t(n);}}schedulePeerReconciliationBestEffort(e){try{return Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>[])}catch{return Promise.resolve([])}}schedulePeerReconciliationInBackground(e){if(!this.disposed)try{this.schedulePeerReconciliationBestEffort(e);}catch{}}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}};var St=class{constructor(e){this.deps=e;this.connectionListeners=[];this.disconnectionListeners=[];this.announcedConnections=new Set;this.stabilityWaitEpochs=new Map;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.connectionListeners=[],this.disconnectionListeners=[],this.announcedConnections.clear(),this.stabilityWaitEpochs.clear());}findLiveConnectionForRemoteNode(e,t){let n=this.deps.registry.get(t);if(n&&!n.isClosed)return n;for(let i of this.deps.registry.values())if(i.remoteNodeId===e&&!i.isClosed)return i;return null}cleanupReplacedConnection(e){this.disposed||(this.deps.registry.delete(e),this.forgetAnnouncedConnection(e));}healOrphanTsConnection(e){if(this.disposed)return;let t=this.deps.registry.get(e);!t||t.isClosed||c$1("[Client][PEER-RECONCILE] observed orphan TS connection",{connectionId:e});}registerConnection(e){if(this.disposed)return;let t=this.deps.registry;t.clearLocalTerminalClose(e.id);let n=t.get(e.id);if(t.set(e.id,e),n&&n!==e&&!n.isClosed&&this.disconnectBestEffort(n),typeof e.setApplicationCrypto=="function"){let s=this.deps.resolveApplicationCryptoForPeer(e.remoteNodeId,e);s&&e.setApplicationCrypto(s);}this.flushPendingNativeMainHandshakesBestEffort(e.remoteNodeId,"connection-registered"),this.flushPendingNativeMainSignalsBestEffort(e.remoteNodeId,"connection-registered");let i=this.deps.getConnectionTrustState(e.id),o=i?.verifiedDeviceId??i?.expectedDeviceId??this.deps.getKnownDeviceIdByNodeId(e.remoteNodeId)??null;o?this.deps.bindConnectionDeviceIdInRust(e,o):this.lookupConnectionDeviceBindingInBackground(e),i?.verified&&o&&this.deps.retireSupersededConnections(e,o,"registered-trusted-replacement"),typeof e.onUpgradeStateChange=="function"&&e.onUpgradeStateChange(()=>{this.disposed||!t.has(e.id)||e.isClosed||this.deps.hasRustPeerLifecycleProjection()||this.deps.applyConnectionTrustProjection(e);}),this.deps.hasRustPeerLifecycleProjection()?this.schedulePeerReconciliationBestEffort("register-connection"):this.deps.applyConnectionTrustProjection(e),typeof e.reportTransportStatusIfChanged=="function"&&e.reportTransportStatusIfChanged(),typeof e.onWebRTCBinaryMessage=="function"&&e.onWebRTCBinaryMessage(s=>this.disposed?false:this.deps.maybeHandleWebRTCExplicitFileEnvelope(e,s)),e.onMessage(s=>{if(!this.disposed)try{Promise.resolve(this.deps.handleMessage(e,s)).catch(a=>{this.disposed||console.warn("[Client] connection message handler failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:a});});}catch(a){this.disposed||console.warn("[Client] connection message handler failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:a});}}),e.onDisconnect(()=>{if(this.disposed||(e.peerMoQReady=false,t.get(e.id)!==e))return;let s=this.deps.hasRustPeerLifecycleProjection();s||t.markLocalTerminalClose(e.id);let a=this.deps.getExistingPeerProjectionForDisconnect(e);t.delete(e.id),this.deps.cleanupConnectionState(e.id,s?"physical-route":"logical-terminal"),s?this.schedulePeerReconciliationBestEffort("connection-disconnect"):this.deps.dispatchLiveConnectionProjection(e,{trustProjection:null,promotionEligible:this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId}),existingProjection:a,terminalTransportClose:true,applicationRouteReady:false,webRtcApplicationRouteReady:false}),this.announcedConnections.delete(e.id)&&this.emitDisconnection(e);});}announceConnectionWhenStable(e){let t=(this.stabilityWaitEpochs.get(e.id)??0)+1;this.stabilityWaitEpochs.set(e.id,t),(async()=>{if(this.disposed)return;let n=await this.waitForStableConnection(e);if(!this.disposed&&this.deps.registry.get(e.id)===e&&this.stabilityWaitEpochs.get(e.id)===t){if(!n){if(!e.isClosed){let i=this.deps.getConnectionTrustState(e.id);console.warn(`[Client] Suppressing unstable connection ${e.id}`,{deviceId:e.deviceId,upgradeState:e.getUpgradeState?.()??null,transportStatus:typeof e.getTransportStatus=="function"?e.getTransportStatus():null,trustRequired:i?.required??null,trustVerified:i?.verified??null,trustFailed:i?.failed??null,trustFailureReason:i?.failureReason??null});}return}this.announcedConnections.has(e.id)||(this.announcedConnections.add(e.id),this.emitConnection(e));}})();}async waitForStableConnection(e){if(this.disposed)return false;let t=this.deps.initializeConnectionTrust(e),n=false,i=false,o=this.deps.hasApplicationRouteForConnection(e),s=this.deps.allowsTransportOnlyStability(e),a=null,c=this.deps.getWasmClient(),l=c&&typeof c.wait_for_settled_peer=="function"?c.wait_for_settled_peer:null;if(l)try{let u=await l.call(c,e.deviceId,this.deps.stableTimeoutMs),f=e.getUpgradeState;if(a=typeof f=="function"?f.call(e):null,o=this.deps.hasApplicationRouteForConnection(e),u?.settledReady&&(!t.required||t.verified)&&(o||s))return !0;if(t.required&&t.failed)return console.warn("[Client][STABILITY] trust failed during settled-peer gate",{connectionId:e.id,deviceId:e.deviceId,settledReady:u?.settledReady??null,trustRequired:t.required,trustVerified:t.verified,trustFailed:t.failed,trustFailureReason:t.failureReason??null,upgradeState:a}),!1}catch{}let d=Date.now(),p=null;for(;Date.now()-d<this.deps.stableTimeoutMs;){if(this.disposed||e.isClosed||t.required&&t.failed)return false;let u$1=await this.deps.isCoreConnectionHealthy(e.deviceId);if(this.disposed)return false;let f=e.getUpgradeState;a=typeof f=="function"?f.call(e):null;let h=a==="upgraded";if(n=u$1,i=h,o=this.deps.hasApplicationRouteForConnection(e),u$1||h){if(p===null&&(p=Date.now()),Date.now()-p>=this.deps.stableWindowMs&&(!t.required||t.verified)&&(o||s))return true}else p=null;await u(this.deps.stablePollMs);}return console.warn("[Client][STABILITY] connection did not become stable before timeout",{connectionId:e.id,deviceId:e.deviceId,trustRequired:t.required,trustVerified:t.verified,trustFailed:t.failed,trustFailureReason:t.failureReason??null,lastCoreHealthy:n,lastUpgradedTransportHealthy:i,lastApplicationRouteReady:o,lastUpgradeState:a,transportStatus:typeof e.getTransportStatus=="function"?e.getTransportStatus():null}),false}onConnection(e){return this.disposed?()=>{}:(this.connectionListeners.push(e),()=>{this.connectionListeners=this.connectionListeners.filter(t=>t!==e);})}onDisconnection(e){return this.disposed?()=>{}:(this.disconnectionListeners.push(e),()=>{this.disconnectionListeners=this.disconnectionListeners.filter(t=>t!==e);})}isConnectionAnnounced(e){return this.announcedConnections.has(e)}forgetAnnouncedConnection(e){this.announcedConnections.delete(e);}emitConnection(e){for(let t of [...this.connectionListeners])try{t(e);}catch(n){console.warn("[Client] connection listener failed",n);}}emitDisconnection(e){for(let t of [...this.disconnectionListeners])try{t(e);}catch(n){console.warn("[Client] disconnection listener failed",n);}}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}flushPendingNativeMainHandshakesBestEffort(e,t){if(!this.disposed)try{Promise.resolve(this.deps.flushPendingNativeMainHandshakesForNode(e,t)).catch(()=>{});}catch{}}flushPendingNativeMainSignalsBestEffort(e,t){if(!this.disposed)try{Promise.resolve(this.deps.flushPendingNativeMainSignalsForNode(e,t)).catch(()=>{});}catch{}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}lookupConnectionDeviceBindingInBackground(e){try{Promise.resolve(this.deps.searchDevices()).then(()=>{if(this.disposed)return;let t=this.deps.getKnownDeviceIdByNodeId(e.remoteNodeId);t&&this.deps.bindConnectionDeviceIdInRust(e,t);}).catch(()=>{});}catch{}}};var It=class{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}async handleMessage(e,t){if(this.disposed)return;if(!!t&&typeof t=="object"&&t.type==="handshake"){if(!await this.handleHandshake(e,t)||this.disposed)return}else if((this.deps.requiresManagedTransportTrust()||this.deps.usesTicketOnlySignalingMode())&&!this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)){console.warn("[Client][SESSION-TOKEN] Dropping application message before admission",{connectionId:e.id,remoteNodeId:e.remoteNodeId}),this.disconnectBestEffort(e);return}this.deps.dispatchMessage(e,t);}async handleHandshake(e,t){if(this.disposed)return false;let n=t.action??"hello",i=await this.deps.handleApplicationKeyAgreement(e,t).catch(m=>this.disposed?{remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null}:(console.warn("[Client][KEY-AGREEMENT] Handshake key agreement failed; closing connection",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:m}),this.disconnectBestEffort(e),{remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null}));if(this.disposed)return false;let o=t.capabilities&&typeof t.capabilities=="object"?t.capabilities:void 0,s=!!o&&Object.prototype.hasOwnProperty.call(o,"webrtc"),a=!!o&&Object.prototype.hasOwnProperty.call(o,"moq"),c=typeof t.moq=="boolean",l=s&&o.webrtc===true,d=a?o.moq===true:!!t.moq,p=this.deps.isWebRTCTransportEnabled(),u=this.deps.requiresManagedTransportTrust(),f=m=>{if(this.disposed||e.isClosed||!l||!p)return;let y=this.deps.getLocalNodeId();this.deps.usesTicketOnlySignalingMode()&&y&&e.remoteNodeId&&y.localeCompare(e.remoteNodeId)<0||(c$1("[Client][HANDSHAKE] requesting WebRTC upgrade from handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:n,reason:m}),e.requestWebRTCUpgrade(m));};if(n==="hello"){let m=await this.deps.validateIncomingSessionTokenWithRetry(t.sessionToken??"",e.id,{remoteNodeId:e.remoteNodeId,source:"handshake-hello",tokenPayload:typeof t.sessionTokenPayload=="string"?t.sessionTokenPayload:void 0});if(this.disposed)return false;if(!m.ok)return console.warn("[Client][SESSION-TOKEN] Rejecting connection \u2014 invalid session token",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:m.reason,hasToken:!!t.sessionToken}),this.disconnectBestEffort(e),false;t.sessionToken&&this.deps.applySessionTokenTrustApproval(e,m.scope??null,"handshake-hello");}c$1("[Client][HANDSHAKE] received",{action:n,connectionId:e.id,remoteNodeId:e.remoteNodeId,channelId:t.channelId??this.deps.getConnectionChannelId(e.id)??null,remoteSupportsWebRTC:l,remoteSupportsMoQ:d,localWebRTCEnabled:p,hasSessionToken:!!t.sessionToken,hasTransportTrust:!!t.transportTrust});let h=t.capabilities?.applicationKeyAgreement===true&&i.cryptoReady?i.replyAction:null;return h&&this.sendHandshakeWithRecoveryInBackground(e,h,null,"application-key-agreement-confirmation","[Client][KEY-AGREEMENT] Failed to advance reciprocal key agreement",i.replyClaimId?()=>this.deps.releaseApplicationKeyAgreementReply(e.id,h,i.replyClaimId):void 0),s&&(e.remoteSupportsWebRTC=l),!u&&p&&l&&(n==="hello"||n==="capability-update"||n==="response"&&!t.transportTrust)&&f(`handshake:${n}`),(a||c)&&(d&&this.deps.getMoQState()==="ready"?(d$1(`[Client] Peer ${e.deviceId.substring(0,6)} supports MoQ. Upgrading...`),this.deps.enableMoQForConnection(e)):d||(e.peerMoQReady=false,this.deps.forgetMoQPeerSubscription(e.id))),this.deps.assignConnectionChannel(e,t.channelId??null),t.transportTrust||u?this.handleTransportTrustHandshakeInBackground(e,t,n,u,f):(t.action==="hello"||!t.action)&&t.sessionToken&&h!=="response"&&this.sendHandshakeWithRecoveryInBackground(e,"response",null,"session-token-response","[Client][SESSION-TOKEN] Failed to send response handshake"),true}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}sendHandshakeInBackground(e,t,n){let i=o=>{this.disposed||console.warn(n,{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:o});};try{Promise.resolve(this.deps.sendTransportHandshake(e,t)).catch(i);}catch(o){i(o);}}sendHandshakeWithRecoveryInBackground(e,t,n,i,o,s){let a=c=>{s?.(),!this.disposed&&console.warn(o,{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:c});};try{Promise.resolve(this.deps.sendTransportHandshakeWithRecovery(e,t,n,i)).catch(a);}catch(c){a(c);}}handleTransportTrustHandshakeInBackground(e,t,n,i,o){let s=a=>{this.disposed||console.warn("[Client][TRUST] Handshake processing failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:a});};try{Promise.resolve(this.handleTransportTrustHandshake(e,t,n,i,o)).catch(s);}catch(a){s(a);}}async handleTransportTrustHandshake(e,t,n,i,o){try{if(this.disposed)return;let s=n,a=t.transportTrust??null,c=this.deps.initializeConnectionTrust(e);if(a?.deviceId&&!c.expectedDeviceId&&this.deps.getKnownDevice(a.deviceId,e.remoteNodeId)&&(c.expectedDeviceId=a.deviceId),s==="hello"){let l=typeof a?.challenge=="string"?a.challenge:null;if(!l&&c.required)if(this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)){let d=this.deps.getSessionTokenApprovedScope(e.id);c.required=!1,c.verified=!0,c.failed=!1,c.failureReason=void 0,c.issuedChallenge=null,this.deps.applyConnectionTrustProjection(e);let p=typeof a?.deviceId=="string"&&a.deviceId.trim()?a.deviceId.trim():c.expectedDeviceId??this.deps.getKnownDeviceIdForNode(e.remoteNodeId)??null;p&&this.deps.sessionTokenScopeAllowsDeviceBinding(d)&&this.deps.bindConnectionDeviceIdInRust(e,p),c$1("[Client][TRUST] Skipping challenge enforcement for session-token-approved connection",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s});}else c.failureReason="missing-transport-trust-challenge",this.deps.applyConnectionTrustProjection(e),c$1("[Client][TRUST] Deferring missing hello challenge enforcement pending response/ack or session-token approval",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s});if(await this.deps.sendTransportHandshakeWithRecovery(e,"response",l,`trust-${s}-response`),this.disposed)return}else if(s==="response"||s==="ack"){let l=await this.deps.verifyRemoteTransportTrust(e,a);if(this.disposed)return;if(!l.verified){if(l.stale){c$1("[Client][TRUST] Ignoring stale transport proof and requesting current challenge",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s,reason:l.reason??"stale-transport-trust-response"}),await this.deps.sendTransportHandshakeWithRecovery(e,"hello",null,"stale-trust-response-rechallenge");return}if(this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)){this.deps.applySessionTokenTrustApproval(e,null,"handshake-proof-bypass-after-session-token");return}if(l.reason==="missing-transport-trust-payload"){c.failureReason=l.reason,this.deps.applyConnectionTrustProjection(e),c$1("[Client][TRUST] Deferring absent optional transport proof pending session-token admission",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s});return}c.required&&await this.deps.enforceConnectionTrustFailure(e,l.reason??"remote-transport-proof-invalid");return}if(this.deps.markConnectionTrustVerified(e,l.deviceId),s==="response"&&o(`handshake:${s}:trust-verified`),s==="response"&&typeof a?.challenge=="string"&&(await this.deps.sendTransportHandshakeWithRecovery(e,"ack",a.challenge,"trust-response-ack"),this.disposed))return}else s==="capability-update"&&(this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)||this.deps.getConnectionTrustState(e.id)?.verified)&&o("capability-update:trust-reused");}catch(s){console.warn("[Client][TRUST] Handshake processing failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:s});}}};var Rt=class Rt{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}async handleUnhandledIncomingStreamEvent(e){if(await this.closeIfDisposed(e,"incoming-acceptor-disposed"))return;let{type:t,stream:n,remoteNodeId:i,traceId:o}=e,s=e.protocolHint;if(t==="bi"&&s==="native-main"&&(s=this.deps.normalizeAuthoritativeIncomingProtocolHint("native-main",i,o)??"native-main",e={...e,protocolHint:s}),!e.invalid){if(t==="bi"&&e.channel?.channelId===Jn){await this.receiveDefaultPeerStream(e);return}if(t==="uni"){if(!this.deps.shouldSkipIncomingStreamProbe()&&await this.deps.tryHandleNativeMainUniStream(n,i,o))return;await this.deps.cancelUnhandledIncomingUniStream(n,i);return}if(t==="bi"&&s==="native-main"){c$1("[Client][INCOMING] Handling native desktop main stream",{remoteNodeId:i,traceId:o||null}),this.handleNativeMainStreamInBackground(n,i,e.transportStableId,o,"[Client][NATIVE-MAIN] Background handler crashed");return}if(this.deps.shouldTreatIncomingStreamAsTransportOnly(e)){this.deps.logIncomingDiagnostic("bi:drop-unhandled-ticket-flow",{remoteNodeId:i||"unknown",traceId:o||null,protocolHint:s,channelId:e.channel?.channelId??null});return}t==="bi"&&s!=="explicit"&&await this.acceptIncomingBiStream(e);}}async receiveDefaultPeerStream(e){let t=e.stream,n=e.remoteNodeId,i=this.deps.getDeterministicConnectionId(n),o=this.deps.getConnection(i);if(!o||o.isClosed||!y(t)){await ie(t,"peer-default-without-live-connection",n);return}let s=t.recv.getReader(),a=t.send.getWriter(),c=new Uint8Array(0);try{for(;;){let{done:l,value:d}=await s.read();if(l)break;if(!d||d.byteLength===0)continue;let p=new Uint8Array(c.byteLength+d.byteLength);for(p.set(c),p.set(d,c.byteLength),c=p;c.byteLength>=4;){let u=new DataView(c.buffer,c.byteOffset,c.byteLength).getUint32(0,!1);if(u===0||u>Rt.MAX_PEER_MESSAGE_FRAME_BYTES)throw new Error(`invalid peer-default frame length ${u}`);if(c.byteLength<4+u)break;o.receiveFrameBody(c.slice(4,4+u)),c=c.slice(4+u);}}if(c.byteLength!==0)throw new Error(`truncated peer-default frame (${c.byteLength} bytes)`)}catch(l){this.deps.logIncomingDiagnostic("peer-default:receive-failed",{connectionId:i,remoteNodeId:n,traceId:e.traceId??null,error:l});}finally{try{await a.close();}catch{}try{s.releaseLock();}catch{}try{a.releaseLock();}catch{}}}async acceptIncomingBiStream(e){if(await this.closeIfDisposed(e,"incoming-acceptor-disposed-before-accept"))return;let{stream:t,remoteNodeId:n,traceId:i}=e,o=e.protocolHint,s=this.deps.getDeterministicConnectionId(n),a=this.deps.getKnownDevice(null,n),c=typeof a?.platformType=="string"?String(a.platformType).toLowerCase():typeof a?.platform_type=="string"?String(a.platform_type).toLowerCase():null;if(!this.deps.usesTicketOnlySignalingMode()&&(c==="desktop"||c==="mobile")){c$1("[Client][INCOMING] Routing unhinted native peer stream through native-main handler",{connectionId:s,remoteNodeId:n,traceId:i||null,protocolHint:o,knownRemotePlatform:c}),this.handleNativeMainStreamInBackground(t,n,e.transportStableId,i,"[Client][NATIVE-MAIN] Unhinted native peer stream handler crashed");return}let l=this.deps.getConnection(s);if(l&&!l.isClosed){let m=l.getUpgradeState(),y=await this.deps.isCoreConnectionHealthy(n).catch(()=>false);if(await this.closeIfDisposed(e,"incoming-acceptor-disposed-after-core-health"))return;let v=typeof l.getControlFrameMode=="function"&&l.getControlFrameMode()==="native-main";if(y){if(!v){c$1("[Client][INCOMING] Closing auxiliary bi stream while typed connection is upgrading/upgraded",{connectionId:s,remoteNodeId:n,traceId:i||null,existingUpgradeState:m,protocolHint:o}),await ie(t,"typed-connection-auxiliary-stream",n);return}c$1("[Client][INCOMING] Routing auxiliary bi stream to native-main handler while connection is upgrading/upgraded",{connectionId:s,remoteNodeId:n,traceId:i||null,existingUpgradeState:m,protocolHint:o}),this.handleNativeMainStreamInBackground(t,n,e.transportStableId,i,"[Client][NATIVE-MAIN] Auxiliary stream handler crashed");return}if((m==="upgrading"||m==="upgraded")&&c$1("[Client][INCOMING] Replacing upgraded connection due to stale core transport",{connectionId:s,remoteNodeId:n,traceId:i||null,existingUpgradeState:m,coreTransportConnected:y}),c$1("[Client][INCOMING] Replacing existing connection main stream",{connectionId:s,remoteNodeId:n,traceId:i||null}),this.deps.cleanupReplacedConnection(s),await this.disconnectConnection(l),await this.closeIfDisposed(e,"incoming-acceptor-disposed-after-existing-disconnect"))return}let d=t;if(!y(d)){console.error("[Client][INCOMING] Unable to construct connection from invalid bi stream",{remoteNodeId:n});return}let p,u;try{p=d.send.getWriter(),u=d.recv.getReader();}catch(m){console.error("[Client][INCOMING] Failed to acquire incoming stream reader/writer",{remoteNodeId:n,error:m});return}let f;f=new ee(s,this.deps.getLocalNodeId(),n,p,u,{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(n),applicationCrypto:this.deps.getOptions()?.applicationCrypto,requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),controlFrameMode:"typed",onTransportStatusChange:m=>this.deps.handleConnectionTransportStatus(f,m.activeTransport,m.parallelTransport),onApplicationRouteReady:m=>{this.deps.handleConnectionApplicationRouteReady(f,m);},onApplicationRouteMissing:m=>{this.deps.handleConnectionApplicationRouteMissing(s,m);}});let h=this.deps.getKnownDeviceIdForNode(n);if(this.deps.initializeConnectionTrust(f,h),this.disposed){await this.disconnectConnection(f);return}this.deps.registerConnection(f),h?this.deps.bindConnectionDeviceIdInRust(f,h):this.lookupAcceptedDeviceBindingInBackground(f,n),this.deps.announceConnectionWhenStable(f),c$1("[Client][HANDSHAKE] sending hello (incoming connection path)",{connectionId:f.id,remoteNodeId:f.remoteNodeId}),this.sendIncomingHelloInBackground(f);}handleNativeMainStreamInBackground(e,t,n,i,o){let s=a=>{this.disposed||console.error(o,{remoteNodeId:t,traceId:i||null,error:a});};try{let a=Number.isSafeInteger(n)&&Number(n)>0?this.deps.handleNativeMainStream(e,t,n):this.deps.handleNativeMainStream(e,t);Promise.resolve(a).catch(s);}catch(a){s(a);}}lookupAcceptedDeviceBindingInBackground(e,t){let n=i=>{this.disposed||console.warn("[Client][BIND] Accept-side searchDevices fallback failed",{connectionId:e.id,remoteNodeId:t,error:i});};try{Promise.resolve(this.deps.searchDevices()).then(()=>{if(this.disposed)return;let i=this.deps.getKnownDeviceIdForNode(t);i?this.deps.bindConnectionDeviceIdInRust(e,i):console.warn("[Client][BIND] Accept-side directory lookup found no deviceId for remote node",{connectionId:e.id,remoteNodeId:t});}).catch(n);}catch(i){n(i);}}sendIncomingHelloInBackground(e){let t=n=>{this.disposed||console.warn("[Client][TRUST] Failed to send incoming handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:n});};try{Promise.resolve(this.deps.sendTransportHandshake(e,"hello")).then(()=>{this.disposed||this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,"protected-hello:incoming");}).catch(t);}catch(n){t(n);}}async disconnectConnection(e){try{await Promise.resolve(e.disconnect());}catch{}}async closeIfDisposed(e,t){return this.disposed?(e.type==="bi"?await ie(e.stream,t,e.remoteNodeId):e.type==="uni"&&await this.deps.cancelUnhandledIncomingUniStream(e.stream,e.remoteNodeId),true):false}};Rt.MAX_PEER_MESSAGE_FRAME_BYTES=4*1024*1024;var bt=Rt;function Ho(r){return r==="desktop"||r==="mobile"||r==="native"}function Uo(r,e,t=false){return true}function jo(r){return !r}function Pt(r,e,t){return r}var ti={ready:false,phase:"frame-start",expectedFrameLength:0,consumedBytes:0,payloadBytes:new Uint8Array};function Go(r,e){let t=new TextEncoder().encode(JSON.stringify(r)),n=new TextEncoder().encode(e.label),i=new Uint8Array(5+n.byteLength+4+t.byteLength),o=new DataView(i.buffer),s=0;return i[s]=e.protocolByte,s+=1,o.setUint32(s,n.byteLength,false),s+=4,i.set(n,s),s+=n.byteLength,o.setUint32(s,t.byteLength,false),s+=4,i.set(t,s),i}async function Ko(r,e,t,n,i=8e3){if(typeof window>"u"||typeof window.dispatchEvent!="function")return null;let o=[],s=c=>{o.push(Promise.resolve(c));};if(window.dispatchEvent(new CustomEvent(r,{detail:{remoteNodeId:e,remoteDeviceId:t,message:n,respondWith:s}})),o.length===0)return null;let a;try{let c=await Promise.race([Promise.allSettled(o),new Promise(l=>{a=setTimeout(()=>l([]),i);})]);for(let l of c)if(l.status==="fulfilled"&&l.value!==void 0&&l.value!==null)return l.value}finally{a&&clearTimeout(a);}return null}function qo(r,e){if(r.byteLength===0)return ti;if(r[0]===e.protocolByte){if(r.byteLength<5)return ti;let i=new DataView(r.buffer,r.byteOffset,r.byteLength),o=i.getUint32(1,false);if(o>0&&o<=e.maxLabelBytes&&r.byteLength>=5+o&&new TextDecoder().decode(r.slice(5,5+o))===e.label){let a=5+o+4;if(r.byteLength<a)return {ready:false,phase:"frame-body",expectedFrameLength:0,consumedBytes:0,payloadBytes:new Uint8Array};let c=i.getUint32(5+o,false);if(c>e.maxFrameBytes)throw new Error(`native-main frame too large: ${c}`);return r.byteLength<a+c?{ready:false,phase:"frame-body",expectedFrameLength:c,consumedBytes:0,payloadBytes:new Uint8Array}:{ready:true,phase:"frame-body",expectedFrameLength:c,consumedBytes:a+c,payloadBytes:r.slice(a,a+c)}}}if(r.byteLength<4)return ti;let n=new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,false);if(n>e.maxFrameBytes)throw new Error(`legacy native-main frame too large: ${n}`);return r.byteLength<4+n?{ready:false,phase:"frame-body",expectedFrameLength:n,consumedBytes:0,payloadBytes:new Uint8Array}:{ready:true,phase:"frame-body",expectedFrameLength:n,consumedBytes:4+n,payloadBytes:r.slice(4,4+n)}}function zo(r){let{host:e,transports:t,trustServices:n}=r;return new Ct(e.getContext(),{ensureWasmRuntimeForP2P:()=>e.ensureWasmRuntimeForP2P(),getOptions:()=>e.getOptions(),getWasmClient:()=>e.getWasmClient(),getLocalNodeId:()=>e.getLocalNodeId(),getDeterministicConnectionId:i=>t.peerIdentity.getDeterministicConnectionId(i),getRegisteredChannel:i=>e.getRegisteredChannel(i),isTransportOnlyChannel:i=>n.channelPolicy.isTransportOnlyChannel(i),rememberRouteRepairTokenForNode:(i,o,s)=>e.rememberRouteRepairTokenForNode(i,o,s),resolveExpectedDeviceIdForSessionTokenScope:(i,o,s,a)=>n.trust.resolveExpectedDeviceIdForSessionTokenScope(i,o,s,a),initializeConnectionTrust:(i,o)=>n.trust.initialize(i,o),refreshApplicationRouteHandshake:(i,o,s)=>t.upgrade.refreshApplicationRouteHandshake(i,o,s),ensureWasmManagedTransport:(i,o,s)=>e.ensureWasmManagedTransport(i,o,s),isLocalIrohRuntimeNotInitializedError:i=>e.isLocalIrohRuntimeNotInitializedError(i),recoverLocalIrohRuntime:i=>e.recoverLocalIrohRuntime(i),getSessionTokenApprovedScope:i=>e.getSessionTokenApprovedScope(i),setSessionTokenApprovedScope:(i,o)=>e.setSessionTokenApprovedScope(i,o),getPeerState:i=>e.getPeerState(i),assignConnectionChannel:(i,o)=>n.channelPolicy.assign(i,o),bindConnectionDeviceIdInRust:(i,o)=>n.deviceBinder.bindConnectionDeviceIdInRust(i,o),approveSessionTokenNode:i=>e.approveSessionTokenNode(i),approveSessionTokenConnection:i=>e.approveSessionTokenConnection(i),applySessionTokenTrustApproval:(i,o,s)=>e.applySessionTokenTrustApproval(i,o,s),announceConnectionWhenStable:i=>r.getLifecycle().announceConnectionWhenStable(i),disconnectNodeTransport:i=>t.health.disconnectNodeTransport(i),shouldUseNativeMainFramingForPeer:(i,o,s)=>Uo(i,o,s),writeNativeMainLabelHeaderOnBiStream:(i,o)=>e.writeNativeMainLabelHeaderOnBiStream(i,o),getRTCConfig:()=>t.getRTCConfig(),createTransportContext:i=>t.contexts.create(i),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(i,o,s)=>t.health.handleCurrentConnectionTransportStatus(i,o,s),handleConnectionApplicationRouteReady:(i,o)=>t.health.handleCurrentConnectionApplicationRouteReady(i,o),handleConnectionApplicationRouteMissing:(i,o)=>t.upgrade.handleApplicationRouteMissing(i,o),sendNativeSignalEnvelope:(i,o,s,a)=>e.sendNativeSignalEnvelope(i,o,s,a),registerConnection:i=>r.getLifecycle().registerConnection(i),cleanupReplacedConnection:i=>r.getLifecycle().cleanupReplacedConnection(i),schedulePeerReconciliation:i=>e.schedulePeerReconciliation(i),consumePendingSessionTokenTrustApproval:i=>e.consumePendingSessionTokenTrustApproval(i),sendTransportHandshake:(i,o)=>t.handshake.sendTransportHandshake(i,o),requestProtectedWebRTCUpgradeIfInitiator:(i,o)=>t.handshake.requestProtectedWebRTCUpgradeIfInitiator(i,o),clearManualDisconnectProjection:i=>e.clearManualDisconnectProjection(i),getPeerScopes:i=>e.getPeerScopes(i),sessionTokenScopeAllowsDeviceBinding:i=>n.trust.sessionTokenScopeAllowsDeviceBinding(i),resolvePromotionEligibility:i=>n.channelPolicy.resolvePromotionEligibility(i),hasRustPeerLifecycleProjection:()=>e.hasRustPeerLifecycleProjection(),dispatchLiveConnectionProjection:(i,o)=>e.dispatchLiveConnectionProjection(i,o),hasApplicationRouteForConnection:i=>t.upgrade.hasApplicationRouteForConnection(i),isWebRtcApplicationRouteReadyForConnection:i=>t.upgrade.isWebRtcApplicationRouteReadyForConnection(i),addPeerScope:(i,o)=>e.addPeerScope(i,o)})}function Qo(r){let{host:e,transports:t,trustServices:n}=r;return new It({registerDisposer:i=>e.registerDisposer(i),resolveApplicationCryptoForPeer:(i,o)=>e.resolveApplicationCryptoForPeer(i,o),handleApplicationKeyAgreement:(i,o)=>e.handleApplicationKeyAgreement(i,o),releaseApplicationKeyAgreementReply:(i,o,s)=>e.releaseApplicationKeyAgreementReply(i,o,s),isWebRTCTransportEnabled:()=>j(e.getOptions()),requiresManagedTransportTrust:()=>e.requiresManagedTransportTrust(e.getDiscoveryMode()),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),getLocalNodeId:()=>e.getLocalNodeId(),validateIncomingSessionTokenWithRetry:(i,o,s)=>e.validateIncomingSessionTokenWithRetry(i,o,s),applySessionTokenTrustApproval:(i,o,s)=>e.applySessionTokenTrustApproval(i,o,s),getConnectionChannelId:i=>n.channelPolicy.getConnectionChannelId(i),sendTransportHandshake:(i,o)=>t.handshake.sendTransportHandshake(i,o),getMoQState:()=>e.getMoQState(),enableMoQForConnection:i=>e.enableMoQForConnection(i),forgetMoQPeerSubscription:i=>e.forgetMoQPeerSubscription(i),assignConnectionChannel:(i,o)=>n.channelPolicy.assign(i,o),initializeConnectionTrust:i=>n.trust.initialize(i),getKnownDevice:(i,o)=>e.getKnownDevice(i,o),isSessionTokenApproved:(i,o)=>e.isSessionTokenApproved(i,o),getSessionTokenApprovedScope:i=>e.getSessionTokenApprovedScope(i),sessionTokenScopeAllowsDeviceBinding:i=>n.trust.sessionTokenScopeAllowsDeviceBinding(i),applyConnectionTrustProjection:i=>e.applyConnectionTrustProjection(i),getKnownDeviceIdForNode:i=>e.getKnownDeviceIdForNode(i),bindConnectionDeviceIdInRust:(i,o)=>n.deviceBinder.bindConnectionDeviceIdInRust(i,o),sendTransportHandshakeWithRecovery:(i,o,s,a)=>t.handshake.sendTransportHandshakeWithRecovery(i,o,s,a),verifyRemoteTransportTrust:(i,o)=>n.trust.verifyRemoteTransportTrust(i,o),enforceConnectionTrustFailure:(i,o)=>n.trust.enforceFailure(i,o),markConnectionTrustVerified:(i,o)=>n.trust.markVerified(i,o),getConnectionTrustState:i=>n.trust.getStateByConnectionId(i),dispatchMessage:(i,o)=>e.dispatchIncomingMessage(i,o)})}function $o(r){let{host:e,registry:t,transports:n,trustServices:i}=r;return new bt({registerDisposer:o=>e.registerDisposer(o),normalizeAuthoritativeIncomingProtocolHint:(o,s,a)=>Pt(o),shouldSkipIncomingStreamProbe:()=>e.shouldSkipIncomingStreamProbe(),tryHandleNativeMainUniStream:(o,s,a)=>e.tryHandleNativeMainUniStream(o,s,a),cancelUnhandledIncomingUniStream:(o,s)=>e.cancelUnhandledIncomingUniStream(o,s,(a,c)=>e.logIncomingDiagnostic(a,c)),handleNativeMainStream:(o,s,a)=>Number.isSafeInteger(a)&&Number(a)>0?e.handleNativeMainStream(o,s,a):e.handleNativeMainStream(o,s),shouldTreatIncomingStreamAsTransportOnly:o=>e.shouldTreatIncomingStreamAsTransportOnly(o),logIncomingDiagnostic:(o,s)=>e.logIncomingDiagnostic(o,s),getDeterministicConnectionId:o=>n.peerIdentity.getDeterministicConnectionId(o),getKnownDevice:(o,s)=>e.getKnownDevice(o,s),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),getConnection:o=>t.get(o),isCoreConnectionHealthy:o=>n.health.isCoreConnectionHealthy(o),cleanupReplacedConnection:o=>r.getLifecycle().cleanupReplacedConnection(o),getLocalNodeId:()=>e.getLocalNodeId(),getRTCConfig:()=>n.getRTCConfig(),createTransportContext:o=>n.contexts.create(o),getOptions:()=>e.getOptions(),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(o,s,a)=>n.health.handleCurrentConnectionTransportStatus(o,s,a),handleConnectionApplicationRouteReady:(o,s)=>n.health.handleCurrentConnectionApplicationRouteReady(o,s),handleConnectionApplicationRouteMissing:(o,s)=>n.upgrade.handleApplicationRouteMissing(o,s),getKnownDeviceIdForNode:o=>e.getKnownDeviceIdForNode(o),initializeConnectionTrust:(o,s)=>i.trust.initialize(o,s),registerConnection:o=>r.getLifecycle().registerConnection(o),bindConnectionDeviceIdInRust:(o,s)=>i.deviceBinder.bindConnectionDeviceIdInRust(o,s),searchDevices:()=>e.searchDevices(),announceConnectionWhenStable:o=>r.getLifecycle().announceConnectionWhenStable(o),sendTransportHandshake:(o,s)=>n.handshake.sendTransportHandshake(o,s),requestProtectedWebRTCUpgradeIfInitiator:(o,s)=>n.handshake.requestProtectedWebRTCUpgradeIfInitiator(o,s)})}function Vo(r){let{host:e,registry:t,transports:n,trustServices:i}=r;return new St({registerDisposer:o=>e.registerDisposer(o),registry:t,resolveApplicationCryptoForPeer:(o,s)=>e.resolveApplicationCryptoForPeer(o,s),flushPendingNativeMainHandshakesForNode:(o,s)=>e.flushPendingNativeMainHandshakesForNode(o,s),flushPendingNativeMainSignalsForNode:(o,s)=>e.flushPendingNativeMainSignalsForNode(o,s),getConnectionTrustState:o=>i.trust.getStateByConnectionId(o),getKnownDeviceIdByNodeId:o=>e.getKnownDeviceIdForNode(o),bindConnectionDeviceIdInRust:(o,s)=>i.deviceBinder.bindConnectionDeviceIdInRust(o,s),searchDevices:()=>e.searchDevices(),retireSupersededConnections:(o,s,a)=>i.deviceBinder.retireSupersededConnections(o,s,a),hasRustPeerLifecycleProjection:()=>e.hasRustPeerLifecycleProjection(),applyConnectionTrustProjection:o=>e.applyConnectionTrustProjection(o),schedulePeerReconciliation:o=>e.schedulePeerReconciliation(o),maybeHandleWebRTCExplicitFileEnvelope:(o,s)=>e.maybeHandleWebRTCExplicitFileEnvelope(o,s),handleMessage:(o,s)=>r.getMessageHandler().handleMessage(o,s),getExistingPeerProjectionForDisconnect:o=>e.getPeerState(o.id)||e.getPeerProjectionList().find(s=>s.connectionIds.includes(o.id)||s.nodeId===o.deviceId),cleanupConnectionState:(o,s)=>{e.forgetMoQPeerSubscription(o),s!=="physical-route"&&(e.clearApplicationCryptoForConnection(o),i.trust.clearForConnection(o),i.channelPolicy.forget(o),e.clearSessionTokenConnectionApproval(o));},dispatchLiveConnectionProjection:(o,s)=>e.dispatchLiveConnectionProjection(o,s),resolvePromotionEligibility:o=>i.channelPolicy.resolvePromotionEligibility(o),enforceConnectionTrustFailure:(o,s)=>i.trust.enforceFailure(o,s),initializeConnectionTrust:o=>i.trust.initialize(o),getWasmClient:()=>e.getWasmClient(),isCoreConnectionHealthy:o=>n.health.isCoreConnectionHealthy(o),hasApplicationRouteForConnection:o=>n.upgrade.hasApplicationRouteForConnection(o),allowsTransportOnlyStability:o=>i.channelPolicy.allowsTransportOnlyStability(o),stableWindowMs:bo,stableTimeoutMs:Ro,stablePollMs:Po})}function Yo(r){return new ni({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getWasmClient:()=>r.wasmClient,getLocalNodeId:()=>r.localNodeId,getDiscoveryMode:()=>r.discoveryMode,registerDisposer:e=>r.lifecycleScope.register(e),getTransportServices:()=>r.transportServices,getTrustServices:()=>r.trustServices,ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),ensureWasmManagedTransport:(e,t,n)=>r.managedTransportDialer.ensureWasmManagedTransport(e,t,n),isLocalIrohRuntimeNotInitializedError:e=>r.managedTransportDialer.isLocalIrohRuntimeNotInitializedError(e),recoverLocalIrohRuntime:e=>r.runtimeBootstrap.recoverLocalIrohRuntime(e),requiresManagedTransportTrust:e=>r.runtimeStatus.requiresManagedTransportTrust(e??r.discoveryMode),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),getRegisteredChannel:e=>r.incomingStreamRouter.getRegisteredChannel(e),maybeHandleWebRTCExplicitFileEnvelope:(e,t)=>r.incomingStreamRouter.maybeHandleWebRTCExplicitFileEnvelope(e,t),dispatchIncomingMessage:(e,t)=>r.incomingStreamRouter.dispatchMessage(e,t),shouldSkipIncomingStreamProbe:()=>r.incomingDiagnostics.shouldSkipIncomingStreamProbe(),cancelUnhandledIncomingUniStream:(e,t,n)=>r.incomingDiagnostics.cancelUnhandledIncomingUniStream(e,t,n),logIncomingDiagnostic:(e,t)=>r.incomingDiagnostics.logIncomingDiagnostic(e,t),shouldTreatIncomingStreamAsTransportOnly:e=>r.applicationIncomingStreams.shouldTreatIncomingStreamAsTransportOnly(e),tryHandleNativeMainUniStream:(e,t,n)=>r.nativeMain.tryHandleNativeMainUniStream(e,t??"",n),handleNativeMainStream:(e,t,n)=>Number.isSafeInteger(n)&&Number(n)>0?r.nativeMain.handleNativeMainStream(e,t??"",n):r.nativeMain.handleNativeMainStream(e,t??""),flushPendingNativeMainHandshakesForNode:(e,t)=>r.nativeMain.flushPendingHandshakesForNode(e,t),flushPendingNativeMainSignalsForNode:(e,t)=>r.nativeMain.flushPendingSignalsForNode(e,t),writeNativeMainLabelHeaderOnBiStream:(e,t)=>r.nativeMain.writeLabelHeaderOnBiStream(e,t),sendNativeSignalEnvelope:(e,t,n,i)=>r.nativeMain.sendSignalEnvelope(e,t,n,i),resolveApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.resolveForPeer(e,t),clearApplicationCryptoForConnection:e=>r.applicationCrypto.clearConnection(e),handleApplicationKeyAgreement:(e,t)=>r.applicationCrypto.handleKeyAgreement(e,t),releaseApplicationKeyAgreementReply:(e,t,n)=>r.applicationCrypto.releaseReplyClaim(e,t,n),shouldNegotiateApplicationKeyAgreement:()=>r.applicationCrypto.shouldNegotiateKeyAgreement(),rememberRouteRepairTokenForNode:(e,t,n)=>r.sessionTokens.rememberRouteRepairTokenForNode(e,t,n),getSessionTokenApprovedScope:e=>r.sessionTokens.getApprovedScope(e),setSessionTokenApprovedScope:(e,t)=>r.sessionTokens.setApprovedScope(e,t),approveSessionTokenNode:e=>r.sessionTokens.approveNode(e),approveSessionTokenConnection:e=>r.sessionTokens.approveConnection(e),applySessionTokenTrustApproval:(e,t,n)=>r.sessionTokens.applyTrustApproval(e,t,n),consumePendingSessionTokenTrustApproval:e=>r.sessionTokens.consumePendingTrustApproval(e),validateIncomingSessionTokenWithRetry:(e,t,n)=>r.sessionTokens.validateIncomingSessionTokenWithRetry(e,t,n),isSessionTokenApproved:(e,t)=>r.sessionTokens.isApproved(e,t),clearSessionTokenConnectionApproval:e=>r.sessionTokens.clearConnectionApproval(e),getPeerState:e=>r.peerServices.getPeerState(e),getPeerScopes:e=>r.peerServices.getPeerScopes(e),addPeerScope:(e,t)=>r.peerServices.addPeerScope(e,t),clearManualDisconnectProjection:e=>r.peerServices.clearManualDisconnectProjection(e),getPeerProjectionList:()=>r.peerServices.listPeerStates(),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),dispatchLiveConnectionProjection:(e,t)=>r.peerProjection.dispatchLiveConnectionProjection(e,t),getKnownDevice:(e,t)=>r.deviceDirectory.getKnownDevice(e,t),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),searchDevices:()=>r.deviceDirectory.searchDevices(),getMoQState:()=>r.moqServices.state,enableMoQForConnection:e=>r.moqServices.enableForConnection(e),forgetMoQPeerSubscription:e=>r.moqServices.forgetPeerSubscription(e)})}var ni=class{constructor(e){this.host=e;this.registry=new mt;}get transports(){return this.host.getTransportServices()}get trustServices(){return this.host.getTrustServices()}get factoryHost(){return {host:this.host,registry:this.registry,transports:this.transports,trustServices:this.trustServices,getLifecycle:()=>this.lifecycle,getMessageHandler:()=>this.messageHandler}}get dialer(){return this._dialer??(this._dialer=zo(this.factoryHost))}get messageHandler(){return this._messageHandler??(this._messageHandler=Qo(this.factoryHost))}get incomingAcceptor(){return this._incomingAcceptor??(this._incomingAcceptor=$o(this.factoryHost))}get lifecycle(){return this._lifecycle??(this._lifecycle=Vo(this.factoryHost))}async ensureManagedApplicationRoute(e){let t=Math.max(1,e.timeoutMs??2e4),n=await this.dialer.connect(e.ticket,t,e.expectedDeviceId,void 0,{admissionAlreadyPresented:true}),i=this.registry.getForPeer(e.connectionId??void 0,e.remoteNodeId??n.remoteNodeId)??n;if(await this.transports.upgrade.refreshApplicationRouteHandshake(i,"managed-transport-adoption",{forceReciprocal:true}),!await this.transports.upgrade.waitForApplicationRouteForConnection(i,t,50))throw new Error(`[Client][HANDSHAKE] application route was not ready for current connection ${i.id}`);return i}};var Tt=class{constructor(){this.wasmClient=null;this.node=null;this.localNodeId="";this.deviceId=null;}};var At=class{constructor(e=(t,n)=>{console.warn(t,n);}){this.logError=e;this.disposers=[];this.destroyed=false;}get isDestroyed(){return this.destroyed}register(e){if(this.destroyed){try{e();}catch(t){this.logError("[Client] late disposer failed",t);}return}this.disposers.push(e);}destroy(){if(!this.destroyed){this.destroyed=true;for(let e of this.disposers.splice(0).reverse())try{e();}catch(t){this.logError("[Client] disposer failed during destroy",t);}}}};var wt=class{constructor(e,t={}){this.session=e;this.namespaces=new Map;this.activePublishers=new Map;this.closed=false;this.maxNamespaces=t.maxPendingAnnounces??64,this.maxSubscribedTracks=t.maxSubscribedTracks??256,this.maxActivePublishers=t.maxActivePublishers??256,this.maxTrackIdChars=t.maxTrackIdChars??512;}async announce(e){let t=e.trim();if(!t)throw new Error("MoQ announce namespace must be non-empty");if(this.namespaces.has(t))throw new Error(`MoQ namespace is already announced: ${t}`);if(this.namespaces.size>=this.maxNamespaces)throw new Error(`MoQ namespace limit exceeded (${this.maxNamespaces})`);let n=new kt.Broadcast,i={broadcast:n,subscribers:new Map};this.namespaces.set(t,i),this.session.requireConnection().publish(kt.Path.from(t),n),d$1(`[MoQ] Draft 14 namespace published: ${t}`),this.acceptTrackRequests(t,i);}hasTrackSubscriber(e,t){return (this.namespaces.get(e.trim())?.subscribers.get(t)?.size??0)>0}async createTrack(e,t){let n=this.resolveTrackId(e,t);if(!n)throw new Error("MoQ track namespace and name must be non-empty and within length limits");let i=this.activePublishers.get(n);if(i)return i;if(this.activePublishers.size>=this.maxActivePublishers)throw new Error(`MoQ active publisher limit exceeded (${this.maxActivePublishers})`);let o=e.trim(),s={close:()=>this.activePublishers.delete(n),push:async a=>{if(this.closed)throw new Error("MoQ publisher closed");let c=this.namespaces.get(o)?.subscribers.get(t);if(!c?.size)throw new Error(`MoQ track lost all subscribers: ${n}`);let l=[],d=0,p=null;for(let u of c)try{u.writeFrame(a.slice()),d+=1;}catch(f){l.push(u),p=f;}for(let u of l)c.delete(u);if(d===0){let u=p instanceof Error?`: ${p.message}`:"";throw new Error(`MoQ track write failed for every subscriber: ${n}${u}`)}}};return this.activePublishers.set(n,s),s}close(){if(!this.closed){this.closed=true;for(let e of this.namespaces.values()){for(let t of e.subscribers.values())for(let n of t)n.close();e.broadcast.close();}this.namespaces.clear(),this.activePublishers.clear();}}async acceptTrackRequests(e,t){try{for(;!this.closed;){let n=await t.broadcast.requested();if(!n)return;if(!this.resolveTrackId(e,n.track.name)||this.totalSubscriberCount()>=this.maxSubscribedTracks){n.track.close(new Error("track subscription rejected"));continue}let o=t.subscribers.get(n.track.name);o||(o=new Set,t.subscribers.set(n.track.name,o)),o.add(n.track);let s=o;n.track.closed.finally(()=>{s.delete(n.track),s.size===0&&t.subscribers.delete(n.track.name);});}}catch(n){this.closed||console.warn("[MoQ] Draft 14 publisher loop failed",n);}}totalSubscriberCount(){let e=0;for(let t of this.namespaces.values())for(let n of t.subscribers.values())e+=n.size;return e}resolveTrackId(e,t){if(typeof e!="string"||typeof t!="string")return null;let n=e.trim();if(!n||!t.trim())return null;let i=`${n}/${t}`;return i.length<=this.maxTrackIdChars?i:null}};var Nt=class{constructor(e,t,n={}){this.session=e;this.onObject=t;this.subscriptions=new Map;this.closed=false;this.maxSubscriptions=n.maxPendingSubscriptions??128,this.maxSubscribeRetries=n.maxSubscribeRetries??120,this.subscribeRetryDelayMs=n.subscribeRetryDelayMs??250,this.maxObjectPayloadBytes=n.maxObjectPayloadBytes??4*1024*1024,this.onSubscriptionTerminated=n.onSubscriptionTerminated;}async subscribe(e,t){let n=e.trim();if(!n||!t.trim())throw new Error("MoQ subscribe namespace and name must be non-empty");let i=`${n}\0${t}`;if(this.subscriptions.has(i))return;if(this.subscriptions.size>=this.maxSubscriptions)throw new Error(`MoQ subscription limit exceeded (${this.maxSubscriptions})`);let o={broadcast:null,track:null,cancelled:false};this.subscriptions.set(i,o),d$1(`[MoQ] Draft 14 subscription opened: ${n}/${t}`),this.consume(i,n,t,o);}close(){if(!this.closed){this.closed=true;for(let e of this.subscriptions.values())e.cancelled=true,e.track?.close(),e.broadcast?.close();this.subscriptions.clear();}}async consume(e,t,n,i){let o=0,s=null;for(;!this.closed&&!i.cancelled;){let a=this.session.requireConnection().consume(kt.Path.from(t)),c=a.subscribe(n,0);i.broadcast=a,i.track=c;try{for(;!this.closed&&!i.cancelled;){let l=await c.readFrameSequence();if(!l)throw new Error("MoQ Draft 14 subscription closed");if(o=0,l.data.byteLength>this.maxObjectPayloadBytes)throw new Error(`MoQ object payload length exceeds limit: ${l.data.byteLength}`);this.onObject(t,n,l.data,{groupId:l.group,objectId:l.frame});}}catch(l){o+=1;let d=l instanceof Error&&/payload length exceeds limit/i.test(l.message);if(this.closed||i.cancelled||d||o>this.maxSubscribeRetries){!this.closed&&!i.cancelled&&(console.warn("[MoQ] Draft 14 subscription failed",l),s=l);break}d$1(`[MoQ] Draft 14 subscription retry ${o}/${this.maxSubscribeRetries}: ${t}/${n}`);}finally{c.close(),a.close(),i.track===c&&(i.track=null),i.broadcast===a&&(i.broadcast=null);}!this.closed&&!i.cancelled&&await new Promise(l=>setTimeout(l,this.subscribeRetryDelayMs));}if(this.subscriptions.get(e)===i&&this.subscriptions.delete(e),s!==null&&!this.closed&&!i.cancelled)try{this.onSubscriptionTerminated?.(t,n,s);}catch(a){console.warn("[MoQ] Subscription termination observer failed",a);}}};var Dt=class{constructor(e,t=()=>{},n=3,i=new URL("https://localhost/"),o={}){this.transport=e;this.relayUrl=i;this.setupComplete=false;this.connection=null;this.closeListeners=[];this.closed=false;this.closeEmitted=false;this.setupResolve=null;if(n!==3)throw new Error("MoQ Draft 14 adapter requires the bidirectional publisher/subscriber role");this.setupPromise=new Promise(s=>{this.setupResolve=s;}),this.publisher=new wt(this),this.subscriber=new Nt(this,t,{onSubscriptionTerminated:o.onSubscriptionTerminated});}requireConnection(){if(this.closed||!this.connection||!this.setupComplete)throw new Error("MoQ Draft 14 session is not ready");return this.connection}async init(){if(this.closed)throw new Error("MoQ session closed");if(this.connection)return;await this.transport.ready;let e=await kt.Connection.connect(this.relayUrl,{transport:this.transport,websocket:{enabled:false}});if(e.version!=="moq-transport-14")throw e.close(),new Error(`MoQ relay negotiated unsupported protocol ${e.version}`);if(this.closed){e.close();return}this.connection=e,this.setupComplete=true,this.setupResolve?.(),this.setupResolve=null,e.closed.then(()=>this.emitClose("relay-session-closed"),t=>this.emitClose(t));}waitForSetup(){return this.setupPromise}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(t=>t!==e);}}close(){if(!this.closed){this.closed=true,this.publisher.close(),this.subscriber.close();try{this.connection?.close();}catch{}this.connection=null;try{this.transport.close();}catch{}this.emitClose("local-close");}}emitClose(e){if(!this.closeEmitted){this.closeEmitted=true,this.closed=true,this.setupComplete=false,this.publisher.close(),this.subscriber.close(),this.connection=null;for(let t of [...this.closeListeners])try{t(e);}catch{}}}};var Zo="#openrtc-moq-route-proof",er=1,Os=512,Hs=750,Us=8;function tr(r){if(r.byteLength===0||r.byteLength>Os)return null;try{let e=JSON.parse(new TextDecoder().decode(r));return e.type!==Zo||e.version!==er||e.role!=="probe"&&e.role!=="ack"||typeof e.probeId!="string"||!/^[A-Za-z0-9_-]{8,64}$/.test(e.probeId)||typeof e.senderId!="string"||e.senderId.length===0||e.senderId.length>128||typeof e.recipientId!="string"||e.recipientId.length===0||e.recipientId.length>128?null:e}catch{return null}}function js(r){return new TextEncoder().encode(JSON.stringify(r))}function Gs(){if(typeof globalThis.crypto?.randomUUID=="function")return globalThis.crypto.randomUUID().replace(/-/g,"");let r=new Uint8Array(16);return globalThis.crypto?.getRandomValues?.(r),r.some(e=>e!==0)?Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,18)}`}var Mt=class{constructor(e){this.deps=e;this.states=new Map;}request(e){let t=this.deps.getCurrentSession(),n=this.deps.getLocalNodeId();if(!t||!this.deps.isCurrentSession(t)||!n||e.isClosed||!e.peerMoQReady)return;let i=this.states.get(e.id);(!i||i.session!==t||i.peerId!==e.remoteNodeId||i.connection!==e)&&(this.clear(e.id),i=this.createState(e,t,e.remoteNodeId)),!i.proven&&!i.inFlight&&!i.retryTimer&&this.schedule(e,i,0);}requestForPeer(e){let t=this.deps.getConnectionById(this.deps.getDeterministicConnectionId(e));t&&this.request(t);}isProven(e){let t=this.deps.getDeterministicConnectionId(e),n=this.states.get(t),i=this.deps.getConnectionById(t);return !!n&&n.proven&&n.peerId===e&&n.connection===i&&this.deps.isCurrentSession(n.session)}handle(e,t,n,i){let o=this.deps.getLocalNodeId();if(!(!o||i.senderId!==t||i.recipientId!==o)){if(i.role==="ack"){let s=this.states.get(n.id);s&&s.session===e&&s.connection===n&&s.peerId===t&&s.probeId===i.probeId&&this.markProven(n,s,"matching-protected-ack");return}this.ensureState(n,e,t),this.send(n,e,{...i,role:"ack",senderId:o,recipientId:t}).catch(s=>{c$1("[Client] MoQ protected route ACK failed",{connectionId:n.id,error:s});});}}clearForPeer(e){this.clear(this.deps.getDeterministicConnectionId(e));}clear(e){let t=this.states.get(e);t?.retryTimer&&clearTimeout(t.retryTimer),this.states.delete(e);}clearAll(){for(let e of [...this.states.keys()])this.clear(e);}createState(e,t,n){let i={session:t,connection:e,peerId:n,probeId:Gs(),attempts:0,inFlight:false,proven:false,retryTimer:null};return this.states.set(e.id,i),i}ensureState(e,t,n){let i=this.states.get(e.id);return i&&i.session===t&&i.connection===e&&i.peerId===n?i:(this.clear(e.id),this.createState(e,t,n))}schedule(e,t,n){t.retryTimer||t.proven||t.attempts>=Us||(t.retryTimer=setTimeout(()=>{t.retryTimer=null,this.sendProbe(e,t);},n));}async sendProbe(e,t){if(t.inFlight||t.proven||e.isClosed||!e.peerMoQReady||this.states.get(e.id)!==t||!this.deps.isCurrentSession(t.session))return;let n=this.deps.getLocalNodeId();if(n){t.inFlight=true,t.attempts+=1;try{await this.send(e,t.session,{type:Zo,version:er,role:"probe",probeId:t.probeId,senderId:n,recipientId:e.remoteNodeId});}catch(i){c$1("[Client] MoQ protected route probe failed",{connectionId:e.id,attempt:t.attempts,error:i});}finally{t.inFlight=false;}!t.proven&&this.states.get(e.id)===t&&this.deps.isCurrentSession(t.session)&&this.schedule(e,t,Hs);}}async send(e,t,n){if(!this.deps.isCurrentSession(t))throw new Error("MoQ route proof session was replaced");let i=this.deps.protectDirectPayload(js(n),e.remoteNodeId,e);if(!l$1(i))throw new Error("MoQ route proof requires application crypto");if(await this.deps.sendProtectedData(e.remoteNodeId,i),!this.deps.isCurrentSession(t))throw new Error("MoQ route proof session changed during send")}markProven(e,t,n){if(t.proven||t.connection!==e||this.deps.getConnectionById(e.id)!==e||this.states.get(e.id)!==t)return;let i=e.getTransportStatus();t.proven=true,t.retryTimer&&(clearTimeout(t.retryTimer),t.retryTimer=null),c$1("[Client] MoQ application route proven",{connectionId:e.id,reason:n}),this.deps.publishTransportStatus(e,"moq",i.activeTransport==="moq"?i.parallelTransport??null:i.activeTransport);}};var Ks=5e3,qs=125,zs=8,Et=class{constructor(e,t){this.ctx=e;this.deps=t;this.session=null;this.state="none";this.readyListeners=[];this.failedListeners=[];this.objectListeners=[];this.reconnectTimer=null;this.reconnectAttempts=0;this.peerSubscriptions=new Set;this.disposed=false;this.routeProofController=new Mt({getLocalNodeId:()=>this.ctx.localNodeId,getCurrentSession:()=>this.session,isCurrentSession:n=>this.isCurrentSession(n),getDeterministicConnectionId:n=>this.deps.getDeterministicConnectionId(n),getConnectionById:n=>this.deps.getConnectionById(n),protectDirectPayload:(n,i,o)=>this.deps.protectDirectPayload(n,i,o),sendProtectedData:(n,i)=>this.sendDataInternal(n,i,{alreadyProtected:true,allowUnprovenRoute:true}),publishTransportStatus:(n,i,o)=>this.deps.handleCurrentConnectionTransportStatus(n,i,o)}),this.ctx.registerDisposer(()=>this.dispose());}get bundle(){return this.state!=="ready"||!this.session?null:{session:this.session,publisher:this.session.publisher,subscriber:this.session.subscriber}}onReady(e){return this.disposed?()=>{}:(this.readyListeners.push(e),()=>{this.readyListeners=this.readyListeners.filter(t=>t!==e);})}onFailed(e){return this.disposed?()=>{}:(this.failedListeners.push(e),()=>{this.failedListeners=this.failedListeners.filter(t=>t!==e);})}onObject(e){return this.disposed?()=>{}:(this.objectListeners.push(e),()=>{this.objectListeners=this.objectListeners.filter(t=>t!==e);})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}closeSession(e){let t=this.session;if(this.session=null,this.peerSubscriptions.clear(),this.routeProofController.clearAll(),!!t)try{t.close();}catch(n){c$1("[Client] MoQ session close failed",{reason:e,error:n});}}dispose(){this.disposed=true,this.clearReconnectTimer(),this.closeSession("client-dispose"),this.state="none",this.readyListeners=[],this.failedListeners=[],this.objectListeners=[];}handleSessionClosed(e,t){this.disposed||this.session===e&&(this.session=null,this.state="failed",this.peerSubscriptions.clear(),this.routeProofController.clearAll(),this.emitFailed(),c$1("[Client] MoQ session closed; scheduling reconnect",{reason:t}),this.scheduleReconnect(t));}scheduleReconnect(e){if(this.disposed||!this.deps.getMoQConfig()||this.reconnectTimer)return;let t=Math.min(this.deps.initialReconnectDelayMs*Math.max(1,2**this.reconnectAttempts),this.deps.maxReconnectDelayMs);this.reconnectAttempts+=1;let n=(this.reconnectAttempts*17%21-10)/100,i=Math.max(this.deps.initialReconnectDelayMs,Math.trunc(t+t*n));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!(this.disposed||!this.deps.getMoQConfig()||this.state==="ready"||this.state==="connecting")&&(d$1(`[Client] Reconnecting MoQ relay after ${i}ms`,e),this.init());},i);}enableForConnection(e){this.state!=="ready"||!this.bundle||(e.peerMoQReady=true,this.subscribePeer(e));}subscribePeer(e){this.subscribePeerNode(e.remoteNodeId,e.id,()=>e.isClosed),this.routeProofController.request(e);}forgetPeerSubscription(e){this.peerSubscriptions.delete(e),this.routeProofController.clear(e);}isApplicationRouteProven(e){return this.routeProofController.isProven(e)}requestApplicationRouteProofForPeer(e){this.routeProofController.requestForPeer(e);}clearApplicationRouteProofForPeer(e){this.routeProofController.clearForPeer(e);}subscribePeerNode(e,t=e,n){if(this.disposed)return;let i=this.bundle,o=e?.trim(),s=t?.trim()||o;!i||!this.ctx.localNodeId||!o||!s||n?.()||this.peerSubscriptions.has(s)||(this.peerSubscriptions.add(s),this.subscribePeerNodeInBackground(i,o,s));}resubscribePeers(){this.peerSubscriptions.clear(),this.ctx.registry.forEach(e=>{!e.isClosed&&e.peerMoQReady&&this.subscribePeer(e);});}async init(){if(this.disposed||!this.deps.getMoQConfig()||this.state==="ready"||this.state==="connecting")return;this.clearReconnectTimer(),this.closeSession("init"),this.state="connecting";let e=this.deps.getMoQConfig(),t=e&&typeof e=="object"?{...this.deps.getDefaultMoQConfig(),...e}:{...this.deps.getDefaultMoQConfig()},n$1=t.relayUrl?.trim();if(!n$1){this.state="failed",this.emitFailed(),console.warn("[Client] MoQ is enabled without a relay URL; configure transports.moq.relayUrl explicitly.");return}let i=t.serverCertificateHashes?.length?{serverCertificateHashes:t.serverCertificateHashes}:void 0,o;try{o=l(n$1,t.accessToken);}catch(c){this.state="failed",this.emitFailed(),console.warn("[Client] MoQ configuration rejected:",n(c,t.accessToken));return}let s=m(n$1),a=null;try{let c=new WebTransport(o,i);if(await c.ready,this.disposed){try{c.close?.();}catch{}return}let l;if(l=new Dt(c,(d,p,u,f)=>{this.handleObject(l,d,p,u,f);},3,new URL(n$1),{onSubscriptionTerminated:(d,p,u)=>this.handleSubscriptionTerminated(l,d,p,u)}),a=l,this.session=a,a.onClose(d=>this.handleSessionClosed(a,d)),await a.init(),this.disposed){a.close();return}if(await a.waitForSetup(),this.disposed||this.session!==a){a.close();return}if(await a.publisher.announce(this.ctx.localNodeId),this.disposed||this.session!==a){a.close();return}if(await this.createDataTracks(),this.disposed||this.session!==a){a.close();return}this.state="ready",this.reconnectAttempts=0,this.peerSubscriptions.clear(),d$1(`[Client] MoQ Session Ready: Pub/Sub via ${s}`),this.emitReady(),this.resubscribePeers(),this.broadcastReadyCapabilityInBackground();}catch(c){if(this.disposed){a&&this.session===a&&(this.session=null),a?.close();return}console.warn("[Client] MoQ init failed:",n(c,t.accessToken)),this.session===a&&(this.session=null),a?.close(),this.state="failed",this.emitFailed(),this.scheduleReconnect(c);}}async createDataTracks(){if(!this.disposed&&!(!this.session||!this.ctx.localNodeId))try{await this.session.publisher.createTrack(this.ctx.localNodeId,"data/broadcast"),d$1("[Client] MoQ Data Track created: data / broadcast");}catch(e){console.warn("Failed to create MoQ broadcast track",e);}}isDataReady(e){let t=this.bundle;if(!t||!this.ctx.localNodeId)return false;let n=e?`data / ${e} `:"data / broadcast";return t.publisher.hasTrackSubscriber(this.ctx.localNodeId,n)}async sendData(e,t,n={}){return this.sendDataInternal(e,t,n)}async sendDataInternal(e,t,n={}){if(this.disposed)throw new Error("MoQ not ready");let i=this.bundle;if(!i)throw new Error("MoQ not ready");if(e&&n.allowUnprovenRoute!==true&&!this.isApplicationRouteProven(e))throw this.requestApplicationRouteProofForPeer(e),new Error(`MoQ application route is not proven for peer: ${e}`);let o=e?`data / ${e} `:"data / broadcast";if(!await this.waitForStableDataReady(e,i.session))throw this.isCurrentSession(i.session)?new Error(`MoQ data track is not subscribed: ${o}`):new Error("MoQ not ready");if(!this.isCurrentSession(i.session))throw new Error("MoQ not ready");let s=await i.publisher.createTrack(this.ctx.localNodeId,o);if(!s)return;if(!this.isCurrentSession(i.session))throw new Error("MoQ not ready");let a=Date.now(),c=n.alreadyProtected?t:this.deps.protectDirectPayload(t,e??void 0),l=e?this.deps.getConnectionById(this.deps.getDeterministicConnectionId(e)):void 0;try{await s.push(c,{isKey:!0,timestamp:a,closeAfterPush:!0});}catch(d){if(e&&this.isCurrentSession(i.session)&&(this.routeProofController.clearForPeer(e),l&&!l.isClosed)){let p=l.getTransportStatus();this.deps.handleCurrentConnectionTransportStatus(l,p.activeTransport,p.parallelTransport??null);}throw d}if(this.isCurrentSession(i.session)&&l&&!l.isClosed&&this.isApplicationRouteProven(e)){let d=typeof l.getTransportStatus=="function"?l.getTransportStatus():null;this.deps.handleCurrentConnectionTransportStatus(l,"moq",d?.parallelTransport??null);}}async waitForStableDataReady(e,t){let n=Date.now(),i=0;for(;this.isCurrentSession(t);){if(this.isDataReady(e)){if(i+=1,i>=zs)return true}else i=0;if(Date.now()-n>=Ks)return false;await u(qs);}return false}isCurrentSession(e){return !this.disposed&&this.state==="ready"&&this.session===e}handleSubscriptionTerminated(e,t,n,i){this.isCurrentSession(e)&&(c$1("[Client] MoQ subscription exhausted; replacing relay session",{namespace:t,name:n,error:i}),e.close(),this.session===e&&this.handleSessionClosed(e,i));}extractTrackPeerId(e){let t=e.replace(/\s+/g,"");if(!t.startsWith("data/"))return;let n=t.slice(5);if(!(!n||n==="broadcast"))return n}handleObject(e,t,n,i,o){if(!this.isCurrentSession(e))return;let s=this.deps.getConnectionById(this.deps.getDeterministicConnectionId(t)),a=this.deps.openDirectPayload(i,t);if(!a.encrypted||!a.payload)return;let c=a.proofEligible?tr(a.payload):null;if(c){s&&!s.isClosed&&this.routeProofController.handle(e,t,s,c);return}s&&!s.isClosed&&typeof s.receiveDataPayload=="function"&&s.receiveDataPayload(a.payload),this.emitObject(t,n,a.payload,o);}emitReady(){for(let e of [...this.readyListeners])try{e();}catch(t){console.warn("[Client] MoQ ready listener failed",t);}}subscribePeerNodeInBackground(e,t,n){let i=()=>{this.peerSubscriptions.delete(n);};try{Promise.allSettled([e.subscriber.subscribe(t,"data/broadcast"),e.subscriber.subscribe(t,`data / ${this.ctx.localNodeId} `)]).then(o=>{this.disposed||o.some(s=>s.status==="rejected")&&i();});}catch{i();}}broadcastReadyCapabilityInBackground(){try{Promise.resolve(this.deps.broadcastTransportCapabilityUpdate("moq-ready")).catch(e=>{this.disposed||c$1("[Client] Late MoQ capability update failed",e);});}catch(e){if(this.disposed)return;c$1("[Client] Late MoQ capability update failed",e);}}emitFailed(){for(let e of [...this.failedListeners])try{e();}catch(t){console.warn("[Client] MoQ failed listener failed",t);}}emitObject(e,t,n,i){for(let o of [...this.objectListeners])try{o(e,t,n,i);}catch(s){console.warn("[Client] MoQ object listener failed",s);}}};function nr(r){return new ii({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getDeterministicConnectionId:e=>r.peerIdentity.getDeterministicConnectionId(e),getConnectionById:e=>r.registry.get(e),protectDirectPayload:(e,t,n)=>r.applicationCrypto.protectDirectMoQPayload(e,t,n),openDirectPayload:(e,t,n)=>r.applicationCrypto.openDirectMoQPayload(e,t,n),handleCurrentConnectionTransportStatus:(e,t,n)=>r.transportHealth.handleCurrentConnectionTransportStatus(e,t,n),broadcastTransportCapabilityUpdate:e=>r.transportHandshake.broadcastTransportCapabilityUpdate(e)})}var ii=class{constructor(e){this.host=e;}get controller(){return this._controller||(this._controller=new Et(this.host.getContext(),{getMoQConfig:()=>this.host.getOptions()?.transports?.moq,getDefaultMoQConfig:()=>({...i}),getDeterministicConnectionId:e=>this.host.getDeterministicConnectionId(e),getConnectionById:e=>this.host.getConnectionById(e),protectDirectPayload:(e,t,n)=>this.host.protectDirectPayload(e,t,n),openDirectPayload:(e,t,n)=>this.host.openDirectPayload(e,t,n),handleCurrentConnectionTransportStatus:(e,t,n)=>this.host.handleCurrentConnectionTransportStatus(e,t,n),broadcastTransportCapabilityUpdate:e=>this.host.broadcastTransportCapabilityUpdate(e),initialReconnectDelayMs:To,maxReconnectDelayMs:Ao})),this._controller}get state(){return this._controller?.state??"none"}get bundle(){return this._controller?.bundle??null}init(){return this.controller.init()}onReady(e){return this.controller.onReady(e)}onFailed(e){return this.controller.onFailed(e)}onObject(e){return this.controller.onObject(e)}isReady(){return this._controller?.state==="ready"}isDataReady(e){return this._controller?.isDataReady(e)??false}isApplicationRouteProven(e){return this._controller?.isApplicationRouteProven(e)??false}requestApplicationRouteProof(e){this._controller?.requestApplicationRouteProofForPeer(e);}clearApplicationRouteProof(e){this._controller?.clearApplicationRouteProofForPeer(e);}enableForConnection(e){this.controller.enableForConnection(e);}subscribePeerNode(e,t){this.controller.subscribePeerNode(e,t);}forgetPeerSubscription(e){this._controller?.forgetPeerSubscription(e);}sendData(e,t,n){return this.controller.sendData(e,t,n)}};function oe(){if(typeof navigator>"u")return false;let r=navigator.userAgent||"",e=navigator.userAgentData?.platform||navigator.platform||"";return /iPhone|iPad|iPod|Android|Mobile|CriOS|FxiOS/i.test(`${r} ${e}`)}function Lt(){return typeof window>"u"?false:new URLSearchParams(window.location.search).has("ticket")}function xt(r){return r?r.routing==="stream-envelope"&&r.readiness==="transport-only":false}function He(r){let e=r.signalingMode??"hosted",t=oe(),n=Lt(),i=e==="ticket-only",o=i&&t;return {flow:i?"ticket-only":"default",signalingMode:e,mobileBrowser:t,ticketQueryPresent:n,diagnosticsMode:o,skipIncomingBiProbe:o,skipIncomingChannelEnvelopeInspection:o,readerCloseStrategy:o?"release-lock":"cancel"}}var Ft=class Ft{constructor(e){this.deps=e;this.pendingReciprocalAdmissions=new Map;this.reciprocalConfirmationsInFlight=new Set;this.legacyReciprocalPresentationsInFlight=new Set;this.disposed=false;}dispose(){this.disposed=true,this.retirePendingReciprocalAdmissions("dispose"),this.legacyReciprocalPresentationsInFlight.clear();}retirePendingReciprocalAdmissions(e){this.pendingReciprocalAdmissions.size>0&&c$1("[Client][AUTH] retiring pending reciprocal admissions",{reason:e,count:this.pendingReciprocalAdmissions.size}),this.pendingReciprocalAdmissions.clear(),this.reciprocalConfirmationsInFlight.clear();}async acceptNativeMessage(e,t,n){if(this.disposed||!t)return false;let i=this.deps.getDeterministicConnectionId(t),o=this.deps.getConnection(i);if(o){try{Promise.resolve(this.deps.handleMessage(o,n)).catch(s=>{this.disposed||console.warn("[Client][NATIVE-MAIN] Existing connection message handling failed",{remoteNodeId:t,connectionId:o.id,error:s});});}catch(s){this.disposed||console.warn("[Client][NATIVE-MAIN] Existing connection message handling failed",{remoteNodeId:t,connectionId:o.id,error:s});}return false}if(n&&typeof n=="object"&&n.type==="handshake"&&(n.action==="hello"||!n.action)){let s=await this.deps.validateIncomingSessionToken(n.sessionToken??"",e??void 0,{remoteNodeId:t,source:"accept-native-message",tokenPayload:typeof n.sessionTokenPayload=="string"?n.sessionTokenPayload:void 0});if(this.disposed)return false;if(!s.ok)return console.warn("[Client][SESSION-TOKEN] Rejecting native connection \u2014 invalid session token",{remoteNodeId:t,reason:s.reason,hasToken:!!n.sessionToken}),true}return false}async resolveLocalHandshakePayload(){let e=await this.deps.getLocalDeviceId().catch(()=>null)||this.deps.getFallbackLocalDeviceId();if(!e)throw new Error("Local device id unavailable for native handshake response");let t=this.deps.isNativeRuntime(),n=t?this.deps.isLikelyMobileBrowser()?"mobile":"desktop":"web",i=t?{canHost:true,canSync:true,readOnly:false}:{canHost:false,canSync:true,readOnly:false},o=n==="mobile"?"Mobile Device":n==="desktop"?"Desktop Device":"Browser Device";return {deviceId:e,deviceName:this.deps.getConfiguredDeviceName()||o,platformType:n,capabilities:i,protocolVersion:this.deps.getNativeMainProtocolVersion(),timestamp:Date.now()}}async handleHandshakeRequest(e,t,n){if(this.disposed)return;let i=await this.resolveLocalHandshakePayload();this.disposed||(await this.deps.writeNativeMainMessage(e,{channel:"handshake",action:"response",requestId:n.requestId,payload:{accepted:true,...i},timestamp:Date.now()}),!this.disposed&&(this.schedulePeerReconciliationBestEffort("native-main-handshake"),c$1("[Client][NATIVE-MAIN] Responded to desktop handshake",{remoteNodeId:t,requestId:n.requestId??null,localDeviceId:i.deviceId})));}async handleSessionTokenRequest(e,t,n,i,o){if(this.disposed)return;let s=this.deps.getSessionTokenRejectionCooldown(t),a=this.deps.getNativeMainConnectionId(t);if(s!==void 0&&Date.now()-s<Ft.TOKEN_REJECTION_COOLDOWN_MS){await this.deps.writeNativeMainMessage(e,{channel:"session-token",action:"response",requestId:n.requestId,payload:{approved:false,reason:"session-token-rejection-cooldown",connectionId:a},timestamp:Date.now()}),console.warn("[Client][AUTH] session-token presentation during rejection cooldown \u2014 wrote rejection for dialer",{remoteNodeId:t,connectionId:a});return}let c=n.payload&&typeof n.payload.token=="string"?n.payload.token.trim():"",l=n.payload&&typeof n.payload.tokenPayload=="string"?n.payload.tokenPayload.trim():void 0,d=await this.deps.validateIncomingSessionToken(c,a,{remoteNodeId:t,source:"native-main-session-token",tokenPayload:l||void 0});if(this.disposed)return;let p,u=n.payload?.reciprocalRequested===true,f=u&&n.payload?.reciprocalMode==="inline-v1"&&Number.isSafeInteger(i)&&Number(i)>0&&typeof o=="string"&&o.trim().length>0;if(d.ok&&f){let h=n.payload?.streamContract==="persistent-control"?"persistent-control":"one-shot-admission";try{let m=this.createPresentationId();p={...await this.deps.getReciprocalSessionAdmission(t,h,Number(i),o,m),presentationId:m};}catch(m){this.disposed||console.warn("[Client][AUTH] reciprocal session admission unavailable",{remoteNodeId:t,connectionId:a,error:m});}}if(!this.disposed&&(await this.deps.writeNativeMainMessage(e,d.ok?{channel:"session-token",action:"response",requestId:n.requestId,payload:{approved:true,scope:d.scope??null,connectionId:a,...p?{reciprocalPresentation:p}:{},...p?{reciprocalMode:"inline-v1"}:{}},timestamp:Date.now()}:{channel:"session-token",action:"response",requestId:n.requestId,payload:{approved:false,reason:d.reason??"session-token-rejected",connectionId:a},timestamp:Date.now()}),!this.disposed)){if(d.ok&&p&&i){for(let[h,m]of this.pendingReciprocalAdmissions)m.remoteNodeId===t&&m.transportStableId===i&&this.pendingReciprocalAdmissions.delete(h);this.pendingReciprocalAdmissions.set(p.presentationId,{connectionId:a,remoteNodeId:t,transportStableId:i,streamInstanceId:o,presentationId:p.presentationId});}if(d.ok){let h=this.deps.getConnection(a);h&&!h.isClosed?this.deps.applySessionTokenTrustApproval(h,d.scope??null,"native-main-session-token"):(this.deps.rememberPendingSessionTokenTrustApproval(a,d.scope??null),this.deps.markSessionTokenApprovedNode(t),this.deps.markSessionTokenApprovedConnection(a)),this.deps.clearSessionTokenRejectionCooldown(t),this.deps.clearTrustFailureCooldown(t),c$1("[Client][AUTH] host approved managed session token",{remoteNodeId:t,connectionId:a,scope:d.scope??null}),this.schedulePeerReconciliationBestEffort("session-token-approval"),u&&(!f||!p)&&this.scheduleLegacyReciprocalSessionAdmission(t,a),(!h||h.isClosed)&&this.kickstartApprovedControlConnection(t,a);return}console.warn("[Client][AUTH] host rejected managed session token",{remoteNodeId:t,connectionId:a,reason:d.reason??"session-token-rejected",hasToken:c.length>0}),this.deps.setSessionTokenRejectionCooldown(t,Date.now()),this.deps.disconnectRemoteNode(t);}}async handleSessionTokenResponseAck(e,t,n,i){let o=typeof t.payload?.reciprocalPresentationId=="string"?t.payload.reciprocalPresentationId.trim():"";if(!o||!Number.isSafeInteger(n)||Number(n)<=0)return false;let s=this.pendingReciprocalAdmissions.get(o);if(!s||s.remoteNodeId!==e||s.transportStableId!==n||s.streamInstanceId!==i||t.payload?.connectionId!==s.connectionId)return console.warn("[Client][AUTH] ignored stale reciprocal admission ACK",{remoteNodeId:e,transportStableId:n??null,presentationId:o}),false;if(this.reciprocalConfirmationsInFlight.has(o))return true;this.reciprocalConfirmationsInFlight.add(o);let a=t.payload?.reciprocalAccepted===true,c=typeof t.payload?.reciprocalScope=="string"&&t.payload.reciprocalScope.trim()||null,l=false;try{l=await this.deps.confirmReciprocalSessionAdmission(e,n,s.streamInstanceId,s.presentationId,a,c);}catch(d){console.warn("[Client][AUTH] reciprocal admission confirmation failed",{remoteNodeId:e,transportStableId:n,presentationId:o,error:d});}finally{this.reciprocalConfirmationsInFlight.delete(o);}return l&&this.pendingReciprocalAdmissions.delete(o),a?l?(c$1("[Client][AUTH] reciprocal admission committed",{remoteNodeId:e,transportStableId:n,presentationId:o,approvalScope:c}),this.schedulePeerReconciliationBestEffort("reciprocal-session-admission-committed"),true):(console.warn("[Client][AUTH] reciprocal admission ACK failed generation-bound confirmation",{remoteNodeId:e,transportStableId:n,presentationId:o}),this.schedulePeerReconciliationBestEffort("reciprocal-session-admission-stale"),true):(console.warn("[Client][AUTH] reciprocal admission was not committed by peer",{remoteNodeId:e,transportStableId:n,presentationId:o,reason:t.payload?.reciprocalReason??"rejected"}),this.schedulePeerReconciliationBestEffort("reciprocal-session-admission-rejected"),true)}handleNativeMainStreamClosed(e,t,n){if(!(!Number.isSafeInteger(t)||Number(t)<=0))for(let[i,o]of this.pendingReciprocalAdmissions)o.remoteNodeId===e&&o.transportStableId===t&&o.streamInstanceId===n&&(this.pendingReciprocalAdmissions.delete(i),this.reciprocalConfirmationsInFlight.delete(i));}createPresentationId(){let e=globalThis.crypto?.randomUUID;return typeof e=="function"?e.call(globalThis.crypto):`reciprocal-${Date.now()}-${Math.random().toString(36).slice(2)}`}scheduleLegacyReciprocalSessionAdmission(e,t){this.disposed||this.legacyReciprocalPresentationsInFlight.has(t)||(this.legacyReciprocalPresentationsInFlight.add(t),queueMicrotask(()=>{if(this.disposed){this.legacyReciprocalPresentationsInFlight.delete(t);return}this.deps.presentLegacyReciprocalSessionAdmission(e).catch(n=>{this.disposed||console.warn("[Client][AUTH] legacy reciprocal session admission failed",{remoteNodeId:e,connectionId:t,error:n});}).finally(()=>{this.legacyReciprocalPresentationsInFlight.delete(t);});}));}kickstartApprovedControlConnection(e,t){let n=i=>{this.disposed||console.warn("[Client][AUTH] post-approval kickstart error",{remoteNodeId:e,connectionId:t,error:i});};try{Promise.resolve(this.deps.ensureIncomingConnectionForRemoteNode(e)).then(i=>{this.disposed||(i?c$1("[Client][AUTH] post-approval kickstart opened control connection",{remoteNodeId:e,connectionId:i.id}):console.warn("[Client][AUTH] post-approval kickstart failed to open control connection",{remoteNodeId:e,connectionId:t}));}).catch(n);}catch(i){n(i);}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};Ft.TOKEN_REJECTION_COOLDOWN_MS=5e3;var _t=Ft;var Bt=class{constructor(e){this.deps=e;this.pendingConnections=new Map;this.disposed=false;}dispose(){this.disposed=true,this.pendingConnections.clear();}async ensureIncomingConnectionForRemoteNode(e){if(this.disposed)return null;let t=this.deps.getDeterministicConnectionId(e),n=this.deps.getConnection(t);if(n&&!n.isClosed)return this.attachNativeSignalSenderIfEligible(n,e),n;let i=this.pendingConnections.get(t);if(i)return i;let o=this.deps.getTrustFailureCooldown(e),s=this.deps.getTrustFailureCooldownMs();if(o!==void 0&&Date.now()-o<s&&!this.deps.isSessionTokenApprovedNode(e))return c$1("[Client][TRUST] Skipping connection rebuild for node in trust-failure cooldown",{remoteNodeId:e,cooldownRemainingMs:s-(Date.now()-o)}),null;let a=this.createIncomingConnection(t,e);this.pendingConnections.set(t,a);try{return await a}finally{this.pendingConnections.delete(t);}}attachNativeSignalSenderIfEligible(e,t){let n=typeof e.getControlFrameMode=="function"?e.getControlFrameMode():"typed";c$1("[Client][NATIVE-MAIN] Reusing existing control connection",{connectionId:e.id,remoteNodeId:t,upgradeState:typeof e.getUpgradeState=="function"?e.getUpgradeState():null,controlFrameMode:n});let i=this.deps.getKnownDevicePlatform(this.deps.getKnownDeviceIdForNode(t),t);if(!this.deps.isNativeMainPeerPlatform(i)&&!this.deps.isSessionTokenApprovedNode(t))return;let o=this.deps.getWasmClient();if(!o||typeof o.open_bi!="function")return;let s=async a=>{await this.deps.sendNativeSignalEnvelope(e,t,a,o);};n!=="native-main"&&typeof e.promoteToNativeMainControlRoute=="function"?(e.promoteToNativeMainControlRoute(s),c$1("[Client][NATIVE-MAIN] Promoted bootstrap connection to native control route",{connectionId:e.id,remoteNodeId:t})):n==="native-main"&&e.setNativeSignalSender(s);}async createIncomingConnection(e,t){if(this.disposed)return null;let n=this.deps.getWasmClient();if(!n||typeof n.open_bi!="function")return null;let i=this.deps.getKnownDeviceIdForNode(t);if(!this.deps.getKnownDevicePlatform(i,t)&&!this.deps.isSessionTokenApprovedNode(t))return c$1("[Client][NATIVE-MAIN] Deferring native-main connection creation until peer platform is known",{remoteNodeId:t,connectionId:e,knownDeviceId:i}),null;let s;try{s=await this.deps.openNativeSignalBiStream(n,t);}catch(c){return console.warn("[Client][NATIVE-MAIN] Failed to open control stream for native signal routing",{remoteNodeId:t,connectionId:e,error:c}),null}if(this.disposed)return await B$1(s,"native-main-connection-disposed-after-open"),null;try{await this.deps.writeNativeMainLabelHeaderOnBiStream(s,t);}catch(c){return console.warn("[Client][NATIVE-MAIN] Failed to write label header on control stream",{remoteNodeId:t,connectionId:e,error:c}),null}if(this.disposed)return await B$1(s,"native-main-connection-disposed-after-label"),null;let a;return a=new ee(e,this.deps.getLocalNodeId(),t,s.send.getWriter(),s.recv.getReader(),{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(t),applicationCrypto:this.deps.getApplicationCrypto(),requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),controlFrameMode:"native-main",onTransportStatusChange:c=>this.deps.handleConnectionTransportStatus(a,c.activeTransport,c.parallelTransport),onApplicationRouteMissing:c=>{this.deps.handleConnectionApplicationRouteMissing(e,c);}}),a.setNativeSignalSender(async c=>{await this.deps.sendNativeSignalEnvelope(a,t,c,n);}),this.deps.initializeConnectionTrust(a,i),this.deps.markConnectionTrustVerified(a,i),this.deps.registerConnection(a),this.deps.announceConnectionWhenStable(a),c$1("[Client][HANDSHAKE] sending hello (native signal routing path)",{connectionId:a.id,remoteNodeId:a.remoteNodeId}),this.sendNativeRoutingHelloInBackground(a),c$1("[Client][NATIVE-MAIN] Created control connection for native signal routing",{connectionId:a.id,remoteNodeId:t,channelId:this.deps.getConnectionChannelId(a.id)??null,rtcEnabled:this.deps.isWebRTCTransportEnabled()}),a}sendNativeRoutingHelloInBackground(e){let t=n=>{this.disposed||console.warn("[Client][TRUST] Failed to send outgoing handshake for native signal routing",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:n});};try{Promise.resolve(this.deps.sendTransportHandshake(e,"hello")).then(()=>{this.disposed||this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,"protected-hello:native-signal-routing");}).catch(t);}catch(n){t(n);}}};var Wt=class{constructor(e,t,n=[0,250,1e3,2500]){this.maxPerNode=e;this.ttlMs=t;this.retryDelaysMs=n;this.pendingByNodeId=new Map;this.retryTimers=new Set;this.disposed=false;}queue(e,t,n,i,o){if(this.disposed)return;let s=this.pendingByNodeId.get(e)??[];s.push({message:t,source:n,traceId:i??null,receivedAtMs:Date.now()}),s.length>this.maxPerNode&&s.splice(0,s.length-this.maxPerNode),this.pendingByNodeId.set(e,s),c$1("[Client][NATIVE-MAIN] Queued TS handshake until control connection is registered",{remoteNodeId:e,action:t.action??"hello",source:n,traceId:i||null,pendingCount:s.length});for(let a of this.retryDelaysMs){let c=setTimeout(()=>{this.retryTimers.delete(c),!this.disposed&&o(e,`queued-handshake-retry:${a}`);},a);this.retryTimers.add(c);}}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear(),this.pendingByNodeId.clear();}}async flush(e,t,n){if(this.disposed)return false;let i=this.pendingByNodeId.get(e);if(!i||i.length===0)return false;let o=n.findManualDisconnectProjectionForNativeNode(e);if(o)return this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Dropped queued TS handshakes for manually disconnected peer",{remoteNodeId:e,peerId:o.peerId,droppedCount:i.length,trigger:t}),false;let s=n.findLiveConnectionForRemoteNode(e);if(s||(s=await n.ensureIncomingConnectionForRemoteNode(e).catch(()=>null)),this.disposed)return false;if(!s){let a=Date.now(),c=i.filter(l=>a-l.receivedAtMs<=this.ttlMs);return c.length===0?(this.pendingByNodeId.delete(e),console.warn("[Client][NATIVE-MAIN] Dropping queued TS handshakes after control connection did not appear",{remoteNodeId:e,trigger:t,droppedCount:i.length})):c.length!==i.length&&this.pendingByNodeId.set(e,c),false}this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Replaying queued TS handshakes to Connection",{remoteNodeId:e,connectionId:s.id,trigger:t,count:i.length});for(let a of i){if(this.disposed)return false;await n.handleMessage(s,a.message);}return true}};var Qs="main";function Ue(){let r=new TextEncoder().encode(Qs),e=new ArrayBuffer(5+r.byteLength),t=new Uint8Array(e);return t[0]=0,new DataView(e).setUint32(1,r.byteLength,false),t.set(r,5),t}function fe(r){let e=JSON.stringify(r),t=new TextEncoder().encode(e),n=new Uint8Array(1+t.byteLength);return n[0]=0,n.set(t,1),n}function re(r){let e=new ArrayBuffer(4+r.byteLength);new DataView(e).setUint32(0,r.byteLength,false);let n=new Uint8Array(e);return n.set(r,4),n}var Ot=class{constructor(e,t){this.config=e;this.deps=t;}protocolConfig(){return {protocolByte:this.config.protocolByte,label:this.config.label,maxLabelBytes:this.config.maxLabelBytes,maxFrameBytes:this.config.maxFrameBytes}}encodeFrame(e){return Go(e,this.protocolConfig())}async dispatchMessage(e,t){return Ko(this.config.eventName,e,this.deps.getRemoteDeviceId(e),t)}async writeAck(e,t,n=null){let i=this.deps.getReceiverDeviceId();await this.writeMessage(e,{channel:"native-main",action:"ack",requestId:t.requestId,payload:{received:true,channel:t.channel,action:t.action,...i?{receiverDeviceId:i}:{},...n!==null?{handlerResponse:n}:{}},timestamp:Date.now(),from:"web"});}async writeMessage(e,t){await e.write(this.encodeFrame(t));}async writeLabeledMessage(e,t){await e.write(Ue()),await e.write(re(new TextEncoder().encode(JSON.stringify(t))));}async writeLabelHeaderOnBiStream(e,t){let n=e.send.getWriter();try{await n.write(Ue());}catch(i){throw console.warn("[Client][NATIVE-MAIN] Label header write failed",{remoteNodeId:t,error:i}),i}finally{try{n.releaseLock();}catch{}}}};var Ht=class{constructor(e){this.deps=e;this.disposed=false;this.activeReaders=new Set;}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.activeReaders)this.cancelReaderBestEffort(e);this.activeReaders.clear();}}async handleNativeMainStream(e,t,n){if(this.disposed||!y(e))return;let i,o,s=false;try{i=e.recv.getReader(),o=e.send.getWriter();}catch(u){console.warn("[Client][NATIVE-MAIN] Unable to acquire stream handles",{remoteNodeId:t,error:u});return}this.activeReaders.add(i);let a=this.createStreamInstanceId(),c=new Uint8Array(0),l="stream-active",d=0,p=()=>{s||(this.deps.registerInboundNativeMainWriter(t,o),s=true);};try{for(;!this.disposed;){let u=this.tryExtractNativeMainPayload(c);for(;!u.ready&&!this.disposed;){let{done:h,value:m}=await i.read();if(this.disposed)return;if(h){l=u.phase==="frame-start"?d>0?"remote-closed-after-frame":"remote-closed-before-frame-length":"remote-closed-mid-frame",(d===0||u.phase!=="frame-start")&&this.schedulePeerReconciliationBestEffort("native-main-stream-close"),u.phase==="frame-start"?c$1("[Client][NATIVE-MAIN] Remote closed native main stream",{remoteNodeId:t,handledFrameCount:d}):console.warn("[Client][NATIVE-MAIN] Native main stream ended mid-frame",{remoteNodeId:t,messageLen:u.expectedFrameLength,bufferedBytes:c.byteLength});return}m&&m.byteLength>0&&(c=w$1([c,new Uint8Array(m)]));try{u=this.tryExtractNativeMainPayload(c);}catch(y){l="invalid-native-main-frame",console.warn("[Client][NATIVE-MAIN] Invalid native main frame",{remoteNodeId:t,error:y});return}}if(u.expectedFrameLength===0){c=c.slice(u.consumedBytes);continue}let f=u.payloadBytes;c=c.slice(u.consumedBytes),d+=1,await this.handleNativeMainPayloadBytes(f,t,o,void 0,"bi",p,n,a);}}catch(u){if(this.disposed)return;l="handler-error",this.schedulePeerReconciliationBestEffort("native-main-handler-error"),console.error("[Client][NATIVE-MAIN] Native main stream handler failed",{remoteNodeId:t,error:u});}finally{this.deps.handleNativeMainStreamClosed(t,n,a),s&&this.deps.clearInboundNativeMainWriter(t,o,l),this.activeReaders.delete(i);try{o.releaseLock();}catch{}try{i.releaseLock();}catch{}}}tryExtractNativeMainPayload(e){return qo(e,this.deps.getProtocolConfig())}async tryHandleNativeMainUniStream(e,t,n){if(this.disposed||!e||typeof e.getReader!="function")return false;let i;try{i=e.getReader();}catch{return false}this.activeReaders.add(i);let o=new Uint8Array(0),s=false;try{for(;!this.disposed;){let a=this.tryExtractNativeMainPayload(o);for(;!a.ready&&!this.disposed;){let{done:c,value:l}=await i.read();if(this.disposed||c)return s;l&&l.byteLength>0&&(o=w$1([o,new Uint8Array(l)])),a=this.tryExtractNativeMainPayload(o);}s=!0,o=o.slice(a.consumedBytes),await this.handleNativeMainPayloadBytes(a.payloadBytes,t,null,n,"uni");}return s}catch(a){return this.disposed?s:s?(console.warn("[Client][NATIVE-MAIN] Read-only native main uni handler failed",{remoteNodeId:t,traceId:n||null,error:a}),true):false}finally{this.activeReaders.delete(i);try{i.releaseLock();}catch{}}}async handleNativeMainPayloadBytes(e,t,n,i,o,s,a,c){if(this.disposed)return;let l=e.byteLength>1&&e[0]===0?e.slice(1):e,d;try{d=JSON.parse(new TextDecoder().decode(l));}catch(h){let m=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;m?m.receiveDataPayload(l):console.warn("[Client][NATIVE-MAIN] Dropping binary app payload: no control connection",{remoteNodeId:t,traceId:i||null,source:o,error:h});return}let p=this.deps.findManualDisconnectProjectionForNativeNode(t);if(this.isHandshakeMessage(d)){if(s?.(),p){c$1("[Client][NATIVE-MAIN] Dropping TS handshake for manually disconnected peer",{remoteNodeId:t,peerId:p.peerId,action:d.action??"hello",source:o});return}let h=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!h){this.deps.queuePendingNativeMainHandshake(t,d,o,i||null);return}c$1("[Client][NATIVE-MAIN] Routed TS handshake to Connection",{remoteNodeId:t,connectionId:h.id,action:d.action??"hello",source:o}),await this.deps.handleMessage(h,d);return}if(this.isNativeSignalEnvelope(d)){if(s?.(),c$1("[Client][NATIVE-MAIN] Received #pluto-signal envelope",{remoteNodeId:t,signalType:d.content?.type??null,transport:d.content?.transport??null,source:o}),p){c$1("[Client][NATIVE-MAIN] Dropping native WebRTC signal for manually disconnected peer",{remoteNodeId:t,peerId:p.peerId,signalType:d.content?.type??null,source:o});return}let h=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!h){this.deps.queuePendingNativeMainSignal(t,d.content,o,i||null);return}h.receiveInternalSignal(d.content),c$1("[Client][NATIVE-MAIN] Routed #pluto-signal to Connection",{remoteNodeId:t,connectionId:h.id,signalType:d.content?.type??null,source:o});return}let u=d;if(c$1("[Client][NATIVE-MAIN] Received native main message",{remoteNodeId:t,channel:u.channel,action:u.action,requestId:u.requestId??null,source:o}),u.channel==="handshake"&&u.action==="request"){n&&await this.deps.handleNativeHandshakeRequest(n,t,u);return}if(u.channel==="session-token"&&u.action==="request"){n&&await this.deps.handleNativeSessionTokenRequest(n,t,u,a,c);return}if(u.channel==="session-token"&&u.action==="event"&&u.payload?.responseAck===true){await this.deps.handleNativeSessionTokenResponseAck(t,u,a,c);return}if(!u.channel&&!u.action&&!u.requestId){s?.();let h=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!h){console.warn("[Client][NATIVE-MAIN] Dropping app payload: no control connection",{remoteNodeId:t,traceId:i||null,source:o});return}h.receiveMessage(d);return}let f=await this.deps.dispatchNativeMainMessage(t,u);this.disposed||n&&await this.writeReceiveAckBestEffort(n,u,f,t,o);}isNativeSignalEnvelope(e){if(!e||typeof e!="object")return false;let t=e;return t.type==="#pluto-signal"&&typeof t.content=="object"&&t.content!==null}isHandshakeMessage(e){return !e||typeof e!="object"?false:e.type==="handshake"}cancelReaderBestEffort(e){try{Promise.resolve(e.cancel("native-main-payload-router-disposed")).catch(()=>{});}catch{}}createStreamInstanceId(){let e=globalThis.crypto?.randomUUID;return typeof e=="function"?e.call(globalThis.crypto):`native-main-stream-${Date.now()}-${Math.random().toString(36).slice(2)}`}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}async writeReceiveAckBestEffort(e,t,n,i,o){if(!this.disposed)try{await this.deps.writeNativeMainReceiveAck(e,t,n);}catch(s){if(this.disposed)return;console.warn("[Client][NATIVE-MAIN] Failed to ack native main message",{remoteNodeId:i,channel:t.channel,action:t.action,source:o,error:s});}}};var Ut=class{constructor(e,t,n=[0,250,1e3,2500]){this.maxPerNode=e;this.ttlMs=t;this.retryDelaysMs=n;this.pendingByNodeId=new Map;this.retryTimers=new Set;this.disposed=false;}queue(e,t,n,i,o){if(this.disposed)return;let s=this.pendingByNodeId.get(e)??[];s.push({content:t,source:n,traceId:i??null,receivedAtMs:Date.now()}),s.length>this.maxPerNode&&s.splice(0,s.length-this.maxPerNode),this.pendingByNodeId.set(e,s),c$1("[Client][NATIVE-MAIN] Queued native WebRTC signal until control connection is registered",{remoteNodeId:e,signalType:t?.type??null,source:n,traceId:i||null,pendingCount:s.length});for(let a of this.retryDelaysMs){let c=setTimeout(()=>{this.retryTimers.delete(c),!this.disposed&&o(e,`queued-signal-retry:${a}`);},a);this.retryTimers.add(c);}}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear(),this.pendingByNodeId.clear();}}async flush(e,t,n){if(this.disposed)return false;let i=this.pendingByNodeId.get(e);if(!i||i.length===0)return false;let o=n.findManualDisconnectProjectionForNativeNode(e);if(o)return this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Dropped queued native WebRTC signals for manually disconnected peer",{remoteNodeId:e,peerId:o.peerId,droppedCount:i.length,trigger:t}),false;let s=n.findLiveConnectionForRemoteNode(e);if(s||(s=await n.ensureIncomingConnectionForRemoteNode(e).catch(()=>null)),this.disposed)return false;if(!s){let a=Date.now(),c=i.filter(l=>a-l.receivedAtMs<=this.ttlMs);return c.length===0?(this.pendingByNodeId.delete(e),console.warn("[Client][NATIVE-MAIN] Dropping queued native WebRTC signals after control connection did not appear",{remoteNodeId:e,trigger:t,droppedCount:i.length})):c.length!==i.length&&this.pendingByNodeId.set(e,c),false}this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Replaying queued native WebRTC signals to Connection",{remoteNodeId:e,connectionId:s.id,trigger:t,count:i.length});for(let a of i){if(this.disposed)return false;s.receiveInternalSignal(a.content);}return true}};var jt=class{constructor(e){this.deps=e;this.disposed=false;}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Native main signal sender is disposed")}async openNativeSignalBiStream(e,t){this.assertActive();let n=e.open_native_main_control_bi;if(typeof n=="function"){let i=await n.call(e,t);return this.assertActive(),i}throw new Error("[Client][NATIVE-MAIN] open_native_main_control_bi is unavailable on this WASM build; native-main signaling cannot open a control stream under mandatory application crypto. Rebuild the openrtc WASM (pnpm --filter openrtc build:wasm).")}async sendViaDedicatedStream(e,t,n,i){this.assertActive();let o=await this.openNativeSignalBiStream(e,t);this.assertActive();let s=o.send.getWriter();try{if(await s.write(Ue()),this.disposed)return;await s.write(re(fe(i)));}catch(a){throw console.warn("[Client][NATIVE-MAIN] Dedicated-stream signal send failed",{remoteNodeId:t,signalType:i?.content?.type??null,error:a}),a}finally{try{s.releaseLock();}catch{}}}async sendEnvelope(e,t,n,i){if(this.disposed)return;let o=n?.content?.transport??null,s=n?.content?.type??null,a=o==="webrtc"&&(s==="sdp"||s==="candidate"||s==="renegotiate"),c=n?.type==="handshake",l=a&&e.getUpgradeState()==="upgrading"||c,d=this.deps.isSessionTokenApprovedNode(t)&&this.deps.isSessionTokenApprovedConnection(e.id),p=d||l,u=this.deps.isSessionTokenApprovedNode(t),f=this.deps.isSessionTokenApprovedConnection(e.id),h=await this.deps.sendViaInboundControlStream(t,n,{ignoreCooldown:l});if(!this.disposed){if(h.sent){if(c$1("[Client][NATIVE-MAIN] Sent native signal over inbound control stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,writerId:h.writerId,writerAgeMs:h.writerAgeMs}),c$1("[Client][NATIVE-MAIN] Signal route=inbound-control",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,writerId:h.writerId,writerAgeMs:h.writerAgeMs}),c$1("[SIGNAL-STREAM][TS] reply-on-persistent-writer",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,writerId:h.writerId,writerAgeMs:h.writerAgeMs}),l&&p&&s!=="renegotiate")try{if(await this.sendViaDedicatedStream(i,t,e,n),this.disposed)return;c$1("[Client][NATIVE-MAIN] Signal route=dedicated-open_bi-mirror",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null});}catch(y){console.warn("[Client][NATIVE-MAIN] Recovery dedicated-stream mirror send failed",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,error:y});}return}if(c$1("[Client][NATIVE-MAIN] Signal route=inbound-control-unavailable",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,reason:h.reason,writerId:h.writerId,writerAgeMs:h.writerAgeMs,inboundError:h.error,hasApprovedNode:u,hasApprovedConnectionId:f,hasApprovedDedicatedStream:d,preferDedicatedSignalPath:l,canUseDedicatedStream:p}),p)try{if(await this.sendViaDedicatedStream(i,t,e,n),this.disposed)return;c$1("[Client][NATIVE-MAIN] Sent native signal over dedicated stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null}),c$1("[Client][NATIVE-MAIN] Signal route=dedicated-open_bi",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,inboundFallbackReason:h.reason});return}catch(m){console.warn("[Client][NATIVE-MAIN] Dedicated-stream signal send failed; falling back to control stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,error:m});}try{if(this.disposed||(await e.sendRawIrohFrame(re(fe(n))),this.disposed))return;c$1("[Client][NATIVE-MAIN] Sent native signal over control stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null}),c$1("[Client][NATIVE-MAIN] Signal route=cached-control-writer",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,inboundFallbackReason:h.reason});return}catch(m){if(console.warn("[Client][NATIVE-MAIN] Control-stream signal send failed",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,error:m}),!p)throw m}this.disposed||(await this.sendViaDedicatedStream(i,t,e,n),!this.disposed&&(c$1("[Client][NATIVE-MAIN] Sent native signal over dedicated stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null}),c$1("[Client][NATIVE-MAIN] Signal route=dedicated-open_bi-fallback",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,inboundFallbackReason:h.reason})));}}};var Gt=class{constructor(){this.writers=new Map;this.writeMutexes=new Map;this.writerMeta=new Map;this.bypassUntilMs=new Map;this.writerSeq=0;this.disposed=false;}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.writers.values())try{e.releaseLock();}catch{}this.writers.clear(),this.writeMutexes.clear(),this.writerMeta.clear(),this.bypassUntilMs.clear();}}registerInboundWriter(e,t){if(this.disposed){try{t.releaseLock();}catch{}return}let n=this.writers instanceof Map?this.writers:null,i=this.writerMeta instanceof Map?this.writerMeta:null;if(!n||!e||!t)return;let o=n.get(e);this.writerSeq+=1;let s=this.writerSeq;n.set(e,t),i?.set(e,{id:s,registeredAtMs:Date.now()}),this.bypassUntilMs instanceof Map&&this.bypassUntilMs.delete(e),c$1("[Client][NATIVE-MAIN] Inbound control writer registered",{remoteNodeId:e,writerId:s,replacedExistingWriter:!!o&&o!==t}),c$1("[SIGNAL-STREAM][TS] writer-registered",{remoteNodeId:e,writerId:s,replacedExistingWriter:!!o&&o!==t});}clearInboundWriter(e,t,n,i="stream-finalize"){if(this.disposed)return;let o=this.writers instanceof Map?this.writers:null,s=this.writeMutexes instanceof Map?this.writeMutexes:null,a=this.writerMeta instanceof Map?this.writerMeta:null;if(!o||!s)return;let c=o.get(e),l=a?.get(e);c===t?(o.delete(e),a?.delete(e),this.bypassUntilMs.set(e,Date.now()+n),c$1("[Client][NATIVE-MAIN] Inbound control writer cleared",{remoteNodeId:e,writerId:l?.id??null,ageMs:l?Date.now()-l.registeredAtMs:null,reason:i}),c$1("[SIGNAL-STREAM][TS] writer-cleared",{remoteNodeId:e,writerId:l?.id??null,ageMs:l?Date.now()-l.registeredAtMs:null,reason:i})):c$1("[Client][NATIVE-MAIN] Inbound control writer clear skipped (mismatch)",{remoteNodeId:e,activeWriterId:l?.id??null,reason:i}),s.delete(e);}async sendViaInboundControlStream(e,t,n,i={}){if(this.disposed)return {sent:false,reason:"writer-registry-disposed",writerId:null,writerAgeMs:null,error:null};let o=this.writers instanceof Map?this.writers:null,s=this.writeMutexes instanceof Map?this.writeMutexes:null,a=this.writerMeta instanceof Map?this.writerMeta:null;if(!o||!s)return {sent:false,reason:"writer-or-mutex-map-unavailable",writerId:null,writerAgeMs:null,error:null};let c=a?.get(e),l=this.bypassUntilMs instanceof Map?this.bypassUntilMs:null,d=l?.get(e)??0;if(!i.ignoreCooldown&&d>Date.now())return {sent:false,reason:"inbound-writer-cooldown",writerId:c?.id??null,writerAgeMs:c?Date.now()-c.registeredAtMs:null,error:null};let p=o.get(e),u=c?.id??null,f=c?Date.now()-c.registeredAtMs:null;if(!p)return l?.set(e,Date.now()+n),{sent:false,reason:"no-inbound-writer",writerId:u,writerAgeMs:f,error:null};let h=re(fe(t)),m=s.get(e)??Promise.resolve(),y,v=new Promise(P=>{y=P;});s.set(e,v);try{return await m.catch(()=>{}),await p.write(h),{sent:!0,reason:"sent",writerId:u,writerAgeMs:f,error:null}}catch(P){return l?.set(e,Date.now()+n),console.warn("[Client][NATIVE-MAIN] Inbound control-stream signal send failed",{remoteNodeId:e,signalType:t?.content?.type??null,writerId:u,writerAgeMs:f,error:P}),{sent:false,reason:"inbound-writer-write-failed",writerId:u,writerAgeMs:f,error:P?.message??String(P)}}finally{y(),s.get(e)===v&&s.delete(e);}}};var Kt=class{constructor(e,t,n){this.deps=e;this.protocolConfig=t;this.timingConfig=n;this.writers=new Gt;this.disposed=false;this.messageIO=new Ot({eventName:t.eventName,protocolByte:t.protocolByte,label:t.label,maxLabelBytes:t.maxLabelBytes,maxFrameBytes:t.maxFrameBytes},{getReceiverDeviceId:()=>e.getReceiverDeviceId(),getRemoteDeviceId:i=>e.getKnownDeviceIdForNode(i)}),this.handshakeQueue=new Wt(n.pendingHandshakeMaxPerNode,n.pendingHandshakeTtlMs),this.signalQueue=new Ut(n.pendingHandshakeMaxPerNode,n.pendingHandshakeTtlMs),this.deps.registerDisposer(()=>this.dispose());}get writerRegistry(){return this.writers}get connectionController(){return this.getConnections()}get handshakeQueueController(){return this.handshakeQueue}get messageIOController(){return this.messageIO}get payloadRouterController(){return this.getPayloadRouter()}dispose(){this.disposed=true,this.handshakeQueue.dispose(),this.signalQueue.dispose(),this.admission?.dispose(),this.connections?.dispose(),this.payloadRouter?.dispose(),this.writers.dispose(),this.signalSender?.dispose();}retirePendingReciprocalAdmissions(e){this.admission?.retirePendingReciprocalAdmissions(e);}async acceptNativeMessage(e,t,n){return this.disposed?false:this.getAdmission().acceptNativeMessage(e,t,n)}tryHandleNativeMainUniStream(e,t,n){return this.disposed?Promise.resolve(false):this.getPayloadRouter().tryHandleNativeMainUniStream(e,t,n)}handleNativeMainStream(e,t,n){return this.disposed?Promise.resolve():Number.isSafeInteger(n)&&Number(n)>0?this.getPayloadRouter().handleNativeMainStream(e,t,n):this.getPayloadRouter().handleNativeMainStream(e,t)}writeLabelHeaderOnBiStream(e,t){return this.disposed?Promise.resolve():this.messageIO.writeLabelHeaderOnBiStream(e,t)}openSignalBiStream(e,t){return this.disposed?Promise.reject(new Error("Native main controller is disposed")):this.getSignalSender().openNativeSignalBiStream(e,t)}async sendSignalEnvelope(e,t,n,i){this.disposed||(await this.getSignalSender().sendEnvelope(e,t,n,i),this.disposed||e.handleBaseTransportAvailable("native-main-control-send"));}ensureIncomingConnectionForRemoteNode(e){return this.disposed?Promise.resolve(null):this.getConnections().ensureIncomingConnectionForRemoteNode(e)}flushPendingHandshakesForNode(e,t){return this.disposed?Promise.resolve(false):this.handshakeQueue.flush(e,t,{findManualDisconnectProjectionForNativeNode:n=>this.deps.findManualDisconnectProjectionForNativeNode(n),findLiveConnectionForRemoteNode:n=>this.deps.findLiveConnectionForRemoteNode(n),ensureIncomingConnectionForRemoteNode:n=>this.deps.ensureIncomingConnectionForRemoteNode(n),handleMessage:(n,i)=>Promise.resolve(this.deps.handleMessage(n,i))})}flushPendingSignalsForNode(e,t){return this.disposed?Promise.resolve(false):this.signalQueue.flush(e,t,{findManualDisconnectProjectionForNativeNode:n=>this.deps.findManualDisconnectProjectionForNativeNode(n),findLiveConnectionForRemoteNode:n=>this.deps.findLiveConnectionForRemoteNode(n),ensureIncomingConnectionForRemoteNode:n=>this.deps.ensureIncomingConnectionForRemoteNode(n)})}getSignalSender(){return this.signalSender||(this.signalSender=new jt({isSessionTokenApprovedNode:e=>this.deps.isSessionTokenApprovedNode(e),isSessionTokenApprovedConnection:e=>this.deps.isSessionTokenApprovedConnection(e),sendViaInboundControlStream:(e,t,n)=>this.writers.sendViaInboundControlStream(e,t,this.timingConfig.inboundWriterRetryCooldownMs,n)}),this.disposed&&this.signalSender.dispose()),this.signalSender}getConnections(){return this.connections||(this.connections=new Bt({getDeterministicConnectionId:e=>this.deps.getDeterministicConnectionId(e),getConnection:e=>this.deps.getConnection(e),getWasmClient:()=>this.deps.getWasmClient(),getLocalNodeId:()=>this.deps.getLocalNodeId(),getKnownDeviceIdForNode:e=>this.deps.getKnownDeviceIdForNode(e),getKnownDevicePlatform:(e,t)=>this.deps.getKnownDevicePlatform(e,t),isNativeMainPeerPlatform:e=>this.deps.isNativeMainPeerPlatform(e),getTrustFailureCooldown:e=>this.deps.getTrustFailureCooldown(e),getTrustFailureCooldownMs:()=>this.timingConfig.trustFailureCooldownMs,isSessionTokenApprovedNode:e=>this.deps.isSessionTokenApprovedNode(e),openNativeSignalBiStream:(e,t)=>this.openSignalBiStream(e,t),writeNativeMainLabelHeaderOnBiStream:(e,t)=>this.writeLabelHeaderOnBiStream(e,t),sendNativeSignalEnvelope:(e,t,n,i)=>this.sendSignalEnvelope(e,t,n,i),getRTCConfig:()=>this.deps.getRTCConfig(),createTransportContext:e=>this.deps.createTransportContext(e),getApplicationCrypto:()=>this.deps.getApplicationCrypto(),shouldNegotiateApplicationKeyAgreement:()=>this.deps.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(e,t,n)=>this.deps.handleConnectionTransportStatus(e,t,n??null),handleConnectionApplicationRouteMissing:(e,t)=>this.deps.handleConnectionApplicationRouteMissing(e,t),initializeConnectionTrust:(e,t)=>{this.deps.initializeConnectionTrust(e,t);},markConnectionTrustVerified:(e,t)=>{this.deps.markConnectionTrustVerified(e,t);},registerConnection:e=>this.deps.registerConnection(e),announceConnectionWhenStable:e=>this.deps.announceConnectionWhenStable(e),sendTransportHandshake:(e,t)=>this.deps.sendTransportHandshake(e,t),requestProtectedWebRTCUpgradeIfInitiator:(e,t)=>this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,t),getConnectionChannelId:e=>this.deps.getConnectionChannelId(e),isWebRTCTransportEnabled:()=>this.deps.isWebRTCTransportEnabled()}),this.disposed&&this.connections.dispose()),this.connections}getAdmission(){return this.admission||(this.admission=new _t({getDeterministicConnectionId:e=>this.deps.getDeterministicConnectionId(e),getNativeMainConnectionId:e=>this.deps.getNativeMainConnectionId(e),getConnection:e=>this.deps.getConnection(e),handleMessage:(e,t)=>this.deps.handleMessage(e,t),getLocalDeviceId:()=>this.deps.getLocalDeviceId(),getFallbackLocalDeviceId:()=>this.deps.getFallbackLocalDeviceId(),getConfiguredDeviceName:()=>this.deps.getConfiguredDeviceName(),getNativeMainProtocolVersion:()=>this.protocolConfig.protocolVersion,isNativeRuntime:()=>this.deps.isNativeRuntime(),isLikelyMobileBrowser:()=>this.deps.isLikelyMobileBrowser(),writeNativeMainMessage:(e,t)=>this.messageIO.writeLabeledMessage(e,t),validateIncomingSessionToken:(e,t,n)=>this.deps.validateIncomingSessionToken(e,t,n),applySessionTokenTrustApproval:(e,t,n)=>this.deps.applySessionTokenTrustApproval(e,t,n),rememberPendingSessionTokenTrustApproval:(e,t)=>this.deps.rememberPendingSessionTokenTrustApproval(e,t),markSessionTokenApprovedNode:e=>this.deps.markSessionTokenApprovedNode(e),markSessionTokenApprovedConnection:e=>this.deps.markSessionTokenApprovedConnection(e),clearSessionTokenRejectionCooldown:e=>this.deps.clearSessionTokenRejectionCooldown(e),getSessionTokenRejectionCooldown:e=>this.deps.getSessionTokenRejectionCooldown(e),setSessionTokenRejectionCooldown:(e,t)=>this.deps.setSessionTokenRejectionCooldown(e,t),clearTrustFailureCooldown:e=>{this.deps.clearTrustFailureCooldown(e);},schedulePeerReconciliation:e=>this.deps.schedulePeerReconciliation(e),ensureIncomingConnectionForRemoteNode:e=>this.deps.ensureIncomingConnectionForRemoteNode(e),getReciprocalSessionAdmission:(e,t,n,i,o)=>this.deps.getReciprocalSessionAdmission(e,t,n,i,o),presentLegacyReciprocalSessionAdmission:e=>this.deps.presentLegacyReciprocalSessionAdmission(e),confirmReciprocalSessionAdmission:(e,t,n,i,o,s)=>this.deps.confirmReciprocalSessionAdmission(e,t,n,i,o,s),disconnectRemoteNode:e=>this.deps.disconnectRemoteNode(e)}),this.disposed&&this.admission.dispose()),this.admission}getPayloadRouter(){return this.payloadRouter||(this.payloadRouter=new Ht({getProtocolConfig:()=>this.messageIO.protocolConfig(),registerInboundNativeMainWriter:(e,t)=>this.writers.registerInboundWriter(e,t),clearInboundNativeMainWriter:(e,t,n)=>this.writers.clearInboundWriter(e,t,this.timingConfig.inboundWriterRetryCooldownMs,n),schedulePeerReconciliation:e=>this.deps.schedulePeerReconciliation(e),ensureIncomingConnectionForRemoteNode:e=>this.deps.ensureIncomingConnectionForRemoteNode(e),queuePendingNativeMainHandshake:(e,t,n,i)=>this.handshakeQueue.queue(e,t,n,i,(o,s)=>{this.flushPendingHandshakesForNode(o,s);}),queuePendingNativeMainSignal:(e,t,n,i)=>this.signalQueue.queue(e,t,n,i,(o,s)=>{this.flushPendingSignalsForNode(o,s);}),findManualDisconnectProjectionForNativeNode:e=>this.deps.findManualDisconnectProjectionForNativeNode(e),handleMessage:(e,t)=>this.deps.handleMessage(e,t),handleNativeHandshakeRequest:(e,t,n)=>this.getAdmission().handleHandshakeRequest(e,t,n),handleNativeSessionTokenRequest:(e,t,n,i,o)=>this.getAdmission().handleSessionTokenRequest(e,t,n,i,o),handleNativeSessionTokenResponseAck:(e,t,n,i)=>this.getAdmission().handleSessionTokenResponseAck(e,t,n,i),handleNativeMainStreamClosed:(e,t,n)=>this.getAdmission().handleNativeMainStreamClosed(e,t,n),dispatchNativeMainMessage:(e,t)=>this.messageIO.dispatchMessage(e,t),writeNativeMainReceiveAck:(e,t,n)=>this.messageIO.writeAck(e,t,n)}),this.disposed&&this.payloadRouter.dispose()),this.payloadRouter}};function ir(r){let{host:e}=r;return new Kt({registerDisposer:t=>e.registerDisposer(t),getDeterministicConnectionId:t=>e.getDeterministicConnectionId(t),getNativeMainConnectionId:t=>e.getNativeMainConnectionId(t),getConnection:t=>e.getConnection(t),getWasmClient:()=>e.getWasmClient(),getLocalNodeId:()=>e.getLocalNodeId(),getReceiverDeviceId:()=>e.getDeviceId()??e.getOptions().localDeviceId??null,getKnownDeviceIdForNode:t=>e.getKnownDeviceIdForNode(t),getKnownDevicePlatform:(t,n)=>e.getKnownDevicePlatform(t,n),isNativeMainPeerPlatform:t=>Ho(t),getTrustFailureCooldown:t=>e.getTrustFailureCooldown(t),isSessionTokenApprovedNode:t=>e.isSessionTokenApprovedNode(t),isSessionTokenApprovedConnection:t=>e.isSessionTokenApprovedConnection(t),getRTCConfig:()=>k$1(e.getOptions(),t=>c$1(t)),createTransportContext:t=>e.createTransportContext(t),getApplicationCrypto:()=>e.getApplicationCrypto(),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(t,n,i)=>e.handleConnectionTransportStatus(t,n,i??null),handleConnectionApplicationRouteMissing:(t,n)=>e.handleConnectionApplicationRouteMissing(t,n),initializeConnectionTrust:(t,n)=>{e.initializeConnectionTrust(t,n);},markConnectionTrustVerified:(t,n)=>{e.markConnectionTrustVerified(t,n);},registerConnection:t=>e.registerConnection(t),announceConnectionWhenStable:t=>e.announceConnectionWhenStable(t),sendTransportHandshake:(t,n)=>e.sendTransportHandshake(t,n),requestProtectedWebRTCUpgradeIfInitiator:(t,n)=>e.requestProtectedWebRTCUpgradeIfInitiator(t,n),getConnectionChannelId:t=>e.getConnectionChannelId(t),isWebRTCTransportEnabled:()=>j(e.getOptions()),getLocalDeviceId:()=>e.getLocalDeviceId(),getFallbackLocalDeviceId:()=>e.getDeviceId()||e.getOptions().localDeviceId||null,getConfiguredDeviceName:()=>e.getOptions().deviceName,isNativeRuntime:()=>typeof window<"u"&&typeof window.__TAURI__<"u",isLikelyMobileBrowser:()=>oe(),validateIncomingSessionToken:(t,n,i)=>e.validateIncomingSessionToken(t,n,i),applySessionTokenTrustApproval:(t,n,i)=>e.applySessionTokenTrustApproval(t,n,i),rememberPendingSessionTokenTrustApproval:(t,n)=>e.rememberPendingSessionTokenTrustApproval(t,n),markSessionTokenApprovedNode:t=>e.markSessionTokenApprovedNode(t),markSessionTokenApprovedConnection:t=>e.markSessionTokenApprovedConnection(t),clearSessionTokenRejectionCooldown:t=>e.clearSessionTokenRejectionCooldown(t),getSessionTokenRejectionCooldown:t=>e.getSessionTokenRejectionCooldown(t),setSessionTokenRejectionCooldown:(t,n)=>e.setSessionTokenRejectionCooldown(t,n),clearTrustFailureCooldown:t=>{e.clearTrustFailureCooldown(t);},schedulePeerReconciliation:t=>e.schedulePeerReconciliation(t),ensureIncomingConnectionForRemoteNode:t=>r.getController().ensureIncomingConnectionForRemoteNode(t),getReciprocalSessionAdmission:async(t,n,i,o,s)=>{let a=e.getRouteRepairSessionTokenForNode(t),c=e.getRouteRepairSessionTokenPayloadForNode(t);if(!a||!c)throw new Error("pending reciprocal session token is unavailable");let l=await e.getLocalDeviceId().catch(()=>null);if(!l)throw new Error("local device identity is unavailable for reciprocal admission");let d=e.getWasmClient();if(typeof d?.prepare_inline_reciprocal_session_admission!="function")throw new Error("WASM runtime does not support inline reciprocal admission");return await d.prepare_inline_reciprocal_session_admission(t,BigInt(i),o,s,a,c,l,n),{token:a,tokenPayload:c,deviceId:l,streamContract:n}},presentLegacyReciprocalSessionAdmission:async t=>{let n=e.getWasmClient(),i=e.getRouteRepairSessionTokenForNode(t),o=e.getRouteRepairSessionTokenPayloadForNode(t);if(!i||!o)throw new Error("pending reciprocal session token is unavailable");let s=await e.getLocalDeviceId().catch(()=>null);if(typeof n?.present_session_token_to_host_with_payload_and_device_id=="function"){await n.present_session_token_to_host_with_payload_and_device_id(t,i,o,s);return}throw new Error("WASM runtime does not support legacy reciprocal session admission")},confirmReciprocalSessionAdmission:async(t,n,i,o,s,a)=>{let c=e.getWasmClient();return typeof c?.confirm_inline_reciprocal_session_admission!="function"?false:c.confirm_inline_reciprocal_session_admission(t,BigInt(n),i,o,s,a)},disconnectRemoteNode:t=>e.disconnectRemoteNode(t),findManualDisconnectProjectionForNativeNode:t=>e.findManualDisconnectProjectionForNativeNode(t),findLiveConnectionForRemoteNode:t=>e.findLiveConnectionForRemoteNode(t),handleMessage:(t,n)=>e.handleMessage(t,n)},{eventName:mo,protocolByte:at,label:ct,maxLabelBytes:lt,maxFrameBytes:go,protocolVersion:ho},{trustFailureCooldownMs:vo,inboundWriterRetryCooldownMs:Co,pendingHandshakeTtlMs:fo,pendingHandshakeMaxPerNode:yo})}function or(r){return new oi({registerDisposer:e=>r.lifecycleScope.register(e),getOptions:()=>r.options,getWasmClient:()=>r.wasmClient,getLocalNodeId:()=>r.localNodeId,getDeviceId:()=>r.deviceId,getDeterministicConnectionId:e=>r.peerIdentity.getDeterministicConnectionId(e),getNativeMainConnectionId:e=>r.peerIdentity.getNativeMainConnectionId(e),getConnection:e=>r.registry.get(e),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),getKnownDevicePlatform:(e,t)=>r.deviceDirectory.getKnownDevicePlatform(e,t),getTrustFailureCooldown:e=>r.connectionTrust.getFailureCooldown(e),getRouteRepairSessionTokenForNode:e=>r.sessionTokens.getRouteRepairTokenForNode(e),getRouteRepairSessionTokenPayloadForNode:e=>r.sessionTokens.getRouteRepairTokenPayloadForNode(e),isSessionTokenApprovedNode:e=>r.sessionTokens.isApprovedNode(e),isSessionTokenApprovedConnection:e=>r.sessionTokens.isApprovedConnection(e),createTransportContext:e=>r.transportContexts.create(e),getApplicationCrypto:()=>r.options?.applicationCrypto,shouldNegotiateApplicationKeyAgreement:()=>r.applicationCrypto.shouldNegotiateKeyAgreement(),handleConnectionTransportStatus:(e,t,n)=>r.transportHealth.handleCurrentConnectionTransportStatus(e,t,n),handleConnectionApplicationRouteMissing:(e,t)=>r.transportUpgrade.handleApplicationRouteMissing(e,t),initializeConnectionTrust:(e,t)=>{r.connectionTrust.initialize(e,t);},markConnectionTrustVerified:(e,t)=>{r.connectionTrust.markVerified(e,t);},registerConnection:e=>r.connectionLifecycle.registerConnection(e),announceConnectionWhenStable:e=>r.connectionLifecycle.announceConnectionWhenStable(e),sendTransportHandshake:(e,t)=>r.transportHandshake.sendTransportHandshake(e,t),requestProtectedWebRTCUpgradeIfInitiator:(e,t)=>r.transportHandshake.requestProtectedWebRTCUpgradeIfInitiator(e,t),getConnectionChannelId:e=>r.connectionChannelPolicy.getConnectionChannelId(e),getLocalDeviceId:()=>r.signalingBackendController.getLocalDeviceId(),validateIncomingSessionToken:(e,t,n)=>r.sessionTokens.validateIncomingSessionTokenWithRetry(e,t,n),applySessionTokenTrustApproval:(e,t,n)=>r.sessionTokens.applyTrustApproval(e,t,n),rememberPendingSessionTokenTrustApproval:(e,t)=>r.sessionTokens.rememberPendingTrustApproval(e,t),markSessionTokenApprovedNode:e=>r.sessionTokens.approveNode(e),markSessionTokenApprovedConnection:e=>r.sessionTokens.approveConnection(e),clearSessionTokenRejectionCooldown:e=>r.sessionTokens.clearRejectionCooldown(e),getSessionTokenRejectionCooldown:e=>r.sessionTokens.getRejectionCooldown(e),setSessionTokenRejectionCooldown:(e,t)=>r.sessionTokens.setRejectionCooldown(e,t),clearTrustFailureCooldown:e=>{r.connectionTrust.clearFailureCooldown(e);},schedulePeerReconciliation:e=>r.peerProjection.schedule(e),disconnectRemoteNode:e=>r.runtimeConnections.disconnectNodeBestEffort(e),findManualDisconnectProjectionForNativeNode:e=>r.peerIdentity.findManualDisconnectProjectionForNativeNode(e),findLiveConnectionForRemoteNode:e=>{let t=r.peerIdentity.getDeterministicConnectionId(e);return r.connectionLifecycle.findLiveConnectionForRemoteNode(e,t)},handleMessage:(e,t)=>r.connectionMessageHandler.handleMessage(e,t)})}var oi=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getController:()=>this.controller}}get controller(){return this._controller??(this._controller=ir(this.factoryHost))}writeLabelHeaderOnBiStream(e,t){return this.controller.writeLabelHeaderOnBiStream(e,t)}flushPendingHandshakesForNode(e,t){return this.controller.flushPendingHandshakesForNode(e,t)}flushPendingSignalsForNode(e,t){return this.controller.flushPendingSignalsForNode(e,t)}};var qt=class{constructor(e,t){this.peerLifecycle=e;this.deps=t;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}watchPeerStates(e){return this.peerLifecycle.watch(e)}getPeerState(e){return this.peerLifecycle.get(e)}listConnectedPeers(){return this.peerLifecycle.listConnected()}isPeerPromotionEligible(e){return this.deps.resolvePromotionEligibility(e)}addPeerScope(e,t="persistent"){let n=this.deps.getWasmClient();return n&&typeof n.add_peer_scope=="function"?(n.add_peer_scope(e,t).then(()=>{this.disposed||this.deps.scheduleRefreshPeerSnapshot();}).catch(()=>{}),this.peerLifecycle.get(e)):this.peerLifecycle.addScope(e,t)}releasePeerScope(e,t){let n=this.deps.getWasmClient();return n&&typeof n.release_peer_scope=="function"?(n.release_peer_scope(e,t??null).then(()=>{this.disposed||this.deps.scheduleRefreshPeerSnapshot();}).catch(()=>{}),this.peerLifecycle.get(e)):this.peerLifecycle.releaseScope(e,t)}getPeerScopes(e){return this.peerLifecycle.get(e)?.scopes??[]}isSamePeer(e,t){let n=this.peerLifecycle.get(e),i=this.peerLifecycle.get(t);return n&&i?n.peerId===i.peerId:false}clearManualDisconnectProjection(e){let t=this.peerLifecycle.get(e);this.peerLifecycle.dispatch({type:"ManualDisconnectCleared",peerId:t?.peerId??e,deviceId:t?.deviceId??e,deviceIdHint:t?.deviceIdHint,nodeId:t?.nodeId,connectionId:t?.connectionId});}async disconnectPeer(e,t="persistent"){let n=this.peerLifecycle.releaseScope(e,t);n&&n.scopes.length>0||await this.forceDisconnectPeer(e);}async forceDisconnectPeer(e){let t=this.peerLifecycle.releaseScope(e),n=this.getPeerCandidates(t?.peerId||e);if(await Promise.allSettled(Array.from(n).map(async i=>{let o=Array.from(this.deps.getConnections()).filter(a=>{let c=a.id.trim().toLowerCase(),l=a.deviceId.trim().toLowerCase();return i===l||i===c||c.includes(i)});await Promise.allSettled(o.map(a=>a.disconnect()));let s=t?.nodeId||(o[0]?.deviceId??null);s&&i===s.trim().toLowerCase()&&await this.deps.disconnectNode(s).catch(()=>{});})),this.deps.hasRustPeerLifecycleProjection()){if(this.disposed)return;await this.deps.schedulePeerReconciliation("disconnect-node").catch(()=>{});}this.disposed||this.peerLifecycle.dispatch({type:"ManualDisconnect",peerId:t?.peerId??e,deviceId:t?.deviceId,deviceIdHint:t?.deviceIdHint,nodeId:t?.nodeId,connectionId:t?.connectionId});}async getPeerHealth(e){let t=this.peerLifecycle.get(e);return t?t.health:"unknown"}getPeerCandidates(e){let t=this.peerLifecycle.get(e),n=new Set;return [e,t?.peerId,t?.deviceId,t?.nodeId,t?.connectionId,...t?.connectionIds??[]].forEach(o=>{if(!o)return;let s=o.trim().toLowerCase();s&&n.add(s);}),n}};function ye(r){if(!r)return null;let e=r.trim();return e?e.toLowerCase():null}function ri(r){return r.deviceId||r.deviceIdHint||r.peerId||null}function zt(r){return [...r].sort()}function Re(r,e){return r?r.peerId===e.peerId&&(r.deviceId??null)===(e.deviceId??null)&&(r.deviceIdHint??null)===(e.deviceIdHint??null)&&(r.nodeId??null)===(e.nodeId??null)&&(r.connectionId??null)===(e.connectionId??null)&&(r.ticket??null)===(e.ticket??null)&&!!r.online==!!e.online&&(r.deviceName??null)===(e.deviceName??null)&&(r.platformType??null)===(e.platformType??null)&&r.status===e.status&&r.health===e.health&&(r.lifecycleStage??null)===(e.lifecycleStage??null)&&(r.generation??null)===(e.generation??null)&&(r.baseTransportState??null)===(e.baseTransportState??null)&&(r.admissionState??null)===(e.admissionState??null)&&(r.transportState??null)===(e.transportState??null)&&(r.protocolState??null)===(e.protocolState??null)&&(r.webrtcState??null)===(e.webrtcState??null)&&!!r.routable==!!e.routable&&(r.activeTransportStableId??null)===(e.activeTransportStableId??null)&&(r.transportGeneration??null)===(e.transportGeneration??null)&&(r.routeGeneration??null)===(e.routeGeneration??null)&&(r.activeTransport??null)===(e.activeTransport??null)&&(r.fallbackTransport??null)===(e.fallbackTransport??null)&&(r.parallelTransport??null)===(e.parallelTransport??null)&&!!r.manualDisconnect==!!e.manualDisconnect&&(r.lastAuthoritativeEventAt??null)===(e.lastAuthoritativeEventAt??null)&&(r.lastTransientEventAt??null)===(e.lastTransientEventAt??null)&&(r.promotionEligible??true)===(e.promotionEligible??true)&&(r.error??null)===(e.error??null)&&JSON.stringify(zt(r.connectionIds))===JSON.stringify(zt(e.connectionIds))&&JSON.stringify(zt(r.scopes))===JSON.stringify(zt(e.scopes)):false}function Pe(r){return r==="closed"||r==="disconnected"||r==="failed"}function rr(r){let{status:e,health:t,lifecycleStage:n,generation:i,baseTransportState:o,admissionState:s,transportState:a,protocolState:c,webrtcState:l,routable:d,activeTransportStableId:p,transportGeneration:u,routeGeneration:f,activeTransport:h,fallbackTransport:m,parallelTransport:y,connectionId:v,error:P,...I}=r;return I}function cr(r){if(Pe(r.status))return "closed";let e=(r.transportState??"").trim().toLowerCase();return e==="connected"||r.connectionId||r.activeTransport?"connected":e==="connecting"||r.status==="connecting"?"connecting":e==="failed"||e==="degraded"?"degraded":"unknown"}function je(r){return Pe(r.status)||r.webrtcState!=="ready"||!r.connectionId||r.activeTransportStableId===null||r.activeTransportStableId===void 0||r.health!=="healthy"||r.transportState!=="connected"?false:[r.activeTransport,r.parallelTransport].filter(t=>typeof t=="string").some(f$1)}function sr(r){return f$1(r)}function si(r){return Pe(r.status)?"closed":je(r)?"ready":r.webrtcState?r.webrtcState:[r.activeTransport,r.parallelTransport].filter(t=>typeof t=="string").some(f$1)?r.transportState==="connected"?"transport-open":"connecting":"unknown"}function $s(r){if(r.manualDisconnect||Pe(r.status))return "closed";let e=si(r);if(e==="ready")return "webrtc-ready";if(e==="connecting"||e==="transport-open"||e==="route-probing")return "upgrading";if(r.routable===true||r.protocolState==="routable")return "protocol-ready";if(r.admissionState==="admitted")return "admitted";let t=r.baseTransportState??cr(r);return t==="connected"?"base-connected":t==="degraded"||r.health==="suspect"||r.health==="stale"?"degraded":r.status==="connecting"?"dialing":"discovered"}function Vs(r){return Pe(r.status)?r.status:r.routable===true||r.protocolState==="routable"||je(r)?"connected":r.status}function ar(r){return {peerId:r.peerId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,nodeId:r.nodeId??null,connectionId:r.connectionId??null,status:r.status,health:r.health,lifecycleStage:r.lifecycleStage??null,generation:r.generation??null,baseTransportState:r.baseTransportState??null,admissionState:r.admissionState??null,transportState:r.transportState??null,protocolState:r.protocolState??null,webrtcState:r.webrtcState??null,routable:r.routable??null,activeTransportStableId:r.activeTransportStableId??null,transportGeneration:r.transportGeneration??null,routeGeneration:r.routeGeneration??null,activeTransport:r.activeTransport??null,parallelTransport:r.parallelTransport??null,manualDisconnect:r.manualDisconnect??false,scopes:r.scopes,error:r.error??null}}function Ys(r,e,t){let n={event:r,before:e?ar(e):null,after:ar(t)};c$1("[OpenRTC][projection]",n);}var Qt=class{constructor(){this.peers=new Map;this.aliases=new Map;this.watchers=new Set;this.disposed=false;}resolveCanonicalPeerId(e){let t=[e.deviceId,e.deviceIdHint,e.nodeId,e.peerId,e.connectionId];for(let n of t){let i=ye(n);if(!i)continue;let o=this.aliases.get(i);if(o)return o}return ri(e)}setAlias(e,t){let n=ye(e);n&&this.aliases.set(n,t);}snapshot(e){let t=je(e),n=e.baseTransportState??cr(e),i=si(e),o=e.routable,s=e.protocolState;return {peerId:e.peerId,deviceId:e.deviceId,deviceIdHint:e.deviceIdHint,nodeId:e.nodeId,connectionId:e.connectionId,connectionIds:Array.from(e.connectionIds.values()),ticket:e.ticket,online:e.online,deviceName:e.deviceName,platformType:e.platformType,status:Vs(e),health:e.health,lifecycleStage:e.lifecycleStage??$s(e),generation:e.generation??e.transportGeneration,baseTransportState:n,admissionState:e.admissionState,transportState:e.transportState,protocolState:s,webrtcState:i,routable:o,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,fallbackTransport:e.fallbackTransport,parallelTransport:e.parallelTransport,manualDisconnect:e.manualDisconnect,lastAuthoritativeEventAt:e.lastAuthoritativeEventAt,lastTransientEventAt:e.lastTransientEventAt,promotionEligible:e.promotionEligible,scopes:Array.from(e.scopes.values()),lastSeenAt:e.lastSeenAt,error:t?void 0:e.error}}emit(){if(this.disposed)return;let e=this.list();this.watchers.forEach(t=>t(e));}rekeyPeer(e,t){let n=this.peers.get(e);if(!n)throw new Error(`Cannot rekey missing peer ${e}`);if(e===t)return n;this.peers.delete(e),n.peerId=t,this.peers.set(t,n);for(let[i,o]of this.aliases.entries())o===e&&this.aliases.set(i,t);return n}upsert(e){let t=e,n=this.resolveCanonicalPeerId(t)??ri(t);if(!n)throw new Error("Peer projection upsert requires a device-keyed identifier.");let i=ri(t)??n,o=this.peers.get(n),s=!!o;o||(o={peerId:n,connectionIds:new Set,status:t.status??"disconnected",health:t.health??"unknown",scopes:new Set},this.peers.set(n,o));let a=s?this.snapshot(o):void 0;if(i!==o.peerId){let N=t.deviceId||o.deviceId||t.deviceIdHint||o.deviceIdHint||t.nodeId||o.nodeId||o.peerId;N&&N!==o.peerId&&(o=this.rekeyPeer(o.peerId,N));}s&&typeof t.transportGeneration=="number"&&typeof o.transportGeneration=="number"&&t.transportGeneration<o.transportGeneration&&t.manualDisconnect!==true&&(t=rr(t)),s&&typeof t.routeGeneration=="number"&&typeof o.routeGeneration=="number"&&(typeof t.transportGeneration!="number"||typeof o.transportGeneration!="number"||t.transportGeneration===o.transportGeneration)&&t.routeGeneration<o.routeGeneration&&t.manualDisconnect!==true&&(t=rr(t)),t.deviceId&&(o.deviceId=t.deviceId),t.deviceIdHint!==void 0&&(o.deviceIdHint=t.deviceIdHint),t.nodeId&&(o.nodeId=t.nodeId);let c={generation:o.generation,lifecycleStage:o.lifecycleStage,protocolState:o.protocolState,webrtcState:o.webrtcState,routable:o.routable,activeTransportStableId:o.activeTransportStableId,transportGeneration:o.transportGeneration,routeGeneration:o.routeGeneration,activeTransport:o.activeTransport,fallbackTransport:o.fallbackTransport,parallelTransport:o.parallelTransport},l=je(o)||si(o)==="ready",p=(t.connectionId===void 0||o.connectionId===void 0||t.connectionId===o.connectionId)&&(t.transportGeneration===void 0||o.transportGeneration===void 0||t.transportGeneration===o.transportGeneration)&&(t.activeTransportStableId===void 0||o.activeTransportStableId===void 0||o.activeTransportStableId===null||t.activeTransportStableId===o.activeTransportStableId),u=t.connectionId!==void 0&&o.connectionId!==void 0&&t.connectionId!==o.connectionId||t.transportGeneration!==void 0&&o.transportGeneration!==void 0&&t.transportGeneration>o.transportGeneration||t.activeTransportStableId!==void 0&&t.activeTransportStableId!==null&&o.activeTransportStableId!==void 0&&o.activeTransportStableId!==null&&t.activeTransportStableId!==o.activeTransportStableId,f=t.activeTransport!==void 0||t.parallelTransport!==void 0||t.activeTransportStableId!==void 0||t.transportGeneration!==void 0||t.routeGeneration!==void 0||t.transportState!==void 0,h=sr(t.activeTransport)||sr(t.parallelTransport)||t.webrtcState==="ready"||t.webrtcState==="connecting",m=t.webrtcState==="closed"||t.webrtcState==="failed"||t.lifecycleStage==="closed"||t.status==="closed"||t.status==="disconnected"||t.status==="failed"||t.manualDisconnect===true,y=t.routable===true||t.protocolState==="routable",v=l&&p&&f&&y&&!h&&!m;u&&(o.generation=void 0,o.lifecycleStage=void 0,o.webrtcState=void 0,o.fallbackTransport=null,o.parallelTransport=null),t.connectionId&&(o.connectionId=t.connectionId,o.connectionIds.add(t.connectionId)),t.ticket!==void 0&&(o.ticket=t.ticket),t.online!==void 0&&(o.online=t.online),t.deviceName!==void 0&&(o.deviceName=t.deviceName),t.platformType!==void 0&&(o.platformType=t.platformType);let P=s&&(o.manualDisconnect===true||Pe(o.status)&&typeof o.error=="string"&&o.error.toLowerCase().includes("manual disconnect")),I=t.status==="connected"||t.status==="connecting"||t.routable===true||t.protocolState==="routable"||t.transportState==="connected"||t.activeTransport!==void 0||t.parallelTransport!==void 0;if(P&&I){let N=this.snapshot(o);return Re(a,N)||this.emit(),N}if(I&&(o.lifecycleStage==="closed"&&t.lifecycleStage===void 0&&(o.lifecycleStage=void 0),o.baseTransportState==="closed"&&t.baseTransportState===void 0&&(o.baseTransportState=void 0),o.webrtcState==="closed"&&t.webrtcState===void 0&&(o.webrtcState=void 0),o.transportState==="closed"&&t.transportState===void 0&&(o.transportState=void 0),o.protocolState==="closed"&&t.protocolState===void 0&&(o.protocolState=void 0)),t.status&&(o.status=t.status),t.health&&(o.health=t.health),t.lifecycleStage!==void 0&&(o.lifecycleStage=t.lifecycleStage),t.generation!==void 0&&(o.generation=t.generation),t.baseTransportState!==void 0&&(o.baseTransportState=t.baseTransportState),t.admissionState!==void 0&&(o.admissionState=t.admissionState),t.transportState!==void 0&&(o.transportState=t.transportState),t.protocolState!==void 0&&(o.protocolState=t.protocolState),t.webrtcState!==void 0&&(o.webrtcState=t.webrtcState),t.routable!==void 0&&(o.routable=t.routable),t.activeTransportStableId!==void 0&&(o.activeTransportStableId=t.activeTransportStableId),t.transportGeneration!==void 0&&(o.transportGeneration=t.transportGeneration),t.routeGeneration!==void 0&&(o.routeGeneration=t.routeGeneration),t.activeTransport!==void 0&&(o.activeTransport=t.activeTransport),t.fallbackTransport!==void 0&&(o.fallbackTransport=t.fallbackTransport),t.parallelTransport!==void 0&&(o.parallelTransport=t.parallelTransport),t.manualDisconnect!==void 0&&(o.manualDisconnect=t.manualDisconnect),t.lastAuthoritativeEventAt!==void 0&&(o.lastAuthoritativeEventAt=t.lastAuthoritativeEventAt),t.lastTransientEventAt!==void 0&&(o.lastTransientEventAt=t.lastTransientEventAt),t.promotionEligible!==void 0&&(o.promotionEligible=t.promotionEligible),(t.transportState!==void 0||t.activeTransportStableId!==void 0||t.activeTransport!==void 0||t.parallelTransport!==void 0)&&!y&&!je(o)&&(o.routable=false,o.protocolState==="routable"&&(o.protocolState=o.transportState==="connected"?"transport-only":o.transportState)),v&&(o.generation=c.generation,o.lifecycleStage=c.lifecycleStage,o.protocolState=c.protocolState,o.webrtcState=c.webrtcState,o.routable=c.routable,o.activeTransportStableId=c.activeTransportStableId,o.transportGeneration=c.transportGeneration,o.routeGeneration=c.routeGeneration,o.activeTransport=c.activeTransport,o.fallbackTransport=c.fallbackTransport,o.parallelTransport=c.parallelTransport),t.clearError?(o.error=void 0,t.manualDisconnect!==true&&(o.manualDisconnect=false)):t.error!==void 0&&(o.error=t.error,t.error.toLowerCase().includes("manual disconnect")&&(o.manualDisconnect=true)),t.lastSeenAt!==void 0&&(o.lastSeenAt=t.lastSeenAt),t.scopes)for(let N of t.scopes)o.scopes.add(N);(o.status==="closed"||o.status==="failed"||o.status==="disconnected")&&(o.routable=false,o.activeTransportStableId=null,o.activeTransport=void 0,o.fallbackTransport=null,o.parallelTransport=null,o.webrtcState="closed",o.baseTransportState="closed",o.lifecycleStage="closed",(!o.transportState||o.transportState==="connected")&&(o.transportState="closed"),(!o.protocolState||o.protocolState==="routable")&&(o.protocolState="closed")),this.setAlias(o.peerId,o.peerId),this.setAlias(o.deviceId,o.peerId),this.setAlias(o.deviceIdHint,o.peerId),this.setAlias(o.nodeId,o.peerId),this.setAlias(o.connectionId,o.peerId);for(let N of o.connectionIds)this.setAlias(N,o.peerId);let C=this.snapshot(o);return Re(a,C)||(Ys(s?"upsert":"create",a??null,C),this.emit()),C}dispatch(e){let t={peerId:e.peerId,deviceId:e.deviceId,deviceIdHint:e.deviceIdHint,nodeId:e.nodeId,connectionId:e.connectionId};switch(e.type){case "ConnectionStateProjected":{let{type:n,...i}=e;return this.upsert(i)}case "ManualDisconnectCleared":return this.upsert({...t,status:"disconnected",health:"unknown",manualDisconnect:false,clearError:true,lastSeenAt:Date.now()});case "RosterDeviceDiscovered":return this.upsert({...t,deviceName:e.deviceName,platformType:e.platformType,ticket:e.ticket,online:e.online??true,scopes:e.scopes,lastSeenAt:e.lastSeenAt??Date.now()});case "PresenceOnline":return this.upsert({...t,online:true,lastSeenAt:e.lastSeenAt??Date.now()});case "PresenceOffline":return this.upsert({...t,online:false});case "DialStarted":return this.get(this.targetLookupId(t))?.status==="connected"?this.get(this.targetLookupId(t)):this.upsert({...t,status:"connecting"});case "BaseTransportConnected":return this.upsert({...t,status:this.get(this.targetLookupId(t))?.status==="connected"?void 0:"connecting",transportState:"connected",baseTransportState:"connected",transportGeneration:e.transportGeneration});case "AdmissionAccepted":return this.upsert({...t,admissionState:"admitted"});case "AdmissionRejected":return this.upsert({...t,admissionState:"rejected",error:e.reason});case "WebRtcNegotiationStarted":return this.upsert({...t,webrtcState:"connecting",generation:e.generation,transportGeneration:e.generation});case "WebRtcFailed":return this.upsert({...t,webrtcState:"failed",transportGeneration:e.transportGeneration});case "ControlPathClosed":return this.upsert({...t,status:"disconnected"});case "HealthObserved":return this.updateHealth(this.targetLookupId(t),e.health);case "ManualDisconnect":return this.upsert({...t,status:"closed",health:"stale",manualDisconnect:true,error:"manual disconnect"});case "ExplicitUnshare":return this.upsert({...t,status:"closed",manualDisconnect:true,error:"explicit unshare"})}}targetLookupId(e){return e.deviceId||e.deviceIdHint||e.peerId||e.nodeId||e.connectionId||""}upsertDevice(e){return this.upsert({deviceId:e.deviceId,nodeId:e.nodeId,ticket:e.ticket,online:e.online,deviceName:e.deviceName,platformType:e.platformType,lastSeenAt:typeof e.updatedAt=="number"?e.updatedAt:typeof e.lastSeenAt=="number"?e.lastSeenAt:Date.now()})}watch(e){return this.disposed?()=>{}:(this.watchers.add(e),e(this.list()),()=>{this.watchers.delete(e);})}dispose(){this.disposed=true,this.watchers.clear();}get(e){let t=ye(e),n=t?this.aliases.get(t):void 0,i=n&&this.peers.get(n)||this.peers.get(e);return i?this.snapshot(i):void 0}list(){return Array.from(this.peers.values()).map(e=>this.snapshot(e)).sort((e,t)=>{let n=e.lastSeenAt??0,i=t.lastSeenAt??0;return n!==i?i-n:e.peerId.localeCompare(t.peerId)})}listConnected(){return this.list().filter(e=>e.status==="connected")}addScope(e,t="persistent"){let n=this.resolveRecord(e);if(!n)return;let i=this.snapshot(n);n.scopes.add(t);let o=this.snapshot(n);return Re(i,o)||this.emit(),o}releaseScope(e,t){let n=this.resolveRecord(e);if(!n)return;let i=this.snapshot(n);t?n.scopes.delete(t):n.scopes.clear();let o=this.snapshot(n);return Re(i,o)||this.emit(),o}hasScopes(e){return (this.resolveRecord(e)?.scopes.size??0)>0}removeConnection(e){let t=this.resolveRecord(e);if(!t)return;let n=this.snapshot(t),i=ye(e);if(i){let s=Array.from(t.connectionIds).find(a=>ye(a)===i);s&&t.connectionIds.delete(s);}t.connectionId&&ye(t.connectionId)===i&&(t.connectionId=Array.from(t.connectionIds)[0]),t.connectionIds.size===0&&t.status==="connected"&&(t.status="closed",t.routable=false,t.transportState="closed",t.protocolState="closed");let o=this.snapshot(t);return Re(n,o)||this.emit(),o}updateHealth(e,t,n){let i=this.resolveRecord(e);if(!i)return;let o=this.snapshot(i);i.health=t,n&&(i.status=n),i.lastSeenAt=Date.now();let s=this.snapshot(i);return Re(o,s)||this.emit(),s}resolveRecord(e){let t=ye(e),n=t?this.aliases.get(t):void 0;return n&&this.peers.get(n)||this.peers.get(e)}};function ai(r){return r.webRtcDataPlaneLive&&!r.routeReady?{activeTransport:r.parallelTransport??"iroh-relay",fallbackTransport:"webrtc",parallelTransport:"webrtc"}:{activeTransport:r.activeTransport??void 0,fallbackTransport:r.parallelTransport??null,parallelTransport:r.parallelTransport??null}}function lr(r){return r.settledReady?"routable":r.hasActiveConnection?"transport-only":r.rustStatusIsConnecting?"connecting":"closed"}function dr(r){return r.hasActiveConnection?"connected":r.rustStatusIsConnecting?"connecting":r.mappedStatusIsTerminal?"closed":"unknown"}function pr(r){return r.routeReady?"ready":r.webRtcDataPlaneLive?"route-probing":r.anyWebRtcTransportLabel?"connecting":"unknown"}function ur(r){return r.terminal?"closed":r.activeIsWebRtc?r.routeReady?"ready":"route-probing":r.parallelIsWebRtc?"route-probing":"unknown"}function Js(r,e){let t=b(r)??"",n=[r,e].map(b).filter(i=>!!i);return {activeTransportLabel:t,labels:n}}function $t(r){let{activeTransportLabel:e,labels:t}=Js(r.activeTransport,r.parallelTransport),n=t.some(f$1);return {webRtcDataPlaneLive:r.source==="rust-session"?!!r.activeConnectionId&&r.activeTransportStableId!==null&&r.activeTransportStableId!==void 0&&(r.sessionStatusNormalized==="connected"||r.sessionStatusNormalized==="connecting")&&r.mappedHealth==="healthy"&&f$1(e):f$1(r.activeTransport),routeReady:r.routeReady,anyWebRtcTransportLabel:n}}function Xs(r){if(r.isClosed)return "closed";let e=r.getUpgradeState();return e==="upgraded"?"webrtc":e==="upgrading"?"webrtc-upgrading":e==="failed"?"iroh-fallback":"connected"}function gr(r){let{connection:e,trustProjection:t,existingProjection:n,terminalTransportClose:i}=r;if(i){let c=n?.peerId??r.peerId??r.deviceId??r.deviceIdHint??e.id;return !c&&!r.deviceId&&!r.deviceIdHint?null:{event:{type:"ConnectionStateProjected",peerId:c,deviceId:n?.deviceId??r.deviceId,deviceIdHint:n?.deviceIdHint??r.deviceIdHint,nodeId:n?.nodeId??e.deviceId,connectionId:e.id,status:"closed",health:"stale",baseTransportState:"closed",transportState:"closed",protocolState:"closed",routable:false,promotionEligible:r.promotionEligible,lastSeenAt:Date.now()}}}if(t)return {event:{type:"ConnectionStateProjected",peerId:t.deviceId??e.remoteNodeId??e.id,deviceId:t.deviceId??void 0,deviceIdHint:t.deviceId??e.remoteNodeId??void 0,nodeId:e.remoteNodeId||e.deviceId,connectionId:e.id,status:e.isClosed?"closed":"connected",health:t.health,transportState:Xs(e),activeTransport:e.getTransportStatus().activeTransport,protocolState:t.protocolState,routable:t.routable,promotionEligible:r.promotionEligible,error:t.error,lastSeenAt:Date.now()}};if(r.peerId||r.deviceId)return {event:{type:"ConnectionStateProjected",peerId:r.peerId??r.deviceId??e.remoteNodeId??e.id,deviceId:r.deviceId,nodeId:e.deviceId,connectionId:e.id,ticket:r.ticket,status:e.isClosed?"closed":"connected",health:"healthy",activeTransport:e.getTransportStatus().activeTransport,promotionEligible:r.promotionEligible,scopes:r.scopes,lastSeenAt:Date.now()}};let o=n?.peerId||n?.deviceId||n?.deviceIdHint,s=n?.deviceId,a=n?.deviceIdHint;return !o&&!s&&!a?null:{event:{type:"ConnectionStateProjected",peerId:o,deviceId:s,deviceIdHint:a,nodeId:e.deviceId,connectionId:e.id,status:e.isClosed?"closed":"connected",health:e.isClosed?"stale":"healthy",activeTransport:e.getTransportStatus().activeTransport,promotionEligible:r.promotionEligible,lastSeenAt:Date.now()}}}function hr(r,e){let t=r.activeConnectionId||r.candidateConnectionIds?.[0]||void 0,n=e.mapRustPeerStatus(r.status),i=String(n).trim().toLowerCase(),o=typeof r.readinessState=="string"&&r.readinessState.trim().length>0,s=e.mapRustPeerHealth(r.health),a=e.localTerminalClosed===true&&!!t,c=$t({source:"rust-session",activeConnectionId:t,activeTransportStableId:r.activeTransportStableId,sessionStatusNormalized:i,mappedHealth:s,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport,routeReady:e.webRtcApplicationRouteReady}),l=o?r.readinessState==="routable":!!r.settledReady,d=l&&!e.applicationRouteFailed,p=a?d:e.trustProjection?e.trustProjection.routable&&l&&!e.applicationRouteFailed:l&&!e.applicationRouteFailed,u=r.status==="connecting",f=lr({settledReady:p,hasActiveConnection:!!t,rustStatusIsConnecting:u}),h=c.webRtcDataPlaneLive&&!c.routeReady,m=p&&!h,y=h&&f==="routable"?"transport-only":f,v=ai({webRtcDataPlaneLive:c.webRtcDataPlaneLive,routeReady:c.routeReady,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport});return {event:{type:"ConnectionStateProjected",peerId:r.peerId??e.transientPeerId??e.anonymousSpacePeerId,deviceId:e.trustProjection?.deviceId??r.deviceId??void 0,deviceIdHint:r.deviceIdHint,nodeId:r.nodeId,connectionId:t,status:a&&!d?"closed":e.applicationRouteFailed?"failed":m?"connected":n,health:a&&!d||e.applicationRouteFailed?"stale":e.trustProjection?.health??s,generation:r.transportGeneration,baseTransportState:a&&!d?"closed":dr({hasActiveConnection:!!t,rustStatusIsConnecting:u,mappedStatusIsTerminal:n==="closed"||n==="failed"||n==="disconnected"}),admissionState:a&&!d?"unknown":p||t?"admitted":"unknown",transportState:a&&!d?"closed":t?"connected":r.status==="connecting"?"connecting":"closed",protocolState:a&&!d?"closed":y,routable:m,activeTransportStableId:a&&!d?void 0:r.activeTransportStableId??void 0,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,activeTransport:a&&!d?void 0:v.activeTransport,fallbackTransport:a&&!d?void 0:v.fallbackTransport,parallelTransport:a&&!d?void 0:v.parallelTransport,webrtcState:a&&!d?"closed":pr({routeReady:c.routeReady,webRtcDataPlaneLive:c.webRtcDataPlaneLive,anyWebRtcTransportLabel:c.anyWebRtcTransportLabel}),promotionEligible:e.promotionEligible,scopes:e.sessionScopes,error:a&&!d?"local-transport-closed":e.applicationRouteFailed?"application-route-timeout":e.trustProjection?.error??(m?void 0:r.error??void 0),clearError:m,lastSeenAt:r.lastSeenAtMs},clearApplicationRouteFailure:d&&m&&t?t:void 0}}function Zs(r){return !(!r.projectedDeviceId&&!r.projectedDeviceIdHint&&!r.existingProjection&&!r.anonymousTerminalProjectionAllowed&&!r.localTerminalClosed)}function mr(r,e){if(!Zs(e))return null;let t=e.localTerminalClosed===true,n=$t({source:"backend-state",activeTransport:r.activeTransport,parallelTransport:r.parallelTransport,routeReady:e.webRtcApplicationRouteReady}),i=e.liveConnection?e.applicationRouteReady:r.routable===true&&(!n.webRtcDataPlaneLive||n.routeReady),o=r.routable===true&&i&&!e.terminalState,s=t&&!o,a=e.terminalState||s,c=a?false:e.trustProjection?e.trustProjection.routable:r.routable,l=c&&i,d=s?"closed":e.terminalState?r.protocolState??"closed":l?"routable":r.transportState==="connected"?"transport-only":e.trustProjection?.protocolState??r.protocolState,p=a?s?"local-transport-closed":r.error??r.lastDisconnectReason??e.trustProjection?.error:e.trustProjection?.error??r.error,u=a?"stale":e.trustProjection?.health??(l||r.transportState==="connected"?"healthy":r.state==="failed"||r.state==="closed"?"stale":"unknown"),f=ai({webRtcDataPlaneLive:n.webRtcDataPlaneLive,routeReady:n.routeReady,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport});return {event:{type:"ConnectionStateProjected",peerId:e.existingProjection?.peerId??(e.anonymousTerminalProjectionAllowed?r.remoteNodeId??r.connectionId:void 0),deviceId:e.projectedDeviceId,deviceIdHint:e.projectedDeviceIdHint,nodeId:r.remoteNodeId??e.existingProjection?.nodeId??void 0,connectionId:r.connectionId,status:s?"closed":r.state==="connected"?"connected":r.state==="connecting"||r.state==="new"?"connecting":r.state==="failed"?"failed":r.state==="closed"?"closed":"disconnected",health:u,generation:r.transportGeneration,baseTransportState:a?"closed":r.transportState==="connected"?"connected":r.transportState==="connecting"||r.state==="connecting"||r.state==="new"?"connecting":r.transportState==="failed"?"degraded":"unknown",admissionState:c||r.readinessState==="routable"?"admitted":a?"unknown":"pending",transportState:s?"closed":r.transportState,protocolState:d,webrtcState:ur({terminal:a,activeIsWebRtc:n.webRtcDataPlaneLive,routeReady:n.routeReady,parallelIsWebRtc:f$1(r.parallelTransport)}),routable:l,activeTransportStableId:s?void 0:r.activeTransportStableId??void 0,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,activeTransport:s?void 0:f.activeTransport,fallbackTransport:s?void 0:f.fallbackTransport,parallelTransport:s?void 0:f.parallelTransport,error:p,lastAuthoritativeEventAt:r.updatedAt??Date.now(),lastSeenAt:r.updatedAt??Date.now()}}}function fr(r,e,t){let n=ea(e,{status:r.status,health:r.health,routable:r.routable,protocolState:r.protocolState},t);return n?{...r,...n}:r}function ea(r,e,t){if(!r||r.isClosed)return null;let{activeTransport:n,parallelTransport:i}=r.getTransportStatus(),o=f$1(n)||f$1(i);if(!o||!r.getWebRTCTransport()||e.status==="closed"||e.status==="failed"||e.status==="disconnected")return null;let c=t.applicationRouteReady&&(e.routable===true||e.protocolState==="routable"),l=t.webRtcApplicationRouteReady;return {status:e.status==="connected"||c?"connected":e.status,health:e.health==="stale"?"healthy":e.health,baseTransportState:"connected",transportState:"connected",protocolState:c?"routable":o&&!l?"transport-only":e.protocolState,webrtcState:l?"ready":"route-probing",routable:c,activeTransport:l?n:"iroh-relay",fallbackTransport:i,parallelTransport:l?i:"webrtc",clearError:c&&l,lastTransientEventAt:Date.now()}}var ci=2e3,li=3e3,Vt=class{constructor(e=ci,t=li){this.tsGraceMs=e;this.rustGraceMs=t;this.tsOrphanSince=new Map;this.rustOrphanSince=new Map;this.reportedRustOrphans=new Set;}evaluateTsOrphans(e,t){let n=new Set(e);for(let o of [...this.tsOrphanSince.keys()])n.has(o)||this.tsOrphanSince.delete(o);for(let o of n)this.tsOrphanSince.has(o)||this.tsOrphanSince.set(o,t);let i=[];for(let o of n){let s=this.tsOrphanSince.get(o);s!==void 0&&t-s>=this.tsGraceMs&&i.push(o);}return {toDisconnect:i}}evaluateRustOrphans(e,t){let n=new Set(e);for(let o of [...this.rustOrphanSince.keys()])n.has(o)||(this.rustOrphanSince.delete(o),this.reportedRustOrphans.delete(o));for(let o of n)this.rustOrphanSince.has(o)||this.rustOrphanSince.set(o,t);let i=[];for(let o of n){let s=this.rustOrphanSince.get(o);s!==void 0&&t-s>=this.rustGraceMs&&!this.reportedRustOrphans.has(o)&&(this.reportedRustOrphans.add(o),i.push(o));}return {toReport:i}}clear(){this.tsOrphanSince.clear(),this.rustOrphanSince.clear(),this.reportedRustOrphans.clear();}};function yr(r){let e=String(r??"").trim().toLowerCase();return e==="connected"||e==="connecting"||e==="new"}function ta(r){let e=String(r.state??"").trim().toLowerCase();return e==="connected"||e==="connecting"||e==="new"}function di(r){return r.activeConnectionId||r.candidateConnectionIds?.[0]||void 0}function na(r,e,t){return e.some(i=>di(i)===r&&yr(i.status))?true:t.some(i=>i.connectionId===r&&ta(i))}function ia(r,e){return r.routable===true&&(r.connectionId===e||r.connectionIds.includes(e))}function oa(r){let e=[],t=[];if(r.hasRustProjection)for(let[n,i]of r.connections)i.isClosed||na(n,r.rustSessions,r.backendStates)||e.push(n);for(let n of r.rustSessions){let i=di(n);if(!i||!yr(n.status)||!(n.settledReady===true||n.readinessState==="routable"||r.peerStates.some(a=>ia(a,i))))continue;let s=r.connections.get(i);(!s||s.isClosed)&&t.push(i);}return {orphanTsConnectionIds:e,orphanRustRecordConnectionIds:t}}function ra(r,e,t,n=Date.now()){if(!r.hasRustPeerLifecycleProjection())return t.clear(),{reportedDrift:{orphanTsConnectionIds:[],orphanRustRecordConnectionIds:[]},closedTsConnectionIds:[]};t.evaluateTsOrphans(e.orphanTsConnectionIds,n);let{toReport:i}=t.evaluateRustOrphans(e.orphanRustRecordConnectionIds,n);return {reportedDrift:{orphanTsConnectionIds:e.orphanTsConnectionIds,orphanRustRecordConnectionIds:i},closedTsConnectionIds:[]}}var Yt=class{constructor(e){this.run=e;this.inFlight=null;this.queuedReason=null;this.disposed=false;this.stats={scheduled:0,coalesced:0,ran:0,orphanTsConnection:0,orphanRustRecord:0,orphanTsConnectionHealed:0};}getStats(){return this.stats}dispose(){this.disposed=true,this.queuedReason=null;}recordDrift(e){e.orphanTsConnectionIds.length>0&&(this.stats.orphanTsConnection+=e.orphanTsConnectionIds.length,b$1("[Client][PEER-RECONCILE] orphan_ts_connection",{count:e.orphanTsConnectionIds.length,connectionIds:e.orphanTsConnectionIds})),e.orphanRustRecordConnectionIds.length>0&&(this.stats.orphanRustRecord+=e.orphanRustRecordConnectionIds.length,b$1("[Client][PEER-RECONCILE] orphan_rust_record",{count:e.orphanRustRecordConnectionIds.length,connectionIds:e.orphanRustRecordConnectionIds}));}recordSelfHeal(e){e.closedTsConnectionIds.length>0&&(this.stats.orphanTsConnectionHealed+=e.closedTsConnectionIds.length,b$1("[Client][PEER-RECONCILE] orphan_ts_connection_healed",{count:e.closedTsConnectionIds.length,connectionIds:e.closedTsConnectionIds})),this.recordDrift(e.reportedDrift);}schedule(e){return this.disposed?Promise.resolve([]):(this.stats.scheduled+=1,this.inFlight?(this.stats.coalesced+=1,this.queuedReason=e,b$1("[Client][PEER-RECONCILE] coalesced",{reason:e}),this.inFlight):(b$1("[Client][PEER-RECONCILE] started",{reason:e}),this.inFlight=this.executeRun(e),this.inFlight))}async executeRun(e){let t=e;try{for(;;){this.stats.ran+=1;let n=await this.run(t);b$1("[Client][PEER-RECONCILE] finished",{reason:t,stats:this.getStats()});let i=this.queuedReason;if(this.queuedReason=null,this.disposed)return [];if(!i)return n;t=i,b$1("[Client][PEER-RECONCILE] rerun",{reason:t});}}finally{this.inFlight=null;}}};async function vr(r,e){let t=r.hasRustPeerLifecycleProjection(),n=false,i=[];if(r.wasmClient&&typeof r.wasmClient.peer_sessions=="function"){let d=await r.wasmClient.peer_sessions();if(Array.isArray(d)){i=d;for(let p of d){let u=di(p);if(!r.hasResolvablePeerIdentity({deviceId:p.deviceId,deviceIdHint:p.deviceIdHint,nodeId:p.nodeId,connectionId:u})){b$1("[Client][PEER-SNAPSHOT] skipping rust session without identity",{status:p.status,health:p.health,settledReady:p.settledReady});continue}r.applyComposedRustSession(p),n=true;}}}(await r.searchDevices().catch(()=>[])).forEach(d=>{if(!r.hasResolvablePeerIdentity({deviceId:d.deviceId??null,nodeId:d.nodeId??null})){b$1("[Client][PEER-SNAPSHOT] skipping device projection without identity",{deviceName:d.deviceName??null,online:d.online??null});return}r.peerLifecycle.upsertDevice(d);}),t||r.connections.forEach(d=>{r.syncConnectionPeerLifecycle(d);});let s=await r.signaling.getConnectionStates().catch(()=>[]);s.forEach(d=>{r.applyBackendConnectionState(d);});let a=r.peerLifecycle.list(),c=oa({hasRustProjection:t,connections:r.connections,rustSessions:i,backendStates:s,peerStates:a}),l=r.getOrphanDriftTracker?.();if(l){let d=ra(r,c,l);r.recordReconciliationSelfHeal?.(d);}else r.recordReconciliationDrift?.(c);return t&&!n&&s.length===0,a}function pi(r,e){return r&&typeof r.supportsRustPeerLifecycleProjection=="function"&&r.supportsRustPeerLifecycleProjection()?true:!!(e&&typeof e.peer_sessions=="function")}var Jt=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.orphanDriftTracker=new Vt(t.orphanReconciliationGrace?.tsConnectionMs??ci,t.orphanReconciliationGrace?.rustRecordMs??li),this.scheduler=new Yt(n=>vr(this.asReconciliationHost())),this.ctx.registerDisposer(()=>this.dispose());}schedule(e){return this.scheduler.schedule(e)}dispose(){this.disposed=true,this.scheduler.dispose(),this.orphanDriftTracker.clear();}getStats(){return this.scheduler.getStats()}hasRustPeerLifecycleProjection(){return pi(this.deps.getSignaling(),this.getPeerSessionReader())}dispatchLiveConnectionProjection(e,t){if(this.disposed)return;let n=gr({connection:e,...t});n&&this.dispatchComposedConnectionState(n.event,e,{applicationRouteReady:t.applicationRouteReady,webRtcApplicationRouteReady:t.webRtcApplicationRouteReady});}applyConnectionTrustProjection(e){if(this.disposed||this.hasRustPeerLifecycleProjection())return;let t=this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId}),n=this.deps.getConnectionTrustProjection({connectionId:e.id,nodeId:e.remoteNodeId}),i=this.deps.hasApplicationRouteForConnection(e),o=this.deps.isWebRtcApplicationRouteReadyForConnection(e);if(!n){this.syncConnectionPeerLifecycle(e);return}this.dispatchLiveConnectionProjection(e,{trustProjection:n,promotionEligible:t,applicationRouteReady:i,webRtcApplicationRouteReady:o});}applyBackendConnectionState(e){if(this.disposed||!e?.connectionId)return;let t=this.deps.getConnectionTrustProjection({connectionId:e.connectionId,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.remoteNodeId??void 0}),n=this.getPeerState(e.connectionId)??(e.remoteNodeId?this.getPeerState(e.remoteNodeId):void 0),i=e.deviceId??t?.deviceId??n?.deviceId??void 0,o=e.deviceIdHint??n?.deviceIdHint??void 0,s=e.state==="closed"||e.state==="failed"||e.state==="disconnected",a=this.deps.hasLocalTerminalConnectionClose(e.connectionId),c=(s||a)&&!!(e.connectionId||e.remoteNodeId);if(!i&&!o&&!n&&!c)return;b$1("[Client] applyBackendConnectionState",{connectionId:e.connectionId,deviceId:i??null,deviceIdHint:o??null,remoteNodeId:e.remoteNodeId??null,state:e.state,transportState:e.transportState??null,protocolState:e.protocolState??null,routable:e.routable??null,updatedAt:e.updatedAt??null,error:e.error??null,mappedPeerId:n?.peerId??null});let l=this.ctx.registry.get(e.connectionId)??(e.remoteNodeId?this.deps.getConnectionForPeer(void 0,e.remoteNodeId):null),d=this.deps.hasApplicationRouteForConnection(l),p=this.deps.isWebRtcApplicationRouteReadyForConnection(l),u=mr(e,{trustProjection:t,existingProjection:n,liveConnection:l,applicationRouteReady:d,webRtcApplicationRouteReady:p,terminalState:s,localTerminalClosed:a,anonymousTerminalProjectionAllowed:c,projectedDeviceId:i,projectedDeviceIdHint:o});u&&this.dispatchComposedConnectionState(u.event,l,{applicationRouteReady:d,webRtcApplicationRouteReady:p});}applyComposedRustSession(e){if(this.disposed)return;let t=e.activeConnectionId||e.candidateConnectionIds?.[0],n=this.deps.hasLocalTerminalConnectionClose(t),i=e.scopes??[],o=!!e.nodeId&&this.deps.sessionTokenApprovedNodes().has(e.nodeId)||!!t&&this.deps.sessionTokenApprovedConnectionIds().has(t),s=!e.peerId&&!e.deviceId&&!e.deviceIdHint&&o?`session-token:${i[0]??"unscoped"}:${e.nodeId??t}`:void 0,a=!e.peerId&&!e.deviceId&&!e.deviceIdHint&&this.ctx.discoveryMode==="space"?e.nodeId??t:void 0,c=this.deps.resolvePromotionEligibility({connectionId:t||void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}),l=this.deps.getConnectionTrustProjection({connectionId:t||void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}),d=this.deps.getConnectionForPeer(t||void 0,e.nodeId??void 0),p=this.deps.hasApplicationRouteForConnection(d),u=!!t&&!p&&this.deps.hasApplicationRouteFailure(t),f=String(this.mapRustPeerStatus(e.status)).trim().toLowerCase(),m=$t({source:"rust-session",activeConnectionId:t,activeTransportStableId:e.activeTransportStableId,sessionStatusNormalized:f,mappedHealth:this.mapRustPeerHealth(e.health),activeTransport:e.activeTransport,parallelTransport:e.parallelTransport,routeReady:false}).webRtcDataPlaneLive&&this.deps.isWebRtcApplicationRouteReadyForConnection(d),y=hr(e,{trustProjection:l,promotionEligible:c,liveConnection:d,applicationRouteReady:p,webRtcApplicationRouteReady:m,applicationRouteFailed:u,localTerminalClosed:n,mapRustPeerStatus:v=>this.mapRustPeerStatus(v),mapRustPeerHealth:v=>this.mapRustPeerHealth(v),peerId:e.peerId,transientPeerId:s,anonymousSpacePeerId:a,sessionScopes:i});y.clearApplicationRouteFailure&&this.deps.clearApplicationRouteFailure(y.clearApplicationRouteFailure),this.dispatchComposedConnectionState(y.event,d,{applicationRouteReady:p,webRtcApplicationRouteReady:m});}syncConnectionPeerLifecycle(e){if(this.disposed)return;let t=this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId}),n=this.getPeerState(e.id)||this.listPeerStates().find(i=>i.connectionIds.includes(e.id)||i.nodeId===e.deviceId);this.dispatchLiveConnectionProjection(e,{trustProjection:null,promotionEligible:t,existingProjection:n,applicationRouteReady:this.deps.hasApplicationRouteForConnection(e),webRtcApplicationRouteReady:this.deps.isWebRtcApplicationRouteReadyForConnection(e)});}mapRustPeerStatus(e){switch((e||"").toLowerCase()){case "connected":return "connected";case "connecting":case "pending":return "connecting";case "failed":return "failed";case "closing":case "closed":return "closed";default:return "disconnected"}}mapRustPeerHealth(e){switch((e||"").toLowerCase()){case "healthy":return "healthy";case "suspect":return "suspect";case "stale":return "stale";default:return "unknown"}}asReconciliationHost(){return {hasRustPeerLifecycleProjection:()=>this.hasRustPeerLifecycleProjection(),wasmClient:this.getPeerSessionReader(),signaling:this.deps.getSignaling(),peerLifecycle:this.deps.peerLifecycle,connections:this.ctx.registry,discoveryMode:this.ctx.discoveryMode,sessionTokenApprovedNodes:this.deps.sessionTokenApprovedNodes(),sessionTokenApprovedConnectionIds:this.deps.sessionTokenApprovedConnectionIds(),hasResolvablePeerIdentity:e=>this.hasResolvablePeerIdentity(e),applyComposedRustSession:e=>this.applyComposedRustSession(e),applyBackendConnectionState:e=>this.applyBackendConnectionState(e),searchDevices:()=>this.deps.searchDevices(),syncConnectionPeerLifecycle:e=>this.syncConnectionPeerLifecycle(e),getOrphanDriftTracker:()=>this.orphanDriftTracker,recordReconciliationSelfHeal:e=>this.scheduler.recordSelfHeal(e),recordReconciliationDrift:e=>this.scheduler.recordDrift(e)}}getPeerSessionReader(){return this.ctx.wasmClient&&typeof this.ctx.wasmClient=="object"?this.ctx.wasmClient:null}hasResolvablePeerIdentity(e){if(e.deviceId||e.deviceIdHint)return true;let t=[e.nodeId,e.connectionId].map(o=>typeof o=="string"?o.trim():"").filter(o=>o.length>0);if(this.ctx.discoveryMode==="space"&&t.length>0)return true;let n=this.deps.sessionTokenApprovedNodes(),i=this.deps.sessionTokenApprovedConnectionIds();return t.some(o=>!!this.getPeerState(o)||n.has(o)||i.has(o))}dispatchComposedConnectionState(e,t,n){let i=fr(e,t,n);this.deps.peerLifecycle.dispatch(i);}getPeerState(e){let t=this.deps.peerLifecycle;return typeof t.get=="function"?t.get(e):void 0}listPeerStates(){let e=this.deps.peerLifecycle;return typeof e.list=="function"?e.list():[]}};function Cr(r){return new ui({getContext:()=>r.getClientContext(),getWasmClient:()=>r.wasmClient,getSignaling:()=>r.signaling,getConnections:()=>r.registry.values(),disconnectNode:e=>r.runtimeConnections.disconnectNode(e),registerDisposer:e=>r.lifecycleScope.register(e),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),getOrphanReconciliationGrace:()=>r.options?.orphanReconciliationGrace,getSessionTokenApprovedNodes:()=>r.sessionTokens.getApprovedNodes(),getSessionTokenApprovedConnectionIds:()=>r.sessionTokens.getApprovedConnectionIds(),resolvePromotionEligibility:e=>r.connectionChannelPolicy.resolvePromotionEligibility(e),getConnectionTrustProjection:e=>r.connectionTrust.getProjection(e),getConnectionForPeer:(e,t)=>r.registry.getForPeer(e??void 0,t??void 0),hasApplicationRouteForConnection:e=>r.transportServices.hasApplicationRouteForConnectionSnapshot(e,e?.id,e?.remoteNodeId),isWebRtcApplicationRouteReadyForConnection:e=>r.transportServices.isWebRtcApplicationRouteReadyForConnectionSnapshot(e),hasLocalTerminalConnectionClose:e=>r.registry.hasLocalTerminalClose(e),hasApplicationRouteFailure:e=>r.transportServices.hasApplicationRouteFailure(e),clearApplicationRouteFailure:e=>r.transportServices.clearApplicationRouteFailure(e),searchDevices:()=>r.deviceDirectory.searchDevices(),healOrphanTsConnection:e=>r.connectionLifecycle.healOrphanTsConnection(e)})}var ui=class{constructor(e){this.host=e;this.store=new Qt;this.host.registerDisposer(()=>{this.store.dispose();});}get projection(){return this._projection||(this._projection=new Jt(this.host.getContext(),{orphanReconciliationGrace:this.host.getOrphanReconciliationGrace(),sessionTokenApprovedNodes:()=>this.host.getSessionTokenApprovedNodes(),sessionTokenApprovedConnectionIds:()=>this.host.getSessionTokenApprovedConnectionIds(),resolvePromotionEligibility:e=>this.host.resolvePromotionEligibility(e),getConnectionTrustProjection:e=>this.host.getConnectionTrustProjection(e),getConnectionForPeer:(e,t)=>this.host.getConnectionForPeer(e,t),hasApplicationRouteForConnection:e=>this.host.hasApplicationRouteForConnection(e),isWebRtcApplicationRouteReadyForConnection:e=>this.host.isWebRtcApplicationRouteReadyForConnection(e),hasLocalTerminalConnectionClose:e=>this.host.hasLocalTerminalConnectionClose(e),hasApplicationRouteFailure:e=>this.host.hasApplicationRouteFailure(e),clearApplicationRouteFailure:e=>this.host.clearApplicationRouteFailure(e),searchDevices:()=>this.host.searchDevices(),healOrphanTsConnection:e=>this.host.healOrphanTsConnection(e),getSignaling:()=>this.host.getSignaling(),peerLifecycle:this.store})),this._projection}get client(){return this._client||(this._client=new qt(this.store,{getWasmClient:()=>this.host.getWasmClient(),getConnections:()=>this.host.getConnections(),disconnectNode:e=>this.host.disconnectNode(e),hasRustPeerLifecycleProjection:()=>this.host.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:e=>this.projection.schedule(e),scheduleRefreshPeerSnapshot:()=>this.projection.schedule("peer-lifecycle-client").then(()=>{}),registerDisposer:e=>this.host.registerDisposer(e),resolvePromotionEligibility:e=>this.host.resolvePromotionEligibility(e)})),this._client}getProjectionStats(){return this._projection?.getStats()}watchPeerStates(e){return this.store.watch?.(e)??(()=>{})}getPeerState(e){return this.store.get?.(e)}listConnectedPeers(){return this.store.listConnected?.()??[]}listPeerStates(){return this.store.list?.()??[]}getPeerScopes(e){return this.getPeerState(e)?.scopes??[]}getPeerStatus(e){return this.getPeerState(e)?.status}hasPeerScopes(e){return this.store.hasScopes?.(e)??this.getPeerScopes(e).length>0}isSamePeer(e,t){let n=this.getPeerState(e),i=this.getPeerState(t);return !!n&&!!i&&n.peerId===i.peerId}getPeerHealth(e){return this.getPeerState(e)?.health??"unknown"}isPeerPromotionEligible(e){return this.client.isPeerPromotionEligible(e)}addPeerScope(e,t="persistent"){return this.client.addPeerScope(e,t)}releasePeerScope(e,t){return this.client.releasePeerScope(e,t)}clearManualDisconnectProjection(e){this.client.clearManualDisconnectProjection(e);}disconnectPeer(e,t="persistent"){return this.client.disconnectPeer(e,t)}forceDisconnectPeer(e){return this.client.forceDisconnectPeer(e)}applyDiscoveredDevice(e){this.store.upsertDevice?.(e);}};function sa(r){return lo({get wasmClient(){return r.getWasmClient()},get roomCreationMode(){return r.getRoomCreationMode()},get appLimits(){return r.getAppLimits()},ensureAuthenticated:e=>r.ensureAuthenticated(e),getTicketWithToken:(e,t)=>r.getTicketWithToken(e,t),getNodeId:()=>r.getNodeId(),connect:(e,t)=>r.connect(e,t),refreshHostedAppSettings:e=>r.refreshHostedAppSettings(e),usesDirectRoomBackend:()=>r.usesDirectRoomBackend(),getRoomBackendTag:()=>r.getRoomBackendTag()})}function Sr(r){return sa({getWasmClient:()=>r.wasmClient,getRoomCreationMode:()=>r.getRoomCreationMode(),getAppLimits:()=>r.getAppLimits(),ensureAuthenticated:e=>r.auth.ensureAuthenticated(e),getTicketWithToken:(e,t)=>r.sessionTokens.getEndpointTicketWithToken(e,t),getNodeId:()=>r.runtimeIdentity.getNodeId(),connect:(e,t)=>r.connectionDialer.connect(e,t),refreshHostedAppSettings:e=>r.signalingBackendController.refreshHostedAppSettings(e),usesDirectRoomBackend:()=>r.runtimeStatus.usesDirectRoomBackend(),getRoomBackendTag:()=>r.runtimeStatus.getRoomBackendTag()})}var Xt=class{constructor(e){this.ctx=e;this.browserBackgrounded=false;this.disposed=false;this.removeBrowserListeners=null;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.removeBrowserListeners?.(),this.removeBrowserListeners=null);}installListeners(){if(this.disposed||this.removeBrowserListeners||typeof document>"u"||typeof window>"u")return;let e=()=>{if(this.disposed)return;let i=document.visibilityState==="hidden";this.handleBackgroundState(i,"visibilitychange");},t=()=>{this.disposed||this.handleBackgroundState(false,"pageshow");},n=()=>{this.disposed||this.reconcileConnectionsAfterAvailabilityHint("online");};e(),document.addEventListener("visibilitychange",e),window.addEventListener("pageshow",t),window.addEventListener("online",n),this.removeBrowserListeners=()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("pageshow",t),window.removeEventListener("online",n);};}async handleBackgroundState(e,t){if(this.disposed)return;let n=this.browserBackgrounded!==e;this.browserBackgrounded=e;let i=this.ctx.wasmClient;if(i&&typeof i.set_app_backgrounded=="function")try{await i.set_app_backgrounded(e);}catch(o){console.warn("[Client][APP] Failed to propagate background state to wasm runtime",{backgrounded:e,source:t,error:o});}this.disposed||!e&&n&&this.reconcileConnectionsAfterAvailabilityHint(t);}reconcileConnectionsAfterForeground(e){this.reconcileConnectionsAfterAvailabilityHint(e);}reconcileConnectionsAfterAvailabilityHint(e){if(!this.disposed)for(let t of this.ctx.registry.values()){if(t.isClosed)continue;let n=t.getUpgradeState();c$1("[Client][APP] Availability recovery reconcile",{source:e,connectionId:t.id,remoteNodeId:t.remoteNodeId,upgradeState:n}),t.handleAppForeground();}}};var Zt=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.admissionRepairInFlight=new Map;this.repairedAdmissionStableIdByNode=new Map;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true,this.admissionRepairInFlight.clear(),this.repairedAdmissionStableIdByNode.clear();}assertActive(){if(this.disposed)throw new Error("Managed transport dialer is disposed")}async repairAdmissionForTransportGeneration(e,t){if(this.assertActive(),!e||!Number.isSafeInteger(t)||t<=0)return false;if(this.repairedAdmissionStableIdByNode.get(e)===t)return true;let n=this.deps.getRouteRepairTokenForNode?.(e)?.trim()??"",i=this.deps.getRouteRepairTokenPayloadForNode?.(e)?.trim()??"";if(!n||!i)return false;let o=this.admissionRepairInFlight.get(e);if(o?.transportStableId===t)return o.promise;let s=this.performAdmissionRepair(e,t,n,i);this.admissionRepairInFlight.set(e,{transportStableId:t,promise:s});try{let a=await s,c=this.admissionRepairInFlight.get(e);return a&&c?.promise===s&&c.transportStableId===t&&this.repairedAdmissionStableIdByNode.set(e,t),a}finally{this.admissionRepairInFlight.get(e)?.promise===s&&this.admissionRepairInFlight.delete(e);}}async performAdmissionRepair(e,t,n,i){let o=this.ctx.wasmClient;if(!o)return false;let s=(await this.deps.getLocalDeviceId().catch(()=>null))?.trim()||this.deps.getFallbackLocalDeviceId()?.trim()||null;this.assertActive();let a=4;for(let c=1;c<=a;c+=1)try{return await this.presentSessionTokenToHost(o,e,n,i,s,2e4),this.assertActive(),c$1("[ManagedTransportDialer] repaired admission for physical generation",{remoteNodeId:e,transportStableId:t,attempt:c}),!0}catch(l){if(!this.isTransientSessionTokenPresentationError(l)||c>=a)throw l;console.warn("[ManagedTransportDialer] current-generation admission repair lost transiently; retrying",{remoteNodeId:e,transportStableId:t,attempt:c,nextAttempt:c+1,error:l instanceof Error?l.message:String(l)}),await this.sleepSessionTokenRetry(c),this.assertActive();}return false}normalizeConnectResult(e,t,n,i){let o=e&&typeof e=="object"?e:{},s=typeof o.connectionId=="string"&&o.connectionId.trim()?o.connectionId.trim():t,a=typeof o.remoteNodeId=="string"&&o.remoteNodeId.trim()?o.remoteNodeId.trim():n,c=typeof o.deviceId=="string"&&o.deviceId.trim()?o.deviceId.trim():i??null,l=typeof o.deviceIdHint=="string"&&o.deviceIdHint.trim()?o.deviceIdHint.trim():c,d=typeof o.state=="string"&&o.state.trim()?o.state.trim():"connected",p=typeof o.approvedScope=="string"&&o.approvedScope.trim()?o.approvedScope.trim():typeof o.approved_scope=="string"&&o.approved_scope.trim()?o.approved_scope.trim():null;return {connectionId:s,deviceId:c,deviceIdHint:l,remoteNodeId:a,state:d,approvedScope:p}}async ensureWasmManagedTransport(e,t,n){this.assertActive();let i=this.ctx.wasmClient;if(!i||typeof i.connect_device!="function")throw new Error("[Client] WASM managed transport requires connect_device()");let o=n?.timeoutMs??2e4,s=e.trim(),{irohTicket:a,tokenSuffix:c}=Y(s),l=c===null?s:a,d=c!==null?ne(a,c):null;if(c!==null&&!d)throw new Error("invalid compound ticket payload for endpoint ticket");let p=typeof d?.t=="string"&&d.t.trim()?d.t.trim():null;if(c!==null&&!p)throw new Error("invalid compound ticket payload for endpoint ticket");let u=await i.endpoint_id_from_ticket(a);this.assertActive(),p&&c&&this.deps.rememberRouteRepairTokenForNode(u,p,c);let f=this.deps.getDeterministicConnectionId(u),h=p?await this.deps.getLocalDeviceId().catch(()=>null):null,m=p&&(h?.trim()||this.deps.getFallbackLocalDeviceId()?.trim())||null;if(this.assertActive(),n?.skipIfConnected&&typeof i.is_connected=="function")try{let T=await i.is_connected(u);if(this.assertActive(),T){let C=c===null?this.deps.getApprovedScope(f):null;if(!(c!==null&&!C&&!n?.admissionAlreadyPresented))return {connectionId:f,deviceId:t??null,deviceIdHint:t??null,remoteNodeId:u,state:"connected",approvedScope:C}}}catch(T){if(this.disposed)throw T}let y=await E(i.connect_device(t??null,l),o,"wasmClient.connect_device");this.assertActive();let v=this.normalizeConnectResult(y,f,u,t??null),P=v.approvedScope??(c===null?this.deps.getApprovedScope(v.connectionId):null);if(c!==null&&!P&&!n?.admissionAlreadyPresented){for(let C=1;C<=4&&!P;C+=1)try{P=await this.presentSessionTokenToHost(i,u,p,c,m,o);}catch(N){if(!this.isTransientSessionTokenPresentationError(N)||C>=4)throw N;console.warn("[ManagedTransportDialer] session-token presentation lost transiently; redialing over iroh",{nodeId:u,remoteDeviceId:t??null,claimedLocalDeviceId:m,attempt:C,nextAttempt:C+1,error:N instanceof Error?N.message:String(N)}),await this.sleepSessionTokenRetry(C),y=await E(i.connect_device(t??null,l),o,`wasmClient.connect_device(session-token-retry-${C})`),this.assertActive(),v=this.normalizeConnectResult(y,f,u,t??null),P=v.approvedScope??(c===null?this.deps.getApprovedScope(v.connectionId):null);}this.assertActive();}let I=P?{...v,approvedScope:P}:v;if(c!==null&&!I.approvedScope&&!n?.admissionAlreadyPresented)throw new Error("Failed to present session token: session token admission failed");return I}async presentSessionTokenToHost(e,t,n,i,o,s){try{if(typeof e.present_session_token_to_host_with_payload_and_device_id=="function"){let a=await E(e.present_session_token_to_host_with_payload_and_device_id(t,n,i,o),s,"wasmClient.present_session_token_to_host_with_payload_and_device_id");return this.normalizeApprovedScope(a)}if(typeof e.present_session_token_to_host_with_payload=="function"){let a=await E(e.present_session_token_to_host_with_payload(t,n,i),s,"wasmClient.present_session_token_to_host_with_payload");return this.normalizeApprovedScope(a)}if(typeof e.present_session_token_to_host=="function"){let a=await E(e.present_session_token_to_host(t,n),s,"wasmClient.present_session_token_to_host");return this.normalizeApprovedScope(a)}}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Failed to present session token: ${c}`)}return null}normalizeApprovedScope(e){return typeof e=="string"&&e.trim()?e.trim():null}isTransientSessionTokenPresentationError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:String(e?.message??e??"");return /session-token-response|missing connection for session-token presentation|failed to open bi-stream|connection lost|stream finished early|0 bytes read|locallyclosed|connection closed|stream closed|reset/i.test(t)}isLocalIrohRuntimeNotInitializedError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:String(e?.message??e??"");return /\bIroh node not initialized\b|\bNode not initialized\b/i.test(t)}sleepSessionTokenRetry(e){let t=Math.min(500,100*Math.max(1,e));return u(t)}};var Ir=Symbol.for("openrtc.wasm-runtime-loader");function ap(r){globalThis[Ir]=r;}async function br(){let r=globalThis[Ir];if(!r)throw new Error("[OpenRTC] Browser WASM runtime is not installed. Use the `openrtc` browser entrypoint; native applications should use `openrtc/native`.");return r()}function aa(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}function ca(r){let t=(Array.isArray(r.urls)?r.urls:[r.urls]).filter(n=>typeof n=="string"&&!n.startsWith("stun:"));return t.length===0?null:{...r,urls:Array.isArray(r.urls)?t:t[0]}}function Rr(r){if(r)return r.map(e=>ca(e)).filter(e=>e!==null)}async function Pr(r,e,t){for(let n=0;n<e;n+=1){if(await r().catch(()=>false))return true;n<e-1&&await u(t);}return false}function gi(r){return !!r?.signaling?.nativeIpc&&r?.transport?.wasm===false&&r?.fallback?.wasm===false}var en=class{constructor(e){this.host=e;this.wasmLoaded=false;this.initPromise=null;this.initPendingTimer=null;this.disposed=false;this.host.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true,this.initPromise=null,this.clearInitPendingTimer();}clearInitPendingTimer(){this.initPendingTimer&&(clearInterval(this.initPendingTimer),this.initPendingTimer=null);}async bootstrapRuntime(e){let t=e.initializeClient??true;if(e.platform==="web")return await e.initializeWeb?.(),t&&await this.init(),{ready:true,mode:"web"};let n=e.quickPollAttempts??5,i=e.quickPollIntervalMs??300,o=e.retryPollAttempts??8,s=e.retryPollIntervalMs??300,a=e.nativeInitEventTimeoutMs??4e3;if(!e.isNativeReady)return console.warn("[Client][INIT] No isNativeReady callback provided for native platform; treating runtime as not ready"),{ready:false,mode:"native"};if(!await Pr(e.isNativeReady,n,i)){await e.retryNativeInit?.();let[l,d]=await Promise.all([e.waitForNativeInitEvent?.(a)??Promise.resolve(false),Pr(e.isNativeReady,o,s)]);if(!(l||d))return {ready:false,mode:"native"}}return t&&await this.init(),{ready:true,mode:"native"}}async init(){if(!this.disposed){if(this.initPromise)return this.initPromise;if(!(this.wasmLoaded&&this.host.wasmClient&&this.host.localNodeId)){if(this.usesNativeIpcRuntimeWithoutWasmFallback())throw this.nativeWasmInitForbiddenError("Client.init()");return this.initPromise=(async()=>{try{d$1("[Client][INIT] Loading WASM module...");let{initWasm:e,WasmClient:t,start:n}=await br();if(await e(aa()),this.disposed)return;n(),this.wasmLoaded=!0,d$1("[Client][INIT] WASM module loaded");let i=d$3(this.host.options),o=typeof this.host.options.apiKey=="string"?this.host.options.apiKey.trim():"",s=typeof this.host.options.spaceKey=="string"?this.host.options.spaceKey.trim():"",a=(this.host.options.discoveryMode===void 0||this.host.options.discoveryMode==="space")&&!!o&&!!s,c=b$2(this.host.options);if(a){let m=await a$1(o,s);if(this.disposed)return;c=`space::${m}`,d$1(`[Client][INIT] space mode: WASM rooms routed to spaces/${m.slice(0,8)}...`);}if(this.disposed)return;this.host.setEffectiveRoomBackendTag(c);let l=new t(i,c);if(this.disposed)return;if(this.host.setWasmClient(l),d$1("PlutoRTC WASM Core Initialized"),this.host.setSignalingWasmClient(l),this.host.installAppLifecycleListeners(),!this.host.usesTicketOnlySignalingMode()){if(await this.host.ensureAuthenticated("init"),this.disposed||(await this.host.syncAuthTokenToWasm("init"),this.disposed))return;this.host.installAuthTokenSync();}let d=`iroh_secret_key_${e$2(this.host.options)}`,p=this.resolveIrohPersistenceMode(),u=await this.resolveIrohSecretKeyBytes(d,p);if(this.disposed||(this.host.setDeviceId(await this.host.getLocalDeviceId().catch(()=>null)),this.disposed))return;let f=Date.now();d$1(`[Client][INIT][IROH] start persistence=${p} hasSecretKey=${!!u} secretKeyLen=${u?.length||0} hasStoredDeviceId=${!!this.host.deviceId}`),this.clearInitPendingTimer(),this.initPendingTimer=setInterval(()=>{let m=Date.now()-f;console.warn(`[Client][INIT][IROH] pending elapsedMs=${m} hasWasmClient=${!!this.host.wasmClient}`);},5e3);let h="";try{h=await E(l.init_iroh(u),2e4);}catch(m){let y=Date.now()-f;throw new Error(`[Client] init_iroh stalled or failed: ${m?.message||m}; elapsed_ms=${y}; persistence=${p}; has_secret_key=${!!u}`)}finally{this.clearInitPendingTimer();}if(this.disposed)return;if(d$1(`[Client][INIT][IROH] complete elapsedMs=${Date.now()-f} nodeId=${h}`),!h)throw new Error("[Client] init_iroh returned empty node id");if(this.host.setLocalNodeId(h),this.host.deviceId||this.host.setDeviceId(await this.host.getLocalDeviceId().catch(()=>null)),this.disposed||(this.host.setNode({initialized:!0,localNodeId:h}),p==="persistent"&&!this.host.options.secretKey&&(await this.persistCurrentIrohSecret(d,u,h),this.disposed)))return;if(this.host.options.transports?.moq)try{Promise.resolve(this.host.initMoQ()).catch(m=>{this.disposed||c$1("[Client][INIT] MoQ startup handoff failed",m);});}catch(m){if(this.disposed)return;c$1("[Client][INIT] MoQ startup handoff failed",m);}if(await this.configureWebRtcIceServers(),this.disposed)return;this.host.isWebRTCTransportEnabled()&&this.broadcastWebRtcReadyCapabilityInBackground();}catch(e){throw console.error("Failed to initialize PlutoRTC:",e),this.initPromise=null,e}})(),this.initPromise}}}broadcastWebRtcReadyCapabilityInBackground(){try{Promise.resolve(this.host.broadcastTransportCapabilityUpdate("webrtc-ready")).catch(e=>{this.disposed||c$1("[Client] Late WebRTC capability update failed",e);});}catch(e){if(this.disposed)return;c$1("[Client] Late WebRTC capability update failed",e);}}async recoverLocalIrohRuntime(e){if(this.disposed)return false;let t=this.host.wasmClient;if(!t||typeof t.init_iroh!="function")return false;try{let n=`iroh_secret_key_${e$2(this.host.options)}`,i=this.resolveIrohPersistenceMode(),o=await this.resolveIrohSecretKeyBytes(n,i);c$1("[Client][CONNECT] recovering local Iroh runtime",{reason:e,hadLocalNodeId:!!this.host.localNodeId,nodeInitialized:!!this.host.node?.initialized,persistenceMode:i,hasSecretKey:!!o});let s=await E(t.init_iroh(o),2e4);return this.disposed||typeof s!="string"||!s?!1:(this.host.setLocalNodeId(s),this.host.setNode({initialized:!0,localNodeId:s}),i==="persistent"&&!this.host.options.secretKey&&await this.persistCurrentIrohSecret(n,o,s),!0)}catch(n){return c$1("[Client][CONNECT] local Iroh runtime recovery failed",{reason:e,error:n instanceof Error?n.message:String(n)}),false}}usesNativeIpcRuntimeWithoutWasmFallback(){return gi(this.host.getRuntimeCapabilities())}nativeWasmInitForbiddenError(e){let t=this.host.getRuntimeCapabilities(),n=`[Client][NATIVE-GUARD] Refusing WASM runtime init during ${e}. This OpenRTC client is using the native IPC runtime with WASM fallback disabled; desktop/Tauri must initialize Iroh through the Rust backend only.`;return console.error(n,{capabilities:t}),new Error(n)}async resolveIrohSecretKeyBytes(e,t){if(this.host.options.secretKey){let o=this.host.options.secretKey.match(/.{1,2}/g);return o?new Uint8Array(o.map(s=>parseInt(s,16))):void 0}if(t!=="persistent")return;let i=(await this.loadPersistedIrohSecretHex(e))?.match(/.{1,2}/g);return i?new Uint8Array(i.map(o=>parseInt(o,16))):void 0}async persistCurrentIrohSecret(e,t,n){let i=t??(typeof this.host.wasmClient?.iroh_secret_key=="function"?await this.host.wasmClient.iroh_secret_key().catch(()=>{}):void 0);if(i&&i.length>0){let o=Array.from(i).map(s=>Number(s).toString(16).padStart(2,"0")).join("");await this.persistIrohSecretHex(e,o),d$1(`[Client][INIT][IROH] persisted secret key bytes=${i.length} nodeId=${n}`);}else console.warn(`[Client][INIT][IROH] unable to persist secret key for nodeId=${n}`);}resolveIrohPersistenceMode(){return this.host.options.endpointIdPersistence??this.host.options.nodeIdPersistence??(typeof this.host.options.transports?.iroh=="object"?this.host.options.transports.iroh.persistenceMode:void 0)??"ephemeral"}getTauriInvoke(){if(typeof window>"u")return null;let e=window.__TAURI_INTERNALS__;return !e||typeof e.invoke!="function"?null:e.invoke.bind(e)}async loadPersistedIrohSecretHex(e){let t$1=t()?this.getTauriInvoke():null;if(t$1){let n=await t$1("openrtc_load_iroh_secret",{namespaceKey:e}).catch(()=>null);if(typeof n=="string"&&n.trim().length>0)return n.trim()}if(typeof sessionStorage<"u"){let n=sessionStorage.getItem(e);if(n)return n}if(typeof localStorage<"u"){let n=localStorage.getItem(e);if(n)return typeof sessionStorage<"u"&&sessionStorage.setItem(e,n),localStorage.removeItem(e),n}return null}async persistIrohSecretHex(e,t$1){let n=t()?this.getTauriInvoke():null;if(n){await n("openrtc_save_iroh_secret",{namespaceKey:e,secretHex:t$1}),typeof localStorage<"u"&&localStorage.removeItem(e);return}typeof sessionStorage<"u"&&sessionStorage.setItem(e,t$1),typeof localStorage<"u"&&localStorage.removeItem(e);}async getTurnCredentialsForTransportConfig(){return typeof this.host.options.turnCredentialsProvider=="function"?await this.host.options.turnCredentialsProvider()??null:await this.host.getTurnCredentials()??null}async configureWebRtcIceServers(){let e=this.host.options.transports?.webrtc;if(!!e&&(e.useTurn===true||e.privacyMode===true||this.host.options.strictMode===true))try{let n=await this.getTurnCredentialsForTransportConfig();if(this.disposed)return;if(n&&n.iceServers){let i=Array.isArray(n.iceServers)?n.iceServers:[n.iceServers];e?.privacyMode||this.host.options.strictMode?(i=Rr(i)??[],d$1(`[Client] Strict / Privacy Mode: Filtered STUN servers. Remaining=${i.length}`)):d$1(`[Client] Automatically fetched ${i.length} TURN servers.`),this.host.options.transports||(this.host.options.transports={}),this.host.options.transports.webrtc||(this.host.options.transports.webrtc={});let o=this.host.options.transports.webrtc||h$1;o.iceServers||(o.iceServers=[]),(this.host.options.strictMode||o.privacyMode)&&(o.iceServers=Rr(o.iceServers)??[]),o.iceServers.push(...i);}}catch(n){console.warn("[Client] Failed to auto-fetch TURN credentials:",n);}if(!this.host.options.strictMode&&!e?.privacyMode){if(this.disposed)return;let n=this.host.options.transports?.webrtc;n&&n.useDefaultIceServers!==false&&(!n.iceServers||Array.isArray(n.iceServers)&&n.iceServers.length===0)&&(d$1("[Client] No ICE servers provided. Using default public STUN servers."),n.iceServers=[...g$1]);}}};var tn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Runtime connection service is disposed")}async connectRaw(e,t=2e4){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let n=await this.deps.ensureWasmManagedTransport(e,null,{timeoutMs:t});return this.assertActive(),{connectionId:n.connectionId,localNodeId:this.ctx.localNodeId??"",remoteNodeId:n.remoteNodeId??n.deviceId??""}}async startAutoConnect(e){if(this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("watch"),this.disposed))return;let t=this.deps.getCurrentUserId();if(!t)throw new Error("startAutoConnect requires an authenticated user");let n=e||await this.deps.getLocalDeviceId()||this.deps.getFallbackDeviceId();if(!this.disposed){if(!n)throw new Error("startAutoConnect requires a local device identity");this.deps.startAutoConnect(t,n);}}async isConnected(e){if(this.disposed||(await this.deps.ensureWasmRuntimeForP2P(),this.disposed)||!e||!e.trim())return false;let t=this.ctx.wasmClient;if(t&&typeof t.is_connected=="function"){let i=await t.is_connected(e);if(this.disposed)return false;if(i)return true}let n=await this.deps.isConnected(e);return this.disposed?false:!!n}async disconnectNode(e){if(this.disposed||!e||!e.trim())return;let t=Array.from(this.ctx.registry.values()).filter(n=>n.deviceId===e);await Promise.allSettled(t.map(n=>this.disconnectConnectionBestEffort(n))),!this.disposed&&await this.deps.disconnectNodeTransport(e);}disconnectNodeBestEffort(e){try{this.disconnectNode(e).catch(()=>{});}catch{}}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}};var nn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Runtime identity service is disposed")}async getTicket(){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let e=await d$2(()=>this.ctx.wasmClient.endpoint_ticket(),{isActive:()=>!this.disposed});return this.assertActive(),e}async getNodeId(){return this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive(),this.ctx.localNodeId??""}async getNodeIdFromTicket(e){if(this.disposed)return null;let t=e.trim();if(!t)return null;let{irohTicket:n}=Y(t),i=this.ctx.wasmClient;if(!i||typeof i.endpoint_id_from_ticket!="function")return null;try{let o=await i.endpoint_id_from_ticket(n);return this.disposed?null:o}catch{return null}}};var on=class{constructor(e,t){this.ctx=e;this.deps=t;this.loggedNativeDiscoveryWasmSkip=false;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Runtime readiness service is disposed")}async ensureWasmRuntimeForP2P(){if(this.assertActive(),!(this.ctx.wasmClient&&this.ctx.localNodeId)&&(await this.deps.init(),this.assertActive(),!this.ctx.wasmClient||!this.ctx.localNodeId))throw new Error("Node not initialized")}async ensureSignalingReadyForDiscovery(e){if(this.disposed||this.deps.usesTicketOnlySignalingMode())return;let t=this.deps.usesNativeIpcRuntimeWithoutWasmFallback();if(!this.deps.getWasmLoaded()&&t)this.loggedNativeDiscoveryWasmSkip||(this.loggedNativeDiscoveryWasmSkip=true,c$1(`[Client][NATIVE-GUARD] Discovery ${e} is using native IPC readiness; skipped WASM init.`));else if(!this.deps.getWasmLoaded()&&!(this.ctx.wasmClient&&this.ctx.localNodeId)&&(await this.deps.init(),this.disposed))return;try{await this.deps.ensureAuthenticated("discovery");}catch(n){console.warn(`[Client][AUTH] ensureAuthenticated failed for ${e}:`,n);}if(!this.disposed)try{this.ctx.wasmClient&&await this.deps.syncAuthTokenToWasm("auth-change");}catch(n){console.warn(`[Client][WASM-AUTH] Token sync failed for ${e}:`,n);}}};var la={scheduled:0,coalesced:0,ran:0,orphanTsConnection:0,orphanRustRecord:0,orphanTsConnectionHealed:0},rn=class{constructor(e){this.deps=e;}usesTicketOnlySignalingMode(){return (this.deps.getOptions()?.signalingMode??"hosted")==="ticket-only"}usesDirectRoomBackend(){let e=this.deps.getOptions();return this.getRoomBackendTag().startsWith("space::")||(e.discoveryMode===void 0||e.discoveryMode==="space")&&typeof e.spaceKey=="string"&&e.spaceKey.trim().length>0}getRoomBackendTag(){return this.deps.getEffectiveRoomBackendTag()}requiresManagedTransportTrust(e){return !this.usesTicketOnlySignalingMode()&&!this.usesDirectRoomBackend()&&e!=="space"&&!!this.deps.getSignalingCurrentUser()?.id}getSignalingTelemetry(){return {transport:"runtime-bridge",wasmLoaded:this.deps.getWasmLoaded(),peerReconciliation:this.getPeerReconciliationStats()}}getPeerReconciliationStats(){return this.deps.getPeerReconciliationStats()??la}getProtocolCapabilities(){let e=ce.getProtocolCapabilities(),t=this.deps.getRuntimeCapabilities(),n=this.deps.getOptions().transports,i=n?.iroh!==false,o=!!n?.webrtc,s=n?.ble===true||typeof n?.ble=="object"&&n.ble.enabled!==false,a=typeof n?.moq=="object"&&typeof n.moq.relayUrl=="string"&&n.moq.relayUrl.trim().length>0;for(let l of Object.values(e)){if(l.routeImplementation==="path-label"){l.configured=void 0;continue}l.configured=l.baseProtocol==="iroh"?i:l.baseProtocol==="webrtc"?o:a;}e.ble.configured=s;let c=(l,d,p)=>{e[l].configured=d,e[l].available=d&&p,d?p||(e[l].reason=`The running host did not report '${l}' as available.`):e[l].reason=`Protocol '${l}' is not enabled in ClientOptions.transports.`;};return c("iroh",i,t?.transport.irohQuic===true),c("webrtc",o,t?.transport.webRtcUpgrade===true||t?.transport.nativeWebRtc===true),c("moq",a,t?.transport.moq===true),e.ble.available=s&&t?.transport.ble===true,s?t?.transport.ble!==true&&(e.ble.reason="The running host did not report 'ble' as compiled and enabled."):e.ble.reason="Protocol 'ble' is not enabled in ClientOptions.transports.",e}async getRuntimeStatus(){let e="unknown";return typeof window<"u"&&(e=window.__TAURI__?"tauri":"browser"),{runtime:e,wasmLoaded:this.deps.getWasmLoaded(),localNodeId:this.deps.getLocalNodeId()||void 0,userId:this.deps.getSignalingCurrentUser()?.id??void 0}}};function Tr(r){let{host:e}=r;return new en({get options(){return e.getOptions()},get wasmClient(){return e.getWasmClient()},get node(){return e.getNode()},get localNodeId(){return e.getLocalNodeId()},get deviceId(){return e.getDeviceId()},setWasmClient:t=>e.setWasmClient(t),setSignalingWasmClient:t=>e.setSignalingWasmClient(t),setNode:t=>e.setNode(t),setLocalNodeId:t=>e.setLocalNodeId(t),setDeviceId:t=>e.setDeviceId(t),setEffectiveRoomBackendTag:t=>e.setEffectiveRoomBackendTag(t),usesTicketOnlySignalingMode:()=>r.getStatus().usesTicketOnlySignalingMode(),ensureAuthenticated:t=>e.ensureAuthenticated(t),syncAuthTokenToWasm:(t,n)=>e.syncAuthTokenToWasm(t,n),installAuthTokenSync:()=>e.installAuthTokenSync(),installAppLifecycleListeners:()=>r.getAppLifecycle().installListeners(),initMoQ:()=>e.initMoQ(),isWebRTCTransportEnabled:()=>e.isWebRTCTransportEnabled(),getLocalDeviceId:()=>e.getLocalDeviceId(),getTurnCredentials:()=>e.getTurnCredentials(),getRuntimeCapabilities:()=>e.getRuntimeCapabilities(),broadcastTransportCapabilityUpdate:t=>e.broadcastTransportCapabilityUpdate(t),registerDisposer:t=>e.registerDisposer(t)})}function Ar(r){let{host:e}=r;return new tn(e.getContext(),{ensureWasmRuntimeForP2P:()=>r.getReadiness().ensureWasmRuntimeForP2P(),ensureSignalingReadyForDiscovery:t=>r.getReadiness().ensureSignalingReadyForDiscovery(t),ensureWasmManagedTransport:(t,n,i)=>r.getManagedDialer().ensureWasmManagedTransport(t,n,i),getCurrentUserId:()=>e.getCurrentUserId(),getLocalDeviceId:()=>e.getLocalDeviceId(),getFallbackDeviceId:()=>e.getDeviceId(),startAutoConnect:(t,n)=>e.startAutoConnect(t,n),isConnected:t=>e.isConnected(t),disconnectNodeTransport:t=>e.disconnectNodeTransport(t)})}function wr(r){return new Zt(r.getContext(),{getDeterministicConnectionId:e=>r.getDeterministicConnectionId(e),getApprovedScope:e=>r.getApprovedScope(e),getLocalDeviceId:()=>r.getLocalDeviceId(),getFallbackLocalDeviceId:()=>r.getDeviceId()??r.getOptions().localDeviceId??null,rememberRouteRepairTokenForNode:(e,t,n)=>r.rememberRouteRepairTokenForNode(e,t,n),getRouteRepairTokenForNode:e=>r.getRouteRepairTokenForNode?.(e),getRouteRepairTokenPayloadForNode:e=>r.getRouteRepairTokenPayloadForNode?.(e)})}function kr(r){return new nn(r.host.getContext(),{ensureWasmRuntimeForP2P:()=>r.getReadiness().ensureWasmRuntimeForP2P()})}function Nr(r){let{host:e}=r;return new on(e.getContext(),{init:()=>r.getBootstrap().init(),usesTicketOnlySignalingMode:()=>r.getStatus().usesTicketOnlySignalingMode(),usesNativeIpcRuntimeWithoutWasmFallback:()=>gi(e.getRuntimeCapabilities()),getWasmLoaded:()=>r.getBootstrapWasmLoaded(),ensureAuthenticated:t=>e.ensureAuthenticated(t),syncAuthTokenToWasm:t=>e.syncAuthTokenToWasm(t)})}function Dr(r){let{host:e}=r;return new rn({getEffectiveRoomBackendTag:()=>e.getEffectiveRoomBackendTag(),getLocalNodeId:()=>e.getLocalNodeId(),getOptions:()=>e.getOptions(),getPeerReconciliationStats:()=>e.getPeerReconciliationStats(),getRuntimeCapabilities:()=>e.getRuntimeCapabilities(),getSignalingCurrentUser:()=>({id:e.getCurrentUserId()}),getWasmLoaded:()=>r.getBootstrapWasmLoaded()})}function Mr(r){return new Xt(r.getContext())}function Er(r){return new hi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getWasmClient:()=>r.wasmClient,setWasmClient:e=>{r.wasmClient=e;},getNode:()=>r.node,setNode:e=>{r.node=e;},getLocalNodeId:()=>r.localNodeId,setLocalNodeId:e=>{r.localNodeId=e;},getDeviceId:()=>r.deviceId,setDeviceId:e=>{r.deviceId=e;},setEffectiveRoomBackendTag:e=>{r.setEffectiveRoomBackendTag(e);},getEffectiveRoomBackendTag:()=>r.getEffectiveRoomBackendTag(),getPeerReconciliationStats:()=>r.getExistingPeerReconciliationStats(),getCurrentUserId:()=>r.signalingBackendController.getCurrentUser()?.id??null,getRuntimeCapabilities:()=>r.signalingBackendController.getRuntimeCapabilities(),getLocalDeviceId:()=>r.signalingBackendController.getLocalDeviceId(),getTurnCredentials:()=>r.signalingBackendController.getTurnCredentials(),setSignalingWasmClient:e=>r.signalingBackendController.setWasmClient(e),startAutoConnect:(e,t)=>r.signalingBackendController.startAutoConnect(e,t),isConnected:e=>r.signalingBackendController.isConnected(e),disconnectNodeTransport:e=>r.transportHealth.disconnectNodeTransport(e),getDeterministicConnectionId:e=>r.peerIdentity.getDeterministicConnectionId(e),getApprovedScope:e=>r.sessionTokens.getApprovedScope(e),rememberRouteRepairTokenForNode:(e,t,n)=>r.sessionTokens.rememberRouteRepairTokenForNode(e,t,n),getRouteRepairTokenForNode:e=>r.sessionTokens.getRouteRepairTokenForNode(e),getRouteRepairTokenPayloadForNode:e=>r.sessionTokens.getRouteRepairTokenPayloadForNode(e),ensureAuthenticated:e=>r.auth.ensureAuthenticated(e),syncAuthTokenToWasm:(e,t)=>r.auth.syncAuthTokenToWasm(e,t),installAuthTokenSync:()=>r.auth.installAuthTokenSync(),initMoQ:()=>r.moqServices.init(),isWebRTCTransportEnabled:()=>j(r.options),broadcastTransportCapabilityUpdate:e=>r.transportHandshake.broadcastTransportCapabilityUpdate(e),registerDisposer:e=>r.lifecycleScope.register(e)})}var hi=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getBootstrap:()=>this.bootstrap,getBootstrapWasmLoaded:()=>this._bootstrap?.wasmLoaded??false,getManagedDialer:()=>this.managedDialer,getReadiness:()=>this.readiness,getStatus:()=>this.status,getAppLifecycle:()=>this.appLifecycle}}get bootstrap(){return this._bootstrap??(this._bootstrap=Tr(this.factoryHost))}get connections(){return this._connections??(this._connections=Ar(this.factoryHost))}get managedDialer(){return this._managedDialer??(this._managedDialer=wr(this.host))}get identity(){return this._identity??(this._identity=kr(this.factoryHost))}get readiness(){return this._readiness??(this._readiness=Nr(this.factoryHost))}get status(){return this._status??(this._status=Dr(this.factoryHost))}get appLifecycle(){return this._appLifecycle??(this._appLifecycle=Mr(this.host))}};var sn=class{constructor(e,t){this.ctx=e;this.deps=t;this.connectionKeyAgreementById=new Map;this.connectionKeyAgreementRemotePublicById=new Map;this.negotiatedByConnectionId=new Map;this.negotiatedByPeerId=new Map;this.negotiatedFingerprintByCrypto=new WeakMap;this.waiters=[];this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}getApplicationCrypto(e){return e?this.deps.getConfiguredApplicationCrypto()??this.negotiatedByConnectionId.get(e.id):this.deps.getConfiguredApplicationCrypto()}getNegotiatedForPeer(e){let t=typeof e=="string"?e.trim():"";if(!t)return;let n=Array.from(this.ctx.registry.values()).reverse().find(l=>!l.isClosed&&(l.id===t||l.remoteNodeId===t));if(n)return this.negotiatedByConnectionId.get(n.id);let i=this.deps.getKnownDeviceNodeId(t),o=[this.deps.getPeerState(t),i?this.deps.getPeerState(i):void 0].filter(l=>!!l);for(let l of o){let d=l.connectionId?.trim();if(d)return this.negotiatedByConnectionId.get(d);for(let p of [...l.connectionIds??[]].reverse()){let u=p?.trim();if(!u)continue;let f=this.negotiatedByConnectionId.get(u);if(f)return f}}let a=Array.from(this.ctx.registry.values()).filter(l=>{let d=this.deps.getKnownDeviceIdForNode(l.remoteNodeId);return l.id===t||l.remoteNodeId===t||l.deviceId===t||i&&l.remoteNodeId===i||d===t}).filter(l=>!l.isClosed).reverse(),c=a.find(l=>l.id===t||l.remoteNodeId===t)??a.find(l=>!!i&&l.remoteNodeId===i)??a[0];return c?this.negotiatedByConnectionId.get(c.id):this.negotiatedByPeerId.get(t)}resolveForPeer(e,t){let n=this.deps.getConfiguredApplicationCrypto();if(n)return n;if(t)return this.negotiatedByConnectionId.get(t.id);if(e)return this.getNegotiatedForPeer(e)}waitForPeer(e,t=1e4){let n=this.resolveForPeer(e);return n||!e||t<=0||this.disposed?Promise.resolve(n):new Promise(i=>{let o={peerId:e,resolve:i,timer:setTimeout(()=>{this.waiters=this.waiters.filter(s=>s!==o),i(void 0);},t)};this.waiters.push(o);})}dispose(){if(this.disposed)return;this.disposed=true;let e=this.waiters.splice(0);for(let t of e)clearTimeout(t.timer),t.resolve(void 0);this.connectionKeyAgreementById.clear(),this.connectionKeyAgreementRemotePublicById.clear(),this.negotiatedByConnectionId.clear(),this.negotiatedByPeerId.clear();}clearConnection(e){let t=this.negotiatedByConnectionId.get(e),n=this.wasmClient;try{n?.clearConnectionApplicationCryptoKey?.(e);}catch(i){console.warn("[Client][KEY-AGREEMENT] Failed to retire native application crypto",{connectionId:e,error:i});}if(this.connectionKeyAgreementById.delete(e),this.connectionKeyAgreementRemotePublicById.delete(e),this.negotiatedByConnectionId.delete(e),!(!t||Array.from(this.negotiatedByConnectionId.values()).includes(t)))for(let[i,o]of this.negotiatedByPeerId)o===t&&this.negotiatedByPeerId.delete(i);}notifyWaiters(){if(this.waiters.length===0)return;let e=[];for(let t of this.waiters){let n=this.resolveForPeer(t.peerId);if(!n){e.push(t);continue}clearTimeout(t.timer),t.resolve(n);}this.waiters=e;}resolveStreamTools(e,t){let n=this.resolveForPeer(e,t);return n&&c$1("[Client][KEY-AGREEMENT] Resolved application stream crypto",{peerId:e??null,connectionId:t?.id??null,keyFingerprint:this.negotiatedFingerprintByCrypto.get(n)??"configured"}),n?n$1(n):void 0}shouldNegotiateKeyAgreement(){if(this.deps.getConfiguredApplicationCrypto())return false;if(this.deps.getAutomaticApplicationKeyAgreement()===false)throw new Error("[OpenRTC] automaticApplicationKeyAgreement cannot be disabled; configure applicationCrypto only for explicit pre-shared-key mode");return true}async ensureConnectionKeyAgreementState(e){let t=this.connectionKeyAgreementById.get(e.id);if(t)return t;let n=io();return this.connectionKeyAgreementById.set(e.id,n),n}async handleKeyAgreement(e,t){if(!this.shouldNegotiateKeyAgreement())return {remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null};await this.ensureConnectionKeyAgreementState(e);let n=so(t.applicationKeyAgreement),i=t.capabilities?.applicationKeyAgreement===true||!!n;if(!n||!i||!this.ctx.localNodeId){if((typeof e.getControlFrameMode=="function"?e.getControlFrameMode():"typed")==="native-main"&&!i&&!n)return {remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null};throw new Error("Peer does not support mandatory application key agreement")}let o=this.connectionKeyAgreementById.get(e.id);if(!o)return {remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null};let s=t.applicationKeyAgreement?.publicKey?.trim()??"",a=xe(n),c=this.connectionKeyAgreementRemotePublicById.get(e.id)??null,l=!!s&&c!==s;e.markApplicationKeyAgreementObserved();let d=this.negotiatedByConnectionId.get(e.id);if(d&&s&&c===s){e.setApplicationCrypto(d);let y=this.ctx.registry.get(e.id);y&&y!==e&&!y.isClosed&&y.setApplicationCrypto(d),this.deps.notifyApplicationRouteReady(e,`key-agreement:${t.action??"hello"}:unchanged`),c$1("[Client][KEY-AGREEMENT] Reused unchanged application crypto",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t.action??"hello"});let v=this.claimReplyAction(e.id,t.action,a);return {remotePublicChanged:false,cryptoReady:true,replyAction:v?.action??null,replyClaimId:v?.claimId??null}}let p=oo(o.secretKey,n,this.ctx.localNodeId,e.remoteNodeId);s&&this.connectionKeyAgreementRemotePublicById.set(e.id,s);let u=m$1(p,{requireEncrypted:true,replayProtection:true}),f=xe(p);this.negotiatedFingerprintByCrypto.set(u,f),this.index(e,u),e.setApplicationCrypto(u);let h=this.ctx.registry.get(e.id);h&&h!==e&&!h.isClosed&&typeof h.setApplicationCrypto=="function"&&h.setApplicationCrypto(u),await this.syncKeyToNative(e.id,p),this.notifyWaiters(),this.deps.notifyApplicationRouteReady(e,`key-agreement:${t.action??"hello"}`),c$1("[Client][KEY-AGREEMENT] Application crypto ready",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t.action??"hello",remoteSupports:i,remotePublicChanged:l,keyFingerprint:f,localPublicFingerprint:xe(o.publicKey),remotePublicFingerprint:xe(n)});let m=this.claimReplyAction(e.id,t.action,a);return {remotePublicChanged:l,cryptoReady:true,replyAction:m?.action??null,replyClaimId:m?.claimId??null}}claimReplyAction(e,t,n){return !n||t==="ack"?null:{action:t==="response"?"ack":"response",claimId:n}}releaseReplyClaim(e,t,n){}index(e,t){this.negotiatedByConnectionId.set(e.id,t);let n=new Set([e.id,e.remoteNodeId,e.deviceId,this.deps.getKnownDeviceIdForNode(e.remoteNodeId)??""]);for(let i of n){let o=typeof i=="string"?i.trim():"";o&&this.negotiatedByPeerId.set(o,t);}}getForConnectionOrPeer(e,t){return this.negotiatedByConnectionId.get(e)??this.negotiatedByPeerId.get(t)}indexPeer(e,t){let n=typeof e=="string"?e.trim():"";n&&this.negotiatedByPeerId.set(n,t);}reindexDevice(e){let t=typeof e.nodeId=="string"?e.nodeId.trim():"";if(!t||!e.deviceId)return;let n=this.getNegotiatedForPeer(t);n&&this.negotiatedByPeerId.set(e.deviceId,n);}async syncRequiredToNative(e){let t=this.wasmClient;!t||typeof t.setConnectionApplicationCryptoRequired!="function"||await t.setConnectionApplicationCryptoRequired(e);}async syncKeyToNative(e,t){let n=this.wasmClient;if(!(!n||typeof n.setConnectionApplicationCryptoKey!="function")){await this.syncRequiredToNative(e);try{await n.setConnectionApplicationCryptoKey(e,Array.from(t));}catch(i){let o=this.ctx.registry.get(e);throw o&&typeof o.requireApplicationCrypto=="function"&&o.requireApplicationCrypto(),console.error("[Client][KEY-AGREEMENT] Failed to sync derived key to native runtime",{connectionId:e,error:i}),i}}}markRequired(e){typeof e.requireApplicationCrypto=="function"&&e.requireApplicationCrypto(),this.syncRequiredToNative(e.id).catch(t=>{console.warn("[Client][KEY-AGREEMENT] Failed to sync required-crypto flag to native runtime",{connectionId:e.id,error:t});});}hydrateAdoptedConnection(e,t){if(e.isClosed||this.resolveForPeer(e.remoteNodeId,e))return false;let n=this.getNegotiatedForPeer(e.remoteNodeId);return n?(this.negotiatedByConnectionId.set(e.id,n),e.setApplicationCrypto(n),this.notifyWaiters(),this.deps.notifyApplicationRouteReady(e,t),c$1("[Client][HANDSHAKE] hydrated adopted connection application crypto from peer index",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t}),true):false}openWebRTCExplicitTransferPayload(e,t){let n=this.resolveForPeer(t?.remoteNodeId,t);return n?n$1(n).openFrame(e):e}protectDirectMoQPayload(e,t,n){return this.resolveForPeer(t,n)?.protectPayload(3,e)??e}openDirectMoQPayload(e,t,n){let i=this.resolveForPeer(t,n);if(!i||!l$1(e))return {payload:null,encrypted:false,proofEligible:false};let o=i.openPayload(3,e);return o?{payload:o,encrypted:true,proofEligible:true}:{payload:i.openPayload(0,e),encrypted:true,proofEligible:false}}get wasmClient(){return this.ctx.wasmClient}};var pa=15e3,ua=2,ga=150,an=class{constructor(e,t){this.ctx=e;this.deps=t;this.pendingTrustApprovals=new Map;this.pendingTrustApprovalScopes=new Map;this.rejectionCooldowns=new Map;this.approvedNodes=new Set;this.approvedConnectionIds=new Set;this.approvedScopesByConnectionId=new Map;this.routeRepairTokenByNodeId=new Map;this.routeRepairTokenPayloadByNodeId=new Map;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(this.disposed)return;this.disposed=true,this.deps.retirePendingReciprocalAdmissions("session-token-service-dispose"),this.deps.clearManagedPresenceTicket(),this.clearInMemoryState();let e=this.wasmClient;e&&typeof e.clear_session_tokens=="function"&&e.clear_session_tokens();}async getEndpointTicketWithToken(e,t=0){if(this.disposed)throw new Error("Session token service is disposed");await this.deps.ensureWasmRuntimeForP2P();let n=this.wasmClient;if(n&&typeof n.endpoint_ticket_with_token=="function"){let o=n.endpoint_ticket_with_token.bind(n);return await d$2(()=>o(e,t),{isActive:()=>!this.disposed})}if(e.trim()==="user-device")throw new Error("Managed user-device admission requires Rust/WASM endpoint_ticket_with_token support.");let i=await this.deps.getTicket();return this.buildCompoundTicketWithToken(i,e,t)}buildCompoundTicketWithToken(e,t,n=0){if(this.disposed)throw new Error("Session token service is disposed");let i=Do(),o=t.trim()==="user-device"?void 0:Date.now()+9e5,s=this.wasmClient;return s&&typeof s.register_session_token=="function"&&(typeof o=="number"&&typeof s.register_session_token_with_expiry_ms=="function"?s.register_session_token_with_expiry_ms(i,t,n,o):s.register_session_token(i,t,n)),dt(e,i,t,n,o)}registerSessionToken(e,t,n){if(this.disposed)return;let i=this.wasmClient;i&&typeof i.register_session_token=="function"&&i.register_session_token(e,t,n);}revokeSessionToken(e){if(this.disposed)return;o("Client.revokeSessionToken",{tokenLength:e.length}),this.deps.retirePendingReciprocalAdmissions("session-token-revoke");let t=this.wasmClient;if(t&&typeof t.revoke_session_token=="function"){let n=t.revoke_session_token(e),i=Array.isArray(n)?n.filter(o=>typeof o=="string"&&!!o.trim()):[];for(let o of i){let s=this.ctx.registry.get(o);this.clearConnectionApproval(o),s&&(this.approvedNodes.delete(s.remoteNodeId),this.disconnectConnectionBestEffort(s));}}}async revokeTokensByScope(e){if(this.disposed)return [];o("Client.revokeTokensByScope",{grantScope:e}),this.deps.retirePendingReciprocalAdmissions(`session-token-scope-revoke:${e}`);let t=e.trim(),n=Array.from(this.approvedScopesByConnectionId.entries()).filter(([,l])=>l===t).map(([l])=>l),i=n.map(l=>this.ctx.registry.get(l)).filter(l=>!!l);if(await this.deps.ensureWasmRuntimeForP2P(),this.disposed)return [];let o$1=this.wasmClient,s=o$1&&typeof o$1.revoke_tokens_by_scope=="function"?await o$1.revoke_tokens_by_scope(e):[],a=Array.from(new Set([...Array.isArray(s)?s:[],...n]));if(a.length===0)return [];for(let l of a)this.clearConnectionApproval(l);let c=Array.from(new Set([...i,...a.map(l=>this.ctx.registry.get(l)).filter(l=>!!l)]));return await Promise.allSettled(c.map(l=>this.disconnectConnectionBestEffort(l))),a}async clearSessionTokens(){if(o("Client.clearSessionTokens",{}),this.deps.retirePendingReciprocalAdmissions("session-token-clear"),this.disposed){this.clearInMemoryState();return}if(await this.deps.ensureWasmRuntimeForP2P(),this.deps.clearManagedPresenceTicket(),this.disposed){this.clearInMemoryState();return}this.clearInMemoryState();let e=this.wasmClient;e&&typeof e.clear_session_tokens=="function"&&e.clear_session_tokens();}async validateIncomingSessionToken(e,t,n){if(this.disposed)return {ok:false,reason:"session-token-service-disposed"};let i=this.wasmClient;if(!i||typeof i.validate_session_token!="function")return e.trim()?{ok:false,reason:"session-token-validator-unavailable"}:{ok:true};try{let o="";return t&&n&&typeof i.validate_session_token_for_connection_with_payload=="function"?o=await i.validate_session_token_for_connection_with_payload(e,t,n):t&&typeof i.validate_session_token_for_connection=="function"?o=await i.validate_session_token_for_connection(e,t):o=i.validate_session_token(e),{ok:!0,scope:o||void 0}}catch(o){return {ok:false,reason:o?.message||`${o}`}}}async validateIncomingSessionTokenWithRetry(e,t,n){if(this.disposed)return {ok:false,reason:"session-token-service-disposed"};let i=await this.validateIncomingSessionToken(e,t,n?.tokenPayload);if(i.ok||!e||!(i.reason??"").toLowerCase().includes("unknown session token"))return i;for(let s=1;s<=ua;s+=1){if(await u(ga*s),this.disposed)return {ok:false,reason:"session-token-service-disposed"};if(i=await this.validateIncomingSessionToken(e,t,n?.tokenPayload),i.ok)return c$1("[Client][SESSION-TOKEN] validation recovered after retry",{source:n?.source??"unknown",remoteNodeId:n?.remoteNodeId??null,connectionId:t??null,attempt:s}),i}return i}rememberPendingTrustApproval(e,t){if(this.disposed||!e)return;this.pendingTrustApprovals.set(e,Date.now());let n=typeof t=="string"?t.trim():"";n?this.pendingTrustApprovalScopes.set(e,n):this.pendingTrustApprovalScopes.delete(e);}consumePendingTrustApproval(e){if(this.disposed)return {approved:false};let t=this.pendingTrustApprovals.get(e);if(!t)return {approved:false};let n=this.pendingTrustApprovalScopes.get(e)??null;return this.pendingTrustApprovals.delete(e),this.pendingTrustApprovalScopes.delete(e),Date.now()-t>pa?{approved:false}:{approved:true,scope:n}}applyTrustApproval(e,t,n="session-token"){if(this.disposed||!e||e.isClosed)return;let o=(typeof t=="string"?t.trim():"")||this.approvedScopesByConnectionId.get(e.id)||"";this.rememberPendingTrustApproval(e.id,o),this.rejectionCooldowns.delete(e.remoteNodeId),this.deps.clearTrustFailureCooldown(e.remoteNodeId),this.approvedNodes.add(e.remoteNodeId),this.approvedConnectionIds.add(e.id),o&&this.approvedScopesByConnectionId.set(e.id,o);let s=this.deps.sessionTokenScopeAllowsDeviceBinding(o),a=s?this.deps.getKnownDeviceIdForNode(e.remoteNodeId):null,c=this.deps.initializeConnectionTrust(e,a);c.required=false,c.verified=true,c.failed=false,c.failureReason=void 0,c.issuedChallenge=null,s?c.verifiedDeviceId=c.verifiedDeviceId??c.expectedDeviceId??a??null:(c.verifiedDeviceId=null,c.expectedDeviceId=null),this.deps.applyConnectionTrustProjection(e);let l=s?c.verifiedDeviceId??c.expectedDeviceId??a??null:null;l&&this.deps.bindConnectionDeviceIdInRust(e,l),o&&this.deps.addPeerScope(e.id,o),c$1("[Client][AUTH] session-token approval applied to connection trust",{connectionId:e.id,remoteNodeId:e.remoteNodeId,scope:t??null,source:n}),this.deps.isWebRTCTransportEnabled()&&e.remoteSupportsWebRTC&&e.requestWebRTCUpgrade("session-token-trust-applied");}clearConnectionApproval(e){this.disposed||(this.approvedConnectionIds.delete(e),this.approvedScopesByConnectionId.delete(e),this.pendingTrustApprovals.delete(e),this.pendingTrustApprovalScopes.delete(e));}approveNode(e){this.disposed||this.approvedNodes.add(e);}approveConnection(e){this.disposed||this.approvedConnectionIds.add(e);}isApproved(e,t){return this.approvedConnectionIds.has(e)||this.approvedNodes.has(t)}isApprovedNode(e){return this.approvedNodes.has(e)}isApprovedConnection(e){return this.approvedConnectionIds.has(e)}getApprovedNodes(){return this.approvedNodes}getApprovedConnectionIds(){return this.approvedConnectionIds}clearRejectionCooldown(e){this.rejectionCooldowns.delete(e);}getRejectionCooldown(e){return this.rejectionCooldowns.get(e)}setRejectionCooldown(e,t){this.disposed||this.rejectionCooldowns.set(e,t);}getApprovedScope(e){return this.approvedScopesByConnectionId.get(e)??null}setApprovedScope(e,t){this.disposed||this.approvedScopesByConnectionId.set(e,t);}rememberRouteRepairTokenForNode(e,t,n){this.disposed||(this.routeRepairTokenByNodeId.set(e,t),this.routeRepairTokenPayloadByNodeId.set(e,n));}async rememberRouteRepairTokenFromTicket(e){if(this.disposed)return false;let t=e.trim();if(!t)return false;let{irohTicket:n,tokenSuffix:i}=Y(t);if(!i)return false;let o=ne(n,i),s=typeof o?.t=="string"?o.t.trim():"",a=this.wasmClient;if(!s||typeof a?.endpoint_id_from_ticket!="function")return false;let c=String(await a.endpoint_id_from_ticket(n)).trim();return !c||this.disposed?false:(this.rememberRouteRepairTokenForNode(c,s,i),true)}getRouteRepairTokenForNode(e){return this.routeRepairTokenByNodeId.get(e)}getRouteRepairTokenPayloadForNode(e){return this.routeRepairTokenPayloadByNodeId.get(e)}clearInMemoryState(){this.routeRepairTokenByNodeId.clear(),this.routeRepairTokenPayloadByNodeId.clear(),this.pendingTrustApprovals.clear(),this.pendingTrustApprovalScopes.clear(),this.rejectionCooldowns.clear(),this.approvedNodes.clear(),this.approvedConnectionIds.clear(),this.approvedScopesByConnectionId.clear();}get wasmClient(){return this.ctx.wasmClient}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}};function Lr(r){return new mi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),getTicket:()=>r.runtimeIdentity.getTicket(),clearManagedPresenceTicketIfExists:()=>r.accessServices.clearManagedPresenceTicketIfExists(),retirePendingReciprocalAdmissionsIfExists:e=>r.retirePendingReciprocalAdmissionsIfExists(e),clearTrustFailureCooldown:e=>{r.connectionTrust.clearFailureCooldown(e);},sessionTokenScopeAllowsDeviceBinding:e=>r.connectionTrust.sessionTokenScopeAllowsDeviceBinding(e),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),initializeConnectionTrust:(e,t)=>r.connectionTrust.initialize(e,t),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),bindConnectionDeviceIdInRust:(e,t)=>r.connectionDeviceBinder.bindConnectionDeviceIdInRust(e,t),addPeerScope:(e,t)=>{r.peerServices.addPeerScope(e,t);},isWebRTCTransportEnabled:()=>j(r.options),getConfiguredApplicationCrypto:()=>r.options?.applicationCrypto,getAutomaticApplicationKeyAgreement:()=>r.options?.automaticApplicationKeyAgreement,getKnownDeviceNodeId:e=>r.deviceDirectory.getKnownDeviceNodeId(e),getPeerState:e=>r.peerServices.getPeerState(e),notifyApplicationRouteReady:(e,t)=>r.transportUpgrade.notifyApplicationRouteReady(e,t)})}var mi=class{constructor(e){this.host=e;}get sessionTokens(){return this._sessionTokens||(this._sessionTokens=new an(this.host.getContext(),{ensureWasmRuntimeForP2P:()=>this.host.ensureWasmRuntimeForP2P(),getTicket:()=>this.host.getTicket(),clearManagedPresenceTicket:()=>this.host.clearManagedPresenceTicketIfExists(),retirePendingReciprocalAdmissions:e=>this.host.retirePendingReciprocalAdmissionsIfExists(e),clearTrustFailureCooldown:e=>this.host.clearTrustFailureCooldown(e),sessionTokenScopeAllowsDeviceBinding:e=>this.host.sessionTokenScopeAllowsDeviceBinding(e),getKnownDeviceIdForNode:e=>this.host.getKnownDeviceIdForNode(e),initializeConnectionTrust:(e,t)=>this.host.initializeConnectionTrust(e,t),applyConnectionTrustProjection:e=>this.host.applyConnectionTrustProjection(e),bindConnectionDeviceIdInRust:(e,t)=>this.host.bindConnectionDeviceIdInRust(e,t),addPeerScope:(e,t)=>this.host.addPeerScope(e,t),isWebRTCTransportEnabled:()=>this.host.isWebRTCTransportEnabled()})),this._sessionTokens}get applicationCrypto(){return this._applicationCrypto||(this._applicationCrypto=new sn(this.host.getContext(),{getConfiguredApplicationCrypto:()=>this.host.getConfiguredApplicationCrypto(),getAutomaticApplicationKeyAgreement:()=>this.host.getAutomaticApplicationKeyAgreement(),getKnownDeviceNodeId:e=>this.host.getKnownDeviceNodeId(e),getKnownDeviceIdForNode:e=>this.host.getKnownDeviceIdForNode(e),getPeerState:e=>this.host.getPeerState(e),notifyApplicationRouteReady:(e,t)=>this.host.notifyApplicationRouteReady(e,t)})),this._applicationCrypto}resolveExistingApplicationCryptoForPeer(e,t){return this._applicationCrypto?.resolveForPeer(e,t)}getApplicationCrypto(e){return this.host.getConfiguredApplicationCrypto()||!e?this.host.getConfiguredApplicationCrypto():this.applicationCrypto.getApplicationCrypto(e)}resolveApplicationCryptoForPeer(e,t){return this.host.getConfiguredApplicationCrypto()||!e&&!t?this.host.getConfiguredApplicationCrypto():this.applicationCrypto.resolveForPeer(e,t)}clearApplicationCryptoForConnection(e){this._applicationCrypto?.clearConnection(e);}releaseApplicationKeyAgreementReply(e,t,n){this._applicationCrypto?.releaseReplyClaim(e,t,n);}waitForApplicationCryptoForPeer(e,t=0){return this.host.getConfiguredApplicationCrypto()||!e||t<=0?Promise.resolve(this.host.getConfiguredApplicationCrypto()):this.applicationCrypto.waitForPeer(e,t)}};var cn=class{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}buildApplicationIncomingStreamEvent(e){if(this.disposed)return e;if((e.protocolHint==="explicit"||!!e.channel?.channelId)&&!this.deps.isManagedApplicationStreamAuthorized(e.remoteNodeId))return this.deps.logIncomingDiagnostic("session-token:drop-unadmitted-application-stream",{remoteNodeId:e.remoteNodeId||"unknown",traceId:e.traceId||null,protocolHint:e.protocolHint??null,channelId:e.channel?.channelId??null}),{...e,invalid:true};if(this.shouldTreatIncomingStreamAsTransportOnly(e))return e;let n=this.deps.resolveApplicationCryptoStreamTools(e.remoteNodeId);if(!n||e.invalid||e.protocolHint==="explicit"||e.protocolHint==="native-main")return e;try{if(e.type==="uni"){let i=e.stream;return !i||typeof i.getReader!="function"?e:i.applicationCryptoWrapped===!0?{...e,applicationCrypto:n}:{...e,stream:n.wrapReadable(i),applicationCrypto:n}}if(e.type==="bi"&&y(e.stream)){let i=e.stream;return i?.applicationCryptoWrapped===!0?{...e,applicationCrypto:n}:e.protocolHint==="control"?{...e,applicationCrypto:n}:{...e,stream:{...i,send:n.wrapWritable(i.send),recv:n.wrapReadable(i.recv)},applicationCrypto:n}}}catch(i){this.deps.logIncomingDiagnostic("application-crypto:wrap-listener-stream-failed",{remoteNodeId:e.remoteNodeId||"unknown",traceId:e.traceId||null,protocolHint:e.protocolHint??null,error:i});}return e}shouldTreatIncomingStreamAsTransportOnly(e){if(this.disposed||e.type!=="bi")return false;let t=e.channel?.channelId;return t?this.deps.isTransportOnlyChannel(t):e.protocolHint!=="explicit"?false:this.deps.usesTicketOnlySignalingMode()?true:this.deps.hasTransportOnlyConnectionForRemoteNode(e.remoteNodeId)}dispatchSyntheticExplicitIncomingStream(e,t){if(this.disposed)return;if(!this.deps.isManagedApplicationStreamAuthorized(e.remoteNodeId)){this.deps.logIncomingDiagnostic("session-token:drop-unadmitted-webrtc-explicit-stream",{connectionId:e.id,remoteNodeId:e.remoteNodeId});return}c$1("[Client][WebRTC][transfer] Dispatching synthetic explicit stream from WebRTC datachannel",{connectionId:e.id,remoteNodeId:e.remoteNodeId,payloadBytes:t.byteLength});let n={send:new WritableStream({write(){}}),recv:new ReadableStream({start(a){a.enqueue(t),a.close();}}),endpoint_id:e.remoteNodeId},i=this.deps.getConnectionChannelId(e.id),o={type:"bi",stream:n,remoteNodeId:e.remoteNodeId,protocolHint:"explicit",traceId:`webrtc-explicit-${Date.now()}`,channel:i?{channelId:i}:null};if(this.deps.dispatchIncomingChannelListeners(o)||this.disposed)return;this.deps.dispatchIncomingGenericListeners(o)||this.handleSyntheticExplicitFallbackInBackground(e,o);}handleSyntheticExplicitFallbackInBackground(e,t){let n=i=>{this.disposed||c$1("[Client][INCOMING] Failed to process synthetic explicit stream",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:i});};try{Promise.resolve(this.deps.handleUnhandledIncomingStreamEvent(t)).catch(n);}catch(i){n(i);}}};var ln=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Application stream controller is disposed")}async closeWritableBestEffort(e){if(e)try{let t=e.getWriter?.();if(!t)return;try{await t.close();}catch{}finally{try{t.releaseLock();}catch{}}}catch{}}async openBi(e){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let t=this.ctx.wasmClient;c$1("[Client][OPEN-BI] Opening bidirectional application stream",{peerId:e,hasOpenPeerBi:typeof t.open_peer_bi=="function"});let n=typeof t.open_peer_bi=="function"?await t.open_peer_bi(e,5e3):await t.open_bi(e);this.disposed&&(await B$1(n,"application-stream-controller-disposed-after-open-bi"),this.assertActive()),c$1("[Client][OPEN-BI] Bidirectional application stream opened",{peerId:e,endpointId:n?.endpoint_id??n?.endpointId??null,applicationCryptoWrapped:n?.applicationCryptoWrapped===true});let i=this.deps.getApplicationCryptoForPeer(e),o=n?.applicationCryptoWrapped===true;if(i&&!o){let s=n$1(i);return {readable:s.wrapReadable(n.recv),writable:s.wrapWritable(n.send)}}return {readable:n.recv,writable:n.send}}async openUni(e){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let t=this.deps.getApplicationCryptoForPeer(e),n=(a,c)=>!t||c?a:n$1(t).wrapWritable(a),i=this.ctx.wasmClient;if(typeof i.open_peer_uni=="function"){let a=await i.open_peer_uni(e,5e3),c=a?.writable??a;return this.disposed&&(await this.closeWritableBestEffort(c),this.assertActive()),n(c,a?.applicationCryptoWrapped===true)}let o=await i.open_uni(e),s=o?.writable??o;return this.disposed&&(await this.closeWritableBestEffort(s),this.assertActive()),n(s,o?.applicationCryptoWrapped===true)}async sendFrame(e,t){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let n=this.ctx.wasmClient;if(typeof n.send_peer_application_frame=="function"){await n.send_peer_application_frame(e,t,5e3),this.assertActive();return}let i=await this.openBi(e),o=i.writable.getWriter();try{await o.write(t),await o.close();}finally{try{o.releaseLock();}catch{}try{await i.readable.cancel("one-shot application frame sent");}catch{}}}};function Ge(r){try{let e=r?.type;return typeof e=="string"?e:"unknown"}catch{return "unknown"}}function Ae(r){try{let e=r?.endpointId;if(typeof e=="string"&&e.trim().length>0)return e}catch{}try{let e=r?.endpoint_id;if(typeof e=="string"&&e.trim().length>0)return e}catch{}return "unknown"}function fi(r){try{let e=r?.transportStableId??r?.transport_stable_id;if(Number.isSafeInteger(e)&&Number(e)>0)return Number(e)}catch{}return null}function xr(r){try{let e=r?.protocolHint;if(e==="control"||e==="explicit"||e==="native-main")return e}catch{}return null}function _r(r){try{if(!r||!("channel"in r))return {present:!1,channel:null};let e=r.channel;if(e==null)return {present:!0,channel:null};if(typeof e!="object")return {present:!1,channel:null};let t=typeof e.channelId=="string"?e.channelId.trim():"";if(!t)return {present:!1,channel:null};let n=e.metadata&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)?e.metadata:null;return {present:!0,channel:{channelId:t,metadata:n}}}catch{return {present:false,channel:null}}}var Te=class Te{constructor(e){this.wasmClient=e;this.clients=new Set;this.listenLoopTask=null;this.activeDispatches=new Set;}addClient(e){this.clients.has(e)||(this.clients.add(e),this.ensureListening());}removeClient(e){this.clients.delete(e);}dispatchIncomingAsync(e,t){let n=Ae(e),i=performance.now(),o=this.dispatchIncoming(e).then(()=>{let s=performance.now()-i;s>50&&console.warn(`[PERFORMANCE] handleIncomingStream loop took abnormally long: ${Math.round(s)}ms`,{endpointId:n,type:t});}).catch(s=>{console.error("[Client][INCOMING] Failed to handle incoming stream via shared hub",{remoteNodeId:n,type:t,error:s instanceof Error?s.message:String(s)});}).finally(()=>{this.activeDispatches.delete(o);});this.activeDispatches.add(o);}ensureListening(){this.listenLoopTask||(this.listenLoopTask=this.listenLoop().finally(()=>{this.listenLoopTask=null,this.clients.size>0&&this.ensureListening();}));}getPrimaryClient(){let e=this.clients.values().next();return e.done?null:e.value}getChannelTargetClients(e){return Array.from(this.clients).reverse().filter(t=>t.hasIncomingChannelListener(e))}async dispatchIncoming(e){let t=this.getPrimaryClient();if(!t)return;let n=Array.from(this.clients).some(a=>a.shouldInspectIncomingChannelEnvelope()),i=await t.normalizeIncomingStreamEvent(e,{inspectChannelEnvelope:n}),o=i.channel?.channelId?.trim();if(o&&t.isInternalSessionChannel(o)){await t.handleUnhandledIncomingStreamEvent(i);return}if(o){for(let a of this.getChannelTargetClients(o))if(a.dispatchIncomingChannelListeners(i))return}let s=this.getPrimaryClient();if(s){if(i.protocolHint==="native-main"){await s.handleUnhandledIncomingStreamEvent(i);return}s.dispatchIncomingGenericListeners(i)||await s.handleUnhandledIncomingStreamEvent(i);}}async listenLoop(){let e=0;for(;;){if(this.clients.size===0)return;let t=null;try{let i=(await this.wasmClient.incoming_streams()).getReader();for(t=i,e=0,oe()&&Lt()&&c$1("[Client][INCOMING][MOBILE] shared-hub reader acquired",{sharedHubClients:this.clients.size});this.clients.size>0;){let{done:o,value:s}=await i.read();if(o)throw new Error("incoming stream reader closed unexpectedly");if(!s)continue;let a=Ge(s);a!=="uni"&&c$1("[Client][INCOMING] Received stream from WASM node",{type:a,endpointId:Ae(s),sharedHubClients:this.clients.size}),this.dispatchIncomingAsync(s,a);}}catch(n){if(this.clients.size===0)return;e+=1;let i=x(e,Te.RETRY_MIN_DELAY_MS,Te.RETRY_MAX_DELAY_MS);console.warn("[Client][INCOMING] Shared listen loop restarting after stream failure",{attempt:e,delayMs:i,mobile:oe(),error:n}),await u(i);}finally{if(t)try{t.releaseLock(),oe()&&Lt()&&c$1("[Client][INCOMING][MOBILE] shared-hub reader released",{sharedHubClients:this.clients.size});}catch{}}}}};Te.RETRY_MIN_DELAY_MS=250,Te.RETRY_MAX_DELAY_MS=2e3;var dn=Te;var Ke=class Ke{constructor(e,t){this.ctx=e;this.deps=t;this.listening=false;this.presenceStarted=false;this.listenLoopTask=null;this.hubClient={hasIncomingChannelListener:n=>this.deps.hasIncomingChannelListener(n),hasAnyIncomingChannelListeners:()=>this.deps.hasAnyIncomingChannelListeners(),shouldInspectIncomingChannelEnvelope:()=>this.deps.shouldInspectIncomingChannelEnvelope(),isInternalSessionChannel:n=>this.deps.isInternalSessionChannel(n),normalizeIncomingStreamEvent:(n,i)=>this.deps.normalizeIncomingStreamEvent(n,i),dispatchIncomingChannelListeners:n=>this.deps.dispatchIncomingChannelListeners(n),dispatchIncomingGenericListeners:n=>this.deps.dispatchIncomingGenericListeners(n),handleUnhandledIncomingStreamEvent:n=>this.deps.handleUnhandledIncomingStreamEvent(n)},this.ctx.registerDisposer(()=>this.stop());}async start(e={}){if(this.listening)return;await this.deps.ensureWasmRuntimeForP2P();let t=false;this.markListening(false);try{let n=this.getSharedIncomingStreamHub();n?(n.addClient(this.hubClient),t=!0):this.listenLoopTask||(this.listenLoopTask=this.listenLoop().finally(()=>{this.listenLoopTask=null;})),e.startPresence!==!1&&(await this.deps.startPresenceForListen(),this.presenceStarted=!0);}catch(n){throw this.markStopped(),this.presenceStarted=false,t&&this.getSharedIncomingStreamHub()?.removeClient(this.hubClient),n}}stop(){let e=this.listening;if(this.markStopped(),e)for(let t of Array.from(this.ctx.registry.values()))t.isClosed||this.disconnectBestEffort(t);this.getSharedIncomingStreamHub()?.removeClient(this.hubClient),e&&this.presenceStarted&&this.deps.setOfflinePresence(),this.presenceStarted=false;}prepareForSignOut(){this.markStopped(),this.presenceStarted=false;}isListening(){return this.listening}markListening(e=true){this.listening=true,this.presenceStarted=e;}markStopped(){this.listening=false;}getSharedIncomingStreamHub(){let e=this.ctx.wasmClient;if(!e||typeof e.incoming_streams!="function")return null;let t=e,n=Ke.incomingStreamHubs.get(t);return n||(n=new dn(e),Ke.incomingStreamHubs.set(t,n)),n}async listenLoop(){await this.deps.getIncomingStreamRouter().listenLoop({isListening:()=>this.listening,getWasmClient:()=>this.ctx.wasmClient,handleIncomingStream:e=>this.handleIncomingStream(e),shouldVerboseIncomingDiagnostics:()=>this.deps.shouldVerboseIncomingDiagnostics(),getLocalNodeId:()=>this.ctx.localNodeId||null,retryMinDelayMs:this.deps.retryMinDelayMs,retryMaxDelayMs:this.deps.retryMaxDelayMs});}async handleIncomingStream(e){return this.deps.handleIncomingStream(e)}shouldInspectIncomingChannelEnvelope(){return this.deps.shouldInspectIncomingChannelEnvelope()}normalizeIncomingStreamEvent(e,t={}){return this.deps.normalizeIncomingStreamEvent(e,t)}dispatchIncomingChannelListeners(e){return this.deps.dispatchIncomingChannelListeners(e)}dispatchIncomingGenericListeners(e){return this.deps.dispatchIncomingGenericListeners(e)}handleUnhandledIncomingStreamEvent(e){return this.deps.handleUnhandledIncomingStreamEvent(e)}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}};Ke.incomingStreamHubs=new WeakMap;var pn=Ke;var un=class{constructor(e){this.deps=e;this.traceSequence=0;}getRuntimeSafetyProfile(){return this.deps.getRuntimeSafetyProfileOverride()??He(this.deps.getOptions()??{})}shouldVerboseIncomingDiagnostics(){return this.getRuntimeSafetyProfile().diagnosticsMode}shouldInspectIncomingChannelEnvelope(){return this.getRuntimeSafetyProfile().skipIncomingChannelEnvelopeInspection?false:this.deps.hasAnyIncomingChannelListeners()||this.deps.requiresIncomingChannelEnvelopeInspection()}nextIncomingTraceId(e,t){Number.isFinite(this.traceSequence)||(this.traceSequence=0),this.traceSequence+=1;let n=t&&t.length>0?t.slice(0,8):"unknown";return `${e}-${n}-${this.traceSequence.toString(36)}`}logIncomingDiagnostic(e,t){this.shouldVerboseIncomingDiagnostics()&&c$1(`[Client][INCOMING][MOBILE] ${e}`,t);}safeReleaseReaderLock(e,t,n,i=(o,s)=>this.logIncomingDiagnostic(o,s)){try{e.releaseLock(),i("releaseLock:ok",{context:t,traceId:n||null});}catch(o){console.warn("[Client][INCOMING] releaseLock failed",{context:t,traceId:n||null,error:o});}}async cancelUnhandledIncomingUniStream(e,t,n=(i,o)=>this.logIncomingDiagnostic(i,o)){if(!(!e||typeof e!="object")){if(this.shouldVerboseIncomingDiagnostics()){n("uni:drop-unhandled",{remoteNodeId:t||"unknown"});return}try{let i=e;if(typeof i.cancel=="function")return;if(typeof i.getReader=="function"){let o=i.getReader();try{await o.read().catch(()=>{});}finally{try{o.releaseLock();}catch{}}d$1("[Client][INCOMING] Released unhandled uni stream reader",{remoteNodeId:t});}}catch(i){console.warn("[Client][INCOMING] Failed to cancel unhandled uni stream",{remoteNodeId:t,error:i});}}}shouldSkipIncomingStreamProbe(){return this.getRuntimeSafetyProfile().skipIncomingBiProbe===true}};var gn=class{constructor(e,t){this.config=e;this.deps=t;}async normalize(e,t){return this.deps.router.normalizeIncomingStreamEvent(e,t,this.normalizationDeps())}async extractIncomingChannelEnvelope(e,t,n){return this.deps.router.extractIncomingChannelEnvelope(e,t,this.channelInspectionDeps(),n)}async classifyBiIncomingStream(e,t){return this.deps.router.classifyBiIncomingStream(e,this.channelInspectionDeps(),t)}async maybeOpenEncryptedExplicitBiStream(e,t,n){return this.deps.router.maybeOpenEncryptedExplicitBiStream(e,this.cryptoProbeConfig(),this.cryptoProbeDeps(),t,n)}maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n){return this.deps.router.maybeWrapIncomingBiStreamWithApplicationCrypto(e,this.cryptoProbeDeps(),t,n)}async maybeOpenEncryptedControlBiStream(e,t,n){return this.deps.router.maybeOpenEncryptedControlBiStream(e,this.cryptoProbeConfig(),this.cryptoProbeDeps(),t,n)}async detectNativeMainStream(e,t,n){return this.deps.router.detectNativeMainStream(e,t,{nativeMainProtocolByte:this.config.nativeMainProtocolByte,explicitProtocolByte:this.config.explicitProtocolByte,label:this.config.nativeMainLabel,maxLabelBytes:this.config.nativeMainMaxLabelBytes},this.channelInspectionDeps(),n)}channelInspectionDeps(){return {logIncomingDiagnostic:(e,t)=>this.deps.logIncomingDiagnostic(e,t),releaseReaderLock:(e,t,n)=>this.deps.releaseReaderLock(e,t,n)}}cryptoProbeConfig(){return {explicitProtocolByte:this.config.explicitProtocolByte,maxEncryptedFrameBytes:this.config.maxEncryptedFrameBytes,probeDeadlineMs:this.config.probeDeadlineMs}}cryptoProbeDeps(){return {...this.channelInspectionDeps(),resolveApplicationCryptoForPeer:e=>this.deps.resolveApplicationCryptoForPeer(e),waitForApplicationCryptoForPeer:e=>this.deps.waitForApplicationCryptoForPeer(e,this.config.explicitApplicationCryptoWaitMs),resolveApplicationCryptoStreamTools:e=>this.deps.resolveApplicationCryptoStreamTools(e)}}normalizationDeps(){return {...this.cryptoProbeDeps(),nextIncomingTraceId:(e,t)=>this.deps.nextIncomingTraceId(e,t),normalizeAuthoritativeIncomingProtocolHint:(e,t,n)=>Pt(e),shouldStripIncomingMainLabel:()=>jo(this.deps.shouldSkipIncomingStreamProbe()),shouldSkipIncomingBiProbeForRemoteNode:e=>this.deps.shouldSkipIncomingBiProbeForRemoteNode(e),inferTicketFlowBiProtocolHint:e=>this.deps.inferTicketFlowBiProtocolHint(e),shouldSkipIncomingStreamProbe:()=>this.deps.shouldSkipIncomingStreamProbe(),isTransportOnlyChannel:e=>this.deps.isTransportOnlyChannel(e),detectNativeMainStream:(e,t,n)=>this.detectNativeMainStream(e,t,n),extractIncomingChannelEnvelope:(e,t,n)=>this.extractIncomingChannelEnvelope(e,t,n),classifyBiIncomingStream:(e,t)=>this.classifyBiIncomingStream(e,t),maybeWrapIncomingBiStreamWithApplicationCrypto:(e,t,n)=>this.maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n),maybeOpenEncryptedExplicitBiStream:(e,t,n)=>this.maybeOpenEncryptedExplicitBiStream(e,t,n),maybeOpenEncryptedControlBiStream:(e,t,n)=>this.maybeOpenEncryptedControlBiStream(e,t,n)}}};var qe=class extends Error{},hn=class{maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n,i){if(!y(e)||e?.applicationCryptoWrapped===true)return e;let o=t.resolveApplicationCryptoStreamTools(n);if(!o)return e;try{return {...e,send:o.wrapWritable(e.send),recv:o.wrapReadable(e.recv),applicationCryptoWrapped:!0}}catch(s){return t.logIncomingDiagnostic("application-crypto:early-wrap-incoming-bi-failed",{remoteNodeId:n||"unknown",traceId:i||null,error:s}),e}}async maybeOpenEncryptedExplicitBiStream(e,t,n,i,o){let s=n.resolveApplicationCryptoForPeer(o);if(!y(e))return e;let a;try{a=e.recv.getReader();}catch{return e}let c=(y,v,P=null)=>C(a,y,{context:v,traceId:i,pendingRead:P,release:I=>n.releaseReaderLock(a,`${v}:${I}`,i),log:(I,T)=>n.logIncomingDiagnostic(I,T)}),l=y=>A$1(e,y),d=[],p=new Uint8Array(0),u=null,f=Date.now()+t.probeDeadlineMs,h=async()=>{let y=await D$1(a,f);return y.status==="timeout"?(u=y.pendingRead??null,false):y.status==="done"?false:(y.value&&y.value.byteLength>0&&(d.push(y.value),p=w$1(d)),true)},m=()=>u?(n.logIncomingDiagnostic("explicit-crypto:probe-deadline",{traceId:i||null,endpointId:o||"unknown",bufferedBytes:p.byteLength}),l(c(p,"explicit-crypto:probe-deadline",u))):null;try{for(;p.byteLength<5&&await h(););let y=m();if(y)return y;if(p.byteLength<5||p[0]!==t.explicitProtocolByte)return l(c(p,"explicit-crypto:not-probeable"));let v=new DataView(p.buffer,p.byteOffset+1,p.byteLength-1).getUint32(0,!1);if(v===0||v>t.maxEncryptedFrameBytes){let N=p.slice(1);return this.looksLikeApplicationCryptoEnvelope(N)?(s||(n.logIncomingDiagnostic("explicit-crypto:await-key",{traceId:i||null,endpointId:o||"unknown"}),s=await n.waitForApplicationCryptoForPeer(o)),s?(n.logIncomingDiagnostic("explicit-crypto:unframed-encrypted-body",{traceId:i||null,endpointId:o||"unknown"}),l(this.unframedEncryptedExplicitReadable(a,N,s,t.explicitProtocolByte,n,i))):this.rejectEncryptedStreamWithoutCrypto(a,n,i,o,"explicit-crypto:unframed-encrypted-body-missing-key")):l(c(p,"explicit-crypto:not-encrypted-length"))}let P=5+v;for(;p.byteLength<P&&await h(););let I=m();if(I)return I;if(p.byteLength<P)return l(c(p,"explicit-crypto:truncated-probe"));let T=p.slice(5,P);if(!l$1(T))return l(c(p,"explicit-crypto:legacy-plaintext"));if(s||(n.logIncomingDiagnostic("explicit-crypto:await-key",{traceId:i||null,endpointId:o||"unknown"}),s=await n.waitForApplicationCryptoForPeer(o)),!s)return n.logIncomingDiagnostic("explicit-crypto:encrypted-body-missing-key",{traceId:i||null,endpointId:o||"unknown"}),this.rejectEncryptedStreamWithoutCrypto(a,n,i,o,"explicit-crypto:encrypted-body-missing-key");let C=c(p.slice(1),"explicit-crypto:encrypted-body");return l(this.encryptedExplicitReadable(C,s,t.explicitProtocolByte,n,i))}catch(y){if(y instanceof qe)throw y;return n.logIncomingDiagnostic("explicit-crypto:probe-error",{traceId:i||null,error:y?.message||String(y)}),l(c(p,"explicit-crypto:probe-error"))}}async maybeOpenEncryptedControlBiStream(e,t,n,i,o){if(!y(e)||e?.applicationCryptoWrapped===true)return e;let s;try{s=e.recv.getReader();}catch{return e}let a=(m,y,v=null)=>C(s,m,{context:y,traceId:i,pendingRead:v,release:P=>n.releaseReaderLock(s,`${y}:${P}`,i),log:(P,I)=>n.logIncomingDiagnostic(P,I)}),c=m=>A$1(e,m),l=[],d=new Uint8Array(0),p=null,u=Date.now()+t.probeDeadlineMs,f=async()=>{let m=await D$1(s,u);return m.status==="timeout"?(p=m.pendingRead??null,false):m.status==="done"?false:(m.value&&m.value.byteLength>0&&(l.push(m.value),d=w$1(l)),true)},h=()=>p?(n.logIncomingDiagnostic("control-crypto:probe-deadline",{traceId:i||null,endpointId:o||"unknown",bufferedBytes:d.byteLength}),c(a(d,"control-crypto:probe-deadline",p))):null;try{for(;d.byteLength<4&&await f(););let m=h();if(m)return m;if(d.byteLength<4)return c(a(d,"control-crypto:not-probeable"));let y=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,!1);if(y===0||y>t.maxEncryptedFrameBytes)return c(a(d,"control-crypto:plaintext-length"));let v=4+Math.min(y,7);for(;d.byteLength<v&&await f(););let P=h();if(P)return P;if(d.byteLength<v)return c(a(d,"control-crypto:truncated-probe"));let I=d.slice(4,v);if(!this.looksLikeApplicationCryptoEnvelope(I))return c(a(d,"control-crypto:plaintext-frame"));let T=n.resolveApplicationCryptoForPeer(o);if(T||(n.logIncomingDiagnostic("control-crypto:await-key",{traceId:i||null,endpointId:o||"unknown"}),T=await n.waitForApplicationCryptoForPeer(o)),!T)return n.logIncomingDiagnostic("control-crypto:encrypted-body-missing-key",{traceId:i||null,endpointId:o||"unknown"}),this.rejectEncryptedStreamWithoutCrypto(s,n,i,o,"control-crypto:encrypted-body-missing-key");n.logIncomingDiagnostic("control-crypto:encrypted-frame",{traceId:i||null,endpointId:o||"unknown",frameLength:y});let C=n$1(T);return {...e,send:C.wrapWritable(e.send),recv:C.wrapReadable(a(d,"control-crypto:encrypted-frame")),applicationCryptoWrapped:!0}}catch(m){if(m instanceof qe)throw m;return n.logIncomingDiagnostic("control-crypto:probe-error",{traceId:i||null,endpointId:o||"unknown",error:m?.message||String(m)}),c(a(d,"control-crypto:probe-error"))}}encryptedExplicitReadable(e,t,n,i,o){let a=n$1(t).wrapReadable(e).getReader(),c=false;return new ReadableStream({async pull(l){if(!c){c=true,l.enqueue(new Uint8Array([n]));return}try{let{done:d,value:p}=await a.read();if(d){l.close(),a.releaseLock();return}p&&l.enqueue(p);}catch(d){l.error(d);try{a.releaseLock();}catch{}}},async cancel(l){try{await a.cancel(l);}catch{}try{a.releaseLock();}catch{}i.logIncomingDiagnostic("explicit-crypto:cancel",{traceId:o||null});}})}unframedEncryptedExplicitReadable(e,t,n,i,o,s){let a=false,c=false;return new ReadableStream({async pull(l){if(!a){a=true,l.enqueue(new Uint8Array([i]));return}if(c){l.close();return}c=true;let d=[t];try{for(;;){let{done:f,value:h}=await e.read();if(f)break;h&&h.byteLength>0&&d.push(new Uint8Array(h));}let p=w$1(d),u=n.openPayload(3,p);if(!u)throw new Error("[OpenRTC] encrypted explicit body failed authentication");l.enqueue(u),l.close();}catch(p){l.error(p);}finally{try{e.releaseLock();}catch{}}},async cancel(l){try{await e.cancel(l);}catch{}try{e.releaseLock();}catch{}o.logIncomingDiagnostic("explicit-crypto:unframed-cancel",{traceId:s||null});}})}looksLikeApplicationCryptoEnvelope(e){return e.byteLength>=7&&e[0]===79&&e[1]===82&&e[2]===84&&e[3]===67&&e[4]===69&&e[5]===49}async rejectEncryptedStreamWithoutCrypto(e,t,n,i,o){let s=new qe(`[OpenRTC] rejected encrypted stream without negotiated application crypto (${o})`);try{await e.cancel(s);}catch{}throw t.releaseReaderLock(e,o,n),t.logIncomingDiagnostic("application-crypto:stream-rejected",{traceId:n||null,endpointId:i||"unknown",context:o}),s}};var we=class{async extractIncomingUniChannelEnvelope(e,t,n,i){let o={send:new WritableStream,recv:e,endpoint_id:t},s=await this.extractIncomingChannelEnvelope(o,t,n,i);return {stream:s.stream.recv,channel:s.channel}}async extractIncomingChannelEnvelope(e,t,n,i){if(!y(e))return {stream:e,channel:null};let o;try{o=e.recv.getReader(),n.logIncomingDiagnostic("channel-envelope:reader-acquired",{traceId:i||null,remoteNodeId:t||"unknown"});}catch(b){return console.warn("[Client][CHANNEL] Incoming stream recv reader unavailable; skipping channel envelope inspection",{remoteNodeId:t,traceId:i||null,error:b}),{stream:e,channel:null}}let s=(b,L)=>C(o,b,{context:L,traceId:i,release:_=>n.releaseReaderLock(o,`${L}:${_}`,i),log:(_,w)=>n.logIncomingDiagnostic(_,w)}),a=b=>A$1(e,b),c=[],l=0;try{for(;l<6;){let{done:b,value:L}=await o.read();if(b)break;if(!L||L.byteLength===0)continue;let _=new Uint8Array(L);c.push(_),l+=_.byteLength;}}catch(b){return console.warn("[Client][CHANNEL] Failed reading incoming channel envelope prefix",{remoteNodeId:t,traceId:i||null,error:b}),n.releaseReaderLock(o,"extractIncomingChannelEnvelope:read-prefix-failed",i),{stream:e,channel:null}}let d=w$1(c);if(d.byteLength<6||d[0]!==127||d[1]!==1)return c$1("[Client][CHANNEL] Incoming stream did not start with channel envelope",{remoteNodeId:t,traceId:i||null,bufferedBytes:d.byteLength,firstBytes:Array.from(d.slice(0,Math.min(d.byteLength,8))).map(b=>b.toString(16).padStart(2,"0")).join(" ")}),{stream:a(s(d,"extractIncomingChannelEnvelope:not-envelope")),channel:null};let p=new DataView(d.buffer,d.byteOffset,d.byteLength),u=p.getUint16(2,false),f=p.getUint16(4,false),h=6+u+f,m=d;if(m.byteLength<h)try{for(;m.byteLength<h;){let{done:b,value:L}=await o.read();if(b)break;!L||L.byteLength===0||(m=w$1([m,new Uint8Array(L)]));}}catch(b){console.warn("[Client][CHANNEL] Failed extending incoming channel envelope read",{remoteNodeId:t,error:b});}if(m.byteLength<h||u===0)return {stream:a(s(m,"extractIncomingChannelEnvelope:truncated-envelope")),channel:null};let y$1=6,v=y$1+u,P=v+f,I=new TextDecoder,T=I.decode(m.slice(y$1,v)).trim(),C$1=null;if(f>0)try{let b=JSON.parse(I.decode(m.slice(v,P)));b&&typeof b=="object"&&!Array.isArray(b)&&(C$1=b);}catch(b){console.warn("[Client][CHANNEL] Failed to parse incoming channel metadata",{remoteNodeId:t,channelId:T,error:b});}if(!T)return {stream:a(s(m,"extractIncomingChannelEnvelope:empty-channel-id")),channel:null};let N=a(s(m.slice(h),"extractIncomingChannelEnvelope:channel-envelope-consumed"));return c$1("[Client][CHANNEL] Incoming channel envelope consumed",{remoteNodeId:t,traceId:i||null,channelId:T,metadata:C$1?Object.keys(C$1):[],bufferedBytes:m.byteLength,remainingBytes:Math.max(0,m.byteLength-h)}),{stream:N,channel:{channelId:T,metadata:C$1}}}async classifyBiIncomingStream(e,t,n,i){if(!y(e))return {stream:e,protocolHint:"unknown"};let o;try{o=e.recv.getReader();}catch{return {stream:e,protocolHint:"unknown"}}let s;try{s=await o.read();}catch{return n.releaseReaderLock(o,"classifyBiIncomingStream:read-failed",i),{stream:e,protocolHint:"unknown"}}if(s.done||!s.value||s.value.byteLength===0)return n.releaseReaderLock(o,"classifyBiIncomingStream:empty-first-read",i),c$1("[Client][INCOMING] classifyBiIncomingStream: empty read",{traceId:i||null,done:s.done,hasValue:!!s.value,byteLength:s.value?.byteLength}),{stream:e,protocolHint:"unknown"};let a=new Uint8Array(s.value),c=a[0];c$1("[Client][INCOMING] classifyBiIncomingStream: first byte",{traceId:i||null,firstByte:"0x"+c.toString(16),EXPLICIT_PROTOCOL_BYTE:"0x"+t.toString(16),isExplicit:c===t,chunkLength:a.length});let l=A$1(e,C(o,a,{context:"classifyBiIncomingStream:first-chunk",traceId:i,release:d=>n.releaseReaderLock(o,`classifyBiIncomingStream:first-chunk:${d}`,i),log:(d,p)=>n.logIncomingDiagnostic(d,p)}));return c===t?{stream:l,protocolHint:"explicit"}:{stream:l,protocolHint:"control"}}async detectNativeMainStream(e,t,n,i,o){if(!y(e))return {handled:false,stream:e,protocolHint:"unknown"};let s;try{s=e.recv.getReader();}catch(T){return console.warn("[Client][NATIVE-MAIN] Incoming stream recv reader unavailable",{remoteNodeId:t,traceId:o||null,error:T}),{handled:false,stream:e,protocolHint:"control"}}let a=(T,C$1)=>C(s,T,{context:C$1,traceId:o,release:N=>i.releaseReaderLock(s,`${C$1}:${N}`,o),log:(N,b)=>i.logIncomingDiagnostic(N,b)}),c=T=>A$1(e,T),l=[],d=0,p=5,u=false;try{for(;d<p;){let{done:T,value:C}=await s.read();if(T){u=!0;break}!C||C.byteLength===0||(l.push(new Uint8Array(C)),d+=C.byteLength);}}catch(T){return console.warn("[Client][NATIVE-MAIN] Failed reading incoming prefix",{remoteNodeId:t,traceId:o||null,error:T}),i.releaseReaderLock(s,"detectNativeMainStream:read-prefix-failed",o),{handled:false,stream:e,protocolHint:"control"}}let f=w$1(l);if(f.byteLength<p||f[0]!==n.nativeMainProtocolByte)return {handled:false,stream:c(a(f,"detectNativeMainStream:not-native-main")),protocolHint:f[0]===n.explicitProtocolByte?"explicit":"control"};let h=new DataView(f.buffer,f.byteOffset,f.byteLength).getUint32(1,false);if(h===0||h>n.maxLabelBytes)return {handled:false,stream:c(a(f,"detectNativeMainStream:invalid-label-length")),protocolHint:"control"};let m=5+h,y$1=f;if(y$1.byteLength<m&&!u){let T=[y$1],C=y$1.byteLength;try{for(;C<m;){let{done:N,value:b}=await s.read();if(N){u=!0;break}if(!b||b.byteLength===0)continue;let L=new Uint8Array(b);T.push(L),C+=L.byteLength;}}catch(N){console.warn("[Client][NATIVE-MAIN] Failed extending prefix read",{remoteNodeId:t,error:N});}y$1=w$1(T);}if(y$1.byteLength<m)return {handled:false,stream:c(a(y$1,"detectNativeMainStream:truncated-label")),protocolHint:"control"};let v=y$1.slice(5,m),P=new TextDecoder().decode(v);if(P!==n.label)return {handled:false,stream:c(a(y$1,"detectNativeMainStream:label-mismatch")),protocolHint:"control"};let I=c(a(y$1.slice(m),"detectNativeMainStream:label-consumed"));return c$1("[Client][NATIVE-MAIN] Detected desktop native main stream",{remoteNodeId:t,traceId:o||null,label:P}),{handled:true,stream:I,protocolHint:"native-main"}}};var mn=class{constructor(){this.transfers=new Map;}clear(){this.transfers.clear();}maybeHandle(e,t,n){if(t.byteLength<25||t[0]!==n.explicitProtocolByte)return false;let i=t.slice(1,17),o=Array.from(i).map(u=>u.toString(16).padStart(2,"0")).join(""),s=`${e.id}:${o}`,a=new DataView(t.buffer,t.byteOffset,t.byteLength),c=a.getUint32(17,false),l=a.getUint32(21,false);if(c===4294967295){if(t.byteLength<29)return true;let u=a.getUint32(25,false),f=29,h=f+u;if(h>t.byteLength)return true;let m=n.openWebRTCExplicitTransferPayload(t.slice(f,h),e);return m?(this.transfers.set(s,{headerBytes:m,chunks:new Map,total:0,received:0}),c$1("[Client][WebRTC][transfer] Incoming WebRTC explicit transfer header received",{connectionId:e.id,remoteNodeId:e.remoteNodeId,transferIdKey:o,headerBytes:u}),true):(this.transfers.delete(s),true)}let d=this.transfers.get(s);if(!d)return true;if(d.total===0)d.total=l;else if(d.total!==l)return this.transfers.delete(s),true;if(d.chunks.has(c))return true;let p=n.openWebRTCExplicitTransferPayload(t.slice(25),e);if(!p)return this.transfers.delete(s),true;if(d.chunks.set(c,p),d.received+=1,d.total>0&&d.received>=d.total){let u=this.reassemble(d,n.explicitProtocolByte);this.transfers.delete(s),u&&(c$1("[Client][WebRTC][transfer] Incoming WebRTC transfer assembled in browser",{connectionId:e.id,remoteNodeId:e.remoteNodeId,transferIdKey:o,chunks:d.total,payloadBytes:u.byteLength}),n.dispatchSyntheticExplicitIncomingStream(e,u));}return true}reassemble(e,t){let n=[],i=0;for(let a=0;a<e.total;a+=1){let c=e.chunks.get(a);if(!c)return null;n.push(c),i+=c.byteLength;}let o=new Uint8Array(5+e.headerBytes.byteLength+i);o[0]=t,new DataView(o.buffer).setUint32(1,e.headerBytes.byteLength,false),o.set(e.headerBytes,5);let s=5+e.headerBytes.byteLength;for(let a of n)o.set(a,s),s+=a.byteLength;return o}};var fn=class{constructor(){this.protocolInspector=new we;}async normalize(e,t,n){let i=n.resolveApplicationCryptoStreamTools(t.endpointId),o=!!i,s=i?i.wrapReadable(e):e,a=t.authoritativeChannel;if(!a&&t.inspectChannelEnvelope){let c=await this.protocolInspector.extractIncomingUniChannelEnvelope(s,t.endpointId,n,t.traceId);s=c.stream,a=c.channel;}return o&&Object.defineProperty(s,"applicationCryptoWrapped",{configurable:true,value:true}),{stream:s,channel:a}}};var yn=class{constructor(e){this.deps=e;this.messageListeners=[];this.roomRequestListeners=[];this.streamListeners=[];this.channelStreamListeners=new Map;this.registeredChannels=new Map;this.protocolInspector=new we;this.cryptoProbe=new hn;this.uniStreamNormalizer=new fn;this.webRTCExplicitTransferAssembler=new mn;this.disposed=false;this.deps?.registerDisposer(()=>this.dispose());for(let t of this.deps?.defaultChannels??[])this.registerChannel(t);}dispose(){this.disposed||(this.disposed=true,this.messageListeners=[],this.roomRequestListeners=[],this.streamListeners=[],this.channelStreamListeners.clear(),this.registeredChannels.clear(),this.webRTCExplicitTransferAssembler.clear());}get webrtcIncomingExplicitTransfers(){return this.webRTCExplicitTransferAssembler.transfers}set webrtcIncomingExplicitTransfers(e){this.webRTCExplicitTransferAssembler.transfers=e;}onMessage(e){return this.disposed?()=>{}:(this.messageListeners.push(e),()=>{this.messageListeners=this.messageListeners.filter(t=>t!==e);})}dispatchMessage(e,t){if(!this.disposed)for(let n of [...this.messageListeners])try{n(e,t);}catch(i){console.warn("[Client] message listener failed",i);}}onIncomingStream(e){return this.disposed?()=>{}:(this.streamListeners.push(e),()=>{this.streamListeners=this.streamListeners.filter(t=>t!==e);})}hasIncomingStreamListeners(){return this.streamListeners.length>0}getRegisteredChannel(e){let t=typeof e=="string"?e.trim():"";return t?this.registeredChannels.get(t)??null:null}registerChannel(e){if(this.disposed)return;let t=e.id.trim();if(!t)throw new Error("Channel registration requires a non-empty channel id.");this.registeredChannels.set(t,{...e,id:t});}unregisterChannel(e){let t=e.trim();t&&(this.registeredChannels.delete(t),this.channelStreamListeners.delete(t));}listChannels(){return Array.from(this.registeredChannels.values())}onIncomingChannelStream(e,t){if(this.disposed)return ()=>{};let n=e.trim();if(!n)throw new Error("Channel stream listener requires a non-empty channel id.");let i=this.channelStreamListeners.get(n)??new Set;return i.add(t),this.channelStreamListeners.set(n,i),()=>{let o=this.channelStreamListeners.get(n);o&&(o.delete(t),o.size===0&&this.channelStreamListeners.delete(n));}}hasIncomingChannelListener(e){let t=e.trim();return t?(this.channelStreamListeners.get(t)?.size??0)>0:false}hasAnyIncomingChannelListeners(){for(let e of this.channelStreamListeners.values())if(e.size>0)return true;return false}requiresIncomingChannelEnvelopeInspection(){for(let e of this.registeredChannels.values())if(e.kind==="system"&&e.routing==="session-default")return true;return false}isInternalSessionChannel(e){let t=this.getRegisteredChannel(e);return t?.kind==="system"&&t.routing==="session-default"}dispatchIncomingChannelListeners(e){let t=e.channel?.channelId?.trim();if(!t)return false;let n=this.channelStreamListeners.get(t);if(!n)return false;for(let i of [...n])try{if(i(e)===!0)return !0}catch(o){console.warn("[Client] incoming channel stream listener failed",o);}return false}dispatchIncomingGenericListeners(e){for(let t of [...this.streamListeners])try{if(t(e)===!0)return !0}catch(n){console.warn("[Client] incoming stream listener failed",n);}return false}onRoomJoinRequest(e){return this.disposed?()=>{}:(this.roomRequestListeners.push(e),()=>{this.roomRequestListeners=this.roomRequestListeners.filter(t=>t!==e);})}async listenLoop(e){let t=0;for(;e.isListening();){let n=e.getWasmClient();if(!n||typeof n.incoming_streams!="function"){console.warn("[Client][INCOMING] incoming_streams is unavailable; stopping listen loop");return}let i=null;try{i=(await n.incoming_streams()).getReader();let s=i;for(t=0,e.shouldVerboseIncomingDiagnostics()&&c$1("[Client][INCOMING][MOBILE] direct listen reader acquired",{localNodeId:e.getLocalNodeId()});e.isListening();){let{done:a,value:c}=await s.read();if(a)throw new Error("incoming stream reader closed unexpectedly");if(!c)continue;let l=Ge(c);l!=="uni"&&c$1("[Client][INCOMING] Received stream from WASM node",{type:l,endpointId:Ae(c)});try{await e.handleIncomingStream(c);}catch(d){let p=c,u=Ge(p),f=Ae(p);console.error("[Client][INCOMING] Failed to handle incoming stream",{remoteNodeId:f,type:u,error:d});}}}catch(o){if(!e.isListening())break;t+=1;let s=x(t,e.retryMinDelayMs,e.retryMaxDelayMs);console.warn("[Client][INCOMING] Listen loop restarting after stream failure",{attempt:t,delayMs:s,mobile:oe(),error:o}),await u(s);}finally{if(i)try{i.releaseLock(),e.shouldVerboseIncomingDiagnostics()&&c$1("[Client][INCOMING][MOBILE] direct listen reader released",{localNodeId:e.getLocalNodeId()});}catch{}}}}async handleIncomingStream(e,t){let n=await t.normalizeIncomingStreamEvent(e,{inspectChannelEnvelope:t.shouldInspectIncomingChannelEnvelope()}),i=t.buildApplicationIncomingStreamEvent(n);if(!n.invalid&&i.invalid)return;if(this.isInternalSessionChannel(i.channel?.channelId)){await t.handleUnhandledIncomingStreamEvent(i);return}if(this.dispatchIncomingChannelListeners(i))return;if(n.protocolHint==="native-main"){await t.handleUnhandledIncomingStreamEvent(n);return}this.dispatchIncomingGenericListeners(i)||await t.handleUnhandledIncomingStreamEvent(n);}async normalizeIncomingStreamEvent(e,t,n){let i="bi",o=e,s="",a=null,c=null,l=null,d={present:false,channel:null},p=false;try{p="type"in e;}catch{p=false;}if(p){i=Ge(e);try{o=e.stream;}catch{o=null;}let y=Ae(e);s=y==="unknown"?"":y,a=fi(e),l=xr(e),d=_r(e);}else {try{s=e.endpoint_id??"";}catch{s="";}a=fi(e);}let u=n.nextIncomingTraceId("incoming",s);l=n.normalizeAuthoritativeIncomingProtocolHint(l,s,u);let f=d.present&&d.channel!==null;n.logIncomingDiagnostic("normalize:start",{traceId:u,hasType:p,type:i,endpointId:s||"unknown",inspectChannelEnvelope:!!t?.inspectChannelEnvelope,authoritativeProtocolHint:l??null,authoritativeChannel:f}),i!=="uni"&&c$1("[Client][INCOMING] handleIncomingStream called",{hasType:p,type:i,endpointId:s});let h="unknown",m=l===null&&!!t?.inspectChannelEnvelope;if(i==="bi"){let y$1=z(o,s,a);if(!y$1||!y(y$1)){let I=false,T=false;try{I=!!o?.send;}catch{}try{T=!!o?.recv;}catch{}return console.error("[Client][INCOMING] Invalid bidirectional stream payload",{remoteNodeId:s,...a?{transportStableId:a}:{},hasSend:I,hasRecv:T}),{type:"bi",stream:o,remoteNodeId:s,...a?{transportStableId:a}:{},traceId:u,protocolHint:"unknown",channel:null,applicationCrypto:n.resolveApplicationCryptoStreamTools(s),invalid:true}}o=y$1,a=y$1.transport_stable_id??a;let v=false;if(l===null&&!f&&n.shouldStripIncomingMainLabel()){let I=await n.detectNativeMainStream(o,s,u);o=I.stream,v=true,h=I.protocolHint;}else l==="native-main"&&(h="native-main");if(h!=="native-main"){if(f)c=d.channel;else if(m){let C=await n.extractIncomingChannelEnvelope(o,s,u);o=C.stream,c=C.channel;}if(!(l==="explicit"||l==="control"||l==="native-main")&&!n.isTransportOnlyChannel(c?.channelId)&&(l!==null||f||c)&&(o=n.maybeWrapIncomingBiStreamWithApplicationCrypto(o,s,u)),l!==null)h=l,n.logIncomingDiagnostic("bi:use-authoritative-metadata",{traceId:u,endpointId:s||"unknown",protocolHint:h,hasChannelEnvelope:!!c});else if(n.shouldSkipIncomingBiProbeForRemoteNode(s)){let C=n.inferTicketFlowBiProtocolHint(s);if(h=C.protocolHint,n.logIncomingDiagnostic("bi:skip-probe-ticket-flow",{traceId:u,endpointId:s||"unknown",inferredProtocolHint:h,hasExistingConnection:C.hasExistingConnection,hasMagicLinkScope:C.hasMagicLinkScope}),!c&&!v&&n.shouldStripIncomingMainLabel()){let N=await n.detectNativeMainStream(o,s,u);o=N.stream,h=N.protocolHint;}}else {let C=await n.classifyBiIncomingStream(o,u);if(o=C.stream,h=C.protocolHint,h!=="explicit"&&!v&&n.shouldStripIncomingMainLabel()){let N=await n.detectNativeMainStream(o,s,u);o=N.stream,h=N.protocolHint;}}}let P=!n.shouldSkipIncomingStreamProbe()&&!n.isTransportOnlyChannel(c?.channelId);if(P&&h==="explicit"&&o?.applicationCryptoWrapped!==true)o=await n.maybeOpenEncryptedExplicitBiStream(o,u,s);else if(P&&h==="control"&&o?.applicationCryptoWrapped!==true&&(o=await n.maybeOpenEncryptedControlBiStream(o,u,s),o?.applicationCryptoWrapped===true)){let I=await n.classifyBiIncomingStream(o,u);o=I.stream,h=I.protocolHint,n.logIncomingDiagnostic("bi:reclassify-decrypted-stream",{traceId:u,endpointId:s||"unknown",protocolHint:h});}if(!c&&m&&o?.applicationCryptoWrapped===true){let I=await n.extractIncomingChannelEnvelope(o,s,u);o=I.stream,c=I.channel;}}else if(i==="uni"&&o&&typeof o.getReader=="function"){let y=await this.uniStreamNormalizer.normalize(o,{endpointId:s,traceId:u,inspectChannelEnvelope:m,authoritativeChannel:f?d.channel:null},n);o=y.stream,c=y.channel;}return n.logIncomingDiagnostic("normalize:done",{traceId:u,endpointId:s||"unknown",type:i,protocolHint:h,hasChannelEnvelope:!!c}),{type:i,stream:o,remoteNodeId:s,...a?{transportStableId:a}:{},traceId:u,protocolHint:h,channel:c,applicationCrypto:n.resolveApplicationCryptoStreamTools(s)}}async extractIncomingChannelEnvelope(e,t,n,i){return this.protocolInspector.extractIncomingChannelEnvelope(e,t,n,i)}async classifyBiIncomingStream(e,t,n){let i=this.deps?.explicitProtocolByte??0;return this.protocolInspector.classifyBiIncomingStream(e,i,t,n)}maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n,i){return this.cryptoProbe.maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n,i)}async maybeOpenEncryptedExplicitBiStream(e,t,n,i,o){return this.cryptoProbe.maybeOpenEncryptedExplicitBiStream(e,t,n,i,o)}async maybeOpenEncryptedControlBiStream(e,t,n,i,o){return this.cryptoProbe.maybeOpenEncryptedControlBiStream(e,t,n,i,o)}async detectNativeMainStream(e,t,n,i,o){return this.protocolInspector.detectNativeMainStream(e,t,n,i,o)}maybeHandleWebRTCExplicitFileEnvelope(e,t){return this.disposed||!this.deps?false:this.webRTCExplicitTransferAssembler.maybeHandle(e,t,this.deps)}};function Wr(r){let{host:e}=r;return new yn({explicitProtocolByte:2,defaultChannels:wo,registerDisposer:t=>e.registerDisposer(t),openWebRTCExplicitTransferPayload:(t,n)=>e.openWebRTCExplicitTransferPayload(t,n),dispatchSyntheticExplicitIncomingStream:(t,n)=>r.getApplicationIncoming().dispatchSyntheticExplicitIncomingStream(t,n)})}function Or(r){let{host:e}=r,t=e.getPresenceForIncomingListen();return new pn(e.getContext(),{ensureWasmRuntimeForP2P:()=>e.ensureWasmRuntimeForP2P(),startPresenceForListen:()=>t.startPresenceLoopForListen(),setOfflinePresence:()=>{t.setOffline();},shouldInspectIncomingChannelEnvelope:()=>r.getDiagnostics().shouldInspectIncomingChannelEnvelope(),handleIncomingStream:n=>r.getRouter().handleIncomingStream(n,{shouldInspectIncomingChannelEnvelope:()=>r.getDiagnostics().shouldInspectIncomingChannelEnvelope(),normalizeIncomingStreamEvent:(i,o)=>r.getNormalizer().normalize(i,o),buildApplicationIncomingStreamEvent:i=>r.getApplicationIncoming().buildApplicationIncomingStreamEvent(i),handleUnhandledIncomingStreamEvent:i=>e.handleUnhandledIncomingStreamEvent(i)}),hasIncomingChannelListener:n=>r.getRouter().hasIncomingChannelListener(n),hasAnyIncomingChannelListeners:()=>r.getRouter().hasAnyIncomingChannelListeners(),isInternalSessionChannel:n=>r.getRouter().isInternalSessionChannel(n),normalizeIncomingStreamEvent:(n,i)=>r.getNormalizer().normalize(n,i),dispatchIncomingChannelListeners:n=>r.getRouter().dispatchIncomingChannelListeners(n),dispatchIncomingGenericListeners:n=>r.getRouter().dispatchIncomingGenericListeners(n),handleUnhandledIncomingStreamEvent:n=>e.handleUnhandledIncomingStreamEvent(n),shouldVerboseIncomingDiagnostics:()=>r.getDiagnostics().shouldVerboseIncomingDiagnostics(),getIncomingStreamRouter:()=>r.getRouter(),retryMinDelayMs:So,retryMaxDelayMs:Io})}function Hr(r,e){return new un({getOptions:()=>r.getOptions(),getRuntimeSafetyProfileOverride:()=>r.getRuntimeSafetyProfile(),hasAnyIncomingChannelListeners:()=>e().hasAnyIncomingChannelListeners(),requiresIncomingChannelEnvelopeInspection:()=>e().requiresIncomingChannelEnvelopeInspection()})}function Ur(r){let{host:e}=r;return new gn({explicitProtocolByte:2,maxEncryptedFrameBytes:16777216,probeDeadlineMs:uo,nativeMainProtocolByte:at,nativeMainLabel:ct,nativeMainMaxLabelBytes:lt,explicitApplicationCryptoWaitMs:1500},{router:r.getRouter(),nextIncomingTraceId:(t,n)=>r.getDiagnostics().nextIncomingTraceId(t,n),logIncomingDiagnostic:(t,n)=>r.getDiagnostics().logIncomingDiagnostic(t,n),releaseReaderLock:(t,n,i)=>r.getDiagnostics().safeReleaseReaderLock(t,n,i),shouldSkipIncomingStreamProbe:()=>r.getDiagnostics().shouldSkipIncomingStreamProbe(),shouldSkipIncomingBiProbeForRemoteNode:t=>e.shouldSkipIncomingBiProbeForRemoteNode(t),inferTicketFlowBiProtocolHint:t=>e.inferTicketFlowBiProtocolHint(t),isTransportOnlyChannel:t=>e.isTransportOnlyChannel(t),resolveApplicationCryptoForPeer:t=>e.resolveApplicationCryptoForPeer(t),waitForApplicationCryptoForPeer:(t,n)=>e.waitForApplicationCryptoForPeer(t,n),resolveApplicationCryptoStreamTools:t=>e.resolveApplicationCryptoStreamTools(t)})}function jr(r){let{host:e}=r;return new cn({registerDisposer:t=>e.registerDisposer(t),resolveApplicationCryptoStreamTools:t=>e.resolveApplicationCryptoStreamTools(t),logIncomingDiagnostic:(t,n)=>r.getDiagnostics().logIncomingDiagnostic(t,n),isTransportOnlyChannel:t=>e.isTransportOnlyChannel(t),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),hasTransportOnlyConnectionForRemoteNode:t=>e.hasTransportOnlyConnectionForRemoteNode(t),isManagedApplicationStreamAuthorized:t=>e.isManagedApplicationStreamAuthorized(t),getConnectionChannelId:t=>e.getConnectionChannelId(t),dispatchIncomingChannelListeners:t=>r.getRouter().dispatchIncomingChannelListeners(t),dispatchIncomingGenericListeners:t=>r.getRouter().dispatchIncomingGenericListeners(t),handleUnhandledIncomingStreamEvent:t=>e.handleUnhandledIncomingStreamEvent(t)})}function Gr(r){return new ln(r.getContext(),{ensureWasmRuntimeForP2P:()=>r.ensureWasmRuntimeForP2P(),getApplicationCryptoForPeer:e=>r.resolveApplicationCryptoForPeer(e)})}function Kr(r){return new vi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getRuntimeSafetyProfile:()=>r.runtimeSafetyProfile,registerDisposer:e=>r.lifecycleScope.register(e),ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),getPresenceForIncomingListen:()=>r.presence,openWebRTCExplicitTransferPayload:(e,t)=>r.applicationCrypto.openWebRTCExplicitTransferPayload(e,t),dispatchSyntheticExplicitIncomingStream:(e,t)=>r.applicationIncomingStreams.dispatchSyntheticExplicitIncomingStream(e,t),handleUnhandledIncomingStreamEvent:e=>r.incomingConnectionAcceptor.handleUnhandledIncomingStreamEvent(e),shouldSkipIncomingBiProbeForRemoteNode:e=>r.transportHealth.shouldSkipIncomingBiProbeForRemoteNode(e),inferTicketFlowBiProtocolHint:e=>r.peerIdentity.inferTicketFlowBiProtocolHint(e),isTransportOnlyChannel:e=>r.connectionChannelPolicy.isTransportOnlyChannel(e),hasTransportOnlyConnectionForRemoteNode:e=>r.transportHealth.hasTransportOnlyConnectionForRemoteNode(e),isManagedApplicationStreamAuthorized:e=>{if(!(r.runtimeStatus.usesTicketOnlySignalingMode()||r.runtimeStatus.requiresManagedTransportTrust(r.discoveryMode)))return true;let n=e?.trim();return n?r.sessionTokens.isApproved(r.peerIdentity.getDeterministicConnectionId(n),n):false},getConnectionChannelId:e=>r.connectionChannelPolicy.getConnectionChannelId(e),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),resolveApplicationCryptoForPeer:e=>r.applicationCrypto.resolveForPeer(e),waitForApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.waitForPeer(e,t),resolveApplicationCryptoStreamTools:e=>r.applicationCrypto.resolveStreamTools(e)})}var vi=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getRouter:()=>this.router,getDiagnostics:()=>this.diagnostics,getNormalizer:()=>this.normalizer,getApplicationIncoming:()=>this.applicationIncoming}}get router(){return this._router??(this._router=Wr(this.factoryHost))}get listen(){return this._listen??(this._listen=Or(this.factoryHost))}get diagnostics(){return this._diagnostics??(this._diagnostics=Hr(this.host,()=>this.router))}get normalizer(){if(this._normalizer||(this._normalizer=Ur(this.factoryHost)),!this._generationFencedNormalizer){let e=this._normalizer;this._generationFencedNormalizer=new Proxy(e,{get:(t,n)=>{if(n==="normalize")return async(o,s)=>(await this.assertCurrentIncomingTransport(o),e.normalize(o,s));let i=Reflect.get(e,n,e);return typeof i=="function"?i.bind(e):i}});}return this._generationFencedNormalizer}async assertCurrentIncomingTransport(e){let t=e,n;try{n=t.type;}catch{return}if(n!=="bi"&&n!=="uni")return;let i,o;try{i=t.endpointId??t.endpoint_id,o=t.transportStableId??t.transport_stable_id;}catch{throw new Error("Rejected incoming WASM stream with unreadable transport generation")}if(typeof i!="string"||i.trim().length===0||!Number.isSafeInteger(o)||Number(o)<=0)throw new Error("Rejected incoming WASM stream without a valid transport generation");let s=this.host.getContext().wasmClient;if(!s||typeof s.is_current_transport_stable_id!="function")throw new Error("Rejected incoming WASM stream because generation validation is unavailable");if(!await s.is_current_transport_stable_id(i.trim(),BigInt(Number(o))))throw new Error("Rejected incoming WASM stream from a retired transport generation")}get applicationIncoming(){return this._applicationIncoming??(this._applicationIncoming=jr(this.factoryHost))}get applicationStreams(){return this._applicationStreams??(this._applicationStreams=Gr(this.host))}prepareListenForSignOut(){this._listen?.prepareForSignOut();}stopListenIfExists(){this._listen?.stop();}};function vn(r,e,t,n){if(!r||r.isClosed)return false;if(!(typeof r.isApplicationCryptoRequired=="function"?r.isApplicationCryptoRequired():false))return true;let o=n??r.remoteNodeId??t??r.deviceId;return !!e(o,r)}function Ci(r){return !r||r.isClosed?false:typeof r.isWebRtcApplicationRouteReady=="function"?r.isWebRtcApplicationRouteReady():false}var Cn=class{constructor(e,t){this.ctx=e;this.deps=t;this.recoveryInFlight=new Set;this.failedConnectionIds=new Set;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true,this.recoveryInFlight.clear(),this.failedConnectionIds.clear();}hasApplicationRouteForPeer(e,t){let n=this.deps.getConnectionForPeer(e,t);return vn(n,this.deps.resolveApplicationCryptoForPeer,e,t)}hasApplicationRouteForConnection(e){return vn(e,this.deps.resolveApplicationCryptoForPeer,e?.id,e?.remoteNodeId)}notifyApplicationRouteReady(e,t){this.disposed||e.isClosed||!this.hasApplicationRouteForConnection(e)||(this.failedConnectionIds.delete(e.id),c$1("[Client][HANDSHAKE] application route ready",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t}),this.deps.hasRustPeerLifecycleProjection()?(this.deps.reportApplicationRouteReady(e,t),this.schedulePeerReconciliationBestEffort("application-route-ready")):this.deps.applyConnectionTrustProjection(e),this.deps.isConnectionAnnounced(e.id)||this.deps.announceConnectionWhenStable(e));}async waitForApplicationRouteForConnection(e,t,n){let i=Date.now()+t;for(;!e.isClosed;){if(this.disposed)return false;if(this.hasApplicationRouteForConnection(e))return true;if(Date.now()>=i)return false;await u(n);}return false}async waitForReciprocalKeyAgreementObservation(e,t,n){let i=Date.now()+n;for(;!e.isClosed;){if(this.disposed||this.ctx.registry.get(e.id)!==e)return false;if(e.getApplicationKeyAgreementObservationEpoch()>t)return true;if(Date.now()>=i)return false;await u(Math.min(50,Math.max(1,n)));}return false}isWebRtcApplicationRouteReadyForConnection(e){return Ci(e)}async sendApplicationRouteHandshakeAttempt(e,t,n,i,o,s="capability-update"){if(!this.disposed){c$1("[Client][HANDSHAKE] refreshing application route handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,action:s,attempt:n+1,maxAttempts:i,preferNativeSignalRoute:o});try{o?await this.deps.sendTransportHandshake(e,s,null,{preferNativeSignalRoute:!0}):await this.deps.sendTransportHandshake(e,s);}catch(a){if(this.disposed)return;console.warn("[Client][HANDSHAKE] application route handshake send failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,action:s,attempt:n+1,error:a});}}}async refreshApplicationRouteHandshake(e,t,n={}){if(this.disposed||e.isClosed||!this.deps.shouldNegotiateApplicationKeyAgreement())return;let i=this.deps.resolveApplicationCryptoForPeer(e.remoteNodeId,e);i&&e.setApplicationCrypto(i);let o=this.hasApplicationRouteForConnection(e);if(o&&!n.forceReciprocal){this.notifyApplicationRouteReady(e,t);return}if(o&&n.forceReciprocal){let c=Math.min(3,this.deps.maxRecoveryAttempts);for(let l=0;l<c;l+=1){let d=e.getApplicationKeyAgreementObservationEpoch();if(await this.sendApplicationRouteHandshakeAttempt(e,t,l,c,true,"response"),await this.waitForReciprocalKeyAgreementObservation(e,d,this.deps.attemptWaitMs)){this.notifyApplicationRouteReady(e,`${t}:reciprocal-confirmed`);return}if(this.disposed||e.isClosed||this.ctx.registry.get(e.id)!==e)return;let p=this.deps.backoffMs[Math.min(l,this.deps.backoffMs.length-1)]??0;p>0&&await u(p);}throw this.failedConnectionIds.add(e.id),this.schedulePeerReconciliationBestEffort("application-route-reciprocal-handshake-exhausted"),new Error(`[Client][HANDSHAKE] reciprocal application key agreement timed out for ${e.id}`)}if(this.recoveryInFlight.has(e.id))return;this.failedConnectionIds.delete(e.id);let s=this.deps.getConnectionControlFrameMode(e),a=t==="connect-existing"?"hello":"capability-update";if(await this.sendApplicationRouteHandshakeAttempt(e,t,0,this.deps.maxRecoveryAttempts,false,a),!this.disposed){if(await this.waitForApplicationRouteForConnection(e,this.deps.attemptWaitMs,50)){this.notifyApplicationRouteReady(e,t);return}if(!this.disposed){if(this.deps.hydrateAdoptedConnectionApplicationCrypto(e,t)){this.failedConnectionIds.delete(e.id);return}if(s==="native-main"&&!e.isClosed&&!this.hasApplicationRouteForConnection(e)){if(await this.sendApplicationRouteHandshakeAttempt(e,t,1,this.deps.maxRecoveryAttempts,true,a),this.disposed)return;if(await this.waitForApplicationRouteForConnection(e,this.deps.attemptWaitMs,50)){this.notifyApplicationRouteReady(e,t);return}if(this.disposed)return;if(this.deps.hydrateAdoptedConnectionApplicationCrypto(e,t)){this.failedConnectionIds.delete(e.id);return}}e.isClosed||this.hasApplicationRouteForConnection(e)||this.driveApplicationRouteRecoveryInBackground(e,t);}}}handleApplicationRouteMissing(e,t){if(this.disposed)return;let n=this.ctx.registry.get(e);!n||n.isClosed||n.id!==t.connectionId||n.remoteNodeId===t.remoteNodeId&&(c$1("[Client][HANDSHAKE] WebRTC route proof is waiting on application crypto; refreshing handshake",{connectionId:e,remoteNodeId:t.remoteNodeId,reason:t.reason,negotiationId:t.negotiationId??null}),this.refreshApplicationRouteAfterProofInBackground(n,t));}refreshApplicationRouteAfterProofInBackground(e,t){let n=i=>{this.disposed||console.warn("[Client][HANDSHAKE] application route refresh after WebRTC proof failed",{connectionId:t.connectionId,remoteNodeId:t.remoteNodeId,reason:t.reason,error:i});};try{Promise.resolve(this.refreshApplicationRouteHandshake(e,t.reason)).catch(n);}catch(i){n(i);}}async driveApplicationRouteRecovery(e,t){if(this.disposed||this.recoveryInFlight.has(e.id))return;this.recoveryInFlight.add(e.id);let n=this.deps.getConnectionControlFrameMode(e),i=this.deps.maxRecoveryAttempts;try{for(let o=2;o<i;o+=1){if(this.disposed||e.isClosed)return;if(this.hasApplicationRouteForConnection(e)){this.notifyApplicationRouteReady(e,t);return}let s=this.deps.backoffMs[Math.min(o,this.deps.backoffMs.length-1)];if(s>0){if(await u(s),this.disposed)return;if(e.isClosed||this.hasApplicationRouteForConnection(e)){e.isClosed||this.notifyApplicationRouteReady(e,t);return}}let a=n==="native-main"&&o%2===1;if(await this.sendApplicationRouteHandshakeAttempt(e,t,o,i,a),this.disposed)return;if(await this.waitForApplicationRouteForConnection(e,this.deps.attemptWaitMs,50)){this.notifyApplicationRouteReady(e,t);return}if(this.disposed)return;if(this.deps.hydrateAdoptedConnectionApplicationCrypto(e,t)){this.failedConnectionIds.delete(e.id);return}}if(e.isClosed||this.hasApplicationRouteForConnection(e)){e.isClosed||this.notifyApplicationRouteReady(e,t);return}this.failedConnectionIds.add(e.id),console.warn("[Client][HANDSHAKE] application route recovery exhausted; marking route failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,controlFrameMode:n,attempts:i}),this.schedulePeerReconciliationBestEffort("application-route-handshake-exhausted");}finally{this.recoveryInFlight.delete(e.id);}}clearFailure(e){let t=typeof e=="string"?e.trim():"";t&&this.failedConnectionIds.delete(t);}hasFailure(e){let t=typeof e=="string"?e.trim():"";return !!t&&this.failedConnectionIds.has(t)}driveApplicationRouteRecoveryInBackground(e,t){if(!this.disposed)try{Promise.resolve(this.driveApplicationRouteRecovery(e,t)).catch(()=>{});}catch{}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};var Sn=class{constructor(e,t){this.ctx=e;this.deps=t;}getDeterministicConnectionId(e){return this.ctx.localNodeId?this.ctx.localNodeId<=e?`${this.ctx.localNodeId}-${e}`:`${e}-${this.ctx.localNodeId}`:`native-main-${e}`}getNativeMainConnectionId(e){return this.getDeterministicConnectionId(e)}findManualDisconnectProjectionForNativeNode(e){let t=typeof e=="string"?e.trim().toLowerCase():"";if(!t)return null;let n=this.getNativeMainConnectionId(e).trim().toLowerCase(),i=o=>{if(!o)return false;let s=String(o.status??"").toLowerCase(),a=String(o.error??"").toLowerCase();return (s==="closed"||s==="disconnected"||s==="failed")&&a.includes("manual disconnect")};for(let o of [e,n]){let s=this.deps.getPeerState(o);if(i(s))return s}return this.deps.listPeerStates().find(o=>{if(!i(o))return false;let s=String(o.nodeId??"").trim().toLowerCase(),a=String(o.connectionId??"").trim().toLowerCase(),c=Array.isArray(o.connectionIds)?o.connectionIds.map(l=>String(l??"").trim().toLowerCase()):[];return s===t||a===n||a.endsWith(`-${t}`)||c.includes(n)||c.some(l=>l.endsWith(`-${t}`))})??null}hasKnownConnectionForRemoteNode(e){let t=typeof e=="string"?e.trim():"";if(!t)return false;if(this.ctx.registry.has(this.getDeterministicConnectionId(t)))return true;for(let n of this.ctx.registry.values()){let i=n;if(i.id===t||i.remoteNodeId===t||i.deviceId===t)return true}return false}inferTicketFlowBiProtocolHint(e){let t=typeof e=="string"?e.trim():"",n=this.hasKnownConnectionForRemoteNode(t),i=false;try{let o=this.deps.getPeerState(t);i=Array.isArray(o?.scopes)&&o.scopes.includes("magic-link");}catch{i=false;}return {protocolHint:this.deps.hasAnyIncomingChannelListeners()||this.deps.hasIncomingStreamListeners()||i?"explicit":"control",hasExistingConnection:n,hasMagicLinkScope:i}}};var In=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}hasTransportOnlyConnectionForRemoteNode(e){if(this.disposed)return false;let t=typeof e=="string"?e.trim():"";if(!t)return false;for(let n of this.ctx.registry.values())if(n.remoteNodeId===t&&this.deps.isTransportOnlyConnectionId(n.id))return true;return false}shouldSkipIncomingBiProbeForRemoteNode(e){return this.disposed||!this.deps.getRuntimeSafetyProfile().skipIncomingBiProbe?false:this.deps.usesTicketOnlySignalingMode()?true:this.hasTransportOnlyConnectionForRemoteNode(e)}async disconnectNodeTransport(e){if(this.disposed||!e||!e.trim())return;let t=this.ctx.wasmClient;if(t&&typeof t.disconnect=="function")try{await t.disconnect(e);}catch{}this.disposed||this.deps.notifyDisconnectRequested(e);}async isCoreConnectionHealthy(e){if(this.disposed||!e)return false;let t=this.ctx.wasmClient;if(t&&typeof t.is_connected=="function")try{let n=!!await t.is_connected(e);return this.disposed?!1:n}catch{}try{let n=await this.deps.isConnected(e);return this.disposed?!1:n}catch{return false}}handleConnectionTransportStatus(e,t,n){this.disposed||this.reportConnectionTransportStatus(e,t,n);}handleCurrentConnectionTransportStatus(e,t,n){return this.disposed?Promise.resolve(false):this.reportCurrentConnectionTransportStatus(e,t,n).then(i=>i!==null)}async reportCurrentConnectionTransportStatus(e,t,n){if(this.disposed||!this.matchesCurrentConnectionIdentityRoute(e,t,n))return null;let i=await this.readCurrentGenerationSnapshot(e.id);return !i||!this.matchesCurrentConnectionIdentityRoute(e,t,n)?null:this.reportConnectionTransportStatus(e.id,t,n,i.transportStableId,i.transportGeneration,i.routeGeneration)}handleConnectionApplicationRouteReady(e,t){this.disposed||this.reportConnectionApplicationRouteReady(e,t);}handleCurrentConnectionApplicationRouteReady(e,t){this.disposed||this.reportCurrentConnectionApplicationRouteReady(e,t);}async reportConnectionTransportStatus(e,t,n,i,o,s,a=true){if(this.disposed||!this.matchesCurrentConnectionRoute(e,t,n))return null;let c=await this.readCurrentGenerationObservation(e,i,o,s);if(!c||!this.matchesCurrentConnectionRoute(e,t,n))return null;let l=this.ctx.wasmClient;if(!l||typeof l.report_transport_status!="function")return null;try{let d=await l.report_transport_status(e,t,n??null,BigInt(c.transportStableId),BigInt(c.transportGeneration),BigInt(c.routeGeneration));return this.disposed||d==null?null:(a&&this.deps.hasRustPeerLifecycleProjection()&&this.schedulePeerReconciliationBestEffort("transport-status-report"),this.generationObservationFromSnapshot(d))}catch(d){return this.disposed||c$1("[Client] Failed to report active transport to Rust",{connectionId:e,activeTransport:t,parallelTransport:n??null,error:d}),null}}async reportConnectionApplicationRouteReady(e,t){if(this.disposed)return;let n=await this.reportConnectionTransportStatus(e,t.activeTransport,t.parallelTransport??null,t.transportStableId,t.transportGeneration,t.routeGeneration,false);n&&await this.settleConnectionApplicationRoute(e,t.activeTransport,t.parallelTransport??null,n);}async reportCurrentConnectionApplicationRouteReady(e,t){if(this.disposed||!this.matchesCurrentConnectionIdentityRoute(e,t.activeTransport,t.parallelTransport))return false;let n=null;for(let i=0;i<2&&!n;i+=1){let o=await this.readCurrentGenerationSnapshot(e.id);if(!o||!this.matchesCurrentConnectionIdentityRoute(e,t.activeTransport,t.parallelTransport))return false;n=await this.reportConnectionTransportStatus(e.id,t.activeTransport,t.parallelTransport??null,o.transportStableId,o.transportGeneration,o.routeGeneration,false),!n&&i===0&&await Promise.resolve();}return !n||!this.matchesCurrentConnectionIdentityRoute(e,t.activeTransport,t.parallelTransport)?false:this.settleConnectionApplicationRoute(e.id,t.activeTransport,t.parallelTransport??null,n)}async settleConnectionApplicationRoute(e,t,n,i){if(this.disposed||!this.matchesCurrentConnectionRoute(e,t,n))return false;let o=this.ctx.wasmClient;if(!o||typeof o.report_managed_connection_settled!="function")return false;try{let s=await o.report_managed_connection_settled(e,!0,null,BigInt(i.transportStableId),BigInt(i.transportGeneration),BigInt(i.routeGeneration));return this.disposed||s==null||!this.matchesCurrentConnectionRoute(e,t,n)?!1:(this.deps.hasRustPeerLifecycleProjection()&&this.schedulePeerReconciliationBestEffort("application-route-ready"),!0)}catch(s){return this.disposed||c$1("[Client] Failed to settle proven application route in Rust",{connectionId:e,activeTransport:t,parallelTransport:n,error:s}),false}}async readCurrentGenerationObservation(e,t,n,i){if(!Number.isSafeInteger(t)||Number(t)<=0||!Number.isSafeInteger(n)||Number(n)<=0||!Number.isSafeInteger(i)||Number(i)<0)return null;let o=await this.readCurrentGenerationSnapshot(e);return !o||t!==o.transportStableId||n!==o.transportGeneration||i!==o.routeGeneration?null:o}async readCurrentGenerationSnapshot(e){let t=this.ctx.wasmClient;if(!t||typeof t.connection_state!="function")return null;try{let n=await t.connection_state(e);if(this.disposed||!n||typeof n!="object")return null;let i=n,o=typeof i.activeTransportStableId=="number"?i.activeTransportStableId:i.active_transport_stable_id,s=typeof i.transportGeneration=="number"?i.transportGeneration:i.transport_generation,a=typeof i.routeGeneration=="number"?i.routeGeneration:i.route_generation;return !Number.isSafeInteger(o)||Number(o)<=0||!Number.isSafeInteger(s)||Number(s)<=0||!Number.isSafeInteger(a)||Number(a)<0?null:{transportStableId:Number(o),transportGeneration:Number(s),routeGeneration:Number(a)}}catch{return null}}generationObservationFromSnapshot(e){if(!e||typeof e!="object")return null;let t=e,n=t.activeTransportStableId??t.active_transport_stable_id,i=t.transportGeneration??t.transport_generation,o=t.routeGeneration??t.route_generation;return !Number.isSafeInteger(n)||Number(n)<=0||!Number.isSafeInteger(i)||Number(i)<=0||!Number.isSafeInteger(o)||Number(o)<0?null:{transportStableId:Number(n),transportGeneration:Number(i),routeGeneration:Number(o)}}matchesCurrentConnectionRoute(e,t,n){let i=this.ctx.registry.get(e);if(!i||i.isClosed||typeof i.getTransportStatus!="function")return false;let o=i.getTransportStatus();return o.activeTransport===t&&(o.parallelTransport??null)===(n??null)}matchesCurrentConnectionIdentityRoute(e,t,n){return this.ctx.registry.get(e.id)===e&&this.matchesCurrentConnectionRoute(e.id,t,n)}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};var ma=[...c];function qr({transportPriority:r,rankRoutes:e,disableIrohFallback:t,runtimeSafetyProfile:n,isMoQReady:i,isMoQDataReady:o,isMoQApplicationRouteProven:s,requestMoQApplicationRouteProof:a,clearMoQApplicationRouteProof:c,sendMoQ:l,sendIrohApplicationFrame:d}){let p=r||ma;return {priorities:p,rankRoutes:e?u=>e(p,u):void 0,disableIrohFallback:t||false,isMoQReady:i,isMoQDataReady:o,isMoQApplicationRouteProven:s,requestMoQApplicationRouteProof:a,clearMoQApplicationRouteProof:c,sendMoQ:l,sendIrohApplicationFrame:d,runtimeFlow:n.flow,readerCloseStrategy:n.readerCloseStrategy}}var bn=class{constructor(e){this.deps=e;}create(e){let t=this.deps.getOptions();return qr({transportPriority:t?.transportPriority,rankRoutes:(n,i)=>this.deps.rankRoutes(n,i),disableIrohFallback:t?.disableIrohFallback,runtimeSafetyProfile:this.deps.getRuntimeSafetyProfile(),isMoQReady:()=>this.deps.isMoQReady(),isMoQDataReady:()=>this.deps.isMoQDataReady(e),isMoQApplicationRouteProven:()=>this.deps.isMoQApplicationRouteProven(e),requestMoQApplicationRouteProof:()=>this.deps.requestMoQApplicationRouteProof(e),clearMoQApplicationRouteProof:()=>this.deps.clearMoQApplicationRouteProof(e),sendMoQ:(n,i)=>this.deps.sendMoQ(e,n,i),sendIrohApplicationFrame:n=>this.deps.sendIrohApplicationFrame(e,n)})}};var Rn=class{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}getConnectionControlFrameMode(e){return typeof e.getControlFrameMode=="function"?e.getControlFrameMode():"typed"}async sendConnectionControlEnvelope(e,t,n={}){if(this.disposed)return;if(this.getConnectionControlFrameMode(e)==="native-main"){if(n.preferNativeSignalRoute&&(typeof e.sendNativeControlEnvelope=="function"?await e.sendNativeControlEnvelope(t):false))return;try{await e.sendRawIrohFrame(re(fe(t)));return}catch(o){if(typeof e.sendNativeControlEnvelope=="function"?await e.sendNativeControlEnvelope(t):false)return;throw o}}if(typeof e.sendControl=="function"){await e.sendControl(t);return}await e.send(t);}async sendTransportHandshake(e,t,n,i={}){if(this.disposed)return;let o=this.deps.shouldNegotiateApplicationKeyAgreement()?await this.deps.ensureConnectionKeyAgreementState(e):null;if(this.disposed)return;let s={webrtc:this.deps.isWebRTCTransportEnabled(),moq:this.deps.isMoQReady(),ble:this.deps.isBleTransportEnabled(),...o?{applicationKeyAgreement:true}:{}},a=t==="hello"?this.deps.getPendingSessionToken(e.remoteNodeId):void 0,c=t==="hello"?this.deps.getPendingSessionTokenPayload(e.remoteNodeId):void 0;c$1("[Client][HANDSHAKE] sending",{action:t,connectionId:e.id,remoteNodeId:e.remoteNodeId,channelId:this.deps.getConnectionChannelId(e.id)??null,capabilities:s,hasSessionToken:!!a,hasSessionTokenPayload:!!c,hasChallengeToSign:!!n});let l={type:"handshake",action:t,capabilities:s,moq:s.moq,channelId:this.deps.getConnectionChannelId(e.id)??void 0,...a?{sessionToken:a}:{},...a&&c?{sessionTokenPayload:c}:{},...o?{applicationKeyAgreement:ro(o.publicKey)}:{}},d=await this.deps.buildLocalTransportTrustPayload(e,n);if(!this.disposed){if(c$1("[Client][HANDSHAKE] local trust payload status",{action:t,connectionId:e.id,remoteNodeId:e.remoteNodeId,hasTransportTrustPayload:!!d,hasChallengeInPayload:!!d?.challenge}),!d){if(this.deps.requiresManagedTransportTrust()){let p=this.deps.initializeConnectionTrust(e);p.failed=true,p.failureReason="local-trusted-identity-unavailable",console.warn("[Client][TRUST] Unable to attach local transport trust payload for managed trust handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t});}await this.sendConnectionControlEnvelope(e,l,i),o&&this.deps.markConnectionApplicationCryptoRequired(e);return}await this.sendConnectionControlEnvelope(e,{...l,transportTrust:d},i),o&&this.deps.markConnectionApplicationCryptoRequired(e),c$1("[Client][HANDSHAKE] sent OK",{action:t,connectionId:e.id,remoteNodeId:e.remoteNodeId});}}async sendTransportHandshakeWithRecovery(e,t,n,i){for(let o=0;o<this.deps.maxRecoveryAttempts;o+=1){if(this.disposed)return;if(e.isClosed)throw new Error("[Client][HANDSHAKE] connection closed before handshake recovery completed");let s=this.getConnectionControlFrameMode(e)==="native-main"&&o%2===1;try{await this.sendTransportHandshake(e,t,n,{preferNativeSignalRoute:s}),t==="ack"&&!s&&this.getConnectionControlFrameMode(e)==="native-main"&&await this.sendTransportHandshake(e,t,n,{preferNativeSignalRoute:!0});return}catch(a){let c=o>=this.deps.maxRecoveryAttempts-1;if(console.warn("[Client][HANDSHAKE] control handshake send failed; retrying if budget remains",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t,reason:i,attempt:o+1,maxAttempts:this.deps.maxRecoveryAttempts,preferNativeSignalRoute:s,finalAttempt:c,error:a}),c)throw a;let l=this.deps.recoveryBackoffMs[Math.min(o,this.deps.recoveryBackoffMs.length-1)]??0;if(l>0&&(await u(l),this.disposed))return}}}async broadcastTransportCapabilityUpdate(e){if(this.disposed)return;if(this.deps.isWebRTCTransportEnabled()){let o=this.deps.getRTCConfig();for(let s of this.deps.getConnections()){if(this.disposed)return;s.updateRTCConfig(o);}}if(this.disposed)return;let t=Array.from(this.deps.getConnections()).filter(o=>!o.isClosed).map(async o=>{await this.sendTransportHandshake(o,"capability-update");}),i=(await Promise.allSettled(t)).filter(o=>o.status==="rejected");i.length>0&&c$1("[Client] Some transport capability updates failed",{reason:e,failures:i.length});}requestProtectedWebRTCUpgradeIfInitiator(e,t){if(this.disposed)return;let n=this.deps.isSessionTokenApproved(e.id,e.remoteNodeId),i=this.deps.getLocalNodeId();!this.deps.usesTicketOnlySignalingMode()&&!n||!this.deps.isWebRTCTransportEnabled()||!i||!e.remoteNodeId||i.localeCompare(e.remoteNodeId)<=0||e.requestWebRTCUpgrade(t);}};function fa(r){let e=r.transports?.ble;return e===true||!!e&&typeof e=="object"&&e.enabled!==false}function zr(r,e){return fa(r)&&e?.transport.ble===true}function $r(r){let{host:e}=r;return new Cn(e.getContext(),{getConnectionForPeer:(t,n)=>e.getConnectionForPeer(t,n)??null,resolveApplicationCryptoForPeer:(t,n)=>e.resolveApplicationCryptoForPeer(t,n),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),hydrateAdoptedConnectionApplicationCrypto:(t,n)=>e.hydrateAdoptedConnectionApplicationCrypto(t,n),sendTransportHandshake:(t,n,i,o)=>r.getHandshake().sendTransportHandshake(t,n,i,o),getConnectionControlFrameMode:t=>r.getHandshake().getConnectionControlFrameMode(t),reportApplicationRouteReady:(t,n)=>{let i=t.getTransportStatus();r.getHealth().handleCurrentConnectionApplicationRouteReady(t,{...i,reason:n});},applyConnectionTrustProjection:t=>e.applyConnectionTrustProjection(t),announceConnectionWhenStable:t=>e.announceConnectionWhenStable(t),isConnectionAnnounced:t=>e.isConnectionAnnounced(t),hasRustPeerLifecycleProjection:()=>e.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:t=>e.schedulePeerReconciliation(t),maxRecoveryAttempts:15,attemptWaitMs:1e3,backoffMs:Yn})}function Vr(r){let{host:e}=r;return new Rn({shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),ensureConnectionKeyAgreementState:t=>e.ensureConnectionKeyAgreementState(t),isWebRTCTransportEnabled:()=>j(e.getOptions()),isMoQReady:()=>e.isMoQReady(),isBleTransportEnabled:()=>zr(e.getOptions(),e.getRuntimeCapabilities()),getConnectionChannelId:t=>e.getConnectionChannelId(t),getPendingSessionToken:t=>e.getPendingSessionToken(t),getPendingSessionTokenPayload:t=>e.getPendingSessionTokenPayload(t),buildLocalTransportTrustPayload:(t,n)=>e.buildLocalTransportTrustPayload(t,n),requiresManagedTransportTrust:()=>e.requiresManagedTransportTrust(e.getDiscoveryMode()),initializeConnectionTrust:t=>e.initializeConnectionTrust(t),markConnectionApplicationCryptoRequired:t=>e.markConnectionApplicationCryptoRequired(t),getRTCConfig:()=>r.getRTCConfig(),getConnections:()=>e.getConnections(),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),isSessionTokenApproved:(t,n)=>e.isSessionTokenApproved(t,n),getLocalNodeId:()=>e.getLocalNodeId()||null,maxRecoveryAttempts:15,recoveryBackoffMs:Yn,registerDisposer:t=>e.registerDisposer(t)})}function Yr(r){return new In(r.getContext(),{getRuntimeSafetyProfile:()=>r.getRuntimeSafetyProfile(),usesTicketOnlySignalingMode:()=>r.usesTicketOnlySignalingMode(),isTransportOnlyConnectionId:e=>r.isTransportOnlyConnectionId(e),notifyDisconnectRequested:e=>r.notifyDisconnectRequested(e),isConnected:e=>r.isBackendConnected(e),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:e=>r.schedulePeerReconciliation(e)})}function Jr(r){return new bn({getOptions:()=>r.getOptions(),getRuntimeSafetyProfile:()=>r.getRuntimeSafetyProfile(),rankRoutes:(e,t)=>{let n=r.getWasmClient(),i=n?.rankRoutes??n?.rank_routes;if(typeof i!="function")return [...t];try{let o=i.call(n,e,t);return Array.isArray(o)?o:[...t]}catch(o){return c$1("[OpenRTC][route-policy] Rust ranking unavailable; preserving candidate order",{error:o instanceof Error?o.message:String(o)}),[...t]}},isMoQReady:()=>r.isMoQReady(),isMoQDataReady:e=>r.isMoQDataReady(e),isMoQApplicationRouteProven:e=>r.isMoQApplicationRouteProven(e),requestMoQApplicationRouteProof:e=>r.requestMoQApplicationRouteProof(e),clearMoQApplicationRouteProof:e=>r.clearMoQApplicationRouteProof(e),sendMoQ:(e,t,n)=>r.sendMoQData(e,t,n),sendIrohApplicationFrame:(e,t)=>r.sendIrohApplicationFrame(e,t)})}function Xr(r){return new Sn(r.getContext(),{getPeerState:e=>r.getPeerState(e),listPeerStates:()=>r.listPeerStates(),hasAnyIncomingChannelListeners:()=>r.hasAnyIncomingChannelListeners(),hasIncomingStreamListeners:()=>r.hasIncomingStreamListeners()})}function Zr(r){return new Si({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getRuntimeSafetyProfile:()=>r.runtimeSafetyProfile,getRuntimeCapabilities:()=>r.signalingBackendController.getRuntimeCapabilities(),getWasmClient:()=>r.wasmClient,registerDisposer:e=>r.lifecycleScope.register(e),getLocalNodeId:()=>r.localNodeId,getDiscoveryMode:()=>r.discoveryMode,hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),getPeerState:e=>r.peerServices.getPeerState(e),listPeerStates:()=>r.peerServices.listPeerStates(),getConnectionForPeer:(e,t)=>r.registry.getForPeer(e,t),getConnections:()=>r.registry.values(),getConnectionChannelId:e=>r.connectionChannelPolicy.getConnectionChannelId(e),isTransportOnlyConnectionId:e=>r.connectionChannelPolicy.isTransportOnlyConnectionId(e),getConnectionTrustState:e=>r.connectionTrust.getStateByConnectionId(e),buildLocalTransportTrustPayload:(e,t)=>r.connectionTrust.buildLocalTransportTrustPayload(e,t),initializeConnectionTrust:e=>r.connectionTrust.initialize(e),resolveApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.resolveForPeer(e,t),resolveExistingApplicationCryptoForPeer:(e,t)=>r.securityServices.resolveExistingApplicationCryptoForPeer(e,t),getConfiguredApplicationCrypto:()=>r.options?.applicationCrypto,shouldNegotiateApplicationKeyAgreement:()=>r.applicationCrypto.shouldNegotiateKeyAgreement(),hydrateAdoptedConnectionApplicationCrypto:(e,t)=>r.applicationCrypto.hydrateAdoptedConnection(e,t),ensureConnectionKeyAgreementState:e=>r.applicationCrypto.ensureConnectionKeyAgreementState(e),markConnectionApplicationCryptoRequired:e=>r.applicationCrypto.markRequired(e),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),announceConnectionWhenStable:e=>r.connectionLifecycle.announceConnectionWhenStable(e),isConnectionAnnounced:e=>r.connectionLifecycle.isConnectionAnnounced(e),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),isMoQReady:()=>r.moqServices.isReady(),isMoQDataReady:e=>r.moqServices.isDataReady(e),isMoQApplicationRouteProven:e=>r.moqServices.isApplicationRouteProven(e),requestMoQApplicationRouteProof:e=>r.moqServices.requestApplicationRouteProof(e),clearMoQApplicationRouteProof:e=>r.moqServices.clearApplicationRouteProof(e),sendMoQData:(e,t,n)=>r.moqServices.sendData(e,t,n),sendIrohApplicationFrame:(e,t)=>r.applicationStreams.sendFrame(e,t),getPendingSessionToken:e=>r.sessionTokens.getRouteRepairTokenForNode(e)??void 0,getPendingSessionTokenPayload:e=>r.sessionTokens.getRouteRepairTokenPayloadForNode(e)??void 0,requiresManagedTransportTrust:e=>r.runtimeStatus.requiresManagedTransportTrust(e??r.discoveryMode),isSessionTokenApproved:(e,t)=>r.sessionTokens.isApproved(e,t),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),notifyDisconnectRequested:e=>r.signalingBackendController.notifyDisconnectRequested(e),isBackendConnected:e=>r.signalingBackendController.isConnected(e),hasAnyIncomingChannelListeners:()=>r.incomingStreamRouter.hasAnyIncomingChannelListeners(),hasIncomingStreamListeners:()=>r.incomingStreamRouter.hasIncomingStreamListeners()})}var Si=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getHandshake:()=>this.handshake,getHealth:()=>this.health,getRTCConfig:()=>this.getRTCConfig()}}get upgrade(){return this._upgrade??(this._upgrade=$r(this.factoryHost))}get handshake(){return this._handshake??(this._handshake=Vr(this.factoryHost))}get health(){return this._health??(this._health=Yr(this.host))}get contexts(){return this._contexts??(this._contexts=Jr(this.host))}get peerIdentity(){return this._peerIdentity??(this._peerIdentity=Xr(this.host))}getRTCConfig(){return k$1(this.host.getOptions(),e=>c$1(e))}hasApplicationRouteForConnectionSnapshot(e,t,n){return vn(e,(i,o)=>this.host.getConfiguredApplicationCrypto()??this.host.resolveExistingApplicationCryptoForPeer(i,o),t,n)}hasApplicationRouteForPeer(e,t){return this.hasApplicationRouteForConnectionSnapshot(this.host.getConnectionForPeer(e,t),e,t)}isWebRtcApplicationRouteReadyForConnectionSnapshot(e){return Ci(e)}hasApplicationRouteFailure(e){return this._upgrade?.hasFailure(e)??false}clearApplicationRouteFailure(e){this._upgrade?.clearFailure(e);}};var Pn=class{constructor(e){this.deps=e;this.channelIds=new Map;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.channelIds.clear());}isChannelPromotionEligible(e){let t=this.deps.getRegisteredChannel(e);return t?t.promotionPolicy!=="never":true}isTransportOnlyChannel(e){return xt(this.deps.getRegisteredChannel(e))}getConnectionChannelId(e){if(this.disposed)return null;let t=typeof e=="string"?e.trim():"";return t?this.channelIds.get(t)??null:null}isTransportOnlyConnectionId(e){return this.isTransportOnlyChannel(this.getConnectionChannelId(e))}allowsTransportOnlyStability(e){let t=this.getConnectionChannelId(e.id);return t?this.isTransportOnlyChannel(t):this.deps.usesTicketOnlySignalingMode()}resolvePromotionEligibility(e){if(this.disposed)return false;let t=this.getConnectionChannelId(e.connectionId);if(t)return this.isChannelPromotionEligible(t);let n=typeof e.nodeId=="string"?e.nodeId.trim():"";for(let i of this.deps.getConnections()){if(e.connectionId&&i.id===e.connectionId)return this.isChannelPromotionEligible(this.getConnectionChannelId(i.id));if(n&&i.remoteNodeId===n)return this.isChannelPromotionEligible(this.getConnectionChannelId(i.id))}return true}assign(e,t){if(this.disposed)return;let n=typeof t=="string"?t.trim():"";if(!n)return;this.channelIds.set(e.id,n);let i=this.deps.getConnectionTrustState(e.id);if(i&&!this.isChannelPromotionEligible(n)&&(i.required=false,i.verified=true,i.failed=false,i.failureReason=void 0,i.issuedChallenge=null,i.verifiedDeviceId||(i.verifiedDeviceId=i.expectedDeviceId||this.deps.getKnownDeviceIdByNodeId(e.remoteNodeId)||null)),this.deps.hasRustPeerLifecycleProjection())this.schedulePeerReconciliationBestEffort("session-token-trust-approved");else for(let o of this.deps.getConnections())if(o.id===e.id){this.deps.applyConnectionTrustProjection(o);break}}forget(e){if(this.disposed)return;let t=typeof e=="string"?e.trim():"";t&&this.channelIds.delete(t);}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};var Tn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}bindConnectionDeviceIdInRust(e,t){if(this.disposed)return;let n=t.trim();if(!n)return;let i=this.deps.getSessionTokenApprovedScope(e.id);if(i&&!this.deps.sessionTokenScopeAllowsDeviceBinding(i)){c$1("[Client][BIND] skipped transient session device binding",{connectionId:e.id,remoteNodeId:e.remoteNodeId,scope:i});return}let o=this.ctx.wasmClient,s=!!o&&typeof o.bind_connection_device_id=="function";c$1("[Client][BIND] bindConnectionDeviceIdInRust entered",{connectionId:e.id,remoteNodeId:e.remoteNodeId,deviceId:n,hasWasmClient:!!o,hasMethod:s}),this.deps.rememberKnownDeviceForNode(e.remoteNodeId,n);let a=this.deps.getApplicationCryptoForConnectionOrPeer(e.id,e.remoteNodeId);if(a&&this.deps.indexApplicationCryptoForPeer(n,a),!!s)try{Promise.resolve(o.bind_connection_device_id(e.id,n)).then(()=>{this.disposed||c$1("[Client][BIND] bind_connection_device_id resolved",{connectionId:e.id,deviceId:n});}).catch(c=>{this.disposed||console.warn("[Client][TRUST] Failed to bind deviceId on Rust connection record",{connectionId:e.id,remoteNodeId:e.remoteNodeId,deviceId:n,error:c});});}catch(c){if(this.disposed)return;console.warn("[Client][TRUST] Failed to bind deviceId on Rust connection record",{connectionId:e.id,remoteNodeId:e.remoteNodeId,deviceId:n,error:c});}}async rejectConnectionInRust(e,t){if(this.disposed)return;let n=this.ctx.wasmClient;if(!(!n||typeof n.reject_connection_admission!="function"))try{await n.reject_connection_admission(e.id,t);}catch(i){if(this.disposed)return;console.warn("[Client][TRUST] Failed to reject connection on Rust admission authority",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,error:i});}}retireSupersededConnections(e,t,n){if(this.disposed)return;let i=t.trim();if(i)for(let o of this.ctx.registry.values())o.id===e.id||o.isClosed||this.deps.getLogicalDeviceIdForConnection(o.id)===i&&(c$1("[Client][CONNECTION] Retiring superseded connection for logical device",{keptConnectionId:e.id,retiredConnectionId:o.id,logicalDeviceId:i,reason:n}),this.disconnectBestEffort(o));}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}};var An=class{constructor(e,t){this.ctx=e;this.deps=t;this.states=new Map;this.failureCooldowns=new Map;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.states.clear(),this.failureCooldowns.clear());}initialize(e,t){if(this.disposed)return {required:false,verified:false,failed:true,failureReason:"connection-trust-manager-disposed",expectedDeviceId:t??null,verifiedDeviceId:null,issuedChallenge:null};let n=this.states.get(e.id);if(n)return t&&!n.expectedDeviceId&&(n.expectedDeviceId=t),n;let i=this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId,deviceId:t??void 0}),o=this.deps.consumePendingSessionTokenTrustApproval(e.id),s=this.deps.getSessionTokenApprovedScope(e.id),a=o.scope??s,c=o.approved||!!s,l=this.deps.getKnownDeviceIdForNode(e.remoteNodeId),d=!c&&i&&this.deps.requiresManagedTransportTrust(),p={required:d,verified:!d,failed:false,expectedDeviceId:t||l||null,verifiedDeviceId:d?null:t||l||null,issuedChallenge:d?f$2():null};return this.states.set(e.id,p),a&&this.deps.addPeerScope(e.id,a),p}sessionTokenScopeAllowsDeviceBinding(e){let t=typeof e=="string"?e.trim():"";return t==="user-device"||t==="persistent"||t==="trusted-device"||t.startsWith("trusted-device:")}resolveExpectedDeviceIdForSessionTokenScope(e,t,n,i){let o=typeof e=="string"?e.trim():"";if(!o)return null;if(!n)return o;let s=new Set,a=c=>{let l=typeof c=="string"?c.trim():"";l&&s.add(l);};if(a(t),i){a(this.deps.getSessionTokenApprovedScope(i.id));for(let c of this.deps.getPeerScopes(i.id))a(c);for(let c of this.deps.getPeerScopes(i.remoteNodeId))a(c);}return Array.from(s).some(c=>this.sessionTokenScopeAllowsDeviceBinding(c))?o:null}getState(e){if(this.disposed)return null;let t=typeof e.connectionId=="string"?e.connectionId.trim():"";if(t)return this.states.get(t)??null;for(let[n,i]of this.states.entries())if(i.verifiedDeviceId&&(i.verifiedDeviceId===e.deviceId||i.verifiedDeviceId===e.deviceIdHint)||i.expectedDeviceId&&(i.expectedDeviceId===e.deviceId||i.expectedDeviceId===e.deviceIdHint))return this.states.get(n)??null;return null}getProjection(e){if(this.disposed)return null;let t=this.getState(e);if(!t)return null;let n=t.verified&&!t.failed,i=typeof e.connectionId=="string"&&e.connectionId.trim()||Array.from(this.states.entries()).find(([,a])=>a===t)?.[0]||"",o=i?this.deps.getSessionTokenApprovedScope(i):null,s=!o||this.sessionTokenScopeAllowsDeviceBinding(o);return n?{routable:true,protocolState:"routable",health:"healthy",deviceId:s?t.verifiedDeviceId??t.expectedDeviceId??e.deviceId??null:null}:t.required?{routable:false,protocolState:"unverified",health:t.failed?"stale":"unknown",error:t.failureReason??"trusted-device-proof-pending",deviceId:s?t.expectedDeviceId??e.deviceId??e.deviceIdHint??null:null}:null}async buildLocalTransportTrustPayload(e,t){if(this.disposed)return null;let n=await k$2().catch(()=>null),i=await this.deps.getLocalDeviceId().catch(()=>null)||this.ctx.deviceId||this.deps.getFallbackLocalDeviceId()||null;if(!n||!i)return null;let o=this.initialize(e),s={version:1,deviceId:i,identityFingerprint:n.fingerprint,challenge:o.issuedChallenge??void 0};if(t&&(s.signedChallenge=await n.signChallenge(t),s.signedChallengeFor=t,!await g(t,s.signedChallenge,h(n.publicKey))))throw new Error("local-transport-trust-signature-self-check-failed");return s}async verifyRemoteTransportTrust(e,t){if(this.disposed)return {verified:false,reason:"connection-trust-manager-disposed"};let n=this.initialize(e);if(!n.required)return {verified:true,deviceId:t?.deviceId??n.expectedDeviceId??null};if(!t)return {verified:false,reason:"missing-transport-trust-payload"};let i=typeof t.deviceId=="string"?t.deviceId.trim():"";if(!i)return {verified:false,reason:"missing-remote-device-id"};if(n.expectedDeviceId&&n.expectedDeviceId!==i)return {verified:false,reason:`expected-device-mismatch:${n.expectedDeviceId}:${i}`};let o=this.deps.getKnownDevice(i,e.remoteNodeId);if(!o){if(await this.deps.refreshKnownDeviceCache(),this.disposed)return {verified:false,reason:"connection-trust-manager-disposed"};o=this.deps.getKnownDevice(i,e.remoteNodeId);}if(!o)return {verified:false,reason:`unknown-trusted-device:${i}`};let s=i$1(o.metadata);if(!s)return {verified:false,reason:`missing-trusted-device-metadata:${i}`};if(t.identityFingerprint&&s.identityFingerprint!==t.identityFingerprint)return {verified:false,reason:`trusted-device-fingerprint-mismatch:${i}`};let a=n.issuedChallenge;return !a||!t.signedChallenge?{verified:false,reason:"missing-signed-transport-challenge"}:typeof t.signedChallengeFor!="string"?{verified:false,reason:"unbound-transport-trust-response"}:t.signedChallengeFor!==a?{verified:false,stale:true,reason:"stale-transport-trust-response"}:await g(a,t.signedChallenge,s.identityPublicKey)?{verified:true,deviceId:i}:{verified:false,reason:`invalid-transport-proof-bound:${i}`}}async enforceFailure(e,t){if(this.disposed)return;let n=this.initialize(e);n.failed=true,n.verified=false,n.failureReason=t,await this.deps.rejectConnectionInRust(e,t),!this.disposed&&(this.deps.applyConnectionTrustProjection(e),console.warn("[Client][TRUST] Disconnecting unverified connection",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t}),this.failureCooldowns.set(e.remoteNodeId,Date.now()),await Promise.allSettled([this.disconnectConnectionBestEffort(e),this.disconnectNodeBestEffort(e.remoteNodeId)]));}markVerified(e,t){if(this.disposed)return;this.failureCooldowns.delete(e.remoteNodeId);let n=this.deps.getSessionTokenApprovedScope(e.id),i=!n||this.sessionTokenScopeAllowsDeviceBinding(n),o=i?t:null,s=this.initialize(e,o);s.verified=true,s.failed=false,s.failureReason=void 0,i?(s.verifiedDeviceId=o||s.verifiedDeviceId||s.expectedDeviceId||null,o&&!s.expectedDeviceId&&(s.expectedDeviceId=o)):(s.verifiedDeviceId=null,s.expectedDeviceId=null),this.deps.applyConnectionTrustProjection(e);let a=s.verifiedDeviceId??s.expectedDeviceId??o??null;a&&(this.deps.bindConnectionDeviceIdInRust(e,a),this.deps.retireSupersededConnections(e,a,"trusted-device-replacement"));}clearForConnection(e){this.disposed||this.states.delete(e);}getStateByConnectionId(e){if(!this.disposed)return this.states.get(e)}getLogicalDeviceIdForConnection(e){let t=this.states.get(e);return t?.verifiedDeviceId??t?.expectedDeviceId??null}clearFailureCooldown(e){this.disposed||this.failureCooldowns.delete(e);}getFailureCooldown(e){if(!this.disposed)return this.failureCooldowns.get(e)}shouldSuppressConnectionRebuild(e,t,n,i=Date.now()){if(this.disposed)return {suppress:false,remainingMs:0};let o=this.failureCooldowns.get(e);return o===void 0||i-o>=t||n?{suppress:false,remainingMs:0}:{suppress:true,remainingMs:t-(i-o)}}logConnectionRebuildSuppressed(e,t){this.disposed||c$1("[Client][TRUST] Skipping connection rebuild for node in trust-failure cooldown",{remoteNodeId:e,cooldownRemainingMs:t});}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}disconnectNodeBestEffort(e){try{return Promise.resolve(this.deps.disconnectNode(e)).catch(()=>{})}catch{return Promise.resolve()}}};function es(r){return new Ii({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getDeviceId:()=>r.deviceId,getDiscoveryMode:()=>r.discoveryMode,registerDisposer:e=>r.lifecycleScope.register(e),getRegisteredChannel:e=>r.incomingStreamRouter.getRegisteredChannel(e),getConnections:()=>r.registry.values(),requiresManagedTransportTrust:e=>r.runtimeStatus.requiresManagedTransportTrust(e??r.discoveryMode),consumePendingSessionTokenTrustApproval:e=>r.sessionTokens.consumePendingTrustApproval(e),getSessionTokenApprovedScope:e=>r.sessionTokens.getApprovedScope(e),addPeerScope:(e,t)=>r.peerServices.addPeerScope(e,t),getPeerScopes:e=>r.peerServices.getPeerScopes(e),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),getKnownDevice:(e,t)=>r.deviceDirectory.getKnownDevice(e,t),refreshKnownDeviceCache:()=>r.deviceDirectory.refreshKnownDeviceCache(),getLocalDeviceId:()=>r.signalingBackendController.getLocalDeviceId(),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),disconnectRuntimeNode:e=>r.runtimeConnections.disconnectNode(e),rememberKnownDeviceForNode:(e,t)=>r.deviceDirectory.rememberKnownDeviceForNode(e,t),getApplicationCryptoForConnectionOrPeer:(e,t)=>r.applicationCrypto.getForConnectionOrPeer(e,t),indexApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.indexPeer(e,t),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode()})}var Ii=class{constructor(e){this.host=e;}get trust(){return this._trust||(this._trust=new An(this.host.getContext(),{requiresManagedTransportTrust:()=>this.host.requiresManagedTransportTrust(this.host.getDiscoveryMode()),resolvePromotionEligibility:e=>this.channelPolicy.resolvePromotionEligibility(e),consumePendingSessionTokenTrustApproval:e=>this.host.consumePendingSessionTokenTrustApproval(e),getSessionTokenApprovedScope:e=>this.host.getSessionTokenApprovedScope(e),addPeerScope:(e,t)=>this.host.addPeerScope(e,t),getPeerScopes:e=>this.host.getPeerScopes(e),getKnownDeviceIdForNode:e=>this.host.getKnownDeviceIdForNode(e),getKnownDevice:(e,t)=>this.host.getKnownDevice(e,t),refreshKnownDeviceCache:()=>this.host.refreshKnownDeviceCache(),getLocalDeviceId:()=>this.host.getLocalDeviceId(),getFallbackLocalDeviceId:()=>this.host.getDeviceId()??this.host.getOptions()?.localDeviceId??null,applyConnectionTrustProjection:e=>this.host.applyConnectionTrustProjection(e),bindConnectionDeviceIdInRust:(e,t)=>this.deviceBinder.bindConnectionDeviceIdInRust(e,t),rejectConnectionInRust:(e,t)=>this.deviceBinder.rejectConnectionInRust(e,t),retireSupersededConnections:(e,t,n)=>this.deviceBinder.retireSupersededConnections(e,t,n),disconnectNode:e=>this.host.disconnectRuntimeNode(e)})),this._trust}get deviceBinder(){return this._deviceBinder||(this._deviceBinder=new Tn(this.host.getContext(),{rememberKnownDeviceForNode:(e,t)=>this.host.rememberKnownDeviceForNode(e,t),getApplicationCryptoForConnectionOrPeer:(e,t)=>this.host.getApplicationCryptoForConnectionOrPeer(e,t),indexApplicationCryptoForPeer:(e,t)=>{this.host.indexApplicationCryptoForPeer(e,t);},getLogicalDeviceIdForConnection:e=>this.trust.getLogicalDeviceIdForConnection(e),getSessionTokenApprovedScope:e=>this.host.getSessionTokenApprovedScope(e),sessionTokenScopeAllowsDeviceBinding:e=>this.trust.sessionTokenScopeAllowsDeviceBinding(e)})),this._deviceBinder}get channelPolicy(){return this._channelPolicy||(this._channelPolicy=new Pn({registerDisposer:e=>this.host.registerDisposer(e),getRegisteredChannel:e=>this.host.getRegisteredChannel(e),getConnections:()=>this.host.getConnections(),getConnectionTrustState:e=>this.trust.getStateByConnectionId(e),getKnownDeviceIdByNodeId:e=>this.host.getKnownDeviceIdForNode(e),hasRustPeerLifecycleProjection:()=>this.host.hasRustPeerLifecycleProjection(),applyConnectionTrustProjection:e=>this.host.applyConnectionTrustProjection(e),schedulePeerReconciliation:e=>this.host.schedulePeerReconciliation(e),usesTicketOnlySignalingMode:()=>this.host.usesTicketOnlySignalingMode()})),this._channelPolicy}};var wn=class{constructor(e){this.host=e;this.kernelHandles=new Tt;this.lifecycleScope=new At;}get wasmClient(){return this.kernelHandles.wasmClient}set wasmClient(e){this.kernelHandles.wasmClient=e;}get node(){return this.kernelHandles.node}set node(e){this.kernelHandles.node=e;}get localNodeId(){return this.kernelHandles.localNodeId}set localNodeId(e){this.kernelHandles.localNodeId=e;}get deviceId(){return this.kernelHandles.deviceId}set deviceId(e){this.kernelHandles.deviceId=e;}get runtimeServices(){return this._runtimeServices??(this._runtimeServices=Er(this))}get runtimeBootstrap(){return this.runtimeServices.bootstrap}get runtimeConnections(){return this.runtimeServices.connections}get managedTransportDialer(){return this.runtimeServices.managedDialer}get runtimeIdentity(){return this.runtimeServices.identity}get runtimeReadiness(){return this.runtimeServices.readiness}get runtimeStatus(){return this.runtimeServices.status}get connectionServices(){return this._connectionServices??(this._connectionServices=Yo(this))}get moqServices(){return this._moqServices??(this._moqServices=nr(this))}get transportServices(){return this._transportServices??(this._transportServices=Zr(this))}get trustServices(){return this._trustServices??(this._trustServices=es(this))}get registry(){return this.connectionServices.registry}get connectionDialer(){return this.connectionServices.dialer}get connectionMessageHandler(){return this.connectionServices.messageHandler}get incomingConnectionAcceptor(){return this.connectionServices.incomingAcceptor}get appLifecycle(){return this.runtimeServices.appLifecycle}get roomClientHost(){return this._roomClientHost??(this._roomClientHost=Sr(this))}get accessServices(){return this._accessServices??(this._accessServices=Lo(this))}get auth(){return this.accessServices.auth}get signalingBackendController(){return this.accessServices.backend}get peerServices(){return this._peerServices??(this._peerServices=Cr(this))}get peerProjection(){return this.peerServices.projection}get connectionLifecycle(){return this.connectionServices.lifecycle}get streamServices(){return this._streamServices??(this._streamServices=Kr(this))}get incomingStreamRouter(){return this.streamServices.router}get incomingListen(){return this.streamServices.listen}get incomingDiagnostics(){return this.streamServices.diagnostics}get incomingStreamNormalizer(){return this.streamServices.normalizer}get applicationIncomingStreams(){return this.streamServices.applicationIncoming}get applicationStreams(){return this.streamServices.applicationStreams}get deviceDirectory(){return this.accessServices.devices}get connectionTrust(){return this.trustServices.trust}get connectionDeviceBinder(){return this.trustServices.deviceBinder}get connectionChannelPolicy(){return this.trustServices.channelPolicy}get nativeMainServices(){return this._nativeMainServices??(this._nativeMainServices=or(this))}get nativeMain(){return this.nativeMainServices.controller}get presence(){return this.accessServices.presence}retirePendingReciprocalAdmissionsIfExists(e){this._nativeMainServices?.controller.retirePendingReciprocalAdmissions(e);}get securityServices(){return this._securityServices??(this._securityServices=Lr(this))}get sessionTokens(){return this.securityServices.sessionTokens}get applicationCrypto(){return this.securityServices.applicationCrypto}get transportUpgrade(){return this.transportServices.upgrade}get transportHandshake(){return this.transportServices.handshake}get transportHealth(){return this.transportServices.health}get transportContexts(){return this.transportServices.contexts}get peerIdentity(){return this.transportServices.peerIdentity}get options(){return this.host.getOptions()}get runtimeSafetyProfile(){return this.host.getRuntimeSafetyProfile()}get discoveryMode(){return this.options.discoveryMode??"space"}get signaling(){return this.host.getSignaling()}get rooms(){return this.host.getRooms()}getRoomCreationMode(){return this.host.getRoomCreationMode()}getAppLimits(){return this.host.getAppLimits()}setSignaling(e){this.host.setSignaling(e);}setRooms(e){this.host.setRooms(e);}setAppLimits(e){this.host.setAppLimits(e);}setRoomCreationMode(e){this.host.setRoomCreationMode(e);}prepareStreamListenForSignOutIfExists(){this._streamServices?.prepareListenForSignOut();}getEffectiveRoomBackendTag(){return this.host.getEffectiveRoomBackendTag()}setEffectiveRoomBackendTag(e){this.host.setEffectiveRoomBackendTag(e);}getExistingPeerReconciliationStats(){return this._peerServices?.getProjectionStats()}hasRustPeerLifecycleProjection(){return pi(this.signaling,this.wasmClient)}getClientContext(){return this._clientContext||(this._clientContext=ko({getRegistry:()=>this.registry,getWasmClient:()=>this.wasmClient,getNode:()=>this.node,getDiscoveryMode:()=>this.discoveryMode,getLocalNodeId:()=>this.localNodeId,getDeviceId:()=>this.deviceId,registerDisposer:e=>this.lifecycleScope.register(e)})),this._clientContext}getApplicationCrypto(e){return this.securityServices.getApplicationCrypto(e)}resolveApplicationCryptoForPeer(e,t){return this.securityServices.resolveApplicationCryptoForPeer(e,t)}clearApplicationCryptoForConnection(e){this._securityServices?.clearApplicationCryptoForConnection(e);}releaseApplicationKeyAgreementReply(e,t,n){this._securityServices?.releaseApplicationKeyAgreementReply(e,t,n);}waitForApplicationCryptoForPeer(e,t=0){return this.securityServices.waitForApplicationCryptoForPeer(e,t)}stopListenIfExists(){this._streamServices?.stopListenIfExists();}hasApplicationRouteForPeer(e,t){return this.transportServices.hasApplicationRouteForPeer(e,t)}ensureManagedApplicationRoute(e){return this.connectionServices.ensureManagedApplicationRoute(e)}};function bi(){return new Proxy({},{get(){}})}function va(){let r=globalThis,e=r.process?.env;return e?.NODE_ENV==="test"||e?.VITEST==="true"||typeof e?.VITEST_WORKER_ID=="string"||typeof r.__vitest_worker__<"u"||typeof r.__vitest_index__<"u"}function A(r){return r.services}var ts={localNodeId:{get(){return A(this).localNodeId},set(r){A(this).localNodeId=r;}},deviceId:{get(){return A(this).deviceId},set(r){A(this).deviceId=r;}},registry:{get(){return A(this).registry}},__registry:{get(){return A(this).registry}},runtimeBootstrap:{get(){return A(this).runtimeBootstrap}},runtimeConnections:{get(){return A(this).runtimeConnections}},runtimeIdentity:{get(){return A(this).runtimeIdentity}},runtimeReadiness:{get(){return A(this).runtimeReadiness}},runtimeStatus:{get(){return A(this).runtimeStatus}},connectionDialer:{get(){return A(this).connectionDialer}},connectionMessageHandler:{get(){return A(this).connectionMessageHandler},set(r){A(this).connectionServices._messageHandler=r;}},connectionLifecycle:{get(){return A(this).connectionLifecycle}},transportUpgrade:{get(){return A(this).transportUpgrade}},transportHandshake:{get(){return A(this).transportHandshake}},transportHealth:{get(){return A(this).transportHealth}},transportContexts:{get(){return A(this).transportContexts}},peerIdentity:{get(){return A(this).peerIdentity}},peerProjection:{get(){return A(this).peerProjection}},peerLifecycle:{get(){return A(this).peerServices.store},set(r){A(this).peerServices.store=r;}},peerLifecycleClient:{get(){return A(this).peerServices.client}},connectionTrust:{get(){return A(this).connectionTrust}},connectionDeviceBinder:{get(){return A(this).connectionDeviceBinder}},connectionChannelPolicy:{get(){return A(this).connectionChannelPolicy}},incomingListen:{get(){return A(this).incomingListen}},incomingStreamRouter:{get(){return A(this).incomingStreamRouter}},incomingDiagnostics:{get(){return A(this).incomingDiagnostics}},incomingStreamNormalizer:{get(){return A(this).incomingStreamNormalizer}},applicationIncomingStreams:{get(){return A(this).applicationIncomingStreams}},applicationCrypto:{get(){return A(this).applicationCrypto}},sessionTokens:{get(){return A(this).sessionTokens}},nativeMain:{get(){return A(this).nativeMain}},auth:{get(){return A(this).auth}},deviceDirectory:{get(){return A(this).deviceDirectory}},presence:{get(){return A(this).presence}},appLifecycle:{get(){return A(this).appLifecycle}},moqController:{get(){return A(this).moqServices.controller}},_runtimeBootstrap:{get(){return A(this)._runtimeServices?._bootstrap}},_auth:{get(){return A(this)._accessServices?._auth}},_presence:{get(){return A(this)._accessServices?._presence}},_peerProjection:{get(){return A(this)._peerServices?._projection},set(r){A(this).peerServices._projection=r;}},_peerLifecycleClient:{get(){return A(this)._peerServices?._client}},_incomingListen:{get(){return A(this)._streamServices?._listen}},_connectionDialer:{get(){return A(this)._connectionServices?._dialer}},_connectionMessageHandler:{get(){return A(this)._connectionServices?._messageHandler},set(r){A(this).connectionServices._messageHandler=r;}},_transportUpgrade:{get(){return A(this)._transportServices?._upgrade}},_applicationCrypto:{get(){return A(this)._securityServices?._applicationCrypto},set(r){A(this).securityServices._applicationCrypto=r;}},_transportContexts:{set(r){A(this).transportServices._contexts=r;}}};function ns(r){if(va()){for(let e of Object.values(ts))e.configurable=true;Object.defineProperties(r.prototype,ts);}}var ze=class{constructor(e){this.appLimits={...f};this.roomCreationMode="client-open";let t=p(e);this.options=t.options,this.runtimeSafetyProfile=He(this.options),this.effectiveRoomBackendTag=t.appTag,this.roomCreationMode=t.roomCreationMode,this.signaling=new me(q(t),bi()),this._services=this.createServiceGraph(),this.rooms=new Ie(this.services.roomClientHost,this.signaling),this.services.signalingBackendController;}get services(){return this._services??(this._services=this.createServiceGraph())}createServiceGraph(){let e=()=>({...this.options??{},apiKey:this.options?.apiKey??"test"});return new wn({getOptions:()=>this.options??e(),getRuntimeSafetyProfile:()=>this.runtimeSafetyProfile??He(e()),getSignaling:()=>this.signaling??(this.signaling=new me(q(e()),bi())),setSignaling:t=>{this.signaling=t;},getRooms:()=>this.rooms,setRooms:t=>{this.rooms=t;},getAppLimits:()=>this.appLimits??(this.appLimits={...f}),setAppLimits:t=>{this.appLimits=t;},getRoomCreationMode:()=>this.roomCreationMode??"client-open",setRoomCreationMode:t=>{this.roomCreationMode=t;},getEffectiveRoomBackendTag:()=>this.effectiveRoomBackendTag??"openrtc",setEffectiveRoomBackendTag:t=>{this.effectiveRoomBackendTag=t;}})}get wasmClient(){return this.services.wasmClient}set wasmClient(e){this.services.wasmClient=e;}get node(){return this.services.node}set node(e){this.services.node=e;}attachIncomingStreamSource(e,t){this.services.wasmClient=e,this.services.localNodeId=t;}getApplicationCrypto(e){return this.services.getApplicationCrypto(e)}resolveApplicationCryptoForPeer(e,t){return this.services.resolveApplicationCryptoForPeer(e,t)}releaseApplicationKeyAgreementReply(e,t,n){this.services.releaseApplicationKeyAgreementReply(e,t,n);}waitForApplicationCryptoForPeer(e,t=1500){return this.services.waitForApplicationCryptoForPeer(e,t)}destroy(){this.services.lifecycleScope.destroy();}dispose(){this.destroy();}get apiKey(){return this.options.apiKey}get discoveryMode(){return this.options.discoveryMode??"space"}usesDirectRoomBackend(){return this.services.runtimeStatus.usesDirectRoomBackend()}getRoomBackendTag(){return this.services.runtimeStatus.getRoomBackendTag()}async refreshHostedAppSettings(e=false){return this.services.signalingBackendController.refreshHostedAppSettings(e)}setSignalingBackend(e){this.services.signalingBackendController.setSignalingBackend(e);}get currentUser(){return this.services.signalingBackendController.getCurrentUser()??null}onAuthChange(e){return this.services.auth.onAuthChange(e)}async signInAnonymously(){return this.services.auth.signInAnonymously()}async signInWithPluto(){return this.services.auth.signInWithPluto()}async signOut(){return this.services.auth.signOut()}getSignalingTelemetry(){return this.services.runtimeStatus.getSignalingTelemetry()}getPeerReconciliationStats(){return this.services.runtimeStatus.getPeerReconciliationStats()}getProtocolCapabilities(){return this.services.runtimeStatus.getProtocolCapabilities()}async getRuntimeStatus(){return this.services.runtimeStatus.getRuntimeStatus()}async searchDevices(){return this.services.deviceDirectory.searchDevices()}async updateDevice(e,t){return this.services.deviceDirectory.updateDevice(e,t)}async deleteDevice(e){return this.services.deviceDirectory.deleteDevice(e)}async cleanupStaleDevices(){return this.services.deviceDirectory.cleanupStaleDevices()}onDevicesChange(e){return this.services.deviceDirectory.onDevicesChange(e)}async subscribeSessions(e,t){return this.services.deviceDirectory.subscribeSessions(e,t)}async startScanningLoop(e){return this.services.deviceDirectory.startScanningLoop(e)}async bootstrapRuntime(e){return this.services.runtimeBootstrap.bootstrapRuntime(e)}updateTransportConfig(e){r(this.options,e);}async init(){return this.services.runtimeBootstrap.init()}async ensureAuthenticated(e){return this.services.auth.ensureAuthenticated(e)}async refreshRuntimeAuthToken(e="runtime-start"){return this.services.auth.refreshRuntimeAuthToken(e)}get moqState(){return this.services.moqServices.state}get moq(){return this.services.moqServices.bundle}onMoQReady(e){return this.services.moqServices.onReady(e)}onMoQFailed(e){return this.services.moqServices.onFailed(e)}refreshTransportCapabilities(e="client-request"){return this.services.transportHandshake.broadcastTransportCapabilityUpdate(e)}onMoQObject(e){return this.services.moqServices.onObject(e)}subscribeMoQPeer(e){this.services.moqServices.enableForConnection(e);}subscribeMoQPeerNode(e,t){this.services.moqServices.subscribePeerNode(e,t);}async connect(e,t=2e4,n,i,o){return this.services.connectionDialer.connect(e,t,n,i,o)}async connectRaw(e,t=2e4){return this.services.runtimeConnections.connectRaw(e,t)}async startAutoConnect(e){return this.services.runtimeConnections.startAutoConnect(e)}async openBi(e){return this.services.applicationStreams.openBi(e)}async openUni(e){return this.services.applicationStreams.openUni(e)}getConnections(){return this.services.registry.all()}getApplicationReadyConnections(e={}){return this.services.registry.applicationReady(e)}getConnectionForPeer(e,t){return this.services.registry.getForPeer(e,t)}hasApplicationRouteForPeer(e,t){return this.services.hasApplicationRouteForPeer(e,t)}ensureManagedApplicationRoute(e){return this.services.ensureManagedApplicationRoute(e)}watchPeerStates(e){return this.services.peerServices.watchPeerStates(e)}getPeerState(e){return this.services.peerServices.getPeerState(e)}listConnectedPeers(){return this.services.peerServices.listConnectedPeers()}isPeerPromotionEligible(e){return this.services.peerServices.isPeerPromotionEligible(e)}addPeerScope(e,t="persistent"){return this.services.peerServices.addPeerScope(e,t)}releasePeerScope(e,t){return this.services.peerServices.releasePeerScope(e,t)}getPeerScopes(e){return this.services.peerServices.getPeerScopes(e)}isSamePeer(e,t){return this.services.peerServices.isSamePeer(e,t)}async refreshPeerSnapshot(){return this.services.peerProjection.schedule("refresh")}async connectPeer(e){return this.services.connectionDialer.connectPeer(e)}clearManualDisconnectProjection(e){this.services.peerServices.clearManualDisconnectProjection(e);}async disconnectPeer(e,t="persistent"){await this.services.peerServices.disconnectPeer(e,t);}async forceDisconnectPeer(e){await this.services.peerServices.forceDisconnectPeer(e);}async getPeerHealth(e){return this.services.peerServices.getPeerHealth(e)}async getTicket(){return this.services.runtimeIdentity.getTicket()}async getNodeId(){return this.services.runtimeIdentity.getNodeId()}async getNodeIdFromTicket(e){return this.services.runtimeIdentity.getNodeIdFromTicket(e)}async getEndpointTicketWithToken(e,t=0){return this.services.sessionTokens.getEndpointTicketWithToken(e,t)}buildCompoundTicketWithToken(e,t,n=0){return this.services.sessionTokens.buildCompoundTicketWithToken(e,t,n)}setManagedPresenceTicket(e){this.services.presence.setManagedPresenceTicket(e);}clearManagedPresenceTicket(){this.services.presence.clearManagedPresenceTicket();}registerSessionToken(e,t,n){this.services.sessionTokens.registerSessionToken(e,t,n);}revokeSessionToken(e){this.services.sessionTokens.revokeSessionToken(e);}async revokeTokensByScope(e){return this.services.sessionTokens.revokeTokensByScope(e)}async clearSessionTokens(){return this.services.sessionTokens.clearSessionTokens()}async startPresenceLoop(e){return this.services.presence.startPresenceLoop(e)}async setOffline(){return this.services.presence.setOffline()}async isConnected(e){return this.services.runtimeConnections.isConnected(e)}async disconnectNode(e){return this.services.runtimeConnections.disconnectNode(e)}async getLocalDeviceId(){return this.services.signalingBackendController.getLocalDeviceId()}async acceptNativeMessage(e,t,n){return this.services.nativeMain.acceptNativeMessage(e,t,n)}async startListening(e){return this.services.incomingListen.start(e)}stopListening(){this.services.stopListenIfExists();}forceReconnectSnapshot(){this.services.signalingBackendController.forceReconnectSnapshot();}wrapChannelWritable(e,t,n){return po(e,t,n)}async updatePresence(e=true,t=3e5,n,i){return this.services.presence.updatePresence(e,t,n,i)}onConnection(e){return this.services.connectionLifecycle.onConnection(e)}onDisconnection(e){return this.services.connectionLifecycle.onDisconnection(e)}onMessage(e){return this.services.incomingStreamRouter.onMessage(e)}onIncomingStream(e){return this.services.incomingStreamRouter.onIncomingStream(e)}registerChannel(e){this.services.incomingStreamRouter.registerChannel(e);}unregisterChannel(e){this.services.incomingStreamRouter.unregisterChannel(e);}listChannels(){return this.services.incomingStreamRouter.listChannels()}onIncomingChannelStream(e,t){return this.services.incomingStreamRouter.onIncomingChannelStream(e,t)}onRoomJoinRequest(e){return this.services.incomingStreamRouter.onRoomJoinRequest(e)}isMoQDataReady(e){return this.services.moqServices.isDataReady(e)}async sendMoQData(e,t,n={}){return this.services.moqServices.sendData(e,t,n)}};ns(ze);var Qe=class Qe{constructor(e){this.locallyDeletedDeviceIds=new Set;this.deviceStatusRefreshWakeups=new Set;this.client=e.client,this.backend=e.backend,this.peerApi=e.peerApi,this.connectToDevice=e.connectToDevice,this.startManagedReconciliation=e.startManagedReconciliation,this.deviceStatusRefreshDebounceMs=e.deviceStatusRefreshDebounceMs;}deviceStatusSnapshotKey(e){return JSON.stringify([...e].map(t=>({deviceId:t.deviceId,deviceName:t.deviceName??null,platformType:t.platformType??null,online:!!t.online,presenceStatus:t.presenceStatus??null,presenceUpdatedAt:t.presenceUpdatedAt??null,presenceExpiresAt:t.presenceExpiresAt??null,connectable:t.connectable??null,connectionStatus:t.connectionStatus??null,settledReady:!!t.settledReady,readinessState:t.readinessState??null,readinessReason:t.readinessReason??null,peerHealth:t.peerHealth??null,peerId:t.peerId??null,promotionEligible:t.promotionEligible??true,connectionId:t.connectionId??null,deviceIdHint:t.deviceIdHint??null,nodeId:t.nodeId??null,ticket:t.ticket??null,activeTransportStableId:t.activeTransportStableId??null,transportGeneration:t.transportGeneration??null,routeGeneration:t.routeGeneration??null,activeTransport:t.activeTransport??null,parallelTransport:t.parallelTransport??null,latencyMs:t.latencyMs??null,latencyByTransport:t.latencyByTransport??null,scopes:[...t.scopes??[]].sort()})).sort((t,n)=>t.deviceId.localeCompare(n.deviceId)))}normalizeLookupKey(e){return typeof e=="string"?e.trim().toLowerCase():""}isLocallyDeletedDevice(e){let t=this.normalizeLookupKey(e);return !!t&&this.locallyDeletedDeviceIds.has(t)}filterLocallyDeletedDevices(e){return (e??[]).filter(t=>!this.isLocallyDeletedDevice(t.deviceId))}isDurableUserDevicePeer(e){return (e.scopes??[]).some(t=>t==="user-device")}matchItem(e,t){let n=this.normalizeLookupKey(t.deviceId),i=this.normalizeLookupKey(t.nodeId),o=this.normalizeLookupKey(t.connectionId),s=new Set([n,this.normalizeLookupKey(t.deviceIdHint),i,o,this.normalizeLookupKey(t.peerId)].filter(Boolean)),a=null,c=null;for(let l of e){let d=this.normalizeLookupKey(l.deviceId),p=this.normalizeLookupKey(l.deviceIdHint),u=this.normalizeLookupKey(l.nodeId),f=this.normalizeLookupKey(l.peerId),h=this.normalizeLookupKey(l.activeConnectionId??l.connectionId);if(![d,p,u,f,h].filter(Boolean).some(E=>s.has(E))||i&&u&&u!==i)continue;let y=i&&u===i?5:n&&d===n?4:n&&f===n?3:n&&p===n?2:o&&h===o?1:0,v=String(l.status??"").trim().toLowerCase(),P=v==="closed"||v==="disconnected"||v==="failed",T=(l.settledReady===true||l.routable===true||String(l.readinessState??l.protocolState??"").trim().toLowerCase()==="routable")&&!P?4:v==="connected"&&l.health==="healthy"?3:!P&&v==="connected"?2:P?0:1,C=l.replacementPending===true?0:1,N=l.transportGeneration??l.generation??0,b=l.routeGeneration??0,L=l.lastSeenAtMs??l.lastAuthoritativeEventAt??0,_=[y,T,C,N,b,L],w=c,D=w===null;if(w){for(let E=0;E<_.length;E+=1)if(_[E]!==w[E]){D=_[E]>w[E];break}}D&&(a=l,c=_);}return a}peerIsCompatibleWithSession(e,t){let n=this.normalizeLookupKey(t.nodeId),i=this.normalizeLookupKey(e.nodeId);if(n&&i&&n!==i)return false;let o=this.normalizeLookupKey(t.activeConnectionId),s=[e.connectionId,...e.connectionIds??[]].map(a=>this.normalizeLookupKey(a)).filter(Boolean);return !(o&&s.length>0&&!s.includes(o))}shouldIgnoreTerminalPeerForRoutableSession(e,t){if(!e||!t)return false;let n=String(e.status??"").trim().toLowerCase(),i=n==="closed"||n==="disconnected"||n==="failed",o=t.settledReady===true||String(t.readinessState??"").trim().toLowerCase()==="routable",s=this.isManualDisconnectPeer(e);return i&&!s&&o&&!!t.activeConnectionId}applyCompatibleOptionalTransportFacet(e$1,t,n){if(!t||!this.isRoutableDeviceStatus(e$1)||n&&!this.peerIsCompatibleWithSession(t,n))return e$1;let i=String(t.status??"").trim().toLowerCase();if(!(t.routable===true||t.protocolState==="routable")||i==="closed"||i==="disconnected"||i==="failed"||t.transportGeneration!==void 0&&e$1.transportGeneration!==void 0&&t.transportGeneration!==e$1.transportGeneration||t.routeGeneration!==void 0&&e$1.routeGeneration!==void 0&&t.routeGeneration!==e$1.routeGeneration)return e$1;let s=b(t.activeTransport),a=b(t.parallelTransport),c=[s,a].find(e);if(!c)return e$1;let l=[e$1.activeTransport,e$1.parallelTransport,s,a].map(b).find(c$2),d=s===c;return {...e$1,activeTransport:d?c:l??c,parallelTransport:d?l??null:c}}latencyForTransport(e,t){let n=b(e);return n==="webrtc-lan"?t.webrtcLan??null:n==="webrtc-turn"?t.webrtcTurn??null:n==="webrtc"?t.webrtc??null:n==="iroh-lan"?t.irohLan??null:n==="iroh-relay"?t.irohRelay??null:n==="iroh"||n==="iroh-quic"?t.iroh??null:n==="ble"?t.ble??null:n==="moq"?t.moq??null:null}applyLocalTransportLatency(e){if(!this.isRoutableDeviceStatus(e))return {...e,latencyMs:null,latencyByTransport:void 0};let t=this.client.getConnectionForPeer,i=(typeof t=="function"?t.call(this.client,e.connectionId,e.nodeId??e.peerId):null)?.getTransportLatencySnapshot()??{},o={...e.latencyByTransport??{},...Object.fromEntries(Object.entries(i).filter(([,l])=>l!=null))},s=Object.values(o).some(l=>l!=null)?o:void 0,c=(s?this.latencyForTransport(e.activeTransport,s)??this.latencyForTransport(e.parallelTransport,s):null)??e.latencyMs??null;return {...e,latencyMs:c,latencyByTransport:s}}isManualDisconnectPeer(e){let t=String(e?.error??"").trim().toLowerCase();return t.includes("manual disconnect")||e?.manualDisconnect===true&&t.length>0}buildFinalDeviceStatusSnapshots(e,t,n,i={}){let o=this.filterLocallyDeletedDevices(e).map(c=>{let l=this.matchItem(t,c),d=this.matchItem(n,c),p=(c.connectionStatus==="closed"||c.connectionStatus==="disconnected"||c.connectionStatus==="failed")&&String(c.readinessReason??"").trim().toLowerCase().includes("manual disconnect"),u=q$1({device:c,session:p?null:l,peer:null,isPromotionEligible:f=>this.client.isPeerPromotionEligible(f)});return p?u:this.applyCompatibleOptionalTransportFacet(u,d,l)}),s=new Set(o.map(c=>this.normalizeLookupKey(c.deviceId))),a=new Set(o.flatMap(c=>[c.deviceId,c.deviceIdHint,c.nodeId,c.peerId,c.connectionId].map(l=>this.normalizeLookupKey(l)).filter(Boolean)));for(let c of n){if(!this.isDurableUserDevicePeer(c))continue;let l=this.statusDeviceFromPeer(c),d=this.normalizeLookupKey(l?.deviceId),p=[c.deviceId,c.deviceIdHint,c.nodeId,c.peerId,c.connectionId].map(u=>this.normalizeLookupKey(u)).filter(Boolean);if(!(!l||!d||s.has(d)||p.some(u=>a.has(u))||this.isLocallyDeletedDevice(d))){s.add(d);for(let u of p)a.add(u);o.push(q$1({device:l,session:this.matchItem(t,l),peer:c,isPromotionEligible:u=>this.client.isPeerPromotionEligible(u)}));}}return o.map(c=>this.applyLocalTransportLatency(c))}applyTerminalPeerTransportState(e,t){if(this.isRoutableDeviceStatus(e))return e;let n=String(t?.status??"").trim().toLowerCase();return n!=="closed"&&n!=="disconnected"&&n!=="failed"?e:{...e,activeTransportStableId:null,activeTransport:void 0,parallelTransport:void 0}}statusDeviceFromPeer(e){let t=e.deviceId?.trim()||e.deviceIdHint?.trim(),n=String(e.status??"").trim().toLowerCase();return !t||n==="closed"||n==="disconnected"||n==="failed"?null:{deviceId:t,deviceName:e.deviceName?.trim()||"Unknown Device",online:e.online??true,ticket:e.ticket??"",nodeId:e.nodeId,platformType:e.platformType,presenceStatus:e.online===false?"offline":"online",connectable:!!e.ticket,connectionStatus:e.status,settledReady:e.routable===true||e.protocolState==="routable",readinessState:e.protocolState,peerHealth:e.health,peerId:e.peerId,scopes:[...e.scopes??[]],connectionId:e.connectionId,deviceIdHint:e.deviceIdHint,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}}runtimeDeviceToStatusSnapshot(e){return q$1({device:e})}isRoutableDeviceStatus(e){return e.settledReady===true||String(e.readinessState??"").trim().toLowerCase()==="routable"}mergeWatchedDevicesIntoStatusSnapshots(e,t){if(!e)return t;let n=new Map(t.map(c=>[c.deviceId,c])),i=this.filterLocallyDeletedDevices(e),o=new Set(i.map(c=>this.normalizeLookupKey(c.deviceId))),s=this.filterLocallyDeletedDevices(t.filter(c=>!o.has(this.normalizeLookupKey(c.deviceId))));return [...i.map(c=>{let l=this.runtimeDeviceToStatusSnapshot(c),d=n.get(c.deviceId);if(!d)return l;let{connectionStatus:p,settledReady:u,readinessState:f,readinessReason:h,peerHealth:m,peerId:y,promotionEligible:v,connectionId:P,activeTransportStableId:I,transportGeneration:T,routeGeneration:C,activeTransport:N,parallelTransport:b,presenceStatus:L,presenceUpdatedAt:_,presenceExpiresAt:w,connectable:D,...E}=d,{connectionStatus:O,settledReady:z,readinessState:ve,readinessReason:ke,peerHealth:Mn,peerId:$e,promotionEligible:En,connectionId:Ne,activeTransportStableId:Ln,transportGeneration:De,routeGeneration:xn,activeTransport:_n,parallelTransport:Ti,presenceStatus:R,presenceUpdatedAt:M,presenceExpiresAt:B,connectable:x,latencyMs:V,latencyByTransport:Ai,deviceIdHint:le,scopes:wi,...Fn}=l,ki=d.presenceUpdatedAt,Ni=M,Me=R!==void 0&&Ni!==void 0&&(ki===void 0||Ni>=ki);return q$1({device:{...E,...Fn,connectionStatus:d.connectionStatus,settledReady:d.settledReady,readinessState:d.readinessState,readinessReason:d.readinessReason,peerHealth:d.peerHealth,peerId:d.peerId,promotionEligible:d.promotionEligible,connectionId:d.connectionId,activeTransportStableId:d.activeTransportStableId,transportGeneration:d.transportGeneration,routeGeneration:d.routeGeneration,activeTransport:d.activeTransport,parallelTransport:d.parallelTransport,latencyMs:d.latencyMs,latencyByTransport:d.latencyByTransport,online:Me?l.online:d.online,presenceStatus:Me?R:d.presenceStatus,presenceUpdatedAt:Me?M:d.presenceUpdatedAt,presenceExpiresAt:Me?B:d.presenceExpiresAt,connectable:Me?x:d.connectable,platformType:d.platformType??l.platformType,deviceIdHint:le??d.deviceIdHint,scopes:d.scopes}})}),...s]}async listDevices(){return this.filterLocallyDeletedDevices(await this.client.searchDevices())}async listDevicesWithStatus(){let e=this.backend;if(e&&typeof e.listDevicesWithStatus=="function"){let t=await e.listDevicesWithStatus(),[n,i]=await Promise.allSettled([typeof e.listPeerSessions=="function"?e.listPeerSessions():Promise.resolve([]),this.peerApi.refreshPeerSnapshot().catch(l=>{let d=this.peerApi.listConnectedPeers();return console.warn(`[RuntimeClient] refreshPeerSnapshot failed during listDevicesWithStatus(); using ${d.length} cached connected peers`,l),d})]),o=n.status==="fulfilled"?n.value:[],s=i.status==="fulfilled"?i.value:[],a=this.filterLocallyDeletedDevices(this.buildFinalDeviceStatusSnapshots(t,o,s,{preserveRoutableInputLifecycle:true}));return (a.some(l=>f$1(l.activeTransport))||o.some(l=>f$1(l.activeTransport))||s.some(l=>f$1(l.activeTransport)))&&b$1("[RuntimeClient] device status snapshot with transport labels",{devices:a.map(l=>({deviceId:l.deviceId,connectionStatus:l.connectionStatus,settledReady:!!l.settledReady,activeTransport:l.activeTransport??null,parallelTransport:l.parallelTransport??null,connectionId:l.connectionId??null})),peerSessions:o.map(l=>({peerId:l.peerId,deviceId:l.deviceId??null,activeConnectionId:l.activeConnectionId??null,status:l.status,activeTransport:l.activeTransport??null,parallelTransport:l.parallelTransport??null})),peers:s.map(l=>({peerId:l.peerId,deviceId:l.deviceId??null,connectionId:l.connectionId??null,status:l.status,activeTransport:l.activeTransport??null,parallelTransport:l.parallelTransport??null}))}),a}throw new Error("[pluto-rtc] listDevicesWithStatus() requires a Rust-backed runtime adapter that implements listDevicesWithStatus().")}async updateDevice(e,t){await this.client.updateDevice(e,t);}async deleteDevice(e){let t=this.normalizeLookupKey(e);await this.client.deleteDevice(e),t&&this.locallyDeletedDeviceIds.add(t);}watchDevices(e){return this.client.onDevicesChange(t=>e(this.filterLocallyDeletedDevices(t)))}watchDevicesWithStatus(e){let t=this.backend;if(!t||typeof t.listDevicesWithStatus!="function")throw new Error("[pluto-rtc] watchDevicesWithStatus() requires a Rust-backed runtime adapter that implements listDevicesWithStatus().");let n=true,i=null,o=null,s=null,a=null,c=false,l=false,d=I=>{let T=this.filterLocallyDeletedDevices(I);u(T);let C=this.deviceStatusSnapshotKey(T);C!==i&&(i=C,e(T));},p=()=>{a&&(clearTimeout(a),a=null);},u=I=>{if(p(),!n)return;let T=Date.now(),C=I.filter(b=>b.presenceStatus==="online").map(b=>typeof b.presenceUpdatedAt=="number"?b.presenceUpdatedAt+3e5:null).filter(b=>typeof b=="number"&&Number.isFinite(b)).sort((b,L)=>b-L)[0];if(C===void 0)return;let N=Math.max(25,C-T+5);a=setTimeout(()=>{a=null,m();},N);},f=()=>{c=false,!(!n||!l)&&(l=false,m());},h=()=>{if(n){if(c){l=true;return}c=true,this.listDevicesWithStatus().then(I=>{n&&d(this.mergeWatchedDevicesIntoStatusSnapshots(o,I));}).catch(I=>{console.warn("[RuntimeDeviceManager] device-status refresh failed",I);}).finally(()=>f());}},m=()=>{!n||s||(s=setTimeout(()=>{s=null,h();},this.deviceStatusRefreshDebounceMs));};this.deviceStatusRefreshWakeups.add(m);let y=this.client.onDevicesChange(I=>{Array.isArray(I)&&(o=this.filterLocallyDeletedDevices(I)),m();}),v=this.peerApi.watchPeerStates(()=>{m();}),P=this.startManagedReconciliation(()=>m());return h(),()=>{n=false,s&&clearTimeout(s),p(),this.deviceStatusRefreshWakeups.delete(m),P(),y(),v();}}notifyLifecycleMutation(){for(let e of this.deviceStatusRefreshWakeups)e();}async connectDeviceWithRetry(e,t,n){return this.connectDevice(e,{localDeviceId:n.localDeviceId,targetUserId:n.targetUserId,onConnected:t.onConnected})}async connectDevice(e,t){let n=e,i=typeof e.ticket=="string"?e.ticket.trim():"";if(!i){let p=(await this.listDevicesWithStatus().catch(()=>this.listDevices().catch(()=>[]))).find(u=>u.deviceId===e.deviceId);p&&(n={...e,...p},i=typeof p.ticket=="string"?p.ticket.trim():"");}if(!i)return {success:false,error:`Cannot connect to ${e.deviceId}: missing endpoint ticket`,attempts:1};let o=this.peerApi.getPeerState(e.deviceId),s=o?.status,a=this.client.hasApplicationRouteForPeer?.(o?.connectionId??void 0)??false;if(s==="connected"&&a)return {success:true,skipped:"already-connecting",attempts:0};this.client.clearManualDisconnectProjection?.(n.deviceId);let c=Date.now(),l=()=>Math.max(1,Qe.EXPLICIT_CONNECT_SETTLE_TIMEOUT_MS-(Date.now()-c));try{let d=await this.connectToDevice({deviceId:n.deviceId,endpointTicket:i,timeoutMs:Qe.EXPLICIT_CONNECT_SETTLE_TIMEOUT_MS}),p=this.backend;if(p&&typeof p.waitForSettledPeer=="function"){let u=l();if(!(await p.waitForSettledPeer(d.deviceId??n.deviceId??d.remoteNodeId??d.connectionId,u))?.settledReady)throw new Error(`Connection to ${n.deviceId} did not become application-routable`)}return await this.peerApi.refreshPeerSnapshot().catch(()=>{}),this.notifyLifecycleMutation(),await t.onConnected?.(n),{success:!0,attempts:1}}catch(d){return {success:false,error:d instanceof Error?d.message:`Cannot connect to ${e.deviceId}`,attempts:1}}}};Qe.EXPLICIT_CONNECT_SETTLE_TIMEOUT_MS=3e4;var kn=Qe;var Nn=class{constructor(e,t){this.client=e;this.backend=t;}normalizeUiConnectionStatus(e){switch((e||"disconnected").trim().toLowerCase()){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "disconnected"}}buildLookup(e,t){let n=new Map,i=(o,s)=>{let a=typeof o=="string"?o.trim():"";!a||n.has(a)||n.set(a,s);};for(let o of e)for(let s of t(o))i(s,o);return n}uniqueLookupIds(...e){let t=new Set,n=[];for(let i of e){let o=typeof i=="string"?i.trim():"";!o||t.has(o)||(t.add(o),n.push(o));}return n}matchSessionByLookupId(e,t){if(!e.length||!t.length)return null;let n=this.buildLookup(e,i=>[i.peerId,i.deviceId,i.deviceIdHint,i.nodeId,i.activeConnectionId]);for(let i of t){let o=n.get(i);if(o)return o}return null}matchLocalPeerState(e,t){let n=this.uniqueLookupIds(...e,t.peerId,t.deviceId,t.deviceIdHint,t.nodeId,t.activeConnectionId);for(let o of n){let s=this.client.getPeerState(o);if(s)return s}let i=this.buildLookup(this.client.listConnectedPeers(),o=>[o.peerId,o.deviceId,o.deviceIdHint,o.nodeId,o.connectionId,...o.connectionIds??[]]);for(let o of n){let s=i.get(o);if(s)return s}return null}async resolvePeerLookupIds(e,t){let n=typeof t.resolvePeerIdentity=="function"?await t.resolvePeerIdentity(e).catch(()=>null):null,i=this.uniqueLookupIds(e,n?.peerId,n?.deviceId,n?.deviceIdHint,n?.nodeId);if(typeof t.listPeerSessions!="function")return i;let o=this.matchSessionByLookupId(await t.listPeerSessions().catch(()=>[]),i);return this.uniqueLookupIds(...i,o?.peerId,o?.deviceId,o?.deviceIdHint,o?.nodeId,o?.activeConnectionId)}async resolvePeerConnectionRecords(e){let t=this.backend;if(!t||typeof t.resolvePeerConnectionRecords!="function")throw new Error("[pluto-rtc] resolvePeerConnectionRecords() requires a Rust-backed runtime adapter that implements resolvePeerConnectionRecords().");return t.resolvePeerConnectionRecords(e)}async getPeerSession(e){let t=this.backend;if(!t||typeof t.getPeerSession!="function")throw new Error("[pluto-rtc] getPeerSession() requires a Rust-backed runtime adapter that implements getPeerSession().");let n=await this.resolvePeerLookupIds(e,t);for(let i of n){let o=await t.getPeerSession(i);if(o)return o}return typeof t.listPeerSessions=="function"?this.matchSessionByLookupId(await t.listPeerSessions(),n):null}async listPeerSessions(){let e=this.backend;if(!e||typeof e.listPeerSessions!="function")throw new Error("[pluto-rtc] listPeerSessions() requires a Rust-backed runtime adapter that implements listPeerSessions().");return e.listPeerSessions()}async waitForConnectedPeer(e,t){let n=this.backend;if(!n||typeof n.waitForSettledPeer!="function")throw new Error("[pluto-rtc] waitForConnectedPeer() requires a Rust-backed runtime adapter that implements waitForSettledPeer().");let i=typeof n.resolvePeerIdentity=="function"?await n.resolvePeerIdentity(e).catch(()=>null):null,o=this.uniqueLookupIds(i?.peerId,i?.deviceId,i?.deviceIdHint,i?.nodeId,e),s=o[0]??e,a=Date.now(),c=await n.waitForSettledPeer(s,t);if(!c?.settledReady)return c;let l=typeof t=="number"?Math.max(0,t):5e3;for(;;){let d=this.matchLocalPeerState(o,c);if(!d||d.routable===true||d.protocolState==="routable")return c;if(Date.now()-a>=l)return {...c,settledReady:false,readinessState:d.protocolState??"transport-only",readinessReason:d.error??"application-route-not-ready"};await new Promise(p=>setTimeout(p,50));}}async getPeerReadiness(e,t){let n=this.client.getPeerState(e)??null,i=typeof t=="number"?await this.waitForConnectedPeer(e,t).catch(()=>null):await this.getPeerSession(e).catch(()=>null),o=this.normalizeUiConnectionStatus(i?.status??n?.status??"disconnected"),s=n?.routable===false&&n?.protocolState==="unverified";return {requestedId:e,connected:o==="connected",settledReady:s?false:!!i?.settledReady,status:o,health:i?.health??n?.health??"unknown",deviceId:i?.deviceId??n?.deviceId??null,deviceIdHint:i?.deviceIdHint??n?.deviceIdHint??null,activeConnectionId:i?.activeConnectionId??n?.connectionId??null,readinessState:s?n?.protocolState:i?.readinessState??n?.protocolState,readinessReason:s?n?.error:i?.readinessReason??n?.error,scopes:[...i?.scopes??n?.scopes??[]]}}async resolvePeerIdentity(e){let t=this.backend;if(!t||typeof t.resolvePeerIdentity!="function")throw new Error("[pluto-rtc] resolvePeerIdentity() requires a Rust-backed runtime adapter that implements resolvePeerIdentity().");return t.resolvePeerIdentity(e)}async resolveIncomingStreamPeer(e){return this.resolvePeerIdentity(e)}addPeerScope(e,t){return this.client.addPeerScope(e,t)}releasePeerScope(e,t){return this.client.releasePeerScope(e,t)}getPeerScopes(e){return this.client.getPeerScopes(e)}isSamePeer(e,t){return this.client.isSamePeer(e,t)}};var rs="drive-view.",Ri=[68,86,67,72],Ca=new TextDecoder;function Pi(r){if(r.byteLength>=Ri.length){let e=true;for(let t=0;t<Ri.length;t+=1)if(r[t]!==Ri[t]){e=false;break}if(e)return true}try{let e=JSON.parse(Ca.decode(r));return typeof e.t=="string"&&e.t.startsWith(rs)}catch{return false}}function is(r){return !!r&&!r.isClosed&&typeof r.send=="function"&&(typeof r.isReadyForApplicationPayload!="function"||r.isReadyForApplicationPayload())}var os=new WeakMap;function Sa(r){if(r instanceof Uint8Array)return Pi(r)?r:null;if(r instanceof ArrayBuffer){let e=new Uint8Array(r);return Pi(e)?e:null}return r&&typeof r=="object"&&typeof r.t=="string"&&r.t.startsWith(rs)?new TextEncoder().encode(JSON.stringify(r)):null}function Ia(r,e){let t=os.get(r);if(!t){t={receivers:new Set([e])},os.set(r,t);let n=i=>{let o=false;for(let s of [...t.receivers])try{o=s(i)||o;}catch(a){c$1("[RuntimeClient][connectScopedChannel] route-scoped receiver failed",{connectionId:r.id,error:String(a)});}return o};return typeof r.onWebRTCBinaryMessage=="function"&&r.onWebRTCBinaryMessage(i=>n(i)),typeof r.onMessage=="function"&&r.onMessage(i=>{let o=Sa(i);o&&n(o);}),()=>t?.receivers.delete(e)}return t.receivers.add(e),()=>t?.receivers.delete(e)}var W=class W{constructor(e,t){this.managedSessionKey=null;this.managedSessionUserId=null;this.managedSessionOptions=null;this.managedSessionTransition=Promise.resolve();this.managedSessionStartInFlight=new Map;this.managedReconciliationTasks=new Set;this.managedReconciliationTimer=null;this.managedReconciliationFollowupTimers=new Set;this.scopedConnectionActorRegistry=null;this.client=new ze(e),this.backend=t??null,t&&this.client.setSignalingBackend(t),this.peerManager=new Nn(this.client,this.backend),this.connectionController=new rt(this.client,this.backend,()=>this.deviceManager.notifyLifecycleMutation()),this.deviceManager=new kn({client:this.client,backend:this.backend,peerApi:{watchPeerStates:n=>this.client.watchPeerStates(n),refreshPeerSnapshot:()=>this.client.refreshPeerSnapshot(),listConnectedPeers:()=>this.client.listConnectedPeers(),getPeerState:n=>this.client.getPeerState(n)},connectToDevice:n=>this.connectionController.connectToDevice(n),startManagedReconciliation:n=>this.startManagedReconciliation(n),deviceStatusRefreshDebounceMs:W.DEVICE_STATUS_REFRESH_DEBOUNCE_MS});}static describeTicketForLogs(e){let t=typeof e=="string"?e.trim():"";if(!t)return {hasTicket:false,isCompound:false,scope:null};let n=t.indexOf(".");if(n<0)return {hasTicket:true,isCompound:false,scope:null};try{let i=t.slice(n+1).replace(/-/g,"+").replace(/_/g,"/"),o=(4-i.length%4)%4,s=JSON.parse(atob(i+"=".repeat(o)));return {hasTicket:!0,isCompound:!0,scope:typeof s?.s=="string"?s.s:null}}catch{return {hasTicket:true,isCompound:true,scope:null}}}async serializeManagedSessionOperation(e,t){let n=Date.now(),i=this.managedSessionTransition,o,s=new Promise(c=>{o=c;});this.managedSessionTransition=s,console.info("[RuntimeClient][managed-session][operation-queued]",{label:e,managedSessionUserId:this.managedSessionUserId,hasManagedSession:this.managedSessionKey!==null}),await i.catch(()=>{});let a=Date.now();console.info("[RuntimeClient][managed-session][operation-started]",{label:e,queueWaitMs:a-n,managedSessionUserId:this.managedSessionUserId,hasManagedSession:this.managedSessionKey!==null});try{return await t()}finally{console.info("[RuntimeClient][managed-session][operation-finished]",{label:e,queueWaitMs:a-n,operationMs:Date.now()-a,managedSessionUserId:this.managedSessionUserId,hasManagedSession:this.managedSessionKey!==null}),o(),this.managedSessionTransition===s&&(this.managedSessionTransition=Promise.resolve());}}get identity(){return this.client.currentUser}resolveManagedSessionUserId(e,t){let n=this.identity?.id??null;return n?(t&&t!==n&&console.warn("[RuntimeClient][managed-session][user-id-override]",{requestedUserId:t,runtimeIdentityUserId:n}),n):t??null}resolveManagedAutoConnectEnabled(e){return e.autoConnectPolicy==="disabled"?false:e.autoConnectPolicy==="enabled"?true:e.autoConnectPolicy==="scoped-only"?false:e.autoConnect!==false}resolveManagedPresenceEnabled(e){return e.presencePolicy==="disabled"?false:e.presencePolicy==="online"?true:e.presence!==false}getEffectiveRuntimeUserId(){return this.identity?.id??this.managedSessionUserId??this.managedSessionOptions?.userId??null}async fetchAndApplyAppLimits(){try{await this.client.refreshHostedAppSettings();}catch(e){console.warn("[pluto-rtc] Could not fetch app limits, using free-tier defaults.",e);}}async resolvePeerStreamTarget(e){let t=this.client.getPeerState(e)??null,n=await this.getPeerSession(e).catch(()=>null),i=n?.activeConnectionId?.trim()||null,o=(i?this.client.getConnections().find(a=>!a.isClosed&&a.id===i):void 0)??null,s=n?.nodeId?.trim()||o?.remoteNodeId?.trim()||t?.nodeId?.trim()||null;return {peer:t,session:n,connection:o,remoteNodeId:s}}compatPeerConnectionFromTarget(e,t){let n=e.session?.activeConnectionId?.trim()||`peer-stream:${t}`,i=e.remoteNodeId||t;return {id:n,deviceId:i,remoteNodeId:i,isClosed:false}}isTransportOnlyStreamChannel(e){let t=typeof e=="string"?e.trim():"";if(!t)return false;let n=this.client.listChannels().find(i=>i.id.trim()===t);return xt(n??null)}nextNativeStartRetryDelayMs(e){return x(e,W.NATIVE_START_RETRY_MIN_DELAY_MS,W.NATIVE_START_RETRY_MAX_DELAY_MS)}hasManagedSession(){return !!(this.managedSessionKey||this.managedSessionUserId)}usesNativeIpcBackend(){let t=this.backend?.getRuntimeCapabilities?.();return t?.adapter==="native-ipc"||t?.adapter==="tauri-ipc"||t?.signaling.nativeIpc===true}startManagedReconciliation(e){return this.managedReconciliationTasks.add(e),this.managedReconciliationTimer||(this.managedReconciliationTimer=setInterval(()=>{this.notifyManagedReconciliation();},W.MANAGED_RECONCILIATION_INTERVAL_MS)),()=>{this.managedReconciliationTasks.delete(e),this.managedReconciliationTasks.size===0&&this.managedReconciliationTimer&&(clearInterval(this.managedReconciliationTimer),this.managedReconciliationTimer=null);}}scheduleManagedReconciliationFollowups(){this.notifyManagedReconciliation();for(let e of this.managedReconciliationFollowupTimers)clearTimeout(e);this.managedReconciliationFollowupTimers.clear();for(let e of [1500,5e3]){let t=setTimeout(()=>{this.managedReconciliationFollowupTimers.delete(t),this.notifyManagedReconciliation();},e);this.managedReconciliationFollowupTimers.add(t);}}stopManagedReconciliation(){this.managedReconciliationTimer&&(clearInterval(this.managedReconciliationTimer),this.managedReconciliationTimer=null);for(let e of this.managedReconciliationFollowupTimers)clearTimeout(e);this.managedReconciliationFollowupTimers.clear(),this.managedReconciliationTasks.clear();}notifyManagedReconciliation(){this.hasManagedSession()&&this.managedReconciliationTasks.forEach(e=>{if(this.hasManagedSession())try{e();}catch{}});}async reconcileNativeManagedSession(e="frontend"){let t=this.backend;t&&typeof t.reconcileNativeManagedSession=="function"&&await t.reconcileNativeManagedSession({reason:e}),await this.refreshPeerSnapshot().catch(()=>[]),this.scheduleManagedReconciliationFollowups();}async notifyNetworkChange(e="host"){let t=this.backend;typeof t.notifyNetworkChange=="function"&&await t.notifyNetworkChange({reason:e});}connectionStateSnapshotKey(e){return JSON.stringify({connectionId:e.connectionId,deviceId:e.deviceId??null,deviceIdHint:e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null,state:e.state,transportState:e.transportState??null,protocolState:e.protocolState??null,routable:e.routable??null,readinessState:e.readinessState??null,readinessReason:e.readinessReason??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null,activeTransport:e.activeTransport??null,parallelTransport:e.parallelTransport??null,replacementInProgress:e.replacementInProgress??null,error:e.error??null,updatedAt:e.updatedAt??null})}async runNativeStartLoop(e){let t=Date.now(),n=0;for(;Date.now()-t<=W.NATIVE_START_RETRY_WINDOW_MS;){n+=1;try{await e.start(),n>1&&c$1(`[RuntimeClient] ${e.label} recovered after ${n} attempts`);return}catch(i){if(this.isUnsupportedRuntimeAdapterError(i,e.label))throw i;let o=this.nextNativeStartRetryDelayMs(n);console.warn(`[RuntimeClient] ${e.label} failed attempt=${n} retry_in_ms=${o}:`,i),await u(o);}}throw new Error(e.exhaustedMessage)}isUnsupportedRuntimeAdapterError(e,t){if(!(e instanceof Error))return false;let n=e.message||"",i=t==="startPresenceLoop"?"startPresenceLoopOnce":t==="startAutoConnect"?"startAutoConnectOnce":null;return !!i&&n.includes(`does not support ${i}`)}onIdentityChange(e){return this.client.onAuthChange(e)}async signInAnonymously(){await this.client.signInAnonymously();}async signInWithPluto(){await this.client.signInWithPluto();}async setAuthContext(e){let t=this.backend;if(!t||typeof t.setAuthContext!="function")throw new Error("RuntimeClient auth context requires a runtime adapter that supports setAuthContext().");let n=typeof e?.userId=="string"&&e.userId.trim()||null,i=this.managedSessionUserId;i&&i!==n&&(console.info("[RuntimeClient][auth-context][managed-session-replace]",{previousUserId:i,nextUserId:n}),await this.stopManagedSession()),await t.setAuthContext(e);}async signOut(){await this.stopManagedSession().catch(()=>{}),await this.client.signOut();}async initialize(){if(this.usesNativeIpcBackend()){console.info("[RuntimeClient][native] initialize() skipped; native IPC backend owns runtime startup");return}await this.client.init();}async getRuntimeStatus(){return this.client.getRuntimeStatus()}getPeerReconciliationStats(){return this.client.getPeerReconciliationStats()}getRuntimePolicy(){return w}getRuntimeCapabilities(){let e=this.backend;return typeof e?.getRuntimeCapabilities=="function"?e.getRuntimeCapabilities():B()}getCapabilityProfile(){return D(this.getRuntimeCapabilities())}async start(e){if(this.usesNativeIpcBackend()){let t=await this.getManagedNodeId({initializeIfMissing:true});if(!t)throw new Error("Native runtime started without a node id for the admitted application-stream queue.");this.client.attachIncomingStreamSource(this.backend,t),await this.client.startListening({startPresence:false});return}e?.clearSessionTokens!==false&&await this.client.clearSessionTokens().catch(()=>{}),await this.client.refreshRuntimeAuthToken("runtime-start"),await this.client.startListening();}stop(){this.client.stopListening();}async getNodeId(){if(this.usesNativeIpcBackend()){let e=await this.getManagedNodeId({initializeIfMissing:true});if(!e)throw new Error("Native node id unavailable from IPC backend");return e}return this.client.getNodeId()}async getNodeIdFromTicket(e){return this.client.getNodeIdFromTicket(e)}async getLocalDeviceId(){return this.client.getLocalDeviceId()}async getLocalDeviceInfo(){let e=this.backend;return !e||typeof e.getLocalDeviceInfo!="function"?null:e.getLocalDeviceInfo()}async getLocalDeviceProfile(e){let t=await this.getLocalDeviceInfo().catch(()=>null),n=e?.localDeviceId??t?.deviceId??await this.getLocalDeviceId().catch(()=>null)??null,i=await this.getRuntimeStatus().catch(()=>({runtime:"unknown",wasmLoaded:false,localNodeId:void 0,userId:void 0})),o=e?.platform??(i.runtime==="tauri"?"native":"web");return {deviceId:n,deviceName:e?.deviceName||t?.deviceName||"Unknown Device",platformType:t?.platformType||(o==="native"?"desktop":"web"),userId:e?.userId??this.identity?.id??i.userId??null,capabilities:t?.capabilities??{can_host:o==="native",can_sync:o==="native",read_only:o!=="native"},lastSeenAt:t?.lastSeenAt||new Date().toISOString(),localNodeId:i.localNodeId||null}}async updateLocalDeviceName(e){let t=this.backend;return !t||typeof t.updateLocalDeviceName!="function"?null:t.updateLocalDeviceName(e)}async getManagedNodeId(e){let t=this.backend;if(console.info("[RuntimeClient][getManagedNodeId] enter",{hasBackend:!!t,hasMethod:!!(t&&typeof t.getManagedNodeId=="function"),backendCtor:t?.constructor?.name??null}),!t||typeof t.getManagedNodeId!="function")return null;let n=await t.getManagedNodeId(e);return console.info("[RuntimeClient][getManagedNodeId] resolved",{result:n}),n}async getTicket(){return this.usesNativeIpcBackend()?this.getEndpointTicket():this.client.getTicket()}async getTicketWithToken(e,t=0){let n=this.backend;if(n?.getEndpointTicketWithToken)try{let i=await n.getEndpointTicketWithToken(e,t);if(i)return i}catch(i){if(this.usesNativeIpcBackend())throw i}if(this.usesNativeIpcBackend())throw new Error("Native endpoint ticket with token unavailable from IPC backend");return this.client.getEndpointTicketWithToken(e,t)}async revokeTokensByScope(e){return this.revokeTokensByScopeInternal(e,{rotateManagedScopeIfActive:true})}async revokeTokensByScopeInternal(e,t){o("revokeTokensByScopeInternal",{grantScope:e,rotateManagedScopeIfActive:t?.rotateManagedScopeIfActive!==false,hasManagedSessionOptions:!!this.managedSessionOptions});let n=this.usesNativeIpcBackend(),i=n?[]:await this.client.revokeTokensByScope(e),o$1=this.backend,s=[];if(o$1?.revokeSessionTokensByScope)s=await o$1.revokeSessionTokensByScope(e).catch(()=>[]);else if(n)throw new Error("Native token revoke requires revokeSessionTokensByScope() on the IPC backend.");let a=Array.from(new Set([...i,...s]));return t?.rotateManagedScopeIfActive!==false&&e===W.MANAGED_USER_DEVICE_SCOPE&&this.managedSessionOptions&&this.managedSessionOptions.presence!==false&&await this.rotateManagedUserDeviceGrant(),a}revokeSessionToken(e){this.client.revokeSessionToken(e);}watchFriendDevices(e,t){let n=this.backend;return n?.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async getFriendTicket(e=0){return this.getTicketWithToken(W.MANAGED_FRIEND_SCOPE,e)}async revokeFriendTokens(){return this.revokeTokensByScope(W.MANAGED_FRIEND_SCOPE)}async updateFriendTicket(e){let t=this.backend;t?.updateFriendTicket&&await t.updateFriendTicket(e);}async getEndpointTicket(){let e=this.backend;if(e&&typeof e.getEndpointTicket=="function")try{return await e.getEndpointTicket()}catch(t){if(this.usesNativeIpcBackend())throw t}if(this.usesNativeIpcBackend())throw new Error("Native endpoint ticket unavailable from IPC backend");return this.client.getTicket()}async startManagedSession(e){let t=this.resolveManagedSessionUserId(e.platform,e.userId??null),n=JSON.stringify({platform:e.platform,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,userId:t,autoConnect:this.resolveManagedAutoConnectEnabled(e),autoConnectPolicy:e.autoConnectPolicy??null,presence:this.resolveManagedPresenceEnabled(e),presencePolicy:e.presencePolicy??null}),i=this.managedSessionStartInFlight.get(n);if(i)return i;let o$1=this.serializeManagedSessionOperation("start",async()=>{if(this.managedSessionKey===n){if(e.platform==="native"&&t){let l=this.backend;if(l&&typeof l.startManagedSessionNative=="function")try{let d=await l.startManagedSessionNative({userId:t,deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,metadata:e.metadata,autoConnect:this.resolveManagedAutoConnectEnabled(e),presence:this.resolveManagedPresenceEnabled(e)});console.info("[RuntimeClient][managed-session][native-replayed]",{userId:t,localNodeId:d.localNodeId,presenceStarted:d.presenceStarted,autoConnectStarted:d.autoConnectStarted,localDeviceId:d.localDevice?.deviceId??null});}catch(d){console.warn("[RuntimeClient][managed-session][native-replay-failed]",{userId:t,message:d instanceof Error?d.message:String(d)});}}let c=await this.getLocalDeviceProfile({deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,platform:e.platform,userId:t});return {mode:e.platform,device:c,stop:async()=>this.stopManagedSession()}}o("managed-session-replace",{previousSessionKey:this.managedSessionKey,nextSessionKey:n}),await this.stopManagedSessionInternal(),this.managedSessionKey=n,this.managedSessionUserId=t,this.managedSessionOptions={...e,userId:t};let s=null,a=null;console.info("[RuntimeClient][managed-session][start]",{platform:e.platform,requestedUserId:e.userId??null,runtimeUserId:this.identity?.id??null,effectiveUserId:this.managedSessionUserId,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,localDeviceId:e.localDeviceId??null,deviceName:e.deviceName??null,presence:this.resolveManagedPresenceEnabled(e),presencePolicy:e.presencePolicy??null,autoConnect:this.resolveManagedAutoConnectEnabled(e),autoConnectPolicy:e.autoConnectPolicy??null});try{if(e.platform==="web")await this.initialize(),this.resolveManagedPresenceEnabled(e)?(await this.client.clearSessionTokens().catch(()=>{}),s=await this.getTicketWithToken(W.MANAGED_USER_DEVICE_SCOPE,0),this.client.setManagedPresenceTicket(s),await this.start({clearSessionTokens:!1})):(this.client.clearManagedPresenceTicket(),await this.start());else {if(!this.managedSessionUserId)throw new Error("Native managed session startup requires an authenticated user id.");await this.client.ensureAuthenticated("discovery");let l=this.backend;if(!l||typeof l.startManagedSessionNative!="function")throw new Error("Native managed session startup requires a native backend-owned startManagedSessionNative() surface.");a=await l.startManagedSessionNative({userId:this.managedSessionUserId,deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,metadata:e.metadata,autoConnect:this.resolveManagedAutoConnectEnabled(e),presence:this.resolveManagedPresenceEnabled(e)}),console.info("[RuntimeClient][managed-session][native-started]",{userId:this.managedSessionUserId,localNodeId:a.localNodeId,ticketScope:a.ticketScope??null,presenceStarted:a.presenceStarted,autoConnectStarted:a.autoConnectStarted,localDeviceId:a.localDevice?.deviceId??null});let d=a.localNodeId??await this.getManagedNodeId({initializeIfMissing:!1});if(!d)throw new Error("Native managed session started without a node id for the admitted application-stream queue.");this.client.attachIncomingStreamSource(this.backend,d),await this.client.startListening({startPresence:!1});}this.fetchAndApplyAppLimits();let c=await this.getLocalDeviceProfile({deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,platform:e.platform,userId:this.managedSessionUserId});return e.platform==="native"?(this.resolveManagedPresenceEnabled(e)&&!a?.presenceStarted&&console.warn("[RuntimeClient][managed-session][native-presence-missing]",{userId:this.managedSessionUserId,deviceId:c.deviceId}),this.resolveManagedAutoConnectEnabled(e)&&c.deviceId&&!a?.autoConnectStarted&&console.warn("[RuntimeClient][managed-session][native-auto-connect-missing]",{userId:this.managedSessionUserId,deviceId:c.deviceId})):this.resolveManagedPresenceEnabled(e)&&(console.info("[RuntimeClient][managed-session][start-presence]",{platform:e.platform,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,userId:this.managedSessionUserId,deviceId:c.deviceId,deviceName:c.deviceName,ticketScope:W.describeTicketForLogs(s).scope}),await this.startPresenceLoop({deviceName:c.deviceName,ticket:s,metadata:e.metadata}),console.info("[RuntimeClient][managed-session][presence-started]",{platform:e.platform,userId:this.managedSessionUserId,deviceId:c.deviceId})),e.platform!=="native"&&this.resolveManagedAutoConnectEnabled(e)&&c.deviceId&&(await this.startAutoConnect(c.deviceId),console.info("[RuntimeClient][managed-session][auto-connect-started]",{platform:e.platform,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,userId:this.managedSessionUserId,deviceId:c.deviceId})),await this.refreshPeerSnapshot().catch(()=>[]),this.scheduleManagedReconciliationFollowups(),{mode:e.platform,device:c,stop:async()=>this.stopManagedSession()}}catch(c){throw console.warn("[RuntimeClient][managed-session][start-failed-cleanup]",{platform:e.platform,requestedUserId:e.userId??null,runtimeUserId:this.identity?.id??null,effectiveUserId:this.managedSessionUserId,message:c instanceof Error?c.message:String(c)}),await this.stopManagedSessionInternal().catch(()=>{}),c}});this.managedSessionStartInFlight.set(n,o$1);try{return await o$1}finally{this.managedSessionStartInFlight.delete(n);}}async stopManagedSession(e){return this.serializeManagedSessionOperation(e?.preserveBackendSession?"stop-preserve-backend":"stop",()=>this.stopManagedSessionInternal(e))}async stopManagedSessionInternal(e){if(!this.managedSessionKey&&!this.managedSessionUserId)return;let t=!!e?.preserveBackendSession;o("stopManagedSessionInternal",{preserveBackendSession:t,managedSessionKey:this.managedSessionKey,managedSessionUserId:this.managedSessionUserId??null});let n=this.backend;this.managedSessionOptions;let o$1=Date.now();if(console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"local-invalidate",elapsedMs:0,managedSessionUserId:this.managedSessionUserId,preserveBackendSession:t}),this.client.clearManagedPresenceTicket(),t?console.info("[RuntimeClient] Preserving native backend-managed session across frontend teardown",{userId:this.managedSessionUserId??this.identity?.id??null,scope:W.MANAGED_USER_DEVICE_SCOPE}):(console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"revoke-user-device-grants",elapsedMs:Date.now()-o$1,managedSessionUserId:this.managedSessionUserId}),await this.revokeTokensByScopeInternal(W.MANAGED_USER_DEVICE_SCOPE,{rotateManagedScopeIfActive:false}).catch(()=>[]),this.stop(),n&&typeof n.stopAuthScopedActivity=="function"?(console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"stop-backend-auth-scope",elapsedMs:Date.now()-o$1,managedSessionUserId:this.managedSessionUserId}),await n.stopAuthScopedActivity({userId:this.managedSessionUserId??this.identity?.id??null})):await this.setOffline().catch(()=>{})),t){this.notifyManagedReconciliation();return}await this.scopedConnectionActorRegistry?.shutdownAll().catch(s=>{console.warn("[RuntimeClient] scoped connection actor shutdown failed",s);}),this.scopedConnectionActorRegistry=null,this.managedSessionKey=null,this.managedSessionUserId=null,this.managedSessionOptions=null,console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"complete",elapsedMs:Date.now()-o$1,managedSessionUserId:null});}async rotateManagedUserDeviceGrant(){let e=this.managedSessionOptions;if(!e||!this.resolveManagedPresenceEnabled(e))return;if(e.platform==="native"){let o=this.backend;if(!o||typeof o.startManagedSessionNative!="function")throw new Error("Native managed ticket rotation requires a native backend-owned startManagedSessionNative() surface.");let s=this.managedSessionUserId??e.userId??this.identity?.id??null;if(!s)throw new Error("Native managed ticket rotation requires an authenticated user id.");await o.startManagedSessionNative({userId:s,deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,metadata:e.metadata,autoConnect:this.resolveManagedAutoConnectEnabled(e),presence:this.resolveManagedPresenceEnabled(e)}),console.info("[RuntimeClient][managed-ticket][rotate]",{scope:W.MANAGED_USER_DEVICE_SCOPE,platform:e.platform,userId:s});return}let t=await this.getTicketWithToken(W.MANAGED_USER_DEVICE_SCOPE,0),n=this.managedSessionUserId??e.userId??this.identity?.id??null;this.client.setManagedPresenceTicket(t);let i=await this.getLocalDeviceProfile({deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,platform:e.platform,userId:e.userId??null});await this.startPresenceLoop({deviceName:i.deviceName,ticket:t,metadata:e.metadata}),console.info("[RuntimeClient][managed-ticket][rotate]",{scope:W.MANAGED_USER_DEVICE_SCOPE,platform:e.platform,userId:n});}async listDevices(){return this.deviceManager.listDevices()}async listDevicesWithStatus(){return this.deviceManager.listDevicesWithStatus()}async updateDevice(e,t){await this.deviceManager.updateDevice(e,t);}async deleteDevice(e){await this.deviceManager.deleteDevice(e);}watchDevices(e){return this.deviceManager.watchDevices(e)}watchDevicesWithStatus(e){return this.deviceManager.watchDevicesWithStatus(e)}async connectDeviceWithRetry(e,t,n){return this.deviceManager.connectDeviceWithRetry(e,t,n)}async connectDevice(e,t){return this.deviceManager.connectDevice(e,t)}watchPeerStates(e){return this.client.watchPeerStates(e)}watchPeerLifecycle(e){return this.watchPeerStates(e)}getPeerState(e){return this.client.getPeerState(e)}async resolvePeerConnectionRecords(e){return this.peerManager.resolvePeerConnectionRecords(e)}async getPeerSession(e){return this.peerManager.getPeerSession(e)}async listPeerSessions(){return this.peerManager.listPeerSessions()}async waitForConnectedPeer(e,t){return this.peerManager.waitForConnectedPeer(e,t)}async getPeerReadiness(e,t){return this.peerManager.getPeerReadiness(e,t)}async resolvePeerIdentity(e){return this.peerManager.resolvePeerIdentity(e)}async resolveIncomingStreamPeer(e){return this.peerManager.resolveIncomingStreamPeer(e)}listConnectedPeers(){return this.client.listConnectedPeers()}addPeerScope(e,t){return this.peerManager.addPeerScope(e,t)}releasePeerScope(e,t){return this.peerManager.releasePeerScope(e,t)}getPeerScopes(e){return this.peerManager.getPeerScopes(e)}isSamePeer(e,t){return this.peerManager.isSamePeer(e,t)}async refreshPeerSnapshot(){return this.client.refreshPeerSnapshot()}async subscribeSessions(e,t){return this.client.subscribeSessions(e,t)}getAppLimits(){return this.client.appLimits}syncRoomRtdbPresenceFromBackend(){let e=this.backend?.rtdbPresence;e&&this.client.rooms.setRtdbPresence(e);}async createRoom(e){return this.syncRoomRtdbPresenceFromBackend(),this.client.rooms.createRoom(e)}async joinRoom(e,t){return this.syncRoomRtdbPresenceFromBackend(),this.client.rooms.joinRoom(e,t)}async leaveRoom(e){return this.client.rooms.leaveRoom(e)}async getRoomMembers(e){return this.client.rooms.getRoomMembers(e)}watchRoom(e,t){return this.client.rooms.watchRoom(e,t)}async connectByTicket(e){return this.client.connect(e.ticket,e.timeoutMs)}async connectPeer(e){return this.client.connectPeer(e)}async connectScopedChannel(e){let t=e.timeoutMs===void 0?void 0:Math.max(1,e.timeoutMs),n=t===void 0?void 0:Date.now()+t,i=R=>{if(n===void 0||t===void 0)return;let M=n-Date.now();if(M<=0)throw new Error(`connectScopedChannel timeout after ${t}ms during ${R}`);return Math.max(1,M)},o=e.scope,s=e.channelId.trim();if(!s)throw new Error("connectScopedChannel requires a channelId");let a=e.peerId??e.peerNodeId??e.deviceId??(e.ticket?await this.getNodeIdFromTicket(e.ticket).catch(()=>null):null);if(!a)throw new Error("connectScopedChannel requires peerId, peerNodeId, deviceId, or a ticket with an embedded node id");let c=this.client.getConnections().find(R=>!R.isClosed&&(R.remoteNodeId===a||R.deviceId===a))??null,l=c?[c.id,c.remoteNodeId,c.deviceId,a,e.deviceId].map(R=>typeof R=="string"?R.trim():"").filter(Boolean).map(R=>this.client.getPeerState(R)).find(R=>R!==void 0):void 0,d=c?await this.resolvePeerConnectionRecords(e.deviceId??a).catch(()=>[]):[],p=this.usesNativeIpcBackend()?await this.getPeerSession(e.deviceId??a).catch(()=>null):null,u$1=d.some(R=>R.state.toLowerCase()==="connected"&&R.transportStableId!==null&&R.transportStableId!==void 0),f=l?.status==="connected"&&l.lifecycleStage!=="closed"&&l.baseTransportState!=="closed"&&l.routable!==false,h=(d.length>0?u$1:f)&&l?.scopes.includes(o)===true,m=p?.status==="connected"&&p.settledReady===true&&p.scopes.includes(o);c$1("[RuntimeClient][connectScopedChannel] existing route decision",{peerId:a,scope:o,hasWrapper:c!==null,projectedStatus:l?.status??null,projectedScopes:l?.scopes??[],managedRecords:d.map(R=>({connectionId:R.connectionId,state:R.state,transportStableId:R.transportStableId??null})),nativeSession:p?{peerId:p.peerId,deviceId:p.deviceId??null,nodeId:p.nodeId??null,status:p.status,settledReady:p.settledReady===true,scopes:p.scopes}:null,reuse:h||m});let y=h?c:null,v=null,P=m?p?.nodeId??a:null;if(!y)if(this.usesNativeIpcBackend()){if(!m)if(e.ticket){let R=o===W.MANAGED_USER_DEVICE_SCOPE?e.deviceId:null,M=await this.connectToDevice({endpointTicket:e.ticket,deviceId:R,timeoutMs:i("native peer dial")}),B=M.remoteNodeId??M.deviceId??M.deviceIdHint??a;P=B,y=this.client.getConnections().find(x=>!x.isClosed&&(x.id===M.connectionId||x.remoteNodeId===B||x.deviceId===B||x.deviceId===e.deviceId))??null;}else throw new Error("native connectScopedChannel requires an endpoint ticket when no connection exists")}else v=this.getScopedConnectionActor({scope:o,peerNodeId:a},{ticket:e.ticket,timeoutMs:i("scoped peer actor"),channelId:s,dial:async()=>{y=await this.connectPeer({ticket:e.ticket,deviceId:e.deviceId??a,scope:o,channelId:s,timeoutMs:i("browser peer dial"),respectManualDisconnect:e.respectManualDisconnect??true});}}),await v.ensureReady();y||(this.usesNativeIpcBackend()?y=this.client.getConnections().find(R=>!R.isClosed&&(R.remoteNodeId===(P??a)||R.deviceId===a))??null:y=await this.connectPeer({ticket:e.ticket,deviceId:e.deviceId??a,scope:o,channelId:s,timeoutMs:i("peer dial fallback"),respectManualDisconnect:e.respectManualDisconnect??true}));let I=y?.remoteNodeId??P??a,T=y,C=e.nativeLabel===true,N=e.framing??"raw",b=async()=>{if(C)try{let M=await this.openPeerNativeBi(I,s,{timeoutMs:i("native labelled stream open"),scope:o});return {connection:M.connection,readable:M.readable,writer:M.writable.getWriter(),openedWithNativeLabel:!0}}catch(M){c$1("[RuntimeClient][connectScopedChannel] native-labelled stream open failed; falling back",{peerId:I,channelId:s,error:String(M)});let B=await this.openPeerBi(I,{timeoutMs:i("scoped stream fallback"),scope:o,channelId:s});return {connection:B.connection,readable:B.readable,writer:B.writable.getWriter(),openedWithNativeLabel:true}}let R=await this.openPeerBi(I,{timeoutMs:i("scoped stream open"),scope:o,channelId:s});return {connection:R.connection,readable:R.readable,writer:R.writable.getWriter(),openedWithNativeLabel:false}},L=await b();y=T??L.connection;let _=L.writer,w=L.openedWithNativeLabel,D=new Set,E=false,O=false,z=0,ve=null,ke=null,Mn=Promise.resolve(),$e=null,En=null,Ne=null,Ln=R=>{s!=="drive-view"||!R||R===En||typeof R.onWebRTCBinaryMessage!="function"&&typeof R.onMessage!="function"||(Ne?.(),Ne=Ia(R,M=>{if(E||!Pi(M))return false;for(let B of [...D])B(M);return true}),En=R);},De=()=>{let R=new Set([y?.id,y?.remoteNodeId,y?.deviceId,I,a,e.deviceId,e.peerId,e.peerNodeId].map(x=>typeof x=="string"?x.trim():"").filter(Boolean)),M=this.client.getConnections().filter(x=>!x.isClosed&&(R.has(x.id)||R.has(x.remoteNodeId)||R.has(x.deviceId??""))),B=M.find(x=>is(x))??M.find(x=>typeof x.sendOnWebRTC=="function"||typeof x.getWebRTCTransport=="function")??M[0]??null;if(B&&B!==y&&(y=B),!y)throw new Error(`Scoped channel '${s}' has no active connection`);return Ln(y),y};Ln(y);let xn=R=>{let M=R.getReader(),B=++z,x=new Uint8Array(0);ve=M,O=false,(async()=>{try{for(;!E&&B===z;){let{value:V,done:Ai}=await M.read();if(Ai)break;if(!(!V||V.byteLength===0)){if(N==="raw"){for(let le of [...D])le(V);continue}for(x=$n(x,V);x.byteLength>=4;){let le=Vn(x,0);if(x.byteLength<4+le)break;let wi=x.slice(4,4+le);x=x.slice(4+le);for(let Fn of [...D])Fn(wi);}}}}catch(V){!E&&B===z&&c$1("[RuntimeClient][connectScopedChannel] physical stream read loop ended with error",{peerId:I,channelId:s,error:String(V)});}finally{B===z&&(O=true,ve===M&&(ve=null));try{M.releaseLock();}catch{}}})();};xn(L.readable);let _n=async()=>{O&&(ke||(ke=(async()=>{let R=_,M=await b();if(E){try{await M.readable.cancel("scoped channel closed during physical stream reopen");}catch{}try{await M.writer.abort("scoped channel closed during physical stream reopen");}catch{}try{M.writer.releaseLock();}catch{}throw new Error(`Scoped channel '${s}' is closed`)}y=M.connection??y,_=M.writer,w=w||M.openedWithNativeLabel,xn(M.readable);try{await R.abort("scoped channel physical stream replaced");}catch{}try{R.releaseLock();}catch{}})().finally(()=>{ke=null;})),await ke);},Ti=async R=>{let M=Mn.then(async()=>{if(E)throw new Error(`Scoped channel '${s}' is closed`);let B=De();if(s==="drive-view"&&is(B))try{await B.send(R),$e=B.getLastApplicationPayloadTransport?.()??B.getTransportStatus?.().activeTransport??null;return}catch(V){c$1("[RuntimeClient][connectScopedChannel] current-route scoped-channel send failed; falling back to stream",{peerId:I,channelId:s,error:String(V)});}let x=N==="u32be"?Qn(R):R;await _n();try{await _.write(x);}catch(V){if(E)throw V;O=true,await _n(),await _.write(x);}$e="stream";});Mn=M.catch(()=>{}),await M;};if(!this.usesNativeIpcBackend()){let R=Math.max(1,Math.min(i("application route settlement")??5e3,5e3)),M=Date.now();for(;;){let B=De();if(typeof B.isReadyForApplicationPayload!="function"||B.isReadyForApplicationPayload())break;if(Date.now()-M>=R){E=true,z+=1;let x=ve;try{await x?.cancel("scoped channel application route timeout");}catch{}try{await _.abort("scoped channel application route timeout");}catch{}try{_.releaseLock();}catch{}throw await v?.shutdown().catch(()=>{}),new Error(`Scoped channel '${s}' timed out waiting for an application payload route`)}await u(20);}}return {channelId:s,peerId:I,get connection(){return De()},send:Ti,onMessage(R){return D.add(R),()=>D.delete(R)},async close(){if(!E){E=true,z+=1,D.clear(),Ne?.(),Ne=null;try{await ve?.cancel("scoped channel closed");}catch{}try{await _.abort("scoped channel closed");}catch{}try{_.releaseLock();}catch{}await v?.shutdown().catch(()=>{});}},diagnostics:()=>{let R=De();return {connectionId:R.id??null,remoteNodeId:R.remoteNodeId??null,transports:R.getAvailableTransports?.()??[],hasSendOnWebRTC:typeof R.sendOnWebRTC=="function",hasWebRTCTransport:typeof R.getWebRTCTransport=="function"?R.getWebRTCTransport()!==null:false,lastSendTransport:$e,framing:N,nativeLabel:w||C}}}}getScopedConnectionActor(e,t){let n=a=>{let c=t?.ticket,l=t?.channelId,d=t?.dial;return new Fe({key:a,dial:async p=>{if(this.assertScopedDialAllowed(p),d){await d(p);return}await this.connectPeer({deviceId:p.peerNodeId,ticket:c,scope:p.scope,channelId:l,respectManualDisconnect:true});},close:async()=>{}})};this.scopedConnectionActorRegistry||(this.scopedConnectionActorRegistry=new Be(n));let i=zn(e.scope,e.peerNodeId),o=this.scopedConnectionActorRegistry.get(i),s=this.scopedConnectionActorRegistry.getOrSpawn(i,n);return (o===null||o!==null&&o!==s)&&$("[runtime-client][scoped-connection-actor]",_e(i.scope,{peerNodeId:i.peerNodeId}),"spawn"),s}assertScopedDialAllowed(e){let t=this.scopedDialCandidateIds(e).find(n=>this.hasManualDisconnectSuppression(n));if(t)throw $("[runtime-client][scoped-connection-actor]",_e(e.scope,{peerNodeId:e.peerNodeId}),"dial_suppressed_manual_disconnect peerId={}",t),new Error(`scoped connection dial suppressed by manual disconnect for peer ${t}`)}scopedDialCandidateIds(e){let t=new Set,n=e.peerNodeId.trim();n&&t.add(n);let i=e.scope.trim();if(i.startsWith("trusted-device:")){let o=i.slice(15).split(":")[0]?.trim();o&&t.add(o);}return [...t]}hasManualDisconnectSuppression(e){let t=this.client.getPeerState(e);if(!t)return false;if(t.manualDisconnect===true)return true;let n=t,i=[t.error,n.lastDisconnectReason].filter(o=>typeof o=="string"&&o.length>0).join(" ");return /manual disconnect/i.test(i)}async shutdownScopedConnectionActors(){if(!this.scopedConnectionActorRegistry)return;let e=this.scopedConnectionActorRegistry.size();$("[runtime-client][scoped-connection-actor]",{sessionKind:"drive-grant-guest"},"shutdown_all count={}",e),await this.scopedConnectionActorRegistry.shutdownAll();}async openPeerBi(e,t){let n=this.backend;if(n&&typeof n.openPeerBi=="function"){await this.waitForBrowserApplicationCrypto(e,t?.timeoutMs);let i=await n.openPeerBi(e,t?.timeoutMs),o=await this.resolvePeerStreamTarget(e);return {connection:o.connection??this.compatPeerConnectionFromTarget(o,e),readable:i.readable,writable:t?.channelId?this.client.wrapChannelWritable(i.writable,t.channelId):i.writable}}throw new Error("[pluto-rtc] openPeerBi() requires a Rust-backed runtime adapter that implements openPeerBi().")}async openPeerNativeBi(e,t,n){let i=this.backend;if(i&&typeof i.openPeerNativeBi=="function"){await this.waitForBrowserApplicationCrypto(e,n?.timeoutMs);let o=await i.openPeerNativeBi(e,t,n?.timeoutMs),s=await this.resolvePeerStreamTarget(e);return {connection:s.connection??this.compatPeerConnectionFromTarget(s,e),readable:o.readable,writable:o.writable}}throw new Error("[pluto-rtc] openPeerNativeBi() requires a Rust-backed runtime adapter that implements openPeerNativeBi().")}async openPeerBiTransportOnly(e,t){let n=this.backend;if(n&&typeof n.openPeerBiTransportOnly=="function"){let i=await n.openPeerBiTransportOnly(e,t?.timeoutMs),o=await this.resolvePeerStreamTarget(e);return {connection:o.connection??this.compatPeerConnectionFromTarget(o,e),readable:i.readable,writable:t?.channelId?this.client.wrapChannelWritable(i.writable,t.channelId):i.writable}}return this.openPeerBi(e,t)}async openPeerUni(e,t){let n=this.backend;if(n&&typeof n.openPeerUni=="function"){await this.waitForBrowserApplicationCrypto(e,t?.timeoutMs);let i=await n.openPeerUni(e,t?.timeoutMs),o=await this.resolvePeerStreamTarget(e);return {connection:o.connection??this.compatPeerConnectionFromTarget(o,e),writable:t?.channelId?this.client.wrapChannelWritable(i.writable,t.channelId):i.writable}}throw new Error("[pluto-rtc] openPeerUni() requires a Rust-backed runtime adapter that implements openPeerUni().")}async waitForBrowserApplicationCrypto(e,t){if(this.usesNativeIpcBackend())return;let n=Math.max(1,t??1e4);if(!await this.client.waitForApplicationCryptoForPeer(e,n))throw new Error(`[OpenRTC] protected application stream to '${e}' timed out waiting for application crypto`)}async connectToDevice(e){return this.connectionController.connectToDevice(e)}async connectRaw(e){return this.connectionController.connectRaw(e)}async openBi(e){return this.connectionController.openBi(e)}async openUni(e){return this.connectionController.openUni(e)}onIncomingStream(e){return this.client.onIncomingStream(e)}registerChannel(e){this.client.registerChannel(e);}unregisterChannel(e){this.client.unregisterChannel(e);}listChannels(){return this.client.listChannels()}onIncomingChannelStream(e,t){return this.client.onIncomingChannelStream(e,t)}async sendExplicitFilePath(e,t,n){let i=this.backend;if(!i||typeof i.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return i.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){let t=this.backend;if(!t||typeof t.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");let n=this.client.getConnectionForPeer(e.connectionId,e.remoteNodeId),i=e.requireApplicationCrypto??(typeof n?.isApplicationCryptoRequired=="function"?n.isApplicationCryptoRequired():void 0),o=e.remoteNodeId??n?.remoteNodeId??e.connectionId??n?.deviceId,s=e.applicationCrypto??this.client.getApplicationCrypto(n??void 0)??this.client.resolveApplicationCryptoForPeer(o,n??void 0)??(i?await this.client.waitForApplicationCryptoForPeer(o):void 0),a=e.receiverPlatformType;if(a===void 0){let l=new Set([e.remoteNodeId,n?.remoteNodeId,n?.deviceId,e.connectionId].map(d=>typeof d=="string"?d.trim():"").filter(d=>d.length>0));if(l.size>0){let p=(await this.listDevicesWithStatus().catch(()=>[])).find(u=>l.has(String(u.deviceId??""))||l.has(String(u.peerId??""))||l.has(String(u.nodeId??""))||l.has(String(u.connectionId??"")));a=typeof p?.platformType=="string"&&p.platformType.trim().length>0?p.platformType:null;}}let c={...e,connection:e.connection??n,remoteNodeId:e.remoteNodeId??n?.remoteNodeId,receiverPlatformType:a,applicationCrypto:s,requireApplicationCrypto:i};return t.sendExplicitFileData(c)}async getTransferHistory(e){let t=this.backend;return !t||typeof t.getTransferHistory!="function"?[]:t.getTransferHistory(e)}async deleteTransferJob(e){let t=this.backend;if(!(!t||typeof t.deleteTransferJob!="function"))return t.deleteTransferJob(e)}async startPresenceLoop(e){let t=this.backend;if(this.usesNativeIpcBackend()&&t&&typeof t.startPresenceLoopOnce=="function"){let n=this.getEffectiveRuntimeUserId();if(!n){await this.client.startPresenceLoop(e);return}let i=await this.getManagedNodeId({initializeIfMissing:true}).catch(()=>null),o=i||await this.getNodeId(),s=e?.ticket||await this.getEndpointTicket(),a=await this.getLocalDeviceProfile({deviceName:e?.deviceName,platform:"native",userId:n}),c=W.describeTicketForLogs(s);console.info("[RuntimeClient][native-presence][start]",{userId:n,localNodeId:o,nodeSource:i?"native-managed":"client-getNodeId-fallback",deviceId:a.deviceId,deviceName:e?.deviceName||a.deviceName,ticketScope:c.scope,isCompoundTicket:c.isCompound});try{await this.runNativeStartLoop({label:"startPresenceLoop",exhaustedMessage:`[RuntimeClient] startPresenceLoop exhausted retries user_id=${n} local_node_id=${o}`,start:()=>t.startPresenceLoopOnce(n,o,e?.deviceName||a.deviceName,s,e?.metadata)});}catch(d){if(!this.isUnsupportedRuntimeAdapterError(d,"startPresenceLoop"))throw d;await this.client.startPresenceLoop(e);return}console.info("[RuntimeClient][native-presence][started]",{userId:n,localNodeId:o,nodeSource:i?"native-managed":"client-getNodeId-fallback",deviceId:a.deviceId});let l=t.rtdbPresence;l&&this.client.rooms.setRtdbPresence(l);return}await this.client.startPresenceLoop(e);}async updatePresence(e){await this.client.updatePresence(e?.isOnline,e?.ttlMs,e?.metadata,e?.ticket);}async refreshLivePresence(e){let t=this.backend;if(!t||typeof t.refreshLivePresence!="function"){await this.updatePresence(e);return}let n=await this.getNodeId(),i=e?.ticket||await this.getEndpointTicket();await t.refreshLivePresence(n,i,e?.metadata);}async setOffline(){await this.client.setOffline();}async cleanupStaleDevices(){await this.client.cleanupStaleDevices();}async startAutoConnect(e){await this.client.refreshRuntimeAuthToken("runtime-start");let t=this.backend;if(t&&typeof t.startAutoConnectOnce=="function"){let n=this.getEffectiveRuntimeUserId();if(!n)throw new Error("startAutoConnect requires an authenticated user");let i=e||await this.getLocalDeviceId();if(!i)throw new Error("startAutoConnect requires a local device id");try{await this.runNativeStartLoop({label:"startAutoConnect",exhaustedMessage:`[RuntimeClient] startAutoConnect exhausted retries user_id=${n} local_device_id=${i}`,start:()=>t.startAutoConnectOnce(n,i)});}catch(o){if(!this.isUnsupportedRuntimeAdapterError(o,"startAutoConnect"))throw o;await this.client.startAutoConnect(e);return}return}await this.client.startAutoConnect(e);}async isConnected(e){return this.connectionController.isConnected(e)}async disconnectNode(e){await this.connectionController.disconnectNode(e);}async disconnectDevice(e){return this.connectionController.disconnectDevice(e)}async setAutoConnectExcluded(e,t){await this.connectionController.setAutoConnectExcluded(e,t);}async disconnectPeer(e,t){await this.connectionController.disconnectPeer(e,t);}async forceDisconnectPeer(e){await this.connectionController.forceDisconnectPeer(e);}async getPeerHealth(e){return this.client.getPeerHealth(e)}async getConnectionStates(){return this.client.signaling.getConnectionStates()}onConnectionStateChange(e){let t=true,n=new Map,i=l=>{if(!t)return;let d=this.connectionStateSnapshotKey(l);n.get(l.connectionId)!==d&&(n.set(l.connectionId,d),e(l));},o=()=>{t&&this.getConnectionStates().then(l=>{l.forEach(d=>i(d));}).catch(()=>{});},s=l=>()=>{t=false,a(),l?.();},a=this.startManagedReconciliation(()=>o()),c=this.client.signaling.onConnectionStateChange(l=>i(l));return o(),typeof c=="function"?s(c):Promise.resolve(c).then(l=>s(typeof l=="function"?l:null))}getConnections(){return this.client.getConnections()}getApplicationReadyConnections(e={}){return this.client.getApplicationReadyConnections(e)}onConnection(e){return this.client.onConnection(e)}onDisconnection(e){return this.client.onDisconnection(e)}onMessage(e){return this.client.onMessage(e)}onConnectionEvent(e){let t=this.client.onConnection(i=>{let{activeTransport:o}=i.getTransportStatus();e({type:"connected",connectionId:i.id,localNodeId:i.localNodeId,remoteNodeId:i.remoteNodeId,transport:o});}),n=this.client.onDisconnection(i=>{let{activeTransport:o}=i.getTransportStatus();e({type:"disconnected",connectionId:i.id,localNodeId:i.localNodeId,remoteNodeId:i.remoteNodeId,transport:o});});return ()=>{t(),n();}}forceReconnectSnapshot(){this.client.forceReconnectSnapshot();}async connect(){await this.initialize(),await this.start();}disconnect(){this.stop();}destroy(){this.stopManagedReconciliation(),this.stop();let e=this.client;e&&typeof e.destroy=="function"&&e.destroy();}dispose(){this.destroy();}onAuthChange(e){return this.onIdentityChange(e)}async setAuth(e){return this.setAuthContext(e)}async signIn(){return this.signInWithPluto()}async getDevices(){return this.listDevices()}onDevices(e,t){return t?.status?this.watchDevicesWithStatus(e):this.watchDevices(e)}async getInvite(){return this.getTicket()}async connectTo(e){return this.connectPeer(e)}async waitFor(e,t){return this.waitForConnectedPeer(e,t)}async openStream(e,t){if(t?.direction==="send")return this.openPeerUni(e,t);if(this.isTransportOnlyStreamChannel(t?.channelId))try{return await this.openPeerBiTransportOnly(e,t)}catch(n){let i=n instanceof Error?n.message:String(n);if(!/application crypto/i.test(i))throw n;c$1("[RuntimeClient] transport-only channel requires encrypted peer stream; falling back",{peerId:e,channelId:t?.channelId??null});}return this.openPeerBi(e,t)}async openChannelStream(e,t,n){return this.openStream(t,{...n,channelId:e})}onStream(e){return this.onIncomingStream(e)}onChannelStream(e,t){return this.onIncomingChannelStream(e,t)}onRoomChange(e,t){return this.watchRoom(e,t)}createSession(e){return new ot(this,e)}};W.NATIVE_START_RETRY_WINDOW_MS=w.managedSession.nativeStartRetryWindowMs,W.NATIVE_START_RETRY_MIN_DELAY_MS=w.managedSession.nativeStartRetryMinDelayMs,W.NATIVE_START_RETRY_MAX_DELAY_MS=w.managedSession.nativeStartRetryMaxDelayMs,W.MANAGED_RECONCILIATION_INTERVAL_MS=w.managedSession.reconciliationIntervalMs,W.DEVICE_STATUS_REFRESH_DEBOUNCE_MS=w.managedSession.deviceStatusRefreshDebounceMs,W.MANAGED_USER_DEVICE_SCOPE="user-device",W.MANAGED_FRIEND_SCOPE="friend";var Dn=W;function lm(r,e){let t=new Dn(r,e),n=r.spaceKey??r.space,i=(r.discoveryMode===void 0||r.discoveryMode==="space")&&typeof r.apiKey=="string"&&r.apiKey.trim().length>0&&typeof n=="string"&&n.trim().length>0,o={runtime:t,async setAuthContext(s){await t.setAuthContext(s);},async syncPlutoAuth(s){if(i)return;let a=G(),c=a.getCurrentUser(),d=(typeof s?.userId=="string"?s.userId.trim():"")||c?.uid||null;if(!d){await o.setAuthContext(null);return}let p=await a.getIdToken({forceRefresh:s?.forceRefresh??false}).catch(()=>null),u=a.getCurrentUser()?.refreshToken??null,f=a.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:d,token:p,refreshToken:u,tokenProvider:async h=>a.getIdToken({forceRefresh:h??true}),expiresAtMs:f});},bindPlutoAuthHost(){let s=G();return o.syncPlutoAuth({userId:s.getCurrentUser()?.uid??null,forceRefresh:false}),s.onIdTokenChanged(a=>{o.syncPlutoAuth({userId:a?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:s=>t.startManagedSession(s),onAuthChange:s=>t.onIdentityChange(s),getManagedNodeId:s=>t.getManagedNodeId(s),getRuntimeStatus:()=>t.getRuntimeStatus(),listDevicesWithStatus:()=>t.listDevicesWithStatus(),watchDevicesWithStatus:s=>t.watchDevicesWithStatus(s),connectDevice:(s,a)=>t.connectDevice(s,a),setAutoConnectExcluded:(s,a)=>t.setAutoConnectExcluded(s,a)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}
|
|
3
|
+
export{lm as A,ap as a,Aa as b,nt as c,no as d,io as e,oo as f,ro as g,ot as h,rt as i,us as j,_e as k,$ as l,X as m,zn as n,qn as o,Fe as p,Be as q,Qn as r,ys as s,vs as t,Cs as u,Ha as v,Ua as w,$n as x,Vn as y,Dn as z};
|