@urun-sh/core 0.6.29 → 0.6.30

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.
@@ -32,4 +32,4 @@ self.onrtctransform = (event) => {
32
32
  self.postMessage({ type: 'err', detail: String(e) }))
33
33
  }
34
34
  }
35
- `;Xn=class{constructor(e){this.sink=e}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=mm(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&this.engage(t)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let r;try{r=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let s=this.sendPc.addTrack(e);this.sender=s,this.currentTrack=e,this.wireTrackLiveness(e);let i=t.RTCRtpScriptTransform;if(s.transform=new i(r,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(o=>this.die(`loopback renegotiate: ${o instanceof Error?o.message:String(o)}`));return}this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let s=r.transceiver?.mid??null;s!==null&&s===this.renderMidOf()&&this.renderRemoteCb?.(r.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let r=await e.createOffer();r.sdp=Od(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let s=await t.createAnswer();s.sdp=Od(s.sdp??""),await t.setLocalDescription(s),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:s.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let r=t.context.createMediaStreamDestination();t.connect(r);let s=r.stream.getAudioTracks()[0]??null;return s?(this.nodeBridge={node:t,dest:r},s):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([fm],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let r=t.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let r=Bi(this.frameSeq,e,t,this.sink.maxDatagramSize()||Tr);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}}});function bm(n){return Math.round(n*(gm/1e6))%2**32>>>0}var gm,_m,vm,wm,ym,Zn,Ud=W(()=>{"use strict";ft();Hi();gm=9e4,_m="avc1.42E01F",vm=60,wm=3,ym=1e4;Zn=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let s=++this.generation,i=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,i.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&s===this.generation;){let{value:a,done:c}=await i.read();if(c)break;if(a){if(o||this.stopped||s!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&s===this.generation&&this.die(`capture: ${a instanceof Error?a.message:String(a)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(e){let t={width:e.codedWidth,height:e.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==t.width||this.encoderDims.height!==t.height){let i=globalThis.VideoEncoder;if(typeof i!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new i({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:_m,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(o){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let s=this.keyframeWanted||this.framesSinceKeyframe>=vm;this.keyframeWanted=!1,this.framesSinceKeyframe=s?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:s})}catch(i){this.onEncoderError(i instanceof Error?i:new Error(String(i)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=Bi(this.frameSeq,bm(e.timestamp),t,this.sink.maxDatagramSize()||Tr,{lane:Cd,keyframe:e.type==="key"});if(r===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(r=>t-r<ym),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=wm){this.die(`video encoder: ${e.message}`);return}console.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",e.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(e){this.stopped||(console.warn(`[urun] WT video uplink lane dead (${e}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}}});function Sm(n){return n.byteLength>=2&&n[0]===1&&n[1]===3}var es,Nd=W(()=>{"use strict";es=class{constructor(e){this.transport=e}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(e){this.deadCb=e}send(e,t){let r=new TextEncoder().encode(e);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let i=this.streams.get(e);if(!i){let a=await this.transport.openUniStream(),c=new Uint8Array(2+r.byteLength);c[0]=1,c[1]=r.byteLength,c.set(r,2),await a.write(c),i={writer:a},this.streams.set(e,i)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await i.writer.write(o),Sm(t)&&(this.streams.delete(e),await i.writer.close().catch(()=>{}))}catch(i){throw this.die(i instanceof Error?i.message:String(i)),i}});return this.chain=s.catch(()=>{}),s}stop(e="stopped"){if(this.dead===null){this.dead=e;for(let t of this.streams.values())t.writer.close().catch(()=>{});this.streams.clear()}}die(e){this.dead===null&&(console.warn(`[urun] WT data uplink lane dead (${e})`),this.stop(e),this.deadCb?.(e))}}});var Wd,km,Tm,Rm,Cm,Em,Pm,Dm,xm,Fd,Im,Am,Vi,ts,$d=W(()=>{"use strict";ft();Dd();xd();Ad();ft();Md();Hi();Ud();Nd();Wd=250,km=25,Tm=2e3,Rm=15e3,Cm=1e3,Em=45e3,Pm=5e3,Dm={llm:!0},xm=500,Fd=10,Im=2,Am=2,Vi=2,ts=class n{constructor(e,t,r,s,i,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=s;this.audioUplink=i;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((c,d)=>{this.firstFrameResolve=c,this.firstFrameReject=d}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new Yn({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,r=t!==void 0&&t!=="";this.hasVideoLane=r,r&&Fi(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(l=>({algorithm:"sha-256",value:Uint8Array.from(atob(l),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let s=await this.wt.createBidirectionalStream();this.writer=s.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=s.readable.getReader(),o=new zn,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let d=c;if(this.lastInboundControlAt=performance.now(),typeof d.pingIntervalMs=="number"&&d.pingIntervalMs>0?this.advertisedPingIntervalMs=d.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,console.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),r&&(Fi(d.codec,"hello-ack"),this.initDecoder(d.codec,d.width,d.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let l={setSource:p=>{this.renderSource=p,this.audioUplinkLane?.setRenderSource?.(p)},onRemote:p=>{this.renderRemoteCb=p}},u=new Jn(this.offer.audio,{...this.audioLane,renderHop:l});try{u.start(),this.audioPlayout=u}catch(p){console.warn(`[urun] WT audio lane failed to start (${p instanceof Error?p.message:String(p)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),u.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let l=this.wt.createUnidirectionalStream?.bind(this.wt);if(!l)throw new Error("WebTransport uni streams are not creatable in this environment");let u=new es({openUniStream:async()=>(await l()).getWriter()});u.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p,u)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(l){let u=l instanceof Error?l.message:String(l);console.warn(`[urun] WT data uplink failed to engage (${u}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(u)}this.controlLoop(i,o,a).catch(l=>this.die(`control loop: ${l}`)),this.datagramLoop().catch(l=>this.die(`datagram loop: ${l}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),xm)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(l=>{this.closedReason=`connection error: ${l}`,this.die(`connection error: ${l}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${Wd}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Rm},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Cm))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,r=typeof e.ur=="number"?e.ur:null;if(t===null&&r===null)return;this.gatewayExposesCounters=!0;let s=this.audioDgramsReceived,i=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:r,recvDownlink:s,sentUplink:i},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,c=r!==null&&o.ur!==null?r-o.ur:null,d=s-o.recvDownlink,l=i-o.sentUplink,u="none";if(a!==null&&a>=Fd&&d<=0?u="downlink":c!==null&&l>=Fd&&c<=0&&(u="uplink"),u==="none"){this.severedStreak="none",this.observePlayoutProgress(d,t);return}if(this.severedStreak!==u){this.severedStreak=u;return}this.severedStreak="none";let p=u==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${l} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+p+` (gateway flow counters ds=${t} ur=${r}, client received=${s} accepted=${i}, confirmed on ${Im} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let r=this.audioPlayout;if(!r){this.playoutScheduledSeen=null;return}let s=r.playoutProgress(),i=s.surfaced;if(this.playoutScheduledSeen!==null&&s.scheduled>this.playoutScheduledSeen&&i){this.playoutScheduledSeen=s.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=s.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Am)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,console.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${s.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{r.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=Vi}return}this.playoutStallStreak<Vi||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${s.scheduled} on ${Vi} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let r=performance.now(),s=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,i=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=s===null&&i===null?!0:(s===null||s>=e.stallMs)&&(i===null||i>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&i!==null&&i>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(i/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let c=!!(this.offer.audio&&this.audioLane),d=this.lastInboundDataAt===null?null:r-this.lastInboundDataAt,l=s!==null?s:this.firstInboundDataAt===null?null:r-this.firstInboundDataAt,u=l!==null&&l>=e.stallMs;if(c&&u&&d!==null&&d<=Pm&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((l??0)/1e3)}s while the data lane delivered a frame ${Math.round((d??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${t.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&i!==null&&i>=Em&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(i/1e3)}s while the path reports alive (${t.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e,t))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let s=this.audioUplinkLane;s?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,s??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let s=this.videoUplinkLane;s?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,s??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let t={onData:(r,s)=>{if(Dm[r]===!0){let i=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=i),this.lastInboundDataAt=i}e.onData(r,s)},onLaneError:r=>e.onLaneError(r)};this.dataLaneSink=t,Id(this.wt.incomingUnidirectionalStreams,t).catch(r=>{this.die(`data lane: ${r instanceof Error?r.message:String(r)}`)})}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r};let o=new s({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,i.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=this.decoderConfig;if(!t){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(t.codec,t.width,t.height),this.decoderErrorLogged=!1}catch(r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${r instanceof Error?r.message:String(r)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,s=>this.onUplinkSendError(s))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let r=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(s=>r-s<Tm),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<km)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let t=0;return{send:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Tr}}engageAudioUplink(){let e=new Xn(this.uplinkSink("audio"));e.onDead(t=>this.onUplinkLaneDead("audio",t,e)),e.onRenderTrack?.(t=>this.renderRemoteCb?.(t)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new Zn(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let t=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(r){let s=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${s}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,s)}}freshLaneBuilt(e){let t={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),t}onUplinkLaneDead(e,t,r){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let s=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,a=i?.builtAt!=null&&Date.now()-i.builtAt>=n.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(a>n.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${s} uplink lane dead (${t}) \u2014 ${n.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${n.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`,r);return}console.warn(`[urun] WT ${s} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${a}/${n.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let c={count:a,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=c:this.videoUplinkRetry=c,c.timer=setTimeout(()=>{c.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},n.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t,r){e==="audio"?this.audioUplink.onUplinkLost(t,r):this.videoUplink.onUplinkLost(t,r)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;if(t.byteLength>=ye&&t[11]===Gn){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;if(typeof s=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new s({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(Td(e)),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async sendControlRaw(e){try{let t=new Uint8Array(4+e.byteLength);new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),await this.writer.write(t),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&r.push(...t.push(i))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;let i=s;if(this.lastInboundControlAt=performance.now(),i.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(Rd(s.raw,"pong"))}catch{}}(i.t==="ping"||i.t==="pong")&&this.observeFlowCounters(i),i.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:i>0?100*s.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Wd)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}}});function Rr(n){if(n instanceof Error)return n.message;if(typeof n=="string")return n;if(n&&typeof n=="object"){try{let e=JSON.stringify(n);if(e!==void 0&&e!=="{}")return e}catch{}return n.constructor?.name??Object.prototype.toString.call(n).slice(8,-1)}return String(n)}function zi(n){if(n)try{return new URL(n).host}catch{return}}function Bd(n){if(!n)return"(no offer url)";try{let e=new URL(n);return e.searchParams.delete("token"),e.toString()}catch{return n.replace(/[?&]token=[^&\s]*/g,"")}}function Mm(n){if(!n)return!1;let e=n.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function Gi(n,e,t,r){if(r!==void 0)return r;let s=Math.min(n*2**Math.max(0,e-2),t);return Math.round(s*(.75+Math.random()*.5))}function Ki(n,e,t){return new Promise((r,s)=>{let i=setTimeout(()=>s(new Error(t)),e);n.then(o=>{clearTimeout(i),r(o)},o=>{clearTimeout(i),s(o)})})}var jd,qd,Lm,rs,Hd=W(()=>{"use strict";$d();jd=2500,qd=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Lm=1e4,rs=class n{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let t=this.session;!t||t.kind!=="webtransport"||t.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&r&&s,webcodecs:r,codecs:qd,wtData:t&&r&&s&&this.opts.dataLane!==void 0,wtAudio:t&&r&&s&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&s&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&r&&s&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&s&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i}),this.noteOfferedWtHost();let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let d=null;try{return d=this.createWebTransportSession(),await Ki(d.start(),this.opts.quicDeadlineMs??jd,"quic connect deadline"),this.wtDialedHost=zi(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(d,i.wtData===!0),this.session=d,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(l){if(console.warn(`[urun] WT dial failed (${Rr(l)}) \u2014 dialed ${Bd(this.offer.webtransport?.url)}`),d?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let u=String(l instanceof Error?l.message:l);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${u}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(u),l}console.warn("[urun] webtransport failed, falling back to webrtc:",l),this.proceedWebRtcDial(`wt failed: ${String(l instanceof Error?l.message:l)}`),this.notifyEstablished("webrtc",String(l instanceof Error?l.message:l))}}if(this.opts.allowWebRtcFallback===!1){let d=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${d} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(d),new Error(`[urun] WT required but unavailable: ${d}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}noteOfferedWtHost(){let e=zi(this.offer?.webtransport?.url);e===void 0||this.wtDialedHost===void 0||e===this.wtDialedHost||(this.wtHostMismatchCount+=1,console.error(`[urun] re-dial offered host ${e} != original host ${this.wtDialedHost}`+(Mm(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,s=this.opts.dataLane!==void 0,i=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:qd,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let d=this.createWebTransportSession();try{await Ki(d.start(),this.opts.quicDeadlineMs??jd,"quic connect deadline")}catch(l){throw console.warn(`[urun] WT dial failed (${Rr(l)}) \u2014 dialed ${Bd(this.offer.webtransport?.url)}`),d.stop().catch(()=>{}),l}if(this.wtDialedHost=zi(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==r)return d.stop().catch(()=>{}),null;try{this.engageQuicDataLane(d,s)}catch(l){throw d.stop().catch(()=>{}),l}if(this.disconnected)return d.stop().catch(()=>{}),null;this.session=d;{let l=this.offer.webtransport;l&&(this.opts.audioLane===void 0||l.audio!==void 0)&&(this.opts.audioUplink===void 0||l.audioUp===!0)&&(this.opts.videoUplink===void 0||l.videoUp===!0)&&(this.opts.dataLane===void 0||l.data===!0)&&(this.opts.dataUplink===void 0||l.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),d}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(s,i)=>r.onData(s,i),onLaneError:s=>r.onLaneError(s)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new ts(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t,!0);return}let r=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),r){this.session=null,this.wtOnlyLeg=!1,console.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",t),this.redialWtAfterDeath(t,!0);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,r)})}redialWtAfterDeath(e,t=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=n.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${n.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}console.error(`[urun] WT re-dial failed ${n.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let r=this.wtRedialFailures+1,s=Gi(n.WT_REDIAL_BASE_MS,r,n.WT_REDIAL_CAP_MS,r===1&&t?0:void 0);console.warn(`[urun] WT re-dial attempt ${r} scheduled in ${Math.round(s)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},s)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){console.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let r=Rr(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX} failed (${r}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${r}`)}}}lateWebRtcFailover(e,t,r){this.disconnected||(async()=>{let s=this.createWebRtc();try{let i=await Ki(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??Lm,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(i){if(s.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=r?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}}});var Om,ns,Vd=W(()=>{"use strict";On();Om=1e4,ns=class{constructor(e,t=Om){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=Vt();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:d,requestId:l,...u}=c;s(u)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(o),a(),i(new Error(`[urun] signaling request not sent: ${e} \u2014 the signaling socket is not open`)))})}notify(e,t){this.carrier.sendSignal({type:e,...t})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${e} \u2014 the signaling socket is not open`,detail:{method:e}})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}}});var Um,ss,zd=W(()=>{"use strict";Um="video",ss=class{constructor(e,t=Um){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}}});function Kd(n){let e=n;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Gd=W(()=>{"use strict"});async function Fm(n,e,t){let s=e?.current()?.name??null;if(s==="live")return"live";if(s==="error")return"gone";if(s==="idle"||s==="connecting")return"live";if(!e)return"unconfirmed";let i=e,o=t.runtimeWaitCapMs??Wm;return new Promise(a=>{let c=!1,d,l=null,u=null,p=!1,f=_=>{c||(c=!0,m(),u!==null&&(clearTimeout(u),u=null),d?.(),a(_))};u=setTimeout(()=>{if(p||c||t.isDisposed())return;p=!0;let _=i.current();n.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${t.sessionId} (server status: ${_?.reason??_?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let h=()=>{l===null&&!c&&(l=setTimeout(()=>f("unconfirmed"),o))},m=()=>{l!==null&&(clearTimeout(l),l=null)};d=e.subscribe(_=>{let v=_?.name;if(v==="live")return f("live");if(v==="error")return f("gone");m(),nt(v)||h()}),nt(s)||h()})}function Qd(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=n.holdWebRtcDial?.(),a=s.createElement("canvas"),c=!1,d=null,l=!1,u=()=>{if(d){for(let P of d.getVideoTracks())try{P.stop()}catch{}d=null}l&&(l=!1,t.onOverrideTrack(null))},p=new rs(new ns(n),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new ss(n,t.streamName??Nm)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(P,N)=>n.dispatchQuicStreamData(P,N),onQuicLane:()=>n.markStreamDataLaneQuic(),onQuicLaneLost:P=>n.quicStreamDataLaneLost(P),onLaneError:P=>n.raiseQuicStreamDataError(P)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:P=>{c||(P&&n.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(P))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>w(),onMediaTransportLost:P=>{c||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(P),w())},onTransportChange:(P,N)=>{c||(P==="webrtc"&&(u(),w()),t.onTransportChange?.(P,N))}}),f=n.onWtOnlyLegDeath?.(P=>p.failCurrentWtLeg(P)),g=null,h=()=>{g!==null&&(clearInterval(g),g=null)},m=t.wtRetryBaseMs??2e3,_=t.wtRetryCapMs??3e4,v=null,S=0,w=()=>{if(c||v!==null||p.activeTransport==="webtransport")return;let P=Gi(m,S+2,_);v=setTimeout(()=>{v=null,S+=1,p.retryWebTransport().then(N=>{if(c){N&&p.disconnect().catch(()=>{});return}if(N)return console.debug(`[urun] webtransport upgraded in background (retry ${S})`),S=0,T(N);w()}).catch(N=>{c||(console.debug(`[urun] webtransport background retry ${S} failed: `+Rr(N)),w())})},P)},b=()=>{v!==null&&(clearTimeout(v),v=null)},T=async P=>{if(c||P.kind!=="webtransport")return;let N=t.pathHealthProbeMs??1e4;h();let G=!1;g=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let $=Kd(P);if(!$){console.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),h();return}let j=$.pathLiveness();if(!j.alive){let Y=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${j.evidence}`+(Y?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),h(),$.fail(`path health: ${j.evidence}`);return}if(!G){if(G=!0,p.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${N}ms \u2014 the QUIC PATH IS HEALTHY (${j.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${N}ms \u2014 no media datagrams reached this client (path healthy: ${j.evidence}); webrtc track remains authoritative`)}},N);try{await P.firstMedia}catch($){h(),console.debug("[urun] webtransport ended before any media flowed:",$);return}if(h(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;d=a.captureStream();let ne=d.getVideoTracks()[0];ne&&(l=!0,t.onOverrideTrack(ne))},y=!1;return(async()=>{let P=await Fm(n,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>c});if(c)return;if(P==="gone"){console.debug(`[urun] session ${e} ended while waiting for a runtime to pick it up \u2014 no media negotiation`),o?.proceed("session ended before a runtime was pulled \u2014 releasing the held WebRTC dial");return}y=!0;let N=await p.connect();if(c){p.disconnect().catch(()=>{});return}await T(N)})().catch(P=>{if(h(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",P);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",P),w();return}o?.proceed(`negotiation unavailable: ${P instanceof Error?P.message:String(P)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",P),w()}),{activeTransport:()=>p.activeTransport,mediaTransportAttempted:()=>y,watchDownlinkStall(P){p.watchDownlinkStall(P)},dispose(){c=!0,f?.(),h(),b(),u(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var Nm,Wm,Yd=W(()=>{"use strict";Hd();Vd();Or();zd();Gd();Nm="video",Wm=45e3});function Ji(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function Vm(n){return`${Hm}:${n}`}function Qi(){return Vt()}function zm(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function Km(n,e,t,r,s,i,o,a,c,d){let l=[],u=null,p=!1,f=null,g=!1,h,m,_=new Promise((k,F)=>{h=k,m=F});_.catch(()=>{});let v=o(),S=null,w=null,b=null,T=null,y=null,P=null,N=!0,G=()=>{b&&(clearTimeout(b),b=null),T&&(T(),T=null)},ne=()=>{y&&(clearTimeout(y),y=null),P&&(P(),P=null)},$=!1,j=()=>{$||!g||($=!0,n.set({rpc:{[e]:null}}))},Y=()=>{N=!1,G(),ne(),S?.(),S=null,w?.(),w=null,a?.removeEventListener("abort",U),v.dispose(),j()},Z=()=>{if(u){if(l.length>0){let k=u;u=null,k.resolve({value:l.shift(),done:!1})}else if(f!==null){let k=u;u=null,k.reject(f)}else if(p){let k=u;u=null,k.resolve({value:void 0,done:!0})}}},he=k=>{p||(l.push(k),Z())},ee=k=>{p||(f=k,p=!0,m(k),Y(),Z())},D=k=>{p||(p=!0,h(k),Y(),Z())},U=()=>{let k=a?.reason;ee(k instanceof je?k:new Gt(e))},B=k=>{if(!(p||!k||typeof k!="object"))switch(ne(),j(),k.t){case"delta":typeof k.delta=="string"&&he(k.delta);break;case"response":D(k.body);break;case"error":{let{message:F,code:Ge}=zm(k.body);ee(new je(F,{requestId:e,code:k.code??Ge}));break}}},te=()=>{let k=v.messages()[Symbol.asyncIterator]();S=()=>{k.return?.(void 0)};let F=()=>{N&&k.next().then(Ge=>{if(N){if(Ge.done){p||D(void 0);return}B(Ge.value),F()}},Ge=>{N&&ee(Ge)})};F()},E=()=>{if(!g){if(g=!0,a){if(a.aborted){ee(new Gt(e));return}a.addEventListener("abort",U,{once:!0})}w=c?.(k=>ee(k))??null,te(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),d&&d>0&&!n.synced&&(b=setTimeout(()=>{b=null,!p&&!n.synced&&ee(new xr(d,e))},d),T=n.onSynced(()=>G())),P=n.onSynced(()=>{P=null,!(p||$||y)&&(y=setTimeout(()=>{y=null,!(p||$)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(Jd/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},Jd))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(E(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(f!==null){let k=f;return f=null,Promise.reject(k)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((k,F)=>{u={resolve:k,reject:F}})},return(){return p||(p=!0,h(void 0),Y()),Promise.resolve({value:void 0,done:!0})},throw(k){return p||(p=!0,m(k),Y()),Promise.reject(k)}}}},body:_,start:E}}function Xd(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Gm(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=Xd(i);c&&(a.rt=c);let d=Xd(o);return d&&(a.br=d),a}var $m,jm,qm,Bm,Jd,Hm,Yi,is,Zd=W(()=>{"use strict";Or();po();Uo();No();Ii();Pr();bt();ad();qn();dd();ud();fd();gd();Ni();Fn();wt();Xe();On();kd();Yd();$m=new Set;jm="rpc",qm="$presence",Bm=3e4,Jd=3e4,Hm="rpc-resp";Yi=class{constructor(e,t,r,s,i){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=i;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,i=null,o={push(c){if(!s)if(r){let d=r;r=null,d.resolve({value:c,done:!1})}else t.push(c)},end(){if(s=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{s=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||s)&&(i=e._streamConsumeUnavailableError(c),a(),r)){let d=r;r=null,d.reject(i)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):i?Promise.reject(i):s?Promise.resolve({value:void 0,done:!0}):new Promise((c,d)=>{r={resolve:c,reject:d}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let s of r)s(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Gm(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Ir(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??bd;return Sd(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},is=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new $n;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,s,i,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=Oc(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=_d(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=hd({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new Vn({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(qm).awareness.setLocalState({role:"client"}),this._activation=new Ur({onPhase:a=>this.onPhase(a),hint:()=>this.doc(co).get(lo)??this.doc("control").get(uo),onData:(a,c)=>this._streamData.onData(a,c)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await Io({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new gt,o=new Kt({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,Ji(t),tr({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),Ze()&&await vt();let c=t.getAccessToken,d=c?async()=>await c()??s:s;return a.setDocTransport({wsUrl:r.wsUrl,token:d}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return ao(this,e)}on(e,t){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(t),this._generationTickStop||(this._generationTickStop=ld(this.doc("control"),r=>{for(let s of Array.from(this._generationTickHandlers))try{s(r)}catch(i){console.warn("[urun] generationTick handler failed:",i)}})),()=>{this._generationTickHandlers.delete(t),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new zr(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new er(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new er(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Yi(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Hn(e,this._sessionId,$m.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=cd(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=jn(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",s=`${t}\0${r}\0${this._sessionId}`;s!==this._docEndpointKey&&(this._docEndpointKey=s,this.connectDocs(id({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=Qi(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;i=setTimeout(()=>s.abort(new Dr(c,r)),c)}let o=this._consumeResponse(r,e,!1,s.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,t,r,s,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(jm),a=Vm(e);return Km(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??Bm)}requestStream(e,t={}){let r=Qi();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Qi(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Qd(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,runtimePhase:{current:()=>this._transport.phase??null,subscribe:t=>this._transport.on("phase",t)},onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}get mediaTransportAttempted(){return this._dialNegotiation?.mediaTransportAttempted()??!1}watchDownlinkStall(e={}){return this._downlinkStallWatch=e,this._dialNegotiation?.watchDownlinkStall(e),()=>{this._downlinkStallWatch=null}}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new Je)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Je);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let s of t)try{s()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let r=Array.from(this._activeRequests);this._activeRequests.clear();for(let s of r)try{s(new Lr)}catch{}for(let s of this._docs.values())s.dispose();this._docs.clear();for(let s of this._streams.values())s.dispose();this._streams.clear(),this._transport.disconnect(e)}}});function el(n){return`urun:session:v2:${n.orgId}:${n.app}:${n.functionName}`}function Xi(){try{return globalThis.sessionStorage??null}catch{return null}}function os(n){if(!n)return;let e=n.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof r?.sub=="string"&&r.sub.length>0?r.sub:void 0}catch{return}}function Qm(n,e){return n!==void 0&&e!==void 0&&n!==e}function eo(n,e){let t=Xi(),r=null;if(t)try{let i=t.getItem(n);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(r={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{r=null}let s=Zi.get(n)??r??null;return!s||Qm(s.actor,e)?null:s}function tl(n,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};Zi.set(n,t);let r=Xi();if(r)try{r.setItem(n,JSON.stringify(t))}catch{}}function as(n){Zi.delete(n);let e=Xi();if(e)try{e.removeItem(n)}catch{}}var Zi,rl=W(()=>{"use strict";Zi=new Map});function sl(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function Jm(n){if(typeof n?.id!="string"||n.id.length===0)throw new Ee("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof n.state!="string"||!nl.has(n.state))throw new Ee(`[urun] session ${n.id} reported an unrecognized state ${JSON.stringify(n.state)} \u2014 this @urun-sh/core build knows only ${[...nl].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof n.recordings_expired=="boolean"?e=n.recordings_expired:console.warn(`[urun] session ${n.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:n.id,label:typeof n.label=="string"&&n.label.length>0?n.label:null,state:n.state,app:typeof n.app=="string"?n.app:"",functionName:typeof n.function=="string"?n.function:"",createdAt:sl(n.created_at),lastActiveAt:sl(n.last_active_at),archived:n.archived===!0,preview:typeof n.preview=="string"&&n.preview.length>0?n.preview:null,recordingsExpired:e,retention:Ym.has(n.retention)?n.retention:(n.retention!==void 0&&console.warn(`[urun] session ${n.id} reported an unrecognized retention ${JSON.stringify(n.retention)} \u2014 defaulting to '24h'`),"24h")}}var nl,Ym,cs,il=W(()=>{"use strict";Xe();bt();nl=new Set(["paused","acquiring","live"]),Ym=new Set(["24h","keep"]);cs=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await Po({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(Jm),nextCursor:r}}async end(e){await Do({...this._request,sessionId:e})}async archive(e){await ys({...this._request,sessionId:e,archived:!0})}async unarchive(e){await ys({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await xo({...this._request,sessionId:e,name:t,source:r.source})}}});var al={};ls(al,{App:()=>eg,sessionDirectory:()=>Zm});function ol(n,e,t){let r=os(t);tl(n,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}function Zm(n,e){return new cs(n,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function eg(n,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,r){if(!(Xm.has(r)||typeof r!="string"))return(s,i)=>{let o=s??{},a=el({orgId:e.orgId,app:n,functionName:r}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,d,l=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,u=l(),p=e.jwt,f=e.getAccessToken?async D=>{let U=await e.getAccessToken(D);return U&&(p=U),U}:void 0,g={...e,getAccessToken:f},h=new gt,m=new Kt({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:u,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),_=new is(u,h,m,Ji(g),tr(g),{activity:i?.activity}),v,S=!1,w=!1,b,T,y=new Promise(D=>{T=D}),P,N=D=>{D.sessionId||b||(b="teardown",P="ticket",gs({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},G=D=>{b||D.sessionId||(b="abandon",gs({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider,reason:"client_abandoned"}))},ne=D=>{let U=D.sessionId||!d?D:{...D,sessionId:d};v=U,T({status:"ready",handle:U}),(w||b==="teardown")&&N(U)};_.setEndHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Je("[urun] session allocation failed before a releasable request was created",{cause:D.cause});let U=v??D.handle;return as(a),b==="teardown"?U.sessionId?{status:"paused",sessionId:U.sessionId,reason:"client_ended"}:{status:"canceled",requestId:U.requestId}:(b="end",U.sessionId?vs({baseUrl:U.baseUrl,sessionId:U.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):_s({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Je("[urun] session allocation failed before a cancellable request was created",{cause:D.cause});let U=v??D.handle;if(U.sessionId)throw new ge(`[urun] cancel() is for a queued admission request, but this call already has session ${U.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:U.sessionId,code:"cancel_on_live_session"});b="end";try{let B=await _s({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return as(a),B}catch(B){throw b==="end"&&(b=void 0),B}});let $=async D=>{let U,B=i?.sessionId??e.sessionKey??d,te,E;if(B===void 0&&!c){let Ce=eo(a);if(Ce?.sessionId){if(E=os(p),Ce.actor!==void 0&&E===void 0&&f){let ds=await Promise.resolve(f()).catch(()=>{});E=os(ds??e.jwt)}te=Ce.actor!==void 0&&E!==void 0&&Ce.actor!==E?void 0:Ce.sessionId}}let q=B??te,k=(Ce,ds)=>Eo({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:Ce,sessionKey:ds,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:Qe=>{m.reportAdmission(Qe),Qe.sessionId&&!d&&(d=Qe.sessionId,U=Qe.sessionId,v&&v.sessionId!==Qe.sessionId&&ne({...v,sessionId:Qe.sessionId}),S||(e.sessionKey||ol(a,Qe.sessionId,p),_.setSessionId(Qe.sessionId)))},onRequest:ne}),F;try{F=await k(D,q)}catch(Ce){if(te===void 0||!(Ce instanceof Q)||Ce.code!=="session_name_not_yours")throw Ce;console.warn(`[urun] session_name_not_yours: the control plane refused session ${te} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),eo(a,E)?.sessionId===te&&as(a),F=await k(l(),void 0)}let Ge=f?await f()??void 0:e.jwt;if(U&&U!==F.sessionId)throw v&&v.sessionId!==F.sessionId&&ne({...v,sessionId:F.sessionId}),new Q(`Gateway contract violation: admission minted session ${U} but allocation completed as ${F.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return d=F.sessionId,v&&v.sessionId!==F.sessionId&&ne({...v,sessionId:F.sessionId}),S||(e.sessionKey||ol(a,F.sessionId,p),_.setSessionId(F.sessionId),_.setArtifactsAuth(tr({...g,baseUrl:F.baseUrl})),m.setEndsAt(F.endsAt),m.seedRegion(bs(F.response))),{url:F.wsUrl,sessionId:F.sessionId,jwt:Ge,iceServers:F.response.ice_servers,endsAt:F.endsAt}},j,Y=0,Z=f?async()=>{let D=Y++>0;return await f(D?{forceRefresh:!0,reason:"background"}:void 0)??j}:()=>j,he=()=>{let D=m.connectedUrl;return D?jn(D):void 0};if(m.setConnectionResolver(async()=>{let D=await $(l());return j=D.jwt,D}),m.on("connected",()=>{m.multiplexer&&h.setTarget(m.multiplexer);let D=m.connectedUrl;D&&_.setDocTransport({wsUrl:D,token:Z,resolveServerUrl:he})}),(async D=>{let U;try{U=await $(D)}catch(B){if(S){T({status:"unavailable",cause:B});return}console.error(`[urun] Failed to create session for ${r}:`,B),v&&G(v);let te=B instanceof Error?B:new Error(String(B)),E=B instanceof Q?B.httpStatus:void 0,q=B instanceof Q?B.code:void 0,k=B instanceof Q?B.retryAfterSeconds:void 0;m.reportAllocationFailure(te,E,q,k),T({status:"unavailable",cause:B});return}S||(m.setAuth({jwt:U.jwt,authProvider:e.authProvider,orgId:e.orgId}),m.setConnection({url:U.url,sessionId:U.sessionId,iceServers:U.iceServers}),Ze()&&await vt(),j=U.jwt,_.setDocTransport({wsUrl:U.url,token:Z,resolveServerUrl:he}),await m.connect({app:n,functionName:r,args:o}),_.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(u).catch(D=>{console.error(`[urun] Failed to connect session for ${r}:`,D)}),e.releaseOnLeave!==!1){let D=vd(()=>{if(S=!0,m.leaveLeg())return;if(m.connectedUrl!==null){m.disconnect();return}m.disconnect();let q=v;q?N(q):w=!0});_.onDisconnect(D);let U,B,te=!1,E=()=>{te||(te=!0,U?.(),B?.())};y.then(q=>{q.status!=="ready"||te||(U=wd(()=>v!==void 0))}),B=_.onPhase(q=>{let k=q?.name;(k==="paused"||k==="error")&&E()}),te&&B(),_.onDisconnect(E)}return _}}})}var Xm,cl=W(()=>{"use strict";Pr();Zd();Ii();bt();Xe();wt();qn();Ni();rl();il();Xm=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive])});var ng={};ls(ng,{createSessionResolver:()=>dl});module.exports=ro(ng);var tg="serve";function dl(n,e){let t=`[urun/${e.adapter}]`,r=n.baseUrl!==void 0||n.orgId!==void 0||n.app!==void 0||n.functionName!==void 0;if(n.session&&r)throw new Error(`${t} pass EITHER a \`session\` (BYO) OR connection settings (\`baseUrl\`/\`orgId\`/\`app\`) \u2014 not both.`);let s,i=()=>{if(n.session){let d=n.session;return Promise.resolve(typeof d=="function"?d():d)}let{baseUrl:o,orgId:a,app:c}=n;if(!o||!a||!c)throw new Error(`${t} missing connection settings: \`baseUrl\`, \`orgId\` and \`app\` are required (or pass a \`session\`).`);return rg({...n,baseUrl:o,orgId:a,app:c})};return()=>s??=i()}async function rg(n){let{App:e}=await Promise.resolve().then(()=>(cl(),al)),t=e(n.app,{baseUrl:n.baseUrl,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}),r=n.functionName??tg;return t[r]()}0&&(module.exports={createSessionResolver});
35
+ `;Xn=class{constructor(e){this.sink=e}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=mm(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&this.engage(t)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let r;try{r=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let s=this.sendPc.addTrack(e);this.sender=s,this.currentTrack=e,this.wireTrackLiveness(e);let i=t.RTCRtpScriptTransform;if(s.transform=new i(r,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(o=>this.die(`loopback renegotiate: ${o instanceof Error?o.message:String(o)}`));return}this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let s=r.transceiver?.mid??null;s!==null&&s===this.renderMidOf()&&this.renderRemoteCb?.(r.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let r=await e.createOffer();r.sdp=Od(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let s=await t.createAnswer();s.sdp=Od(s.sdp??""),await t.setLocalDescription(s),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:s.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let r=t.context.createMediaStreamDestination();t.connect(r);let s=r.stream.getAudioTracks()[0]??null;return s?(this.nodeBridge={node:t,dest:r},s):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([fm],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let r=t.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let r=Bi(this.frameSeq,e,t,this.sink.maxDatagramSize()||Tr);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}}});function bm(n){return Math.round(n*(gm/1e6))%2**32>>>0}var gm,_m,vm,wm,ym,Zn,Ud=W(()=>{"use strict";ft();Hi();gm=9e4,_m="avc1.42E01F",vm=60,wm=3,ym=1e4;Zn=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let s=++this.generation,i=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,i.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&s===this.generation;){let{value:a,done:c}=await i.read();if(c)break;if(a){if(o||this.stopped||s!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&s===this.generation&&this.die(`capture: ${a instanceof Error?a.message:String(a)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(e){let t={width:e.codedWidth,height:e.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==t.width||this.encoderDims.height!==t.height){let i=globalThis.VideoEncoder;if(typeof i!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new i({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:_m,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(o){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let s=this.keyframeWanted||this.framesSinceKeyframe>=vm;this.keyframeWanted=!1,this.framesSinceKeyframe=s?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:s})}catch(i){this.onEncoderError(i instanceof Error?i:new Error(String(i)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=Bi(this.frameSeq,bm(e.timestamp),t,this.sink.maxDatagramSize()||Tr,{lane:Cd,keyframe:e.type==="key"});if(r===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(r=>t-r<ym),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=wm){this.die(`video encoder: ${e.message}`);return}console.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",e.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(e){this.stopped||(console.warn(`[urun] WT video uplink lane dead (${e}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}}});function Sm(n){return n.byteLength>=2&&n[0]===1&&n[1]===3}var es,Nd=W(()=>{"use strict";es=class{constructor(e){this.transport=e}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(e){this.deadCb=e}send(e,t){let r=new TextEncoder().encode(e);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let i=this.streams.get(e);if(!i){let a=await this.transport.openUniStream(),c=new Uint8Array(2+r.byteLength);c[0]=1,c[1]=r.byteLength,c.set(r,2),await a.write(c),i={writer:a},this.streams.set(e,i)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await i.writer.write(o),Sm(t)&&(this.streams.delete(e),await i.writer.close().catch(()=>{}))}catch(i){throw this.die(i instanceof Error?i.message:String(i)),i}});return this.chain=s.catch(()=>{}),s}stop(e="stopped"){if(this.dead===null){this.dead=e;for(let t of this.streams.values())t.writer.close().catch(()=>{});this.streams.clear()}}die(e){this.dead===null&&(console.warn(`[urun] WT data uplink lane dead (${e})`),this.stop(e),this.deadCb?.(e))}}});var Wd,km,Tm,Rm,Cm,Em,Pm,Dm,xm,Fd,Im,Am,Vi,ts,$d=W(()=>{"use strict";ft();Dd();xd();Ad();ft();Md();Hi();Ud();Nd();Wd=250,km=25,Tm=2e3,Rm=15e3,Cm=1e3,Em=45e3,Pm=5e3,Dm={llm:!0},xm=500,Fd=10,Im=2,Am=2,Vi=2,ts=class n{constructor(e,t,r,s,i,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=s;this.audioUplink=i;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((c,d)=>{this.firstFrameResolve=c,this.firstFrameReject=d}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new Yn({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,r=t!==void 0&&t!=="";this.hasVideoLane=r,r&&Fi(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(l=>({algorithm:"sha-256",value:Uint8Array.from(atob(l),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let s=await this.wt.createBidirectionalStream();this.writer=s.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=s.readable.getReader(),o=new zn,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let d=c;if(this.lastInboundControlAt=performance.now(),typeof d.pingIntervalMs=="number"&&d.pingIntervalMs>0?this.advertisedPingIntervalMs=d.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,console.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),r&&(Fi(d.codec,"hello-ack"),this.initDecoder(d.codec,d.width,d.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let l={setSource:p=>{this.renderSource=p,this.audioUplinkLane?.setRenderSource?.(p)},onRemote:p=>{this.renderRemoteCb=p}},u=new Jn(this.offer.audio,{...this.audioLane,renderHop:l});try{u.start(),this.audioPlayout=u}catch(p){console.warn(`[urun] WT audio lane failed to start (${p instanceof Error?p.message:String(p)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),u.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let l=this.wt.createUnidirectionalStream?.bind(this.wt);if(!l)throw new Error("WebTransport uni streams are not creatable in this environment");let u=new es({openUniStream:async()=>(await l()).getWriter()});u.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p,u)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(l){let u=l instanceof Error?l.message:String(l);console.warn(`[urun] WT data uplink failed to engage (${u}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(u)}this.controlLoop(i,o,a).catch(l=>this.die(`control loop: ${l}`)),this.datagramLoop().catch(l=>this.die(`datagram loop: ${l}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),xm)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(l=>{this.closedReason=`connection error: ${l}`,this.die(`connection error: ${l}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${Wd}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Rm},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Cm))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,r=typeof e.ur=="number"?e.ur:null;if(t===null&&r===null)return;this.gatewayExposesCounters=!0;let s=this.audioDgramsReceived,i=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:r,recvDownlink:s,sentUplink:i},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,c=r!==null&&o.ur!==null?r-o.ur:null,d=s-o.recvDownlink,l=i-o.sentUplink,u="none";if(a!==null&&a>=Fd&&d<=0?u="downlink":c!==null&&l>=Fd&&c<=0&&(u="uplink"),u==="none"){this.severedStreak="none",this.observePlayoutProgress(d,t);return}if(this.severedStreak!==u){this.severedStreak=u;return}this.severedStreak="none";let p=u==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${l} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+p+` (gateway flow counters ds=${t} ur=${r}, client received=${s} accepted=${i}, confirmed on ${Im} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let r=this.audioPlayout;if(!r){this.playoutScheduledSeen=null;return}let s=r.playoutProgress(),i=s.surfaced;if(this.playoutScheduledSeen!==null&&s.scheduled>this.playoutScheduledSeen&&i){this.playoutScheduledSeen=s.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=s.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Am)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,console.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${s.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{r.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=Vi}return}this.playoutStallStreak<Vi||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${s.scheduled} on ${Vi} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let r=performance.now(),s=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,i=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=s===null&&i===null?!0:(s===null||s>=e.stallMs)&&(i===null||i>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&i!==null&&i>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(i/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let c=!!(this.offer.audio&&this.audioLane),d=this.lastInboundDataAt===null?null:r-this.lastInboundDataAt,l=s!==null?s:this.firstInboundDataAt===null?null:r-this.firstInboundDataAt,u=l!==null&&l>=e.stallMs;if(c&&u&&d!==null&&d<=Pm&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((l??0)/1e3)}s while the data lane delivered a frame ${Math.round((d??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${t.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&i!==null&&i>=Em&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(i/1e3)}s while the path reports alive (${t.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e,t))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let s=this.audioUplinkLane;s?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,s??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let s=this.videoUplinkLane;s?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,s??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let t={onData:(r,s)=>{if(Dm[r]===!0){let i=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=i),this.lastInboundDataAt=i}e.onData(r,s)},onLaneError:r=>e.onLaneError(r)};this.dataLaneSink=t,Id(this.wt.incomingUnidirectionalStreams,t).catch(r=>{this.die(`data lane: ${r instanceof Error?r.message:String(r)}`)})}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r};let o=new s({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,i.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=this.decoderConfig;if(!t){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(t.codec,t.width,t.height),this.decoderErrorLogged=!1}catch(r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${r instanceof Error?r.message:String(r)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,s=>this.onUplinkSendError(s))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let r=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(s=>r-s<Tm),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<km)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let t=0;return{send:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Tr}}engageAudioUplink(){let e=new Xn(this.uplinkSink("audio"));e.onDead(t=>this.onUplinkLaneDead("audio",t,e)),e.onRenderTrack?.(t=>this.renderRemoteCb?.(t)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new Zn(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let t=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(r){let s=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${s}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,s)}}freshLaneBuilt(e){let t={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),t}onUplinkLaneDead(e,t,r){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let s=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,a=i?.builtAt!=null&&Date.now()-i.builtAt>=n.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(a>n.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${s} uplink lane dead (${t}) \u2014 ${n.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${n.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`,r);return}console.warn(`[urun] WT ${s} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${a}/${n.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let c={count:a,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=c:this.videoUplinkRetry=c,c.timer=setTimeout(()=>{c.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},n.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t,r){e==="audio"?this.audioUplink.onUplinkLost(t,r):this.videoUplink.onUplinkLost(t,r)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;if(t.byteLength>=ye&&t[11]===Gn){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;if(typeof s=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new s({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(Td(e)),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async sendControlRaw(e){try{let t=new Uint8Array(4+e.byteLength);new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),await this.writer.write(t),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&r.push(...t.push(i))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;let i=s;if(this.lastInboundControlAt=performance.now(),i.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(Rd(s.raw,"pong"))}catch{}}(i.t==="ping"||i.t==="pong")&&this.observeFlowCounters(i),i.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:i>0?100*s.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Wd)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}}});function Rr(n){if(n instanceof Error)return n.message;if(typeof n=="string")return n;if(n&&typeof n=="object"){try{let e=JSON.stringify(n);if(e!==void 0&&e!=="{}")return e}catch{}return n.constructor?.name??Object.prototype.toString.call(n).slice(8,-1)}return String(n)}function zi(n){if(n)try{return new URL(n).host}catch{return}}function Bd(n){if(!n)return"(no offer url)";try{let e=new URL(n);return e.searchParams.delete("token"),e.toString()}catch{return n.replace(/[?&]token=[^&\s]*/g,"")}}function Mm(n){if(!n)return!1;let e=n.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function Gi(n,e,t,r){if(r!==void 0)return r;let s=Math.min(n*2**Math.max(0,e-2),t);return Math.round(s*(.75+Math.random()*.5))}function Ki(n,e,t){return new Promise((r,s)=>{let i=setTimeout(()=>s(new Error(t)),e);n.then(o=>{clearTimeout(i),r(o)},o=>{clearTimeout(i),s(o)})})}var jd,qd,Lm,rs,Hd=W(()=>{"use strict";$d();jd=2500,qd=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Lm=1e4,rs=class n{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let t=this.session;!t||t.kind!=="webtransport"||t.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&r&&s,webcodecs:r,codecs:qd,wtData:t&&r&&s&&this.opts.dataLane!==void 0,wtAudio:t&&r&&s&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&s&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&r&&s&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&s&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i}),this.noteOfferedWtHost();let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let d=null;try{return d=this.createWebTransportSession(),await Ki(d.start(),this.opts.quicDeadlineMs??jd,"quic connect deadline"),this.wtDialedHost=zi(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(d,i.wtData===!0),this.session=d,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(l){if(console.warn(`[urun] WT dial failed (${Rr(l)}) \u2014 dialed ${Bd(this.offer.webtransport?.url)}`),d?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let u=String(l instanceof Error?l.message:l);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${u}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(u),l}console.warn("[urun] webtransport failed, falling back to webrtc:",l),this.proceedWebRtcDial(`wt failed: ${String(l instanceof Error?l.message:l)}`),this.notifyEstablished("webrtc",String(l instanceof Error?l.message:l))}}if(this.opts.allowWebRtcFallback===!1){let d=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${d} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(d),new Error(`[urun] WT required but unavailable: ${d}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}noteOfferedWtHost(){let e=zi(this.offer?.webtransport?.url);e===void 0||this.wtDialedHost===void 0||e===this.wtDialedHost||(this.wtHostMismatchCount+=1,console.error(`[urun] re-dial offered host ${e} != original host ${this.wtDialedHost}`+(Mm(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,s=this.opts.dataLane!==void 0,i=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:qd,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let d=this.createWebTransportSession();try{await Ki(d.start(),this.opts.quicDeadlineMs??jd,"quic connect deadline")}catch(l){throw console.warn(`[urun] WT dial failed (${Rr(l)}) \u2014 dialed ${Bd(this.offer.webtransport?.url)}`),d.stop().catch(()=>{}),l}if(this.wtDialedHost=zi(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==r)return d.stop().catch(()=>{}),null;try{this.engageQuicDataLane(d,s)}catch(l){throw d.stop().catch(()=>{}),l}if(this.disconnected)return d.stop().catch(()=>{}),null;this.session=d;{let l=this.offer.webtransport;l&&(this.opts.audioLane===void 0||l.audio!==void 0)&&(this.opts.audioUplink===void 0||l.audioUp===!0)&&(this.opts.videoUplink===void 0||l.videoUp===!0)&&(this.opts.dataLane===void 0||l.data===!0)&&(this.opts.dataUplink===void 0||l.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),d}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(s,i)=>r.onData(s,i),onLaneError:s=>r.onLaneError(s)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new ts(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t,!0);return}let r=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),r){this.session=null,this.wtOnlyLeg=!1,console.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",t),this.redialWtAfterDeath(t,!0);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,r)})}redialWtAfterDeath(e,t=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=n.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${n.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}console.error(`[urun] WT re-dial failed ${n.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let r=this.wtRedialFailures+1,s=Gi(n.WT_REDIAL_BASE_MS,r,n.WT_REDIAL_CAP_MS,r===1&&t?0:void 0);console.warn(`[urun] WT re-dial attempt ${r} scheduled in ${Math.round(s)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},s)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){console.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let r=Rr(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX} failed (${r}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${r}`)}}}lateWebRtcFailover(e,t,r){this.disconnected||(async()=>{let s=this.createWebRtc();try{let i=await Ki(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??Lm,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(i){if(s.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=r?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}}});var Om,ns,Vd=W(()=>{"use strict";On();Om=1e4,ns=class{constructor(e,t=Om){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=Vt();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:d,requestId:l,...u}=c;s(u)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(o),a(),i(new Error(`[urun] signaling request not sent: ${e} \u2014 the signaling socket is not open`)))})}notify(e,t){this.carrier.sendSignal({type:e,...t})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${e} \u2014 the signaling socket is not open`,detail:{method:e}})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}}});var Um,ss,zd=W(()=>{"use strict";Um="video",ss=class{constructor(e,t=Um){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}}});function Kd(n){let e=n;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Gd=W(()=>{"use strict"});async function Fm(n,e,t){let s=e?.current()?.name??null;if(s==="live")return"live";if(s==="error")return"gone";if(s==="idle"||s==="connecting")return"live";if(!e)return"unconfirmed";let i=e,o=t.runtimeWaitCapMs??Wm;return new Promise(a=>{let c=!1,d,l=null,u=null,p=!1,f=_=>{c||(c=!0,m(),u!==null&&(clearTimeout(u),u=null),d?.(),a(_))};u=setTimeout(()=>{if(p||c||t.isDisposed())return;p=!0;let _=i.current();n.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${t.sessionId} (server status: ${_?.reason??_?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let h=()=>{l===null&&!c&&(l=setTimeout(()=>f("unconfirmed"),o))},m=()=>{l!==null&&(clearTimeout(l),l=null)};d=e.subscribe(_=>{let v=_?.name;if(v==="live")return f("live");if(v==="error")return f("gone");m(),nt(v)||h()}),nt(s)||h()})}function Qd(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=n.holdWebRtcDial?.(),a=s.createElement("canvas"),c=!1,d=null,l=!1,u=()=>{if(d){for(let P of d.getVideoTracks())try{P.stop()}catch{}d=null}l&&(l=!1,t.onOverrideTrack(null))},p=new rs(new ns(n),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new ss(n,t.streamName??Nm)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(P,N)=>n.dispatchQuicStreamData(P,N),onQuicLane:()=>n.markStreamDataLaneQuic(),onQuicLaneLost:P=>n.quicStreamDataLaneLost(P),onLaneError:P=>n.raiseQuicStreamDataError(P)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:P=>{c||(P&&n.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(P))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>w(),onMediaTransportLost:P=>{c||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(P),w())},onTransportChange:(P,N)=>{c||(P==="webrtc"&&(u(),w()),t.onTransportChange?.(P,N))}}),f=n.onWtOnlyLegDeath?.(P=>p.failCurrentWtLeg(P)),g=null,h=()=>{g!==null&&(clearInterval(g),g=null)},m=t.wtRetryBaseMs??2e3,_=t.wtRetryCapMs??3e4,v=null,S=0,w=()=>{if(c||v!==null||p.activeTransport==="webtransport")return;let P=Gi(m,S+2,_);v=setTimeout(()=>{v=null,S+=1,p.retryWebTransport().then(N=>{if(c){N&&p.disconnect().catch(()=>{});return}if(N)return console.debug(`[urun] webtransport upgraded in background (retry ${S})`),S=0,T(N);w()}).catch(N=>{c||(console.debug(`[urun] webtransport background retry ${S} failed: `+Rr(N)),w())})},P)},b=()=>{v!==null&&(clearTimeout(v),v=null)},T=async P=>{if(c||P.kind!=="webtransport")return;let N=t.pathHealthProbeMs??1e4;h();let G=!1;g=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let $=Kd(P);if(!$){console.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),h();return}let j=$.pathLiveness();if(!j.alive){let Y=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${j.evidence}`+(Y?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),h(),$.fail(`path health: ${j.evidence}`);return}if(!G){if(G=!0,p.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${N}ms \u2014 the QUIC PATH IS HEALTHY (${j.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${N}ms \u2014 no media datagrams reached this client (path healthy: ${j.evidence}); webrtc track remains authoritative`)}},N);try{await P.firstMedia}catch($){h(),console.debug("[urun] webtransport ended before any media flowed:",$);return}if(h(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;d=a.captureStream();let ne=d.getVideoTracks()[0];ne&&(l=!0,t.onOverrideTrack(ne))},y=!1;return(async()=>{let P=await Fm(n,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>c});if(c)return;if(P==="gone"){console.debug(`[urun] session ${e} ended while waiting for a runtime to pick it up \u2014 no media negotiation`),o?.proceed("session ended before a runtime was pulled \u2014 releasing the held WebRTC dial");return}y=!0;let N=await p.connect();if(c){p.disconnect().catch(()=>{});return}await T(N)})().catch(P=>{if(h(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",P);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",P),w();return}o?.proceed(`negotiation unavailable: ${P instanceof Error?P.message:String(P)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",P),w()}),{activeTransport:()=>p.activeTransport,mediaTransportAttempted:()=>y,watchDownlinkStall(P){p.watchDownlinkStall(P)},dispose(){c=!0,f?.(),h(),b(),u(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var Nm,Wm,Yd=W(()=>{"use strict";Hd();Vd();Or();zd();Gd();Nm="video",Wm=45e3});function Ji(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function Vm(n){return`${Hm}:${n}`}function Qi(){return Vt()}function zm(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function Km(n,e,t,r,s,i,o,a,c,d){let l=[],u=null,p=!1,f=null,g=!1,h,m,_=new Promise((k,F)=>{h=k,m=F});_.catch(()=>{});let v=o(),S=null,w=null,b=null,T=null,y=null,P=null,N=!0,G=()=>{b&&(clearTimeout(b),b=null),T&&(T(),T=null)},ne=()=>{y&&(clearTimeout(y),y=null),P&&(P(),P=null)},$=!1,j=()=>{$||!g||($=!0,n.set({rpc:{[e]:null}}))},Y=()=>{N=!1,G(),ne(),S?.(),S=null,w?.(),w=null,a?.removeEventListener("abort",U),v.dispose(),j()},Z=()=>{if(u){if(l.length>0){let k=u;u=null,k.resolve({value:l.shift(),done:!1})}else if(f!==null){let k=u;u=null,k.reject(f)}else if(p){let k=u;u=null,k.resolve({value:void 0,done:!0})}}},he=k=>{p||(l.push(k),Z())},ee=k=>{p||(f=k,p=!0,m(k),Y(),Z())},D=k=>{p||(p=!0,h(k),Y(),Z())},U=()=>{let k=a?.reason;ee(k instanceof je?k:new Gt(e))},B=k=>{if(!(p||!k||typeof k!="object"))switch(ne(),j(),k.t){case"delta":typeof k.delta=="string"&&he(k.delta);break;case"response":D(k.body);break;case"error":{let{message:F,code:Ge}=zm(k.body);ee(new je(F,{requestId:e,code:k.code??Ge}));break}}},te=()=>{let k=v.messages()[Symbol.asyncIterator]();S=()=>{k.return?.(void 0)};let F=()=>{N&&k.next().then(Ge=>{if(N){if(Ge.done){p||D(void 0);return}B(Ge.value),F()}},Ge=>{N&&ee(Ge)})};F()},E=()=>{if(!g){if(g=!0,a){if(a.aborted){ee(new Gt(e));return}a.addEventListener("abort",U,{once:!0})}w=c?.(k=>ee(k))??null,te(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),d&&d>0&&!n.synced&&(b=setTimeout(()=>{b=null,!p&&!n.synced&&ee(new xr(d,e))},d),T=n.onSynced(()=>G())),P=n.onSynced(()=>{P=null,!(p||$||y)&&(y=setTimeout(()=>{y=null,!(p||$)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(Jd/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},Jd))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(E(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(f!==null){let k=f;return f=null,Promise.reject(k)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((k,F)=>{u={resolve:k,reject:F}})},return(){return p||(p=!0,h(void 0),Y()),Promise.resolve({value:void 0,done:!0})},throw(k){return p||(p=!0,m(k),Y()),Promise.reject(k)}}}},body:_,start:E}}function Xd(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Gm(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=Xd(i);c&&(a.rt=c);let d=Xd(o);return d&&(a.br=d),a}var $m,jm,qm,Bm,Jd,Hm,Yi,is,Zd=W(()=>{"use strict";Or();po();Uo();No();Ii();Pr();bt();ad();qn();dd();ud();fd();gd();Ni();Fn();wt();Xe();On();kd();Yd();$m=new Set;jm="rpc",qm="$presence",Bm=3e4,Jd=3e4,Hm="rpc-resp";Yi=class{constructor(e,t,r,s,i){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=i;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_directOut=!1;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,i=null,o={push(c){if(!s)if(r){let d=r;r=null,d.resolve({value:c,done:!1})}else t.push(c)},end(){if(s=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{s=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||s)&&(i=e._streamConsumeUnavailableError(c),a(),r)){let d=r;r=null,d.reject(i)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):i?Promise.reject(i):s?Promise.resolve({value:void 0,done:!0}):new Promise((c,d)=>{r={resolve:c,reject:d}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}get directOut(){return this._directOut}_setOverrideTrack(e,t){if(this._overrideTrack===e&&this._directOut===(t?.directOut??!1))return;this._overrideTrack=e,this._directOut=e?t?.directOut??!1:!1,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let r=e??this._transport.getTrackByName(this._name)??this._track,s=this._handlers.get("track");if(s)for(let i of s)i(r)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Gm(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Ir(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??bd;return Sd(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},is=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new $n;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,s,i,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=Oc(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=_d(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=hd({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new Vn({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(qm).awareness.setLocalState({role:"client"}),this._activation=new Ur({onPhase:a=>this.onPhase(a),hint:()=>this.doc(co).get(lo)??this.doc("control").get(uo),onData:(a,c)=>this._streamData.onData(a,c)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await Io({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new gt,o=new Kt({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,Ji(t),tr({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),Ze()&&await vt();let c=t.getAccessToken,d=c?async()=>await c()??s:s;return a.setDocTransport({wsUrl:r.wsUrl,token:d}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return ao(this,e)}on(e,t){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(t),this._generationTickStop||(this._generationTickStop=ld(this.doc("control"),r=>{for(let s of Array.from(this._generationTickHandlers))try{s(r)}catch(i){console.warn("[urun] generationTick handler failed:",i)}})),()=>{this._generationTickHandlers.delete(t),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new zr(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new er(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new er(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Yi(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Hn(e,this._sessionId,$m.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=cd(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=jn(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",s=`${t}\0${r}\0${this._sessionId}`;s!==this._docEndpointKey&&(this._docEndpointKey=s,this.connectDocs(id({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=Qi(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;i=setTimeout(()=>s.abort(new Dr(c,r)),c)}let o=this._consumeResponse(r,e,!1,s.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,t,r,s,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(jm),a=Vm(e);return Km(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??Bm)}requestStream(e,t={}){let r=Qi();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Qi(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Qd(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,runtimePhase:{current:()=>this._transport.phase??null,subscribe:t=>this._transport.on("phase",t)},onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t,{directOut:!0}),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}get mediaTransportAttempted(){return this._dialNegotiation?.mediaTransportAttempted()??!1}watchDownlinkStall(e={}){return this._downlinkStallWatch=e,this._dialNegotiation?.watchDownlinkStall(e),()=>{this._downlinkStallWatch=null}}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new Je)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Je);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let s of t)try{s()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let r=Array.from(this._activeRequests);this._activeRequests.clear();for(let s of r)try{s(new Lr)}catch{}for(let s of this._docs.values())s.dispose();this._docs.clear();for(let s of this._streams.values())s.dispose();this._streams.clear(),this._transport.disconnect(e)}}});function el(n){return`urun:session:v2:${n.orgId}:${n.app}:${n.functionName}`}function Xi(){try{return globalThis.sessionStorage??null}catch{return null}}function os(n){if(!n)return;let e=n.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof r?.sub=="string"&&r.sub.length>0?r.sub:void 0}catch{return}}function Qm(n,e){return n!==void 0&&e!==void 0&&n!==e}function eo(n,e){let t=Xi(),r=null;if(t)try{let i=t.getItem(n);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(r={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{r=null}let s=Zi.get(n)??r??null;return!s||Qm(s.actor,e)?null:s}function tl(n,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};Zi.set(n,t);let r=Xi();if(r)try{r.setItem(n,JSON.stringify(t))}catch{}}function as(n){Zi.delete(n);let e=Xi();if(e)try{e.removeItem(n)}catch{}}var Zi,rl=W(()=>{"use strict";Zi=new Map});function sl(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function Jm(n){if(typeof n?.id!="string"||n.id.length===0)throw new Ee("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof n.state!="string"||!nl.has(n.state))throw new Ee(`[urun] session ${n.id} reported an unrecognized state ${JSON.stringify(n.state)} \u2014 this @urun-sh/core build knows only ${[...nl].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof n.recordings_expired=="boolean"?e=n.recordings_expired:console.warn(`[urun] session ${n.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:n.id,label:typeof n.label=="string"&&n.label.length>0?n.label:null,state:n.state,app:typeof n.app=="string"?n.app:"",functionName:typeof n.function=="string"?n.function:"",createdAt:sl(n.created_at),lastActiveAt:sl(n.last_active_at),archived:n.archived===!0,preview:typeof n.preview=="string"&&n.preview.length>0?n.preview:null,recordingsExpired:e,retention:Ym.has(n.retention)?n.retention:(n.retention!==void 0&&console.warn(`[urun] session ${n.id} reported an unrecognized retention ${JSON.stringify(n.retention)} \u2014 defaulting to '24h'`),"24h")}}var nl,Ym,cs,il=W(()=>{"use strict";Xe();bt();nl=new Set(["paused","acquiring","live"]),Ym=new Set(["24h","keep"]);cs=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await Po({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(Jm),nextCursor:r}}async end(e){await Do({...this._request,sessionId:e})}async archive(e){await ys({...this._request,sessionId:e,archived:!0})}async unarchive(e){await ys({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await xo({...this._request,sessionId:e,name:t,source:r.source})}}});var al={};ls(al,{App:()=>eg,sessionDirectory:()=>Zm});function ol(n,e,t){let r=os(t);tl(n,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}function Zm(n,e){return new cs(n,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function eg(n,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,r){if(!(Xm.has(r)||typeof r!="string"))return(s,i)=>{let o=s??{},a=el({orgId:e.orgId,app:n,functionName:r}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,d,l=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,u=l(),p=e.jwt,f=e.getAccessToken?async D=>{let U=await e.getAccessToken(D);return U&&(p=U),U}:void 0,g={...e,getAccessToken:f},h=new gt,m=new Kt({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:u,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),_=new is(u,h,m,Ji(g),tr(g),{activity:i?.activity}),v,S=!1,w=!1,b,T,y=new Promise(D=>{T=D}),P,N=D=>{D.sessionId||b||(b="teardown",P="ticket",gs({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},G=D=>{b||D.sessionId||(b="abandon",gs({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider,reason:"client_abandoned"}))},ne=D=>{let U=D.sessionId||!d?D:{...D,sessionId:d};v=U,T({status:"ready",handle:U}),(w||b==="teardown")&&N(U)};_.setEndHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Je("[urun] session allocation failed before a releasable request was created",{cause:D.cause});let U=v??D.handle;return as(a),b==="teardown"?U.sessionId?{status:"paused",sessionId:U.sessionId,reason:"client_ended"}:{status:"canceled",requestId:U.requestId}:(b="end",U.sessionId?vs({baseUrl:U.baseUrl,sessionId:U.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):_s({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Je("[urun] session allocation failed before a cancellable request was created",{cause:D.cause});let U=v??D.handle;if(U.sessionId)throw new ge(`[urun] cancel() is for a queued admission request, but this call already has session ${U.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:U.sessionId,code:"cancel_on_live_session"});b="end";try{let B=await _s({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return as(a),B}catch(B){throw b==="end"&&(b=void 0),B}});let $=async D=>{let U,B=i?.sessionId??e.sessionKey??d,te,E;if(B===void 0&&!c){let Ce=eo(a);if(Ce?.sessionId){if(E=os(p),Ce.actor!==void 0&&E===void 0&&f){let ds=await Promise.resolve(f()).catch(()=>{});E=os(ds??e.jwt)}te=Ce.actor!==void 0&&E!==void 0&&Ce.actor!==E?void 0:Ce.sessionId}}let q=B??te,k=(Ce,ds)=>Eo({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:Ce,sessionKey:ds,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:Qe=>{m.reportAdmission(Qe),Qe.sessionId&&!d&&(d=Qe.sessionId,U=Qe.sessionId,v&&v.sessionId!==Qe.sessionId&&ne({...v,sessionId:Qe.sessionId}),S||(e.sessionKey||ol(a,Qe.sessionId,p),_.setSessionId(Qe.sessionId)))},onRequest:ne}),F;try{F=await k(D,q)}catch(Ce){if(te===void 0||!(Ce instanceof Q)||Ce.code!=="session_name_not_yours")throw Ce;console.warn(`[urun] session_name_not_yours: the control plane refused session ${te} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),eo(a,E)?.sessionId===te&&as(a),F=await k(l(),void 0)}let Ge=f?await f()??void 0:e.jwt;if(U&&U!==F.sessionId)throw v&&v.sessionId!==F.sessionId&&ne({...v,sessionId:F.sessionId}),new Q(`Gateway contract violation: admission minted session ${U} but allocation completed as ${F.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return d=F.sessionId,v&&v.sessionId!==F.sessionId&&ne({...v,sessionId:F.sessionId}),S||(e.sessionKey||ol(a,F.sessionId,p),_.setSessionId(F.sessionId),_.setArtifactsAuth(tr({...g,baseUrl:F.baseUrl})),m.setEndsAt(F.endsAt),m.seedRegion(bs(F.response))),{url:F.wsUrl,sessionId:F.sessionId,jwt:Ge,iceServers:F.response.ice_servers,endsAt:F.endsAt}},j,Y=0,Z=f?async()=>{let D=Y++>0;return await f(D?{forceRefresh:!0,reason:"background"}:void 0)??j}:()=>j,he=()=>{let D=m.connectedUrl;return D?jn(D):void 0};if(m.setConnectionResolver(async()=>{let D=await $(l());return j=D.jwt,D}),m.on("connected",()=>{m.multiplexer&&h.setTarget(m.multiplexer);let D=m.connectedUrl;D&&_.setDocTransport({wsUrl:D,token:Z,resolveServerUrl:he})}),(async D=>{let U;try{U=await $(D)}catch(B){if(S){T({status:"unavailable",cause:B});return}console.error(`[urun] Failed to create session for ${r}:`,B),v&&G(v);let te=B instanceof Error?B:new Error(String(B)),E=B instanceof Q?B.httpStatus:void 0,q=B instanceof Q?B.code:void 0,k=B instanceof Q?B.retryAfterSeconds:void 0;m.reportAllocationFailure(te,E,q,k),T({status:"unavailable",cause:B});return}S||(m.setAuth({jwt:U.jwt,authProvider:e.authProvider,orgId:e.orgId}),m.setConnection({url:U.url,sessionId:U.sessionId,iceServers:U.iceServers}),Ze()&&await vt(),j=U.jwt,_.setDocTransport({wsUrl:U.url,token:Z,resolveServerUrl:he}),await m.connect({app:n,functionName:r,args:o}),_.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(u).catch(D=>{console.error(`[urun] Failed to connect session for ${r}:`,D)}),e.releaseOnLeave!==!1){let D=vd(()=>{if(S=!0,m.leaveLeg())return;if(m.connectedUrl!==null){m.disconnect();return}m.disconnect();let q=v;q?N(q):w=!0});_.onDisconnect(D);let U,B,te=!1,E=()=>{te||(te=!0,U?.(),B?.())};y.then(q=>{q.status!=="ready"||te||(U=wd(()=>v!==void 0))}),B=_.onPhase(q=>{let k=q?.name;(k==="paused"||k==="error")&&E()}),te&&B(),_.onDisconnect(E)}return _}}})}var Xm,cl=W(()=>{"use strict";Pr();Zd();Ii();bt();Xe();wt();qn();Ni();rl();il();Xm=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive])});var ng={};ls(ng,{createSessionResolver:()=>dl});module.exports=ro(ng);var tg="serve";function dl(n,e){let t=`[urun/${e.adapter}]`,r=n.baseUrl!==void 0||n.orgId!==void 0||n.app!==void 0||n.functionName!==void 0;if(n.session&&r)throw new Error(`${t} pass EITHER a \`session\` (BYO) OR connection settings (\`baseUrl\`/\`orgId\`/\`app\`) \u2014 not both.`);let s,i=()=>{if(n.session){let d=n.session;return Promise.resolve(typeof d=="function"?d():d)}let{baseUrl:o,orgId:a,app:c}=n;if(!o||!a||!c)throw new Error(`${t} missing connection settings: \`baseUrl\`, \`orgId\` and \`app\` are required (or pass a \`session\`).`);return rg({...n,baseUrl:o,orgId:a,app:c})};return()=>s??=i()}async function rg(n){let{App:e}=await Promise.resolve().then(()=>(cl(),al)),t=e(n.app,{baseUrl:n.baseUrl,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}),r=n.functionName??tg;return t[r]()}0&&(module.exports={createSessionResolver});
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
2
- import"../chunk-NLAOQUYQ.mjs";var p="serve";function d(n,o){let e=`[urun/${o.adapter}]`,r=n.baseUrl!==void 0||n.orgId!==void 0||n.app!==void 0||n.functionName!==void 0;if(n.session&&r)throw new Error(`${e} pass EITHER a \`session\` (BYO) OR connection settings (\`baseUrl\`/\`orgId\`/\`app\`) \u2014 not both.`);let u,c=()=>{if(n.session){let s=n.session;return Promise.resolve(typeof s=="function"?s():s)}let{baseUrl:i,orgId:t,app:a}=n;if(!i||!t||!a)throw new Error(`${e} missing connection settings: \`baseUrl\`, \`orgId\` and \`app\` are required (or pass a \`session\`).`);return l({...n,baseUrl:i,orgId:t,app:a})};return()=>u??=c()}async function l(n){let{App:o}=await import("../app-RSRN5JAF.mjs"),e=o(n.app,{baseUrl:n.baseUrl,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}),r=n.functionName??p;return e[r]()}export{d as createSessionResolver};
2
+ import"../chunk-NLAOQUYQ.mjs";var p="serve";function d(n,o){let e=`[urun/${o.adapter}]`,r=n.baseUrl!==void 0||n.orgId!==void 0||n.app!==void 0||n.functionName!==void 0;if(n.session&&r)throw new Error(`${e} pass EITHER a \`session\` (BYO) OR connection settings (\`baseUrl\`/\`orgId\`/\`app\`) \u2014 not both.`);let u,c=()=>{if(n.session){let s=n.session;return Promise.resolve(typeof s=="function"?s():s)}let{baseUrl:i,orgId:t,app:a}=n;if(!i||!t||!a)throw new Error(`${e} missing connection settings: \`baseUrl\`, \`orgId\` and \`app\` are required (or pass a \`session\`).`);return l({...n,baseUrl:i,orgId:t,app:a})};return()=>u??=c()}async function l(n){let{App:o}=await import("../app-QPMMX4XX.mjs"),e=o(n.app,{baseUrl:n.baseUrl,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}),r=n.functionName??p;return e[r]()}export{d as createSessionResolver};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
2
- import{ea as a,fa as b}from"./chunk-SAKVBT4A.mjs";import"./chunk-LIGXGD7T.mjs";import"./chunk-NLAOQUYQ.mjs";export{b as App,a as sessionDirectory};
2
+ import{ea as a,fa as b}from"./chunk-2HOATHCZ.mjs";import"./chunk-LIGXGD7T.mjs";import"./chunk-NLAOQUYQ.mjs";export{b as App,a as sessionDirectory};
@@ -438,6 +438,8 @@ interface SessionStream {
438
438
 
439
439
  readonly track: MediaStreamTrack | null;
440
440
 
441
+ readonly directOut: boolean;
442
+
441
443
  attach(track: MediaStreamTrack): Promise<void>;
442
444
 
443
445
  attachVideo(track: MediaStreamTrack): Promise<void>;
@@ -438,6 +438,8 @@ interface SessionStream {
438
438
 
439
439
  readonly track: MediaStreamTrack | null;
440
440
 
441
+ readonly directOut: boolean;
442
+
441
443
  attach(track: MediaStreamTrack): Promise<void>;
442
444
 
443
445
  attachVideo(track: MediaStreamTrack): Promise<void>;
@@ -438,6 +438,8 @@ interface SessionStream {
438
438
 
439
439
  readonly track: MediaStreamTrack | null;
440
440
 
441
+ readonly directOut: boolean;
442
+
441
443
  attach(track: MediaStreamTrack): Promise<void>;
442
444
 
443
445
  attachVideo(track: MediaStreamTrack): Promise<void>;
@@ -438,6 +438,8 @@ interface SessionStream {
438
438
 
439
439
  readonly track: MediaStreamTrack | null;
440
440
 
441
+ readonly directOut: boolean;
442
+
441
443
  attach(track: MediaStreamTrack): Promise<void>;
442
444
 
443
445
  attachVideo(track: MediaStreamTrack): Promise<void>;