@urun-sh/core 0.6.40 → 0.6.41
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.
- package/dist/adapter/index.js +2 -2
- package/dist/adapter/index.mjs +1 -1
- package/dist/{app-MGYVBX2I.mjs → app-WK7H3ZNF.mjs} +1 -1
- package/dist/{chunk-UVRSEGB2.mjs → chunk-2QAHTS3L.mjs} +1 -1
- package/dist/{chunk-2WN3OQWP.mjs → chunk-EWKKEBQJ.mjs} +2 -2
- package/dist/{chunk-WVJ4Y5IW.mjs → chunk-JXGR4FYX.mjs} +1 -1
- package/dist/index.browser.d.mts +5 -0
- package/dist/index.browser.d.ts +5 -0
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +2 -2
- package/dist/index.d.mts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.js +1 -1
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.js +1 -1
- package/dist/internal.mjs +1 -1
- package/package.json +1 -1
package/dist/adapter/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Sl=Object.create;var Dr=Object.defineProperty;var kl=Object.getOwnPropertyDescriptor;var Tl=Object.getOwnPropertyNames;var Rl=Object.getPrototypeOf,Cl=Object.prototype.hasOwnProperty;var W=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var L=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ms=(n,e)=>{for(var t in e)Dr(n,t,{get:e[t],enumerable:!0})},lo=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tl(e))!Cl.call(n,s)&&s!==t&&Dr(n,s,{get:()=>e[s],enumerable:!(r=kl(e,s))||r.enumerable});return n};var Je=(n,e,t)=>(t=n!=null?Sl(Rl(n)):{},lo(e||!n||!n.__esModule?Dr(t,"default",{value:n,enumerable:!0}):t,n)),uo=n=>lo(Dr({},"__esModule",{value:!0}),n);var xr,vt,Ir=W(()=>{"use strict";xr=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let r;try{r=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!r.channel)return;let s=this._handlers.get(r.channel);if(s)for(let i of s)i(r)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}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)}}emit(e,t){if(this._disposed)return;let r=JSON.stringify({channel:e,...t});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(r);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(r),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},vt=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[r,s]of this._handlers)for(let i of s)this._targetUnsubscribes.push(e.on(r,i));let t=this._pendingSends;this._pendingSends=[];for(let r of t)e.emit(r.channel,r.data)}rewriteSessionChannels(e,t){if(e===t)return;let r=`session:${e}:`,s=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(r)?s+o.slice(r.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(r)?s+o.channel.slice(r.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let r=this._handlers.get(e);r||(r=new Set,this._handlers.set(e,r)),r.add(t);let s=this._target?.on(e,t);return s&&this._targetUnsubscribes.push(s),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e),s?.(),s&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==s))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}}});function Pl(n){return n.replace(/\bhttps?:\/\/[^\s)]+/g,"the session gateway")}function po(n){let e=n.replace(El,"");return Pl(e||n.replace(/^\[urun\] /,""))}function ho(n){let e=n.error?.httpStatus;if(e===401||e===403)return"The backend rejected this client \u2014 sign in again or check the auth token / org access.";if(n.error?.code==="session_archived")return"This session is archived \u2014 call directory.unarchive(sessionId) (the session directory's un-archive verb), then reconnect with the same id.";let t=n.error?.retryAfterSeconds,r=t!==void 0?` It asked for ${Math.round(t)}s.`:"";return e===429?`The backend is shedding load \u2014 its admission queue is full, so this is capacity, not your request.${r} The SDK already retried with backoff; try again in a moment.`:e===408?`The request timed out before the backend answered \u2014 that is a timeout, not a verdict on your request.${r} The SDK already retried with backoff; try again in a moment.`:e!==void 0&&e>=500?"The backend is having an outage (nothing is wrong with your request) \u2014 the SDK already retried with backoff, so try again shortly and report the status above if it persists.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."}function fo(n,e){let t=e.error?.reason,r=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(n){case"create-failed":{let s=e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:"",i=e.error?.code;return i==="queue_ttl_expired"||i==="stale_poll_expired"?{message:`[urun] the queued session REQUEST timed out while waiting${s} (${i}) \u2014 the session itself is untouched`,hint:"Nothing was lost and nothing needs replacing: connect again with the same session and the control plane re-admits the request (a poll that arrives in time re-drives it on its own)."}:i==="session_archived"?{message:`[urun] this session is archived${s} \u2014 un-archive it before resuming`+(t?`: ${po(t)}`:""),hint:ho(e)}:i==="client_release"?{message:`[urun] the session's admission request was closed (client_release)${s} \u2014 this dial cannot attach through it`,hint:"The request row is terminal; retrying the same dial only repeats the 410. Create a fresh session (a new dial). The SDK itself never closes a request \u2014 a whenLive timeout only rejects."}:{message:`[urun] session create failed${s}${t?`: ${po(t)}`:""}`,hint:ho(e)}}case"never-live":{let s=r!==void 0?` after ${r}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`,o=e.lastServerStatus!==void 0&&["requested","queued","pending","allocating","provisioning","waking","waiting_for_capacity","unavailable","allocated","starting"].includes(e.lastServerStatus);return e.error?.code==="expired"?o?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before a runtime picked it up${s}${i} \u2014 the backend never dispatched the session (no runtime pulled it), so no media transport could ever connect`,hint:"Not a network problem \u2014 the session was still waiting for a runtime. Retry in a moment; if it persists, the backend dispatch lane is stuck."}:{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${s} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?o?{message:`[urun] session ${e.sessionId} was created but no runtime ever picked it up${s}${i} \u2014 the backend has not dispatched the session yet (a runtime pulls the demand, then the session server exists)`,hint:"Waiting for a runtime \u2014 not a network, VPN, or firewall problem. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] session ${e.sessionId} was created but never went live${s}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${s} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${t?`: ${t}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${t?`: ${t}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"runtime-failed":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} failed at runtime${t?`: ${t}`:""}`,hint:"The session function crashed on the backend \u2014 check the app logs. The session itself is parked, not gone: attach to it again once the app is fixed."};case"produce-timeout":return{message:`[urun] publishing a track timed out${t?`: ${t}`:""} \u2014 the SFU never acked the produce (the runtime\u2019s inbound port for the stream was not advertised in time)`,hint:"The runtime was still cold or the backend was at capacity when the track was published. Retry in a moment; if it persists, the backend never opened the stream to receive it."};case"insufficient-credits":return{message:`[urun] session create refused${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""} \u2014 the org has insufficient credits${t?`: ${t}`:""}`,hint:"Out of credits \u2014 add credits to keep running sessions."}}}var Xe,_e,Pe,He,Ar,Lr,Mr,Nr,Or,Qt,Ur,El,wt,Yt,B,Ze=W(()=>{"use strict";Xe=class extends Error{code="session_end_unavailable";constructor(e="[urun] this session handle cannot terminally end the session; disconnect the viewer instead",t){super(e),this.name="SessionEndUnavailableError",t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},_e=class extends Error{code;httpStatus;requestId;sessionId;constructor(e,t){super(e),this.name="SessionEndError",this.code=t.code??"session_end_failed",this.httpStatus=t.httpStatus,this.requestId=t.requestId,this.sessionId=t.sessionId,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},Pe=class extends Error{code;httpStatus;constructor(e,t){super(e),this.name="SessionDirectoryError",this.code=t?.code??"session_directory_failed",this.httpStatus=t?.httpStatus,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},He=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},Ar=class extends He{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},Lr=class extends He{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},Mr=class extends Error{stream;owner;attempted;constructor(e,t,r){super(`[urun] stream "${e}" is already produced by the ${t}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},Nr=15e3,Or=class extends Error{kind;stream;timeoutMs;constructor(e,t){let r=t?.timeoutMs??Nr,s=t?.stream??e,i=s!==e?` "${s}"`:"";super(`[urun] SFU did not ack producer ${e}${i} within ${Math.round(r/1e3)}s \u2014 the server never replied to 'produce'. The runtime's inbound port for this stream is likely unadvertised (a cold or capacity-queued runtime), so the SFU has nothing to forward the track to; the published track never reached the runtime.`),this.name="ProduceAckTimeout",this.kind=e,this.stream=s,this.timeoutMs=r,Object.setPrototypeOf(this,new.target.prototype)}},Qt=class extends He{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},Ur=class extends He{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}},El=/^\[urun\] (?:timed out waiting for session allocation at|session allocation wait expired at|session allocation poll failed at|session allocation failed at|session allocation at|session create at) \S+(?::[ \t]+|[ \t]+|$)/;wt=class extends Error{kind;status;hint;constructor(e,t,r){let{message:s,hint:i}=fo(e,t);super(s),this.name="SessionFailedError",this.kind=e,this.status=t,this.hint=i,r?.cause!==void 0&&(this.cause=r.cause),Object.setPrototypeOf(this,new.target.prototype)}},Yt=class extends Error{code="transport_session_mismatch";connectedSessionId;requestedSessionId;constructor(e,t){super(`[urun] cannot retarget a connected transport to a different session: this leg is live on ${e??"(unknown)"} but setConnection() asked for ${t} \u2014 disconnect() this leg first (or use a fresh session handle)`),this.name="TransportSessionMismatchError",this.connectedSessionId=e,this.requestedSessionId=t,Object.setPrototypeOf(this,new.target.prototype)}},B=class extends Error{httpStatus;code;balanceCredits;platformStatus;retryAfterSeconds;constructor(e,t){super(e),this.name="SessionAllocationError",this.httpStatus=t?.httpStatus,this.code=t?.code,this.balanceCredits=t?.balanceCredits,this.platformStatus=t?.platformStatus,this.retryAfterSeconds=t?.retryAfterSeconds,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}}});function st(n){if(!n)return!1;let e=typeof n=="string"?n:n.name;return e==="queued"||e==="unavailable"||e==="provisioning"||e==="waiting_for_capacity"}function go(n,e={}){let{signal:t}=e;return new Promise((r,s)=>{if(t?.aborted){s(t.reason instanceof Error?t.reason:new Error("whenLive aborted"));return}if(n.phase?.name==="live"){r();return}if(n.phase?.name==="error"){let w=n.phase,b=n.status??{phase:w.name,transportState:"disconnected",sessionId:w.sessionId,requestId:w.requestId,queue:w.queue,error:w.error,region:w.region};s(new wt(w.error?.kind??"transport-failed",b));return}let o,a,c=!1,d=w=>{c||(c=!0,a!==void 0&&clearTimeout(a),t?.removeEventListener("abort",l),o?.(),w?s(w):r())},l=()=>{d(t?.reason instanceof Error?t.reason:new Error("whenLive aborted"))};t?.addEventListener("abort",l,{once:!0});let u=()=>{let w=n.phase;return n.status??{phase:w?.name??"idle",transportState:"disconnected",sessionId:w?.sessionId,requestId:w?.requestId,queue:w?.queue,error:w?.error,region:w?.region}},p=w=>d(new wt(w,u())),m=e.timeout!==void 0,g=Date.now(),f=m?e.timeout:Dl,h=()=>{a!==void 0&&(clearTimeout(a),a=void 0)},_=()=>{if(c||f<=0)return;clearTimeout(a);let w=g+f-Date.now();a=setTimeout(()=>{if(!m&&st(n.phase?.name)){a=void 0;return}let b=u();b.elapsedMs===void 0&&(b.elapsedMs=f),a=void 0,t?.removeEventListener("abort",l),o?.(),o=void 0,d(new wt("never-live",b))},Math.max(0,w))},v=w=>{!m||c||f<=0||w?.runtime?.wake?.expectedWakePath==="cold-boot"&&(mo<=f||(f=mo,_()))},S=w=>{if(!c){if(!m&&st(w?.name)){h();return}if(m){v(w),a===void 0&&f>0&&_();return}a===void 0&&(g=Date.now(),_())}};o=n.onPhase(w=>{w?.name==="live"?d():w?.name==="error"?p(w.error?.kind??"transport-failed"):S(w)}),c||S(n.phase),c&&o()})}var Dl,mo,Wr=W(()=>{"use strict";Ze();Dl=45e3,mo=6e5});function xl(n){if(typeof n=="string"&&n.length>0)return n;if(n&&typeof n=="object"){let e=n.note;if(typeof e=="string"&&e.length>0)return e}}var gs,_o,vo,Il,Fr,wo=W(()=>{"use strict";gs="platform",_o="activation",vo="desired.activation";Il=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],Fr=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let s=()=>this._firstMedia(e);r.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",s));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of Il){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let s={state:t,elapsedMs:r,stream:e.name},i=xl(this._options.hint());i!==void 0&&(s.hint=i),e.lastEvent=s;for(let o of Array.from(this._handlers))o(s)}}});function it(){return typeof process<"u"&&process.stdout!=null&&typeof process.stdout.write=="function"}function et(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function bo(){return et()?"Chrome111":void 0}function ko(){return typeof globalThis.RTCPeerConnection<"u"?null:So??"the WebRTC peer globals (RTCPeerConnection) are not installed in this runtime"}function yt(){return et()?$r||($r=Ll(),$r):Promise.resolve()}async function Ll(){let n=globalThis;if(typeof n.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;n.WebSocket=t}catch(e){yo("WebSocket",e)}if(typeof n.RTCPeerConnection>"u")try{let e=await import("werift");Ol(n,e)}catch(e){So=yo("werift",e)}}function Ol(n,e){let{RTCPeerConnection:t,useH264:r,useVP8:s,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:d,useVideoOrientation:l}=e,u=()=>({video:[r(),s()],audio:[i()]}),p=()=>({video:[o(),a(),c(),d(),l()],audio:[o(),c(),d()]});class m extends t{constructor(f){super({...f,codecs:f?.codecs??u(),headerExtensions:f?.headerExtensions??p()})}async setRemoteDescription(f){await super.setRemoteDescription(f);let _=this.sctpManager,v=_?.sctpTransport,S=_?.connectSctp;!v||typeof S!="function"||v.dtlsTransport?.state==="connected"&&v.sctp?.associationState!==Ml&&await S.call(_)}}n.RTCPeerConnection=m;for(let g of Al)e[g]!=null&&typeof n[g]>"u"&&(n[g]=e[g])}function yo(n,e){let t=e instanceof Error?e.message:String(e),r=`optional dependency "${n}" unavailable (${t})`;return console.warn(`[urun-sh/core] Node WebRTC support: ${r}. Realtime media will not work in this Node process; install "${n}" to enable it. Doc/KV transport over WebSocket is unaffected.`),r}var Al,$r,So,Ml,bt=W(()=>{"use strict";Al=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],$r=null,So=null;Ml=4});function Br(n,e=Math.random){if(!Number.isFinite(n)||n<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${n}`);let t=Math.min(qr,_s*2**n);return Math.round(e()*t)}function vs(n){if(n instanceof B){let e=n.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return n instanceof Error?n.name==="TypeError"||n.name==="TimeoutError"||n.name==="AbortError":!1}function ws(){return jr<1?!1:(jr-=1,!0)}function ys(){jr=Math.min(To,jr+Ul)}var _s,qr,Jt,To,Ul,jr,Ro=W(()=>{"use strict";Ze();_s=500,qr=15e3,Jt=6;To=10,Ul=.5,jr=To});function te(n){return n.trim().replace(/\/+$/,"")}function tr(n,e){let t=[],r=s=>{if(!s)return;let i=te(s);i&&!t.includes(i)&&t.push(i)};r(n);for(let s of e??[])r(s);for(let s of wu(n))r(s);return t}function Vr(n){try{return new URL(te(n)).pathname===Fl}catch{return!1}}function bs(n){try{if(typeof fetch!="function")return;let e=te(n.baseUrl),t=n.sessionId?`${e}/api/sessions/${encodeURIComponent(n.sessionId)}/end`:`${e}/api/session-requests/${encodeURIComponent(n.requestId)}/cancel`;fetch(t,{method:"POST",headers:n.reason!==void 0?{...Ue(n,n.jwt),"Content-Type":"application/json"}:Ue(n,n.jwt),...n.reason!==void 0?{body:JSON.stringify({reason:n.reason})}:{},keepalive:!0}).catch(()=>{})}catch{}}async function Ss(n){try{let e=`${te(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/cancel`,t=await Oe(n);if(n.getAccessToken&&!t)throw new _e("[urun] session request cancel refused: getAccessToken resolved no token (an unauthenticated cancel is never sent)",{requestId:n.requestId,code:"no_access_token"});let r=await fetch(e,{method:"POST",headers:Ue(n,t),keepalive:!0});if((r.status===401||r.status===403)&&n.getAccessToken){let o=await Oe(n,{forceRefresh:!0,reason:"unauthorized"});o&&o!==t&&(r=await fetch(e,{method:"POST",headers:Ue(n,o),keepalive:!0}))}let s=await Zt(r);if(!r.ok)throw new _e(`[urun] session request cancel failed: ${Kr(s,r.status)}`,{requestId:n.requestId,code:s.error_code,httpStatus:r.status});let i=String(s.status??"");if(i==="cancelled"||i==="canceled"||i==="closed")return{status:"canceled",requestId:n.requestId};if(i==="failed"||i==="rejected"||i==="expired")return{status:"canceled",requestId:n.requestId,platformStatus:i};throw new _e(`[urun] session request cancel returned an unrecognized request status ${JSON.stringify(i)} (recognized: cancelled/canceled, closed, failed, rejected, expired)`,{requestId:n.requestId,code:"invalid_release_response",httpStatus:r.status})}catch(e){throw e instanceof _e?e:new _e("[urun] session request cancel failed",{requestId:n.requestId,cause:e})}}async function ks(n){let e;try{e=await zr(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/end`,{method:"POST",keepalive:!0},"session end")}catch(a){if(a instanceof _e)throw a;let c=a;throw new _e(c?.message??"[urun] session end request failed",{sessionId:n.sessionId,...c?.code!==void 0?{code:c.code}:{},...c?.httpStatus!==void 0?{httpStatus:c.httpStatus}:{},cause:a})}let t=Cs(e)?e:{},r=String(t.status??""),s=typeof t.pause_reason=="string"?t.pause_reason:void 0,i=typeof t.terminal_reason=="string"?t.terminal_reason:void 0,o=er(s)?s:er(i)?i:void 0;if(r==="paused")return{status:"paused",sessionId:String(t.logical_id??t.id??n.sessionId),...o!==void 0?{reason:o}:{}};throw new _e(`[urun] session end returned ${JSON.stringify(r)} for session ${n.sessionId} \u2014 an end PARKS the session, so the only contract-valid answer is "paused" (a terminal word on this route would be a session-plane terminal write, which is forbidden)`,{sessionId:n.sessionId,code:"invalid_end_response"})}function Io(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function Ts(n,e=Date.now()){if(!n)return null;let t=n.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),s=r.padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return typeof i.exp!="number"||!Number.isFinite(i.exp)?null:i.exp*1e3-e}catch{return null}}async function Eo(n,e){let t=Date.now()+Co;for(;;){await ot(Gl);let r=await Oe(n);if(r)return r;if(Date.now()>=t)throw new B(`[urun] session allocation at ${e} never got an access token: the wired getAccessToken resolved nothing within ${Math.round(Co/1e3)}s (no unauthenticated request was sent)`)}}function Ql(n,e){if(!n)return null;try{let t=new URL(n),r=e?new URL(te(e)):null,s=t.pathname==="/api/sessions/create"||t.pathname==="/api/sessions/create/";return t.protocol!=="https:"||!s||!Zl(t,r)?null:te(t.origin)}catch{return null}}function Yl(n,e){if(!n||!n.trim())return{outcome:"absent"};if(!Jl(e))return{outcome:"bootstrap-only"};let t=n.includes("://")?n:`https://${n}`,r;try{r=new URL(t)}catch{return{outcome:"rejected",reason:"not a parseable URL or host"}}return r.protocol!=="https:"?{outcome:"rejected",reason:`scheme ${r.protocol} is not https:`}:r.pathname!=="/"&&r.pathname!==""?{outcome:"rejected",reason:`expected a bare origin, got path ${r.pathname}`}:Hr(r.hostname)?{outcome:"pinned",base:te(r.origin)}:{outcome:"rejected",reason:`host ${r.hostname} is outside the urun.sh trust set`}}function Jl(n){if(!n)return!1;try{let e=new URL(te(n));return e.protocol==="https:"&&Hr(e.hostname)}catch{return!1}}function Xl(n){let e=te(n);try{return te(new URL(e).origin)}catch{return e}}function Zl(n,e){return Hr(n.hostname)&&(!e||Hr(e.hostname))}function Hr(n){let e=n.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}function eu(n){let e=n instanceof B?n.retryAfterSeconds:void 0;return e===void 0||!Number.isFinite(e)||e<=0?0:Math.min(e*1e3,qr)}function Lo(n,e){let t=eu(e);return t>0?Math.max(n,Date.now()+t):n}async function Mo(n){if(Vr(n.baseUrl))return ou(n);let e=tr(n.baseUrl,n.fallbackUrls),t=null,r=0,s=e.length>1;for(let i=0;i<Jt;i++){for(let o of e)try{let a=await au(o,n,{pollAttempts:$l,retryAfterLimitMs:s?jl:void 0});return ys(),a}catch(a){if(t=a instanceof Error?a:new Error(String(a)),r=Lo(r,t),t instanceof De||t instanceof at||lu(t))throw t}if(!vs(t))break;if(i+1<Jt){if(!ws())break;await ot(Math.max(Br(i),r-Date.now()))}}throw t??new Error("[urun] session allocation failed")}async function ou(n){let e=te(n.baseUrl),t=n.jwt??await n.getAccessToken?.({reason:"background"})??void 0;if(!t)throw new B("[urun] hub allocation requires a client token (jwt or getAccessToken)",{httpStatus:401});let r=await fetch(`${e}/sessions`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({...Vr(n.baseUrl)?{shape:n.shape??"cpu:1"}:{resource_class:"cpu"},idempotency_key:n.idempotencyKey,metadata:{app:n.app,function:n.functionName,org:n.orgId,...n.sessionKey?{logical_id:n.sessionKey}:{}}})}),s=await r.text();if(!r.ok)throw new B(`[urun] hub create failed (${r.status}): ${s.slice(0,300)}`,{httpStatus:r.status});let i=JSON.parse(s),o=null;for(;iu[i.state];){let c=Date.now();if(i.state==="queued"||i.state==="retry_pending"){o=null;let l=i.queue_deadline_at===null?null:typeof i.queue_deadline_at=="number"&&i.queue_deadline_at>0?i.queue_deadline_at:c+ru;if(l!==null&&c>=l+nu)throw new B(`[urun] hub session ${i.session_id} is still ${i.state} past the hub's queue deadline (${i.last_error??i.pause_reason??"hub reported no reason"})`,{httpStatus:504,platformStatus:i.state})}else if(o??=c+su,c>=o)throw new B(`[urun] hub session ${i.session_id} stuck ${i.state} past the boot patience window (${i.last_error??"hub reported no reason"})`,{httpStatus:504,platformStatus:i.state});n.onAdmission?.({status:i.state,sessionId:i.session_id}),await ot(tu);let d=await fetch(`${e}/sessions/${encodeURIComponent(i.session_id)}`,{headers:{authorization:`Bearer ${t}`}});if(!d.ok){if(d.status===404)throw new B(`[urun] hub session ${i.session_id} disappeared (${d.status})`,{httpStatus:d.status});continue}i=await d.json()}if(i.state==="failed"||i.state==="completed")throw new B(`[urun] hub session ${i.session_id} reached ${i.state} (${i.last_error??i.terminal_reason??"no reason recorded"})`,{httpStatus:503,platformStatus:i.state});if(i.state==="paused")throw new B(`[urun] hub session ${i.session_id} is parked (${i.pause_reason??i.last_error??"no reason recorded"})`,{httpStatus:503,platformStatus:i.state});if(i.state!=="running"||!i.sfu_endpoint)throw new B(`[urun] hub session ${i.session_id} ended in state=${i.state} without an sfu_endpoint (${i.last_error??i.terminal_reason??"no reason recorded"})`,{httpStatus:504,platformStatus:i.state});let a=Oo(i);if(!a)throw new B(`[urun] hub session ${i.session_id} is running but carried no sfu_attach credential (hub deployment predates lane 52, or HUB_GRANT_SECRET is unset)`,{httpStatus:502,platformStatus:i.state});return{baseUrl:e,sessionId:i.session_id,wsUrl:i.sfu_endpoint,endsAt:null,sfuAttach:a,response:i}}function Oo(n){let e=n.sfu_attach;if(!(!e||typeof e.token!="string"||typeof e.gen!="number"||!Number.isInteger(e.gen)||e.gen<0||e.token.length===0))return{url:n.sfu_endpoint??"",token:e.token,gen:e.gen}}async function Uo(n){let e=te(n.baseUrl),t=await fetch(`${e}/sessions/${encodeURIComponent(n.sessionId)}`,{headers:n.jwt?{authorization:`Bearer ${n.jwt}`}:{}});if(t.status===401||t.status===403)throw new B(`[urun] hub session view refresh refused (${t.status}) for ${n.sessionId}`,{httpStatus:t.status});if(!t.ok)return null;let r=await t.json();if(r.session_id!==n.sessionId||r.state!=="running"||!r.sfu_endpoint)return null;let s=Oo(r);return s?{url:r.sfu_endpoint,sessionId:r.session_id,sfuAttach:s}:null}async function au(n,e,t){let r,s,i,o,a=Xl(n),c=0,d=new Set,l=Date.now(),u=l+t.pollAttempts*Ao,p=!1,m=12e4,g=10080*60,f=S=>{if(typeof S!="number"||!Number.isFinite(S)||S<=0||S>g)return;let w=l+S*1e3+m;w>u&&(u=w,p=!0)},h=()=>p?Number.POSITIVE_INFINITY:t.pollAttempts,_=8,v=0;for(let S=0;S<h();S++){if(p&&Date.now()>=u)throw Xt(a,!!r,o);s=i??await Oe(e),i=void 0,e.getAccessToken&&!s&&(s=await Eo(e,a));let w=!!r,b=Date.now(),T;if(r){let $=0,j=G=>{let Z=Math.min(qr,_s*2**$),he=Math.max(Math.ceil(Z/2),Br($));return $+=1,Math.min(Math.max(G,he),Math.max(0,u-Date.now()))};for(;;){let G=u-Date.now();if(G<=0)throw Xt(a,!0,o);let Z=Math.max(1,Math.min(ql,Math.floor(G/1e3)));{let ee=Ts(s);if(ee!==null&&ee<Z*1e3+Hl)try{let Me=await Oe(e,{forceRefresh:!0});Me&&Me!==s&&(s=Me)}catch{}}b=Date.now();try{T=await fetch(`${a}/api/session-requests/${encodeURIComponent(r)}?wait_s=${Z}`,{headers:Ue(e,s),redirect:"manual",signal:gu((Z+Bl)*1e3)})}catch{let ee=j(0);if(ee<=0)throw Xt(a,!0,o);await ot(ee);continue}if(o=`HTTP ${T.status}`,!zl.has(T.status))break;try{await T.body?.cancel()}catch(ee){throw new at(`[urun] session allocation poll response cleanup failed at ${a}`,{cause:ee})}let he=j(Do(T,{},t.retryAfterLimitMs));if(he<=0)throw Xt(a,!0,o);await ot(he)}}else T=await fetch(`${a}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Ue(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(cu(e))});if(T.type==="opaqueredirect"||T.status>=300&&T.status<400){try{await T.body?.cancel()}catch{}throw new De(`[urun] ${w?"session poll":"session create"} at ${a} answered an HTTP redirect (status ${T.status}) \u2014 browsers cannot follow a cross-origin redirect with credentials; the control plane must emit the JSON redirect envelope ({status:"redirect", location})`)}let y=await Zt(T);if(o=typeof y.status=="string"&&y.status?y.status:`HTTP ${T.status}`,T.status!==401&&T.status!==403&&(v=0),!r&&y.status==="redirect"){let $=Ql(y.location,a);if(!$)throw new B(`[urun] session create at ${a} answered a redirect envelope without a usable location (${JSON.stringify(y.location??null)}) \u2014 refusing to re-issue an authenticated create to an untrusted target`);if($===a)throw new B(`[urun] session create at ${a} redirected to ITSELF \u2014 control-plane region apex map misconfiguration`);if(c>=Kl)throw new B(`[urun] session create followed ${c} region redirects and was redirected AGAIN (${a} -> ${$}) \u2014 region forward loop, giving up loudly`);c+=1,a=$;continue}if(y.request_id)try{e.onRequest?.({requestId:y.request_id,baseUrl:a,...y.session_id?{sessionId:y.session_id}:{}})}catch{}if(T.ok&&(y.status==="allocated"||!y.status&&!!y.session_id)&&!!y.session_id){let $=y.session_id,j=Yl(y.session_api_base,a);if(j.outcome==="rejected")throw new De(`[urun] gateway allocated session ${y.session_id} with an unusable session_api_base (${JSON.stringify(y.session_api_base)}): ${j.reason} \u2014 refusing to pin the session to a region it may not belong to`);if(j.outcome==="pinned"&&j.base!==a&&(a=j.base,y.request_id))try{e.onRequest?.({requestId:y.request_id,baseUrl:a,...y.session_id?{sessionId:y.session_id}:{}})}catch{}let G=jo(y.ws_url,a,$,"gateway allocated session");return{baseUrl:a,sessionId:$,wsUrl:G,endsAt:Io(y.ends_at),response:y}}if(T.status===202||y.status==="pending"||y.status==="queued"||y.queued){if(r=y.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(f(y.effective_max_queue_time_s),e.onAdmission)try{e.onAdmission(mu(y,r))}catch{}let $=Date.now()-b<Vl;w&&$&&await ot(Do(T,y,t.retryAfterLimitMs));continue}if((T.status===401||T.status===403)&&e.getAccessToken&&y.error_code!=="session_name_not_yours"){let $=s??"";if(d.add($),p&&(v+=1,v>_))throw new at(`[urun] session allocation failed at ${a}: authorization refused ${_} consecutive refreshes while the admission wait was extended (last server status: ${o??"none received"}) \u2014 the token provider keeps minting fresh tokens the control plane rejects`,{httpStatus:T.status,code:y.error_code,platformStatus:y.status});let j=await Oe(e,{forceRefresh:!0,reason:"unauthorized"});if(j&&!d.has(j)){i=j;continue}if(j===void 0){let G=await Eo(e,a);if(!d.has(G)){i=G;continue}}}let N=Kr(y,T.status),J=y.error_code??(T.status===402?"insufficient_credits":void 0),se=w?at:B;throw new se(`[urun] session allocation failed at ${a}: ${N}`,{httpStatus:T.status,code:J,balanceCredits:typeof y.balance_credits=="number"?y.balance_credits:void 0,platformStatus:y.status,retryAfterSeconds:Ps(T,y)})}throw Xt(a,!!r,o)}function Xt(n,e=!1,t){let r=e?at:B;return new r(`[urun] session allocation wait expired at ${n} \u2014 the CLIENT-side wait budget elapsed (last server status: ${t??"none received"}; the gateway reported no failure)`)}function Ue(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function Oe(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function cu(n){let e=n.priority==="preempt";return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey,...n.sessionKey&&!e?{logical_id:n.sessionKey}:{},...n.concurrencyKey&&!e?{concurrency_key:n.concurrencyKey}:{},...n.label&&!n.sessionKey?{label:n.label}:{},...e?{priority:"preempt"}:{},...n.sharedApp?{shared_app:!0}:{}}}async function zr(n,e,t,r){let s=await Oe(n);if(n.getAccessToken&&!s)throw new Pe(`[urun] ${r} refused: getAccessToken resolved no token (an unauthenticated request is never sent)`,{code:"no_access_token"});let i=tr(n.baseUrl,n.fallbackUrls),o;for(let a of i){let c=`${te(a)}${e}`,d=p=>fetch(c,{method:t.method,headers:t.body!==void 0?{...Ue(n,p),"Content-Type":"application/json"}:Ue(n,p),...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...t.keepalive?{keepalive:!0}:{}}),l;try{if(l=await d(s),(l.status===401||l.status===403)&&n.getAccessToken){let p=await Oe(n,{forceRefresh:!0,reason:"unauthorized"});p&&p!==s&&(l=await d(p))}}catch(p){o=p;continue}let u=await Zt(l);if(!l.ok)throw new Pe(`[urun] ${r} failed: ${Kr(u,l.status)}`,{code:u.error_code,httpStatus:l.status});return u}throw new Pe(`[urun] ${r} request failed`,{cause:o})}async function No(n){let e=new URLSearchParams;n.app&&e.set("app",n.app),n.functionName&&e.set("function",n.functionName),n.includeArchived&&e.set("include_archived","true"),n.limit!==void 0&&e.set("limit",String(n.limit)),n.cursor&&e.set("cursor",n.cursor);let t=e.toString(),r=await zr(n,`/api/sessions${t?`?${t}`:""}`,{method:"GET"},"session list");if(!Array.isArray(r?.sessions))throw new Pe("[urun] session list returned no `sessions` array \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_response"});return{rows:r.sessions,nextCursor:r.next_cursor??null}}async function Rs(n){let e=n.archived?"archive":"unarchive";await zr(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/${e}`,{method:"POST"},`session ${e}`)}async function Wo(n){await ks(n)}async function Fo(n){let e=n.name.trim();if(e.length===0)throw new Pe("[urun] session name refused: a name is required (an empty name is not a rename)",{code:"invalid_session_name"});await zr(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/name`,{method:"POST",body:{name:e,...n.source?{source:n.source}:{}}},"session name")}async function $o(n){let e=tr(n.baseUrl,n.fallbackUrls),t=null,r=0;for(let s=0;s<Jt;s++){for(let i of e)try{let o={baseUrl:i,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},a=`${te(i)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,c=await Oe(o);if(n.getAccessToken&&!c)throw new B(`[urun] viewer-connect for ${n.sessionId} refused: getAccessToken resolved no token (an unauthenticated viewer-connect is never sent)`);let d=await fetch(a,{headers:Ue(o,c)});if((d.status===401||d.status===403)&&n.getAccessToken){let p=await Oe(o,{forceRefresh:!0,reason:"unauthorized"});p&&p!==c&&(d=await fetch(a,{headers:Ue(o,p)}))}if(!d.ok){let p=await Zt(d);throw new B(`[urun] viewer-connect for ${n.sessionId} failed: `+Kr(p,d.status),{httpStatus:d.status,retryAfterSeconds:Ps(d,p)})}let l=await Zt(d),u=jo(l.ws_url,i,n.sessionId,"viewer-connect");return ys(),{baseUrl:te(i),sessionId:n.sessionId,wsUrl:u,endsAt:Io(l.ends_at),response:l}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),r=Lo(r,t),t instanceof De)throw t}if(!vs(t))break;if(s+1<Jt){if(!ws())break;await ot(Math.max(Br(s),r-Date.now()))}}throw t??new Error("[urun] viewer-connect failed")}async function Zt(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function Kr(n,e){let t=n.error_code,r=n.error_message||n.message||n.error,s=t&&r&&r!==t?`${t}: ${r}`:r||t;return s?`${s} (HTTP ${e})`:`HTTP ${e}`}function lu(n){return n instanceof B&&n.httpStatus!==void 0&&du.has(n.httpStatus)}function Cs(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function er(n){return typeof n=="string"&&n.trim().length>0}function Po(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}function pu(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0}function hu(n){if(Cs(n)&&!(!er(n.snapshot_id)||!er(n.snapshot_compat_key)||!Po(n.artifact_size_bytes)||!Po(n.durable_arena_bytes)||n.volatile_arena_bytes!==0||!pu(n.uncovered_weight_bytes)))return{snapshotId:n.snapshot_id,snapshotCompatKey:n.snapshot_compat_key,artifactSizeBytes:n.artifact_size_bytes,durableArenaBytes:n.durable_arena_bytes,volatileArenaBytes:0,uncoveredWeightBytes:n.uncovered_weight_bytes}}function fu(n){if(!Cs(n)||n.schema!=="urun.runtime.wake.v1"||n.portability!=="portable"&&n.portability!=="none"||n.expected_wake_path!=="portable-golden-restore"&&n.expected_wake_path!=="cold-boot"||typeof n.reason_code!="string"||!uu.has(n.reason_code)||n.expectation_basis!=="snapshot-registry"||n.restore_observation!=="not-observed")return;let e=n.reason_code;if(n.portability==="portable"&&n.expected_wake_path==="portable-golden-restore"&&e==="capture-attested"){let t=hu(n.golden);return t?{schema:"urun.runtime.wake.v1",portability:"portable",expectedWakePath:"portable-golden-restore",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed",golden:t}:void 0}if(n.portability==="none"&&n.expected_wake_path==="cold-boot"&&e!=="capture-attested"&&n.golden===void 0)return{schema:"urun.runtime.wake.v1",portability:"none",expectedWakePath:"cold-boot",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed"}}function Es(n){if("serving_region"in n)return typeof n.serving_region=="string"&&n.serving_region.length>0?n.serving_region:null}function mu(n,e){let r={status:typeof n.status=="string"&&n.status.length>0?n.status:n.queued?"queued":"pending",requestId:e};er(n.session_id)&&(r.sessionId=n.session_id);let s=Es(n);s!==void 0&&(r.region=s),typeof n.runtime_ready=="boolean"&&(r.runtimeReady=n.runtime_ready),(n.runtime_status==="unbound"||n.runtime_status==="starting"||n.runtime_status==="ready")&&(r.runtimeStatus=n.runtime_status),typeof n.reason=="string"&&n.reason.length>0&&(r.reason=n.reason),typeof n.decision_reason=="string"&&n.decision_reason.length>0&&(r.decisionReason=n.decision_reason),typeof n.provisioning_refusal_source=="string"&&n.provisioning_refusal_source.length>0&&(r.refusalSource=n.provisioning_refusal_source),typeof n.provisioning_refusal_message=="string"&&n.provisioning_refusal_message.length>0&&(r.refusalMessage=n.provisioning_refusal_message),typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(r.queue={position:n.queue_position,depth:n.queue_depth});let i=n.runtime_state;if(i==="unavailable"||i==="starting"||i==="busy"){r.runtime={state:i},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(r.runtime.reason=n.runtime_reason);let o=fu(n.runtime_wake);o&&(r.runtime.wake=o)}return r}function Ps(n,e){let t=Number(n.headers.get("Retry-After")||""),r=Number(e.retry_after_seconds??t);return Number.isFinite(r)&&r>0?r:void 0}function Do(n,e,t){let r=Ps(n,e),s=t??Ao;return r!==void 0?Math.min(r*1e3,s):1e3}function ot(n){return new Promise(e=>setTimeout(e,n))}function gu(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}function jo(n,e,t,r){if(!n)throw new De(`[urun] ${r} ${t} without ws_url`);let s,i;try{s=new URL(n)}catch{throw new De(r==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${t}`:`[urun] ${r} ${t} with non-absolute ws_url`)}try{i=new URL(te(e))}catch{throw new De(`[urun] ${r} ${t} has invalid gateway base URL`)}let o=_u(i.hostname)&&i.protocol==="http:";if(!(o&&s.protocol==="ws:"||s.protocol==="wss:"))throw new De(`[urun] ${r} ${t} with insecure ws_url`);if(!vu(s,i,o))throw new De(`[urun] ${r} ${t} with cross-origin ws_url`);return s.toString()}function _u(n){return n==="localhost"||n==="127.0.0.1"||n==="::1"||n.endsWith(".localhost")}function vu(n,e,t){return!!(t||n.hostname===e.hostname&&n.port===e.port||xo(n.hostname)&&xo(e.hostname))}function xo(n){return n==="urun.sh"||n.endsWith(".urun.sh")}function wu(n){try{return new URL(n).hostname!==Nl?[]:Wl}catch{return[]}}var Nl,Wl,Fl,$l,jl,ql,Bl,Hl,Vl,Ao,zl,Kl,Gl,Co,tu,ru,nu,su,iu,du,uu,De,at,St=W(()=>{"use strict";Ze();bt();Ro();Nl="session-api.prod.cloud.urun.sh",Wl=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];Fl="/v1";$l=120,jl=1e3,ql=20,Bl=5,Hl=5e3;Vl=500,Ao=1e4,zl=new Set([502,503,504]),Kl=2,Gl=50,Co=1e4;tu=500,ru=9e5,nu=6e4,su=6e5,iu={queued:!0,claimed:!0,starting:!0,retry_pending:!0};du=new Set([400,402,409]);uu=new Set(["capture-attested","no-portable-golden","portable-golden-release-mismatch","portable-golden-attestation-invalid"]);De=class extends Error{},at=class extends B{}});function nr(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function qo(n){if(!n||typeof n!="object")throw new ve("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=Ve(e,"artifact_id")||Ve(e,"id"),r=Ve(e,"filename"),s=Ve(e,"kind"),i=Ve(e,"status")||"ready",o=yu(e,"size_bytes"),a=Ve(e,"sha256");if(!t||!r||!s||o==null||!a)throw new ve("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:Ve(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:Ve(e,"created_at"),expiresAt:Ve(e,"expires_at")}}function Ve(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function yu(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function bu(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function Su(n){return n===401||n===403}function ku(n,e,t){return n===401?new Ds(t,e):n===404?new xs(t,e):new ve(t,n,e)}function Bo(n){if(!n||typeof n!="object"||Array.isArray(n))throw new ve("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var ve,Ds,xs,rr,Ho=W(()=>{"use strict";St();ve=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},Ds=class extends ve{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},xs=class extends ve{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};rr=class{_options;constructor(e){this._options=e}async list(e){let r=Bo(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new ve("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(qo)}async getDownloadUrl(e,t){let r=Bo(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!bu(s))throw new ve("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:qo(r.artifact),downloadUrl:s}}async _request(e,t){let r=tr(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of r)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof ve&&Su(s.status))throw s}throw s??new ve("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${te(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:c}=await this._readError(o,e);throw ku(o.status,a,c)}try{return await o.json()}catch(a){throw new ve(`[urun] runtime artifacts: invalid JSON response from ${te(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let r=te(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}});function Tu(n){return/^(\d+[smhdw])+$/.test(n)}function Ru(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new Gr(r,e??"unauthorized");if(n===404)return new Is(r,e??"not_found");if(n===400)return new Qr(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new As(r,e);case"pin_requires_active_temp":return new Ls(r,e);case"permanent_locked":return new Ms(r,e)}return new Ne(r,{status:n,code:e??`http_${n}`})}var Ne,Gr,Is,As,Ls,Ms,Qr,Yr,Vo=W(()=>{"use strict";Ne=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},Gr=class extends Ne{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Is=class extends Ne{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},As=class extends Ne{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},Ls=class extends Ne{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},Ms=class extends Ne{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},Qr=class extends Ne{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};Yr=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!Tu(t))throw new Qr(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new Ne("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,r.body))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw Ru(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let i={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new Gr("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}}});var Ko=L((Bg,zo)=>{"use strict";var kt=1e3,Tt=kt*60,Rt=Tt*60,ct=Rt*24,Cu=ct*7,Eu=ct*365.25;zo.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return Pu(n);if(t==="number"&&isFinite(n))return e.long?xu(n):Du(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function Pu(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Eu;case"weeks":case"week":case"w":return t*Cu;case"days":case"day":case"d":return t*ct;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Rt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Tt;case"seconds":case"second":case"secs":case"sec":case"s":return t*kt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Du(n){var e=Math.abs(n);return e>=ct?Math.round(n/ct)+"d":e>=Rt?Math.round(n/Rt)+"h":e>=Tt?Math.round(n/Tt)+"m":e>=kt?Math.round(n/kt)+"s":n+"ms"}function xu(n){var e=Math.abs(n);return e>=ct?Jr(n,e,ct,"day"):e>=Rt?Jr(n,e,Rt,"hour"):e>=Tt?Jr(n,e,Tt,"minute"):e>=kt?Jr(n,e,kt,"second"):n+" ms"}function Jr(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var Os=L((Hg,Go)=>{"use strict";function Iu(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=Ko(),t.destroy=d,Object.keys(n).forEach(l=>{t[l]=n[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let u=0;for(let p=0;p<l.length;p++)u=(u<<5)-u+l.charCodeAt(p),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(l){let u,p=null,m,g;function f(...h){if(!f.enabled)return;let _=f,v=Number(new Date),S=v-(u||v);_.diff=S,_.prev=u,_.curr=v,u=v,h[0]=t.coerce(h[0]),typeof h[0]!="string"&&h.unshift("%O");let w=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(T,y)=>{if(T==="%%")return"%";w++;let E=t.formatters[y];if(typeof E=="function"){let N=h[w];T=E.call(_,N),h.splice(w,1),w--}return T}),t.formatArgs.call(_,h),(_.log||t.log).apply(_,h)}return f.namespace=l,f.useColors=t.useColors(),f.color=t.selectColor(l),f.extend=r,f.destroy=t.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(m!==t.namespaces&&(m=t.namespaces,g=t.enabled(l)),g),set:h=>{p=h}}),typeof t.init=="function"&&t.init(f),f}function r(l,u){let p=t(this.namespace+(typeof u>"u"?":":u)+l);return p.log=this.log,p}function s(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let u=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of u)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function i(l,u){let p=0,m=0,g=-1,f=0;for(;p<l.length;)if(m<u.length&&(u[m]===l[p]||u[m]==="*"))u[m]==="*"?(g=m,f=p,m++):(p++,m++);else if(g!==-1)m=g+1,f++,p=f;else return!1;for(;m<u.length&&u[m]==="*";)m++;return m===u.length}function o(){let l=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),l}function a(l){for(let u of t.skips)if(i(l,u))return!1;for(let u of t.names)if(i(l,u))return!0;return!1}function c(l){return l instanceof Error?l.stack||l.message:l}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Go.exports=Iu});var Qo=L((me,Xr)=>{"use strict";me.formatArgs=Lu;me.save=Mu;me.load=Ou;me.useColors=Au;me.storage=Uu();me.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();me.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Au(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Lu(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Xr.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,r=0;n[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),n.splice(r,0,e)}me.log=console.debug||console.log||(()=>{});function Mu(n){try{n?me.storage.setItem("debug",n):me.storage.removeItem("debug")}catch{}}function Ou(){let n;try{n=me.storage.getItem("debug")||me.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Uu(){try{return localStorage}catch{}}Xr.exports=Os()(me);var{formatters:Nu}=Xr.exports;Nu.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Jo={};ms(Jo,{createSupportsColor:()=>Ns,default:()=>qu});function ke(n,e=globalThis.Deno?globalThis.Deno.args:en.default.argv){let t=n.startsWith("-")?"":n.length===1?"-":"--",r=e.indexOf(t+n),s=e.indexOf("--");return r!==-1&&(s===-1||r<s)}function Wu(){if(!("FORCE_COLOR"in Q))return;if(Q.FORCE_COLOR==="true")return 1;if(Q.FORCE_COLOR==="false")return 0;if(Q.FORCE_COLOR.length===0)return 1;let n=Math.min(Number.parseInt(Q.FORCE_COLOR,10),3);if([0,1,2,3].includes(n))return n}function Fu(n){return n===0?!1:{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function $u(n,{streamIsTTY:e,sniffFlags:t=!0}={}){let r=Wu();r!==void 0&&(Zr=r);let s=t?Zr:r;if(s===0)return 0;if(t){if(ke("color=16m")||ke("color=full")||ke("color=truecolor"))return 3;if(ke("color=256"))return 2}if("TF_BUILD"in Q&&"AGENT_NAME"in Q)return 1;if(n&&!e&&s===void 0)return 0;let i=s||0;if(Q.TERM==="dumb")return i;if(en.default.platform==="win32"){let o=Yo.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in Q)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in Q)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in Q)||Q.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in Q)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Q.TEAMCITY_VERSION)?1:0;if(Q.COLORTERM==="truecolor"||Q.TERM==="xterm-kitty"||Q.TERM==="xterm-ghostty"||Q.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Q){let o=Number.parseInt((Q.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Q.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Q.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Q.TERM)||"COLORTERM"in Q?1:i}function Ns(n,e={}){let t=$u(n,{streamIsTTY:n&&n.isTTY,...e});return Fu(t)}var en,Yo,Us,Q,Zr,ju,qu,Xo=W(()=>{"use strict";en=Je(require("process"),1),Yo=Je(require("os"),1),Us=Je(require("tty"),1);({env:Q}=en.default);ke("no-color")||ke("no-colors")||ke("color=false")||ke("color=never")?Zr=0:(ke("color")||ke("colors")||ke("color=true")||ke("color=always"))&&(Zr=1);ju={stdout:Ns({isTTY:Us.default.isatty(1)}),stderr:Ns({isTTY:Us.default.isatty(2)})},qu=ju});var ea=L((ne,rn)=>{"use strict";var Bu=require("tty"),tn=require("util");ne.init=Yu;ne.log=Ku;ne.formatArgs=Vu;ne.save=Gu;ne.load=Qu;ne.useColors=Hu;ne.destroy=tn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ne.colors=[6,2,3,4,5,1];try{let n=(Xo(),uo(Jo));n&&(n.stderr||n).level>=2&&(ne.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}ne.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),n[t]=r,n},{});function Hu(){return"colors"in ne.inspectOpts?!!ne.inspectOpts.colors:Bu.isatty(process.stderr.fd)}function Vu(n){let{namespace:e,useColors:t}=this;if(t){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${s};1m${e} \x1B[0m`;n[0]=i+n[0].split(`
|
|
1
|
+
"use strict";var Sl=Object.create;var Dr=Object.defineProperty;var kl=Object.getOwnPropertyDescriptor;var Tl=Object.getOwnPropertyNames;var Rl=Object.getPrototypeOf,Cl=Object.prototype.hasOwnProperty;var W=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var L=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ms=(n,e)=>{for(var t in e)Dr(n,t,{get:e[t],enumerable:!0})},lo=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tl(e))!Cl.call(n,s)&&s!==t&&Dr(n,s,{get:()=>e[s],enumerable:!(r=kl(e,s))||r.enumerable});return n};var Je=(n,e,t)=>(t=n!=null?Sl(Rl(n)):{},lo(e||!n||!n.__esModule?Dr(t,"default",{value:n,enumerable:!0}):t,n)),uo=n=>lo(Dr({},"__esModule",{value:!0}),n);var xr,vt,Ir=W(()=>{"use strict";xr=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let r;try{r=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!r.channel)return;let s=this._handlers.get(r.channel);if(s)for(let i of s)i(r)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}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)}}emit(e,t){if(this._disposed)return;let r=JSON.stringify({channel:e,...t});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(r);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(r),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},vt=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[r,s]of this._handlers)for(let i of s)this._targetUnsubscribes.push(e.on(r,i));let t=this._pendingSends;this._pendingSends=[];for(let r of t)e.emit(r.channel,r.data)}rewriteSessionChannels(e,t){if(e===t)return;let r=`session:${e}:`,s=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(r)?s+o.slice(r.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(r)?s+o.channel.slice(r.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let r=this._handlers.get(e);r||(r=new Set,this._handlers.set(e,r)),r.add(t);let s=this._target?.on(e,t);return s&&this._targetUnsubscribes.push(s),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e),s?.(),s&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==s))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}}});function Pl(n){return n.replace(/\bhttps?:\/\/[^\s)]+/g,"the session gateway")}function po(n){let e=n.replace(El,"");return Pl(e||n.replace(/^\[urun\] /,""))}function ho(n){let e=n.error?.httpStatus;if(e===401||e===403)return"The backend rejected this client \u2014 sign in again or check the auth token / org access.";if(n.error?.code==="session_archived")return"This session is archived \u2014 call directory.unarchive(sessionId) (the session directory's un-archive verb), then reconnect with the same id.";let t=n.error?.retryAfterSeconds,r=t!==void 0?` It asked for ${Math.round(t)}s.`:"";return e===429?`The backend is shedding load \u2014 its admission queue is full, so this is capacity, not your request.${r} The SDK already retried with backoff; try again in a moment.`:e===408?`The request timed out before the backend answered \u2014 that is a timeout, not a verdict on your request.${r} The SDK already retried with backoff; try again in a moment.`:e!==void 0&&e>=500?"The backend is having an outage (nothing is wrong with your request) \u2014 the SDK already retried with backoff, so try again shortly and report the status above if it persists.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."}function fo(n,e){let t=e.error?.reason,r=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(n){case"create-failed":{let s=e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:"",i=e.error?.code;return i==="queue_ttl_expired"||i==="stale_poll_expired"?{message:`[urun] the queued session REQUEST timed out while waiting${s} (${i}) \u2014 the session itself is untouched`,hint:"Nothing was lost and nothing needs replacing: connect again with the same session and the control plane re-admits the request (a poll that arrives in time re-drives it on its own)."}:i==="session_archived"?{message:`[urun] this session is archived${s} \u2014 un-archive it before resuming`+(t?`: ${po(t)}`:""),hint:ho(e)}:i==="client_release"?{message:`[urun] the session's admission request was closed (client_release)${s} \u2014 this dial cannot attach through it`,hint:"The request row is terminal; retrying the same dial only repeats the 410. Create a fresh session (a new dial). The SDK itself never closes a request \u2014 a whenLive timeout only rejects."}:{message:`[urun] session create failed${s}${t?`: ${po(t)}`:""}`,hint:ho(e)}}case"never-live":{let s=r!==void 0?` after ${r}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`,o=e.lastServerStatus!==void 0&&["requested","queued","pending","allocating","provisioning","waking","waiting_for_capacity","unavailable","allocated","starting"].includes(e.lastServerStatus);return e.error?.code==="expired"?o?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before a runtime picked it up${s}${i} \u2014 the backend never dispatched the session (no runtime pulled it), so no media transport could ever connect`,hint:"Not a network problem \u2014 the session was still waiting for a runtime. Retry in a moment; if it persists, the backend dispatch lane is stuck."}:{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${s} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?o?{message:`[urun] session ${e.sessionId} was created but no runtime ever picked it up${s}${i} \u2014 the backend has not dispatched the session yet (a runtime pulls the demand, then the session server exists)`,hint:"Waiting for a runtime \u2014 not a network, VPN, or firewall problem. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] session ${e.sessionId} was created but never went live${s}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${s} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${t?`: ${t}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${t?`: ${t}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"runtime-failed":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} failed at runtime${t?`: ${t}`:""}`,hint:"The session function crashed on the backend \u2014 check the app logs. The session itself is parked, not gone: attach to it again once the app is fixed."};case"produce-timeout":return{message:`[urun] publishing a track timed out${t?`: ${t}`:""} \u2014 the SFU never acked the produce (the runtime\u2019s inbound port for the stream was not advertised in time)`,hint:"The runtime was still cold or the backend was at capacity when the track was published. Retry in a moment; if it persists, the backend never opened the stream to receive it."};case"insufficient-credits":return{message:`[urun] session create refused${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""} \u2014 the org has insufficient credits${t?`: ${t}`:""}`,hint:"Out of credits \u2014 add credits to keep running sessions."}}}var Xe,_e,Pe,He,Ar,Lr,Mr,Nr,Or,Qt,Ur,El,wt,Yt,B,Ze=W(()=>{"use strict";Xe=class extends Error{code="session_end_unavailable";constructor(e="[urun] this session handle cannot terminally end the session; disconnect the viewer instead",t){super(e),this.name="SessionEndUnavailableError",t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},_e=class extends Error{code;httpStatus;requestId;sessionId;constructor(e,t){super(e),this.name="SessionEndError",this.code=t.code??"session_end_failed",this.httpStatus=t.httpStatus,this.requestId=t.requestId,this.sessionId=t.sessionId,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},Pe=class extends Error{code;httpStatus;constructor(e,t){super(e),this.name="SessionDirectoryError",this.code=t?.code??"session_directory_failed",this.httpStatus=t?.httpStatus,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},He=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},Ar=class extends He{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},Lr=class extends He{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},Mr=class extends Error{stream;owner;attempted;constructor(e,t,r){super(`[urun] stream "${e}" is already produced by the ${t}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},Nr=15e3,Or=class extends Error{kind;stream;timeoutMs;constructor(e,t){let r=t?.timeoutMs??Nr,s=t?.stream??e,i=s!==e?` "${s}"`:"";super(`[urun] SFU did not ack producer ${e}${i} within ${Math.round(r/1e3)}s \u2014 the server never replied to 'produce'. The runtime's inbound port for this stream is likely unadvertised (a cold or capacity-queued runtime), so the SFU has nothing to forward the track to; the published track never reached the runtime.`),this.name="ProduceAckTimeout",this.kind=e,this.stream=s,this.timeoutMs=r,Object.setPrototypeOf(this,new.target.prototype)}},Qt=class extends He{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},Ur=class extends He{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}},El=/^\[urun\] (?:timed out waiting for session allocation at|session allocation wait expired at|session allocation poll failed at|session allocation failed at|session allocation at|session create at) \S+(?::[ \t]+|[ \t]+|$)/;wt=class extends Error{kind;status;hint;constructor(e,t,r){let{message:s,hint:i}=fo(e,t);super(s),this.name="SessionFailedError",this.kind=e,this.status=t,this.hint=i,r?.cause!==void 0&&(this.cause=r.cause),Object.setPrototypeOf(this,new.target.prototype)}},Yt=class extends Error{code="transport_session_mismatch";connectedSessionId;requestedSessionId;constructor(e,t){super(`[urun] cannot retarget a connected transport to a different session: this leg is live on ${e??"(unknown)"} but setConnection() asked for ${t} \u2014 disconnect() this leg first (or use a fresh session handle)`),this.name="TransportSessionMismatchError",this.connectedSessionId=e,this.requestedSessionId=t,Object.setPrototypeOf(this,new.target.prototype)}},B=class extends Error{httpStatus;code;balanceCredits;platformStatus;retryAfterSeconds;constructor(e,t){super(e),this.name="SessionAllocationError",this.httpStatus=t?.httpStatus,this.code=t?.code,this.balanceCredits=t?.balanceCredits,this.platformStatus=t?.platformStatus,this.retryAfterSeconds=t?.retryAfterSeconds,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}}});function st(n){if(!n)return!1;let e=typeof n=="string"?n:n.name;return e==="queued"||e==="unavailable"||e==="provisioning"||e==="waiting_for_capacity"}function go(n,e={}){let{signal:t}=e;return new Promise((r,s)=>{if(t?.aborted){s(t.reason instanceof Error?t.reason:new Error("whenLive aborted"));return}if(n.phase?.name==="live"){r();return}if(n.phase?.name==="error"){let w=n.phase,b=n.status??{phase:w.name,transportState:"disconnected",sessionId:w.sessionId,requestId:w.requestId,queue:w.queue,error:w.error,region:w.region};s(new wt(w.error?.kind??"transport-failed",b));return}let o,a,c=!1,d=w=>{c||(c=!0,a!==void 0&&clearTimeout(a),t?.removeEventListener("abort",l),o?.(),w?s(w):r())},l=()=>{d(t?.reason instanceof Error?t.reason:new Error("whenLive aborted"))};t?.addEventListener("abort",l,{once:!0});let u=()=>{let w=n.phase;return n.status??{phase:w?.name??"idle",transportState:"disconnected",sessionId:w?.sessionId,requestId:w?.requestId,queue:w?.queue,error:w?.error,region:w?.region}},p=w=>d(new wt(w,u())),m=e.timeout!==void 0,g=Date.now(),f=m?e.timeout:Dl,h=()=>{a!==void 0&&(clearTimeout(a),a=void 0)},_=()=>{if(c||f<=0)return;clearTimeout(a);let w=g+f-Date.now();a=setTimeout(()=>{if(!m&&st(n.phase?.name)){a=void 0;return}let b=u();b.elapsedMs===void 0&&(b.elapsedMs=f),a=void 0,t?.removeEventListener("abort",l),o?.(),o=void 0,d(new wt("never-live",b))},Math.max(0,w))},v=w=>{!m||c||f<=0||w?.runtime?.wake?.expectedWakePath==="cold-boot"&&(mo<=f||(f=mo,_()))},S=w=>{if(!c){if(!m&&st(w?.name)){h();return}if(m){v(w),a===void 0&&f>0&&_();return}a===void 0&&(g=Date.now(),_())}};o=n.onPhase(w=>{w?.name==="live"?d():w?.name==="error"?p(w.error?.kind??"transport-failed"):S(w)}),c||S(n.phase),c&&o()})}var Dl,mo,Wr=W(()=>{"use strict";Ze();Dl=45e3,mo=6e5});function xl(n){if(typeof n=="string"&&n.length>0)return n;if(n&&typeof n=="object"){let e=n.note;if(typeof e=="string"&&e.length>0)return e}}var gs,_o,vo,Il,Fr,wo=W(()=>{"use strict";gs="platform",_o="activation",vo="desired.activation";Il=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],Fr=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let s=()=>this._firstMedia(e);r.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",s));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of Il){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let s={state:t,elapsedMs:r,stream:e.name},i=xl(this._options.hint());i!==void 0&&(s.hint=i),e.lastEvent=s;for(let o of Array.from(this._handlers))o(s)}}});function it(){return typeof process<"u"&&process.stdout!=null&&typeof process.stdout.write=="function"}function et(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function bo(){return et()?"Chrome111":void 0}function ko(){return typeof globalThis.RTCPeerConnection<"u"?null:So??"the WebRTC peer globals (RTCPeerConnection) are not installed in this runtime"}function yt(){return et()?$r||($r=Ll(),$r):Promise.resolve()}async function Ll(){let n=globalThis;if(typeof n.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;n.WebSocket=t}catch(e){yo("WebSocket",e)}if(typeof n.RTCPeerConnection>"u")try{let e=await import("werift");Ol(n,e)}catch(e){So=yo("werift",e)}}function Ol(n,e){let{RTCPeerConnection:t,useH264:r,useVP8:s,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:d,useVideoOrientation:l}=e,u=()=>({video:[r(),s()],audio:[i()]}),p=()=>({video:[o(),a(),c(),d(),l()],audio:[o(),c(),d()]});class m extends t{constructor(f){super({...f,codecs:f?.codecs??u(),headerExtensions:f?.headerExtensions??p()})}async setRemoteDescription(f){await super.setRemoteDescription(f);let _=this.sctpManager,v=_?.sctpTransport,S=_?.connectSctp;!v||typeof S!="function"||v.dtlsTransport?.state==="connected"&&v.sctp?.associationState!==Ml&&await S.call(_)}}n.RTCPeerConnection=m;for(let g of Al)e[g]!=null&&typeof n[g]>"u"&&(n[g]=e[g])}function yo(n,e){let t=e instanceof Error?e.message:String(e),r=`optional dependency "${n}" unavailable (${t})`;return console.warn(`[urun-sh/core] Node WebRTC support: ${r}. Realtime media will not work in this Node process; install "${n}" to enable it. Doc/KV transport over WebSocket is unaffected.`),r}var Al,$r,So,Ml,bt=W(()=>{"use strict";Al=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],$r=null,So=null;Ml=4});function Br(n,e=Math.random){if(!Number.isFinite(n)||n<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${n}`);let t=Math.min(qr,_s*2**n);return Math.round(e()*t)}function vs(n){if(n instanceof B){let e=n.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return n instanceof Error?n.name==="TypeError"||n.name==="TimeoutError"||n.name==="AbortError":!1}function ws(){return jr<1?!1:(jr-=1,!0)}function ys(){jr=Math.min(To,jr+Ul)}var _s,qr,Jt,To,Ul,jr,Ro=W(()=>{"use strict";Ze();_s=500,qr=15e3,Jt=6;To=10,Ul=.5,jr=To});function te(n){return n.trim().replace(/\/+$/,"")}function tr(n,e){let t=[],r=s=>{if(!s)return;let i=te(s);i&&!t.includes(i)&&t.push(i)};r(n);for(let s of e??[])r(s);for(let s of wu(n))r(s);return t}function Vr(n){try{return new URL(te(n)).pathname===Fl}catch{return!1}}function bs(n){try{if(typeof fetch!="function")return;let e=te(n.baseUrl),t=n.sessionId?`${e}/api/sessions/${encodeURIComponent(n.sessionId)}/end`:`${e}/api/session-requests/${encodeURIComponent(n.requestId)}/cancel`;fetch(t,{method:"POST",headers:n.reason!==void 0?{...Ue(n,n.jwt),"Content-Type":"application/json"}:Ue(n,n.jwt),...n.reason!==void 0?{body:JSON.stringify({reason:n.reason})}:{},keepalive:!0}).catch(()=>{})}catch{}}async function Ss(n){try{let e=`${te(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/cancel`,t=await Oe(n);if(n.getAccessToken&&!t)throw new _e("[urun] session request cancel refused: getAccessToken resolved no token (an unauthenticated cancel is never sent)",{requestId:n.requestId,code:"no_access_token"});let r=await fetch(e,{method:"POST",headers:Ue(n,t),keepalive:!0});if((r.status===401||r.status===403)&&n.getAccessToken){let o=await Oe(n,{forceRefresh:!0,reason:"unauthorized"});o&&o!==t&&(r=await fetch(e,{method:"POST",headers:Ue(n,o),keepalive:!0}))}let s=await Zt(r);if(!r.ok)throw new _e(`[urun] session request cancel failed: ${Kr(s,r.status)}`,{requestId:n.requestId,code:s.error_code,httpStatus:r.status});let i=String(s.status??"");if(i==="cancelled"||i==="canceled"||i==="closed")return{status:"canceled",requestId:n.requestId};if(i==="failed"||i==="rejected"||i==="expired")return{status:"canceled",requestId:n.requestId,platformStatus:i};throw new _e(`[urun] session request cancel returned an unrecognized request status ${JSON.stringify(i)} (recognized: cancelled/canceled, closed, failed, rejected, expired)`,{requestId:n.requestId,code:"invalid_release_response",httpStatus:r.status})}catch(e){throw e instanceof _e?e:new _e("[urun] session request cancel failed",{requestId:n.requestId,cause:e})}}async function ks(n){let e;try{e=await zr(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/end`,{method:"POST",keepalive:!0},"session end")}catch(a){if(a instanceof _e)throw a;let c=a;throw new _e(c?.message??"[urun] session end request failed",{sessionId:n.sessionId,...c?.code!==void 0?{code:c.code}:{},...c?.httpStatus!==void 0?{httpStatus:c.httpStatus}:{},cause:a})}let t=Cs(e)?e:{},r=String(t.status??""),s=typeof t.pause_reason=="string"?t.pause_reason:void 0,i=typeof t.terminal_reason=="string"?t.terminal_reason:void 0,o=er(s)?s:er(i)?i:void 0;if(r==="paused")return{status:"paused",sessionId:String(t.logical_id??t.id??n.sessionId),...o!==void 0?{reason:o}:{}};throw new _e(`[urun] session end returned ${JSON.stringify(r)} for session ${n.sessionId} \u2014 an end PARKS the session, so the only contract-valid answer is "paused" (a terminal word on this route would be a session-plane terminal write, which is forbidden)`,{sessionId:n.sessionId,code:"invalid_end_response"})}function Io(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function Ts(n,e=Date.now()){if(!n)return null;let t=n.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),s=r.padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return typeof i.exp!="number"||!Number.isFinite(i.exp)?null:i.exp*1e3-e}catch{return null}}async function Eo(n,e){let t=Date.now()+Co;for(;;){await ot(Gl);let r=await Oe(n);if(r)return r;if(Date.now()>=t)throw new B(`[urun] session allocation at ${e} never got an access token: the wired getAccessToken resolved nothing within ${Math.round(Co/1e3)}s (no unauthenticated request was sent)`)}}function Ql(n,e){if(!n)return null;try{let t=new URL(n),r=e?new URL(te(e)):null,s=t.pathname==="/api/sessions/create"||t.pathname==="/api/sessions/create/";return t.protocol!=="https:"||!s||!Zl(t,r)?null:te(t.origin)}catch{return null}}function Yl(n,e){if(!n||!n.trim())return{outcome:"absent"};if(!Jl(e))return{outcome:"bootstrap-only"};let t=n.includes("://")?n:`https://${n}`,r;try{r=new URL(t)}catch{return{outcome:"rejected",reason:"not a parseable URL or host"}}return r.protocol!=="https:"?{outcome:"rejected",reason:`scheme ${r.protocol} is not https:`}:r.pathname!=="/"&&r.pathname!==""?{outcome:"rejected",reason:`expected a bare origin, got path ${r.pathname}`}:Hr(r.hostname)?{outcome:"pinned",base:te(r.origin)}:{outcome:"rejected",reason:`host ${r.hostname} is outside the urun.sh trust set`}}function Jl(n){if(!n)return!1;try{let e=new URL(te(n));return e.protocol==="https:"&&Hr(e.hostname)}catch{return!1}}function Xl(n){let e=te(n);try{return te(new URL(e).origin)}catch{return e}}function Zl(n,e){return Hr(n.hostname)&&(!e||Hr(e.hostname))}function Hr(n){let e=n.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}function eu(n){let e=n instanceof B?n.retryAfterSeconds:void 0;return e===void 0||!Number.isFinite(e)||e<=0?0:Math.min(e*1e3,qr)}function Lo(n,e){let t=eu(e);return t>0?Math.max(n,Date.now()+t):n}async function Mo(n){if(Vr(n.baseUrl))return ou(n);let e=tr(n.baseUrl,n.fallbackUrls),t=null,r=0,s=e.length>1;for(let i=0;i<Jt;i++){for(let o of e)try{let a=await au(o,n,{pollAttempts:$l,retryAfterLimitMs:s?jl:void 0});return ys(),a}catch(a){if(t=a instanceof Error?a:new Error(String(a)),r=Lo(r,t),t instanceof De||t instanceof at||lu(t))throw t}if(!vs(t))break;if(i+1<Jt){if(!ws())break;await ot(Math.max(Br(i),r-Date.now()))}}throw t??new Error("[urun] session allocation failed")}async function ou(n){let e=te(n.baseUrl),t=n.jwt??await n.getAccessToken?.({reason:"background"})??void 0;if(!t)throw new B("[urun] hub allocation requires a client token (jwt or getAccessToken)",{httpStatus:401});let r=await fetch(`${e}/sessions`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({...Vr(n.baseUrl)?{shape:n.shape??"cpu:1"}:{resource_class:"cpu"},idempotency_key:n.idempotencyKey,metadata:{app:n.app,function:n.functionName,org:n.orgId,...n.sessionKey?{logical_id:n.sessionKey}:{}}})}),s=await r.text();if(!r.ok)throw new B(`[urun] hub create failed (${r.status}): ${s.slice(0,300)}`,{httpStatus:r.status});let i=JSON.parse(s);n.onRequest?.({requestId:i.session_id,baseUrl:e,sessionId:i.session_id});let o=null;for(;iu[i.state];){let c=Date.now();if(i.state==="queued"||i.state==="retry_pending"){o=null;let l=i.queue_deadline_at===null?null:typeof i.queue_deadline_at=="number"&&i.queue_deadline_at>0?i.queue_deadline_at:c+ru;if(l!==null&&c>=l+nu)throw new B(`[urun] hub session ${i.session_id} is still ${i.state} past the hub's queue deadline (${i.last_error??i.pause_reason??"hub reported no reason"})`,{httpStatus:504,platformStatus:i.state})}else if(o??=c+su,c>=o)throw new B(`[urun] hub session ${i.session_id} stuck ${i.state} past the boot patience window (${i.last_error??"hub reported no reason"})`,{httpStatus:504,platformStatus:i.state});n.onAdmission?.({status:i.state,sessionId:i.session_id}),await ot(tu);let d=await fetch(`${e}/sessions/${encodeURIComponent(i.session_id)}`,{headers:{authorization:`Bearer ${t}`}});if(!d.ok){if(d.status===404)throw new B(`[urun] hub session ${i.session_id} disappeared (${d.status})`,{httpStatus:d.status});continue}i=await d.json()}if(i.state==="failed"||i.state==="completed")throw new B(`[urun] hub session ${i.session_id} reached ${i.state} (${i.last_error??i.terminal_reason??"no reason recorded"})`,{httpStatus:503,platformStatus:i.state});if(i.state==="paused")throw new B(`[urun] hub session ${i.session_id} is parked (${i.pause_reason??i.last_error??"no reason recorded"})`,{httpStatus:503,platformStatus:i.state});if(i.state!=="running"||!i.sfu_endpoint)throw new B(`[urun] hub session ${i.session_id} ended in state=${i.state} without an sfu_endpoint (${i.last_error??i.terminal_reason??"no reason recorded"})`,{httpStatus:504,platformStatus:i.state});let a=Oo(i);if(!a)throw new B(`[urun] hub session ${i.session_id} is running but carried no sfu_attach credential (hub deployment predates lane 52, or HUB_GRANT_SECRET is unset)`,{httpStatus:502,platformStatus:i.state});return{baseUrl:e,sessionId:i.session_id,wsUrl:i.sfu_endpoint,endsAt:null,sfuAttach:a,response:i}}function Oo(n){let e=n.sfu_attach;if(!(!e||typeof e.token!="string"||typeof e.gen!="number"||!Number.isInteger(e.gen)||e.gen<0||e.token.length===0))return{url:n.sfu_endpoint??"",token:e.token,gen:e.gen}}async function Uo(n){let e=te(n.baseUrl),t=await fetch(`${e}/sessions/${encodeURIComponent(n.sessionId)}`,{headers:n.jwt?{authorization:`Bearer ${n.jwt}`}:{}});if(t.status===401||t.status===403)throw new B(`[urun] hub session view refresh refused (${t.status}) for ${n.sessionId}`,{httpStatus:t.status});if(!t.ok)return null;let r=await t.json();if(r.session_id!==n.sessionId||r.state!=="running"||!r.sfu_endpoint)return null;let s=Oo(r);return s?{url:r.sfu_endpoint,sessionId:r.session_id,sfuAttach:s}:null}async function au(n,e,t){let r,s,i,o,a=Xl(n),c=0,d=new Set,l=Date.now(),u=l+t.pollAttempts*Ao,p=!1,m=12e4,g=10080*60,f=S=>{if(typeof S!="number"||!Number.isFinite(S)||S<=0||S>g)return;let w=l+S*1e3+m;w>u&&(u=w,p=!0)},h=()=>p?Number.POSITIVE_INFINITY:t.pollAttempts,_=8,v=0;for(let S=0;S<h();S++){if(p&&Date.now()>=u)throw Xt(a,!!r,o);s=i??await Oe(e),i=void 0,e.getAccessToken&&!s&&(s=await Eo(e,a));let w=!!r,b=Date.now(),T;if(r){let $=0,j=G=>{let Z=Math.min(qr,_s*2**$),he=Math.max(Math.ceil(Z/2),Br($));return $+=1,Math.min(Math.max(G,he),Math.max(0,u-Date.now()))};for(;;){let G=u-Date.now();if(G<=0)throw Xt(a,!0,o);let Z=Math.max(1,Math.min(ql,Math.floor(G/1e3)));{let ee=Ts(s);if(ee!==null&&ee<Z*1e3+Hl)try{let Me=await Oe(e,{forceRefresh:!0});Me&&Me!==s&&(s=Me)}catch{}}b=Date.now();try{T=await fetch(`${a}/api/session-requests/${encodeURIComponent(r)}?wait_s=${Z}`,{headers:Ue(e,s),redirect:"manual",signal:gu((Z+Bl)*1e3)})}catch{let ee=j(0);if(ee<=0)throw Xt(a,!0,o);await ot(ee);continue}if(o=`HTTP ${T.status}`,!zl.has(T.status))break;try{await T.body?.cancel()}catch(ee){throw new at(`[urun] session allocation poll response cleanup failed at ${a}`,{cause:ee})}let he=j(Do(T,{},t.retryAfterLimitMs));if(he<=0)throw Xt(a,!0,o);await ot(he)}}else T=await fetch(`${a}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Ue(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(cu(e))});if(T.type==="opaqueredirect"||T.status>=300&&T.status<400){try{await T.body?.cancel()}catch{}throw new De(`[urun] ${w?"session poll":"session create"} at ${a} answered an HTTP redirect (status ${T.status}) \u2014 browsers cannot follow a cross-origin redirect with credentials; the control plane must emit the JSON redirect envelope ({status:"redirect", location})`)}let y=await Zt(T);if(o=typeof y.status=="string"&&y.status?y.status:`HTTP ${T.status}`,T.status!==401&&T.status!==403&&(v=0),!r&&y.status==="redirect"){let $=Ql(y.location,a);if(!$)throw new B(`[urun] session create at ${a} answered a redirect envelope without a usable location (${JSON.stringify(y.location??null)}) \u2014 refusing to re-issue an authenticated create to an untrusted target`);if($===a)throw new B(`[urun] session create at ${a} redirected to ITSELF \u2014 control-plane region apex map misconfiguration`);if(c>=Kl)throw new B(`[urun] session create followed ${c} region redirects and was redirected AGAIN (${a} -> ${$}) \u2014 region forward loop, giving up loudly`);c+=1,a=$;continue}if(y.request_id)try{e.onRequest?.({requestId:y.request_id,baseUrl:a,...y.session_id?{sessionId:y.session_id}:{}})}catch{}if(T.ok&&(y.status==="allocated"||!y.status&&!!y.session_id)&&!!y.session_id){let $=y.session_id,j=Yl(y.session_api_base,a);if(j.outcome==="rejected")throw new De(`[urun] gateway allocated session ${y.session_id} with an unusable session_api_base (${JSON.stringify(y.session_api_base)}): ${j.reason} \u2014 refusing to pin the session to a region it may not belong to`);if(j.outcome==="pinned"&&j.base!==a&&(a=j.base,y.request_id))try{e.onRequest?.({requestId:y.request_id,baseUrl:a,...y.session_id?{sessionId:y.session_id}:{}})}catch{}let G=jo(y.ws_url,a,$,"gateway allocated session");return{baseUrl:a,sessionId:$,wsUrl:G,endsAt:Io(y.ends_at),response:y}}if(T.status===202||y.status==="pending"||y.status==="queued"||y.queued){if(r=y.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(f(y.effective_max_queue_time_s),e.onAdmission)try{e.onAdmission(mu(y,r))}catch{}let $=Date.now()-b<Vl;w&&$&&await ot(Do(T,y,t.retryAfterLimitMs));continue}if((T.status===401||T.status===403)&&e.getAccessToken&&y.error_code!=="session_name_not_yours"){let $=s??"";if(d.add($),p&&(v+=1,v>_))throw new at(`[urun] session allocation failed at ${a}: authorization refused ${_} consecutive refreshes while the admission wait was extended (last server status: ${o??"none received"}) \u2014 the token provider keeps minting fresh tokens the control plane rejects`,{httpStatus:T.status,code:y.error_code,platformStatus:y.status});let j=await Oe(e,{forceRefresh:!0,reason:"unauthorized"});if(j&&!d.has(j)){i=j;continue}if(j===void 0){let G=await Eo(e,a);if(!d.has(G)){i=G;continue}}}let N=Kr(y,T.status),J=y.error_code??(T.status===402?"insufficient_credits":void 0),se=w?at:B;throw new se(`[urun] session allocation failed at ${a}: ${N}`,{httpStatus:T.status,code:J,balanceCredits:typeof y.balance_credits=="number"?y.balance_credits:void 0,platformStatus:y.status,retryAfterSeconds:Ps(T,y)})}throw Xt(a,!!r,o)}function Xt(n,e=!1,t){let r=e?at:B;return new r(`[urun] session allocation wait expired at ${n} \u2014 the CLIENT-side wait budget elapsed (last server status: ${t??"none received"}; the gateway reported no failure)`)}function Ue(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function Oe(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function cu(n){let e=n.priority==="preempt";return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey,...n.sessionKey&&!e?{logical_id:n.sessionKey}:{},...n.concurrencyKey&&!e?{concurrency_key:n.concurrencyKey}:{},...n.label&&!n.sessionKey?{label:n.label}:{},...e?{priority:"preempt"}:{},...n.sharedApp?{shared_app:!0}:{}}}async function zr(n,e,t,r){let s=await Oe(n);if(n.getAccessToken&&!s)throw new Pe(`[urun] ${r} refused: getAccessToken resolved no token (an unauthenticated request is never sent)`,{code:"no_access_token"});let i=tr(n.baseUrl,n.fallbackUrls),o;for(let a of i){let c=`${te(a)}${e}`,d=p=>fetch(c,{method:t.method,headers:t.body!==void 0?{...Ue(n,p),"Content-Type":"application/json"}:Ue(n,p),...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...t.keepalive?{keepalive:!0}:{}}),l;try{if(l=await d(s),(l.status===401||l.status===403)&&n.getAccessToken){let p=await Oe(n,{forceRefresh:!0,reason:"unauthorized"});p&&p!==s&&(l=await d(p))}}catch(p){o=p;continue}let u=await Zt(l);if(!l.ok)throw new Pe(`[urun] ${r} failed: ${Kr(u,l.status)}`,{code:u.error_code,httpStatus:l.status});return u}throw new Pe(`[urun] ${r} request failed`,{cause:o})}async function No(n){let e=new URLSearchParams;n.app&&e.set("app",n.app),n.functionName&&e.set("function",n.functionName),n.includeArchived&&e.set("include_archived","true"),n.limit!==void 0&&e.set("limit",String(n.limit)),n.cursor&&e.set("cursor",n.cursor);let t=e.toString(),r=await zr(n,`/api/sessions${t?`?${t}`:""}`,{method:"GET"},"session list");if(!Array.isArray(r?.sessions))throw new Pe("[urun] session list returned no `sessions` array \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_response"});return{rows:r.sessions,nextCursor:r.next_cursor??null}}async function Rs(n){let e=n.archived?"archive":"unarchive";await zr(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/${e}`,{method:"POST"},`session ${e}`)}async function Wo(n){await ks(n)}async function Fo(n){let e=n.name.trim();if(e.length===0)throw new Pe("[urun] session name refused: a name is required (an empty name is not a rename)",{code:"invalid_session_name"});await zr(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/name`,{method:"POST",body:{name:e,...n.source?{source:n.source}:{}}},"session name")}async function $o(n){let e=tr(n.baseUrl,n.fallbackUrls),t=null,r=0;for(let s=0;s<Jt;s++){for(let i of e)try{let o={baseUrl:i,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},a=`${te(i)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,c=await Oe(o);if(n.getAccessToken&&!c)throw new B(`[urun] viewer-connect for ${n.sessionId} refused: getAccessToken resolved no token (an unauthenticated viewer-connect is never sent)`);let d=await fetch(a,{headers:Ue(o,c)});if((d.status===401||d.status===403)&&n.getAccessToken){let p=await Oe(o,{forceRefresh:!0,reason:"unauthorized"});p&&p!==c&&(d=await fetch(a,{headers:Ue(o,p)}))}if(!d.ok){let p=await Zt(d);throw new B(`[urun] viewer-connect for ${n.sessionId} failed: `+Kr(p,d.status),{httpStatus:d.status,retryAfterSeconds:Ps(d,p)})}let l=await Zt(d),u=jo(l.ws_url,i,n.sessionId,"viewer-connect");return ys(),{baseUrl:te(i),sessionId:n.sessionId,wsUrl:u,endsAt:Io(l.ends_at),response:l}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),r=Lo(r,t),t instanceof De)throw t}if(!vs(t))break;if(s+1<Jt){if(!ws())break;await ot(Math.max(Br(s),r-Date.now()))}}throw t??new Error("[urun] viewer-connect failed")}async function Zt(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function Kr(n,e){let t=n.error_code,r=n.error_message||n.message||n.error,s=t&&r&&r!==t?`${t}: ${r}`:r||t;return s?`${s} (HTTP ${e})`:`HTTP ${e}`}function lu(n){return n instanceof B&&n.httpStatus!==void 0&&du.has(n.httpStatus)}function Cs(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function er(n){return typeof n=="string"&&n.trim().length>0}function Po(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}function pu(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0}function hu(n){if(Cs(n)&&!(!er(n.snapshot_id)||!er(n.snapshot_compat_key)||!Po(n.artifact_size_bytes)||!Po(n.durable_arena_bytes)||n.volatile_arena_bytes!==0||!pu(n.uncovered_weight_bytes)))return{snapshotId:n.snapshot_id,snapshotCompatKey:n.snapshot_compat_key,artifactSizeBytes:n.artifact_size_bytes,durableArenaBytes:n.durable_arena_bytes,volatileArenaBytes:0,uncoveredWeightBytes:n.uncovered_weight_bytes}}function fu(n){if(!Cs(n)||n.schema!=="urun.runtime.wake.v1"||n.portability!=="portable"&&n.portability!=="none"||n.expected_wake_path!=="portable-golden-restore"&&n.expected_wake_path!=="cold-boot"||typeof n.reason_code!="string"||!uu.has(n.reason_code)||n.expectation_basis!=="snapshot-registry"||n.restore_observation!=="not-observed")return;let e=n.reason_code;if(n.portability==="portable"&&n.expected_wake_path==="portable-golden-restore"&&e==="capture-attested"){let t=hu(n.golden);return t?{schema:"urun.runtime.wake.v1",portability:"portable",expectedWakePath:"portable-golden-restore",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed",golden:t}:void 0}if(n.portability==="none"&&n.expected_wake_path==="cold-boot"&&e!=="capture-attested"&&n.golden===void 0)return{schema:"urun.runtime.wake.v1",portability:"none",expectedWakePath:"cold-boot",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed"}}function Es(n){if("serving_region"in n)return typeof n.serving_region=="string"&&n.serving_region.length>0?n.serving_region:null}function mu(n,e){let r={status:typeof n.status=="string"&&n.status.length>0?n.status:n.queued?"queued":"pending",requestId:e};er(n.session_id)&&(r.sessionId=n.session_id);let s=Es(n);s!==void 0&&(r.region=s),typeof n.runtime_ready=="boolean"&&(r.runtimeReady=n.runtime_ready),(n.runtime_status==="unbound"||n.runtime_status==="starting"||n.runtime_status==="ready")&&(r.runtimeStatus=n.runtime_status),typeof n.reason=="string"&&n.reason.length>0&&(r.reason=n.reason),typeof n.decision_reason=="string"&&n.decision_reason.length>0&&(r.decisionReason=n.decision_reason),typeof n.provisioning_refusal_source=="string"&&n.provisioning_refusal_source.length>0&&(r.refusalSource=n.provisioning_refusal_source),typeof n.provisioning_refusal_message=="string"&&n.provisioning_refusal_message.length>0&&(r.refusalMessage=n.provisioning_refusal_message),typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(r.queue={position:n.queue_position,depth:n.queue_depth});let i=n.runtime_state;if(i==="unavailable"||i==="starting"||i==="busy"){r.runtime={state:i},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(r.runtime.reason=n.runtime_reason);let o=fu(n.runtime_wake);o&&(r.runtime.wake=o)}return r}function Ps(n,e){let t=Number(n.headers.get("Retry-After")||""),r=Number(e.retry_after_seconds??t);return Number.isFinite(r)&&r>0?r:void 0}function Do(n,e,t){let r=Ps(n,e),s=t??Ao;return r!==void 0?Math.min(r*1e3,s):1e3}function ot(n){return new Promise(e=>setTimeout(e,n))}function gu(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}function jo(n,e,t,r){if(!n)throw new De(`[urun] ${r} ${t} without ws_url`);let s,i;try{s=new URL(n)}catch{throw new De(r==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${t}`:`[urun] ${r} ${t} with non-absolute ws_url`)}try{i=new URL(te(e))}catch{throw new De(`[urun] ${r} ${t} has invalid gateway base URL`)}let o=_u(i.hostname)&&i.protocol==="http:";if(!(o&&s.protocol==="ws:"||s.protocol==="wss:"))throw new De(`[urun] ${r} ${t} with insecure ws_url`);if(!vu(s,i,o))throw new De(`[urun] ${r} ${t} with cross-origin ws_url`);return s.toString()}function _u(n){return n==="localhost"||n==="127.0.0.1"||n==="::1"||n.endsWith(".localhost")}function vu(n,e,t){return!!(t||n.hostname===e.hostname&&n.port===e.port||xo(n.hostname)&&xo(e.hostname))}function xo(n){return n==="urun.sh"||n.endsWith(".urun.sh")}function wu(n){try{return new URL(n).hostname!==Nl?[]:Wl}catch{return[]}}var Nl,Wl,Fl,$l,jl,ql,Bl,Hl,Vl,Ao,zl,Kl,Gl,Co,tu,ru,nu,su,iu,du,uu,De,at,St=W(()=>{"use strict";Ze();bt();Ro();Nl="session-api.prod.cloud.urun.sh",Wl=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];Fl="/v1";$l=120,jl=1e3,ql=20,Bl=5,Hl=5e3;Vl=500,Ao=1e4,zl=new Set([502,503,504]),Kl=2,Gl=50,Co=1e4;tu=500,ru=9e5,nu=6e4,su=6e5,iu={queued:!0,claimed:!0,starting:!0,retry_pending:!0};du=new Set([400,402,409]);uu=new Set(["capture-attested","no-portable-golden","portable-golden-release-mismatch","portable-golden-attestation-invalid"]);De=class extends Error{},at=class extends B{}});function nr(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function qo(n){if(!n||typeof n!="object")throw new ve("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=Ve(e,"artifact_id")||Ve(e,"id"),r=Ve(e,"filename"),s=Ve(e,"kind"),i=Ve(e,"status")||"ready",o=yu(e,"size_bytes"),a=Ve(e,"sha256");if(!t||!r||!s||o==null||!a)throw new ve("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:Ve(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:Ve(e,"created_at"),expiresAt:Ve(e,"expires_at")}}function Ve(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function yu(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function bu(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function Su(n){return n===401||n===403}function ku(n,e,t){return n===401?new Ds(t,e):n===404?new xs(t,e):new ve(t,n,e)}function Bo(n){if(!n||typeof n!="object"||Array.isArray(n))throw new ve("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var ve,Ds,xs,rr,Ho=W(()=>{"use strict";St();ve=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},Ds=class extends ve{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},xs=class extends ve{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};rr=class{_options;constructor(e){this._options=e}async list(e){let r=Bo(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new ve("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(qo)}async getDownloadUrl(e,t){let r=Bo(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!bu(s))throw new ve("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:qo(r.artifact),downloadUrl:s}}async _request(e,t){let r=tr(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of r)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof ve&&Su(s.status))throw s}throw s??new ve("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${te(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:c}=await this._readError(o,e);throw ku(o.status,a,c)}try{return await o.json()}catch(a){throw new ve(`[urun] runtime artifacts: invalid JSON response from ${te(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let r=te(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}});function Tu(n){return/^(\d+[smhdw])+$/.test(n)}function Ru(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new Gr(r,e??"unauthorized");if(n===404)return new Is(r,e??"not_found");if(n===400)return new Qr(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new As(r,e);case"pin_requires_active_temp":return new Ls(r,e);case"permanent_locked":return new Ms(r,e)}return new Ne(r,{status:n,code:e??`http_${n}`})}var Ne,Gr,Is,As,Ls,Ms,Qr,Yr,Vo=W(()=>{"use strict";Ne=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},Gr=class extends Ne{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Is=class extends Ne{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},As=class extends Ne{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},Ls=class extends Ne{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},Ms=class extends Ne{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},Qr=class extends Ne{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};Yr=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!Tu(t))throw new Qr(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new Ne("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,r.body))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw Ru(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let i={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new Gr("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}}});var Ko=L((Bg,zo)=>{"use strict";var kt=1e3,Tt=kt*60,Rt=Tt*60,ct=Rt*24,Cu=ct*7,Eu=ct*365.25;zo.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return Pu(n);if(t==="number"&&isFinite(n))return e.long?xu(n):Du(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function Pu(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Eu;case"weeks":case"week":case"w":return t*Cu;case"days":case"day":case"d":return t*ct;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Rt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Tt;case"seconds":case"second":case"secs":case"sec":case"s":return t*kt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Du(n){var e=Math.abs(n);return e>=ct?Math.round(n/ct)+"d":e>=Rt?Math.round(n/Rt)+"h":e>=Tt?Math.round(n/Tt)+"m":e>=kt?Math.round(n/kt)+"s":n+"ms"}function xu(n){var e=Math.abs(n);return e>=ct?Jr(n,e,ct,"day"):e>=Rt?Jr(n,e,Rt,"hour"):e>=Tt?Jr(n,e,Tt,"minute"):e>=kt?Jr(n,e,kt,"second"):n+" ms"}function Jr(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var Os=L((Hg,Go)=>{"use strict";function Iu(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=Ko(),t.destroy=d,Object.keys(n).forEach(l=>{t[l]=n[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let u=0;for(let p=0;p<l.length;p++)u=(u<<5)-u+l.charCodeAt(p),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(l){let u,p=null,m,g;function f(...h){if(!f.enabled)return;let _=f,v=Number(new Date),S=v-(u||v);_.diff=S,_.prev=u,_.curr=v,u=v,h[0]=t.coerce(h[0]),typeof h[0]!="string"&&h.unshift("%O");let w=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(T,y)=>{if(T==="%%")return"%";w++;let E=t.formatters[y];if(typeof E=="function"){let N=h[w];T=E.call(_,N),h.splice(w,1),w--}return T}),t.formatArgs.call(_,h),(_.log||t.log).apply(_,h)}return f.namespace=l,f.useColors=t.useColors(),f.color=t.selectColor(l),f.extend=r,f.destroy=t.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(m!==t.namespaces&&(m=t.namespaces,g=t.enabled(l)),g),set:h=>{p=h}}),typeof t.init=="function"&&t.init(f),f}function r(l,u){let p=t(this.namespace+(typeof u>"u"?":":u)+l);return p.log=this.log,p}function s(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let u=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of u)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function i(l,u){let p=0,m=0,g=-1,f=0;for(;p<l.length;)if(m<u.length&&(u[m]===l[p]||u[m]==="*"))u[m]==="*"?(g=m,f=p,m++):(p++,m++);else if(g!==-1)m=g+1,f++,p=f;else return!1;for(;m<u.length&&u[m]==="*";)m++;return m===u.length}function o(){let l=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),l}function a(l){for(let u of t.skips)if(i(l,u))return!1;for(let u of t.names)if(i(l,u))return!0;return!1}function c(l){return l instanceof Error?l.stack||l.message:l}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Go.exports=Iu});var Qo=L((me,Xr)=>{"use strict";me.formatArgs=Lu;me.save=Mu;me.load=Ou;me.useColors=Au;me.storage=Uu();me.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();me.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Au(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Lu(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Xr.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,r=0;n[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),n.splice(r,0,e)}me.log=console.debug||console.log||(()=>{});function Mu(n){try{n?me.storage.setItem("debug",n):me.storage.removeItem("debug")}catch{}}function Ou(){let n;try{n=me.storage.getItem("debug")||me.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Uu(){try{return localStorage}catch{}}Xr.exports=Os()(me);var{formatters:Nu}=Xr.exports;Nu.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Jo={};ms(Jo,{createSupportsColor:()=>Ns,default:()=>qu});function ke(n,e=globalThis.Deno?globalThis.Deno.args:en.default.argv){let t=n.startsWith("-")?"":n.length===1?"-":"--",r=e.indexOf(t+n),s=e.indexOf("--");return r!==-1&&(s===-1||r<s)}function Wu(){if(!("FORCE_COLOR"in Q))return;if(Q.FORCE_COLOR==="true")return 1;if(Q.FORCE_COLOR==="false")return 0;if(Q.FORCE_COLOR.length===0)return 1;let n=Math.min(Number.parseInt(Q.FORCE_COLOR,10),3);if([0,1,2,3].includes(n))return n}function Fu(n){return n===0?!1:{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function $u(n,{streamIsTTY:e,sniffFlags:t=!0}={}){let r=Wu();r!==void 0&&(Zr=r);let s=t?Zr:r;if(s===0)return 0;if(t){if(ke("color=16m")||ke("color=full")||ke("color=truecolor"))return 3;if(ke("color=256"))return 2}if("TF_BUILD"in Q&&"AGENT_NAME"in Q)return 1;if(n&&!e&&s===void 0)return 0;let i=s||0;if(Q.TERM==="dumb")return i;if(en.default.platform==="win32"){let o=Yo.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in Q)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in Q)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in Q)||Q.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in Q)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Q.TEAMCITY_VERSION)?1:0;if(Q.COLORTERM==="truecolor"||Q.TERM==="xterm-kitty"||Q.TERM==="xterm-ghostty"||Q.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Q){let o=Number.parseInt((Q.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Q.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Q.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Q.TERM)||"COLORTERM"in Q?1:i}function Ns(n,e={}){let t=$u(n,{streamIsTTY:n&&n.isTTY,...e});return Fu(t)}var en,Yo,Us,Q,Zr,ju,qu,Xo=W(()=>{"use strict";en=Je(require("process"),1),Yo=Je(require("os"),1),Us=Je(require("tty"),1);({env:Q}=en.default);ke("no-color")||ke("no-colors")||ke("color=false")||ke("color=never")?Zr=0:(ke("color")||ke("colors")||ke("color=true")||ke("color=always"))&&(Zr=1);ju={stdout:Ns({isTTY:Us.default.isatty(1)}),stderr:Ns({isTTY:Us.default.isatty(2)})},qu=ju});var ea=L((ne,rn)=>{"use strict";var Bu=require("tty"),tn=require("util");ne.init=Yu;ne.log=Ku;ne.formatArgs=Vu;ne.save=Gu;ne.load=Qu;ne.useColors=Hu;ne.destroy=tn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ne.colors=[6,2,3,4,5,1];try{let n=(Xo(),uo(Jo));n&&(n.stderr||n).level>=2&&(ne.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}ne.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),n[t]=r,n},{});function Hu(){return"colors"in ne.inspectOpts?!!ne.inspectOpts.colors:Bu.isatty(process.stderr.fd)}function Vu(n){let{namespace:e,useColors:t}=this;if(t){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${s};1m${e} \x1B[0m`;n[0]=i+n[0].split(`
|
|
2
2
|
`).join(`
|
|
3
3
|
`+i),n.push(s+"m+"+rn.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=zu()+e+" "+n[0]}function zu(){return ne.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Ku(...n){return process.stderr.write(tn.formatWithOptions(ne.inspectOpts,...n)+`
|
|
4
4
|
`)}function Gu(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function Qu(){return process.env.DEBUG}function Yu(n){n.inspectOpts={};let e=Object.keys(ne.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=ne.inspectOpts[e[t]]}rn.exports=Os()(ne);var{formatters:Zo}=rn.exports;Zo.o=function(n){return this.inspectOpts.colors=this.useColors,tn.inspect(n,this.inspectOpts).split(`
|
|
@@ -32,4 +32,4 @@ self.onrtctransform = (event) => {
|
|
|
32
32
|
self.postMessage({ type: 'err', detail: String(e) }))
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
|
-
`;ss=class n{constructor(e,t){this.sink=e;this.seqState=t??{seq:0}}sink;stopped=!1;deadCb=null;seqState;static FLOW_WINDOW_MS=5e3;static FLOW_MIN_SENT_PER_WINDOW=25;sentCount=0;flowTimer=null;flowLastSent=0;flowLastDelivered=0;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()}sentDatagrams(){return this.sentCount}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=Wm(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),this.startFlowWatch())}}startFlowWatch(){this.flowTimer||this.stopped||(this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),this.flowTimer=setInterval(()=>{if(this.stopped)return;let e=this.sentCount-this.flowLastSent,t=this.sink.delivered()-this.flowLastDelivered;this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),e>0&&console.log(`[urun] WT mic uplink flow: wrote=${(e/(n.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s accepted=${(t/(n.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s`),!(e<n.FLOW_MIN_SENT_PER_WINDOW)&&(t*2>=e||console.error(`[urun] WT mic uplink flow STARVED: wrote ${e} datagrams in ${n.FLOW_WINDOW_MS/1e3}s but QUIC accepted only ${t}`))},n.FLOW_WINDOW_MS))}stop(){if(!this.stopped){this.stopped=!0,this.flowTimer!==null&&(clearInterval(this.flowTimer),this.flowTimer=null),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=Vd(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let s=await t.createAnswer();s.sdp=Vd(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([Nm],{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=Yi(this.seqState.seq,e,t,this.sink.maxDatagramSize()||Er);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.seqState.seq=this.seqState.seq+1>>>0;return}for(let s of r)this.sink.send(s),this.sentCount++;this.seqState.seq=this.seqState.seq+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 Hm(n){return Math.round(n*(Fm/1e6))%2**32>>>0}var Fm,$m,jm,qm,Bm,is,zd=W(()=>{"use strict";gt();Ji();Fm=9e4,$m="avc1.42E01F",jm=60,qm=3,Bm=1e4;is=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>=jm;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=Yi(this.frameSeq,Hm(e.timestamp),t,this.sink.maxDatagramSize()||Er,{lane:Md,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<Bm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=qm){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 Vm(n){return n.byteLength>=2&&n[0]===1&&n[1]===3}var os,Kd=W(()=>{"use strict";os=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),Vm(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 Gd,zm,Km,Gm,Qm,Ym,Jm,Xm,Zm,Qd,eg,tg,Xi,as,Yd=W(()=>{"use strict";gt();Nd();Wd();$d();gt();Hd();Ji();zd();Kd();Gd=250,zm=25,Km=2e3,Gm=15e3,Qm=1e3,Ym=45e3,Jm=5e3,Xm={llm:!0},Zm=500,Qd=10,eg=2,tg=2,Xi=2,as=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 rs({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&&Vi(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 Xn,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&&(Vi(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 ns(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 os({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(),Zm)),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 ${Gd}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Gm},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Qm))}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>=Qd&&d<=0?u="downlink":c!==null&&l>=Qd&&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 ${eg} 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<tg)){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=Xi}return}this.playoutStallStreak<Xi||(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 ${Xi} 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<=Jm&&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>=Ym&&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(Xm[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,Fd(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<Km),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<zm)&&(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;uplinkSeqState={seq:0};uplinkSink(e){this.datagramWriter();let t=0;return{send:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Er}}engageAudioUplink(){let e=new ss(this.uplinkSink("audio"),this.uplinkSeqState);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 is(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>=be&&t[11]===es){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(Ad(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(Ld(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(()=>{})},Gd)}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 Pr(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 Zd(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 ng(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 to(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 eo(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,Xd,rg,cs,el=W(()=>{"use strict";Yd();Jd=2500,Xd=["av01.0.08M.08","avc1.42E01F","avc1.640028"],rg=1e4,cs=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:Xd,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 eo(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 (${Pr(l)}) \u2014 dialed ${Zd(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}`+(ng(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:Xd,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let d=this.createWebTransportSession();try{await eo(d.start(),this.opts.quicDeadlineMs??Jd,"quic connect deadline")}catch(l){throw console.warn(`[urun] WT dial failed (${Pr(l)}) \u2014 dialed ${Zd(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 as(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.onWtLegDeath?.(t),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=to(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=Pr(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 eo(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??rg,"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 sg,ds,tl=W(()=>{"use strict";Fn();sg=1e4,ds=class{constructor(e,t=sg){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=zt();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 ig,ls,rl=W(()=>{"use strict";ig="video",ls=class{constructor(e,t=ig){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 nl(n){let e=n;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var sl=W(()=>{"use strict"});async function cg(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??ag;return new Promise(a=>{let c=!1,d,l=null,u=null,p=!1,m=_=>{c||(c=!0,h(),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 f=()=>{l===null&&!c&&(l=setTimeout(()=>m("unconfirmed"),o))},h=()=>{l!==null&&(clearTimeout(l),l=null)};d=e.subscribe(_=>{let v=_?.name;if(v==="live")return m("live");if(v==="error")return m("gone");h(),st(v)||f()}),st(s)||f()})}function il(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 E of d.getVideoTracks())try{E.stop()}catch{}d=null}l&&(l=!1,t.onOverrideTrack(null))},p=new cs(new ds(n),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new ls(n,t.streamName??og)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(E,N)=>n.dispatchQuicStreamData(E,N),onQuicLane:()=>n.markStreamDataLaneQuic(),onQuicLaneLost:E=>n.quicStreamDataLaneLost(E),onLaneError:E=>n.raiseQuicStreamDataError(E)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:E=>{c||(E&&n.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(E))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>w(),onMediaTransportLost:E=>{c||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(E),w())},onWtLegDeath:()=>{n.noteMediaLegDeath?.()},onTransportChange:(E,N)=>{c||(E==="webrtc"&&(u(),w()),t.onTransportChange?.(E,N))}}),m=n.onWtOnlyLegDeath?.(E=>p.failCurrentWtLeg(E)),g=null,f=()=>{g!==null&&(clearInterval(g),g=null)},h=t.wtRetryBaseMs??2e3,_=t.wtRetryCapMs??3e4,v=null,S=0,w=()=>{if(c||v!==null||p.activeTransport==="webtransport")return;let E=to(h,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: `+Pr(N)),w())})},E)},b=()=>{v!==null&&(clearTimeout(v),v=null)},T=async E=>{if(c||E.kind!=="webtransport")return;let N=t.pathHealthProbeMs??1e4;f();let J=!1;g=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let $=nl(E);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)"),f();return}let j=$.pathLiveness();if(!j.alive){let G=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${j.evidence}`+(G?" \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"),f(),$.fail(`path health: ${j.evidence}`);return}if(!J){if(J=!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 E.firstMedia}catch($){f(),console.debug("[urun] webtransport ended before any media flowed:",$);return}if(f(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;d=a.captureStream();let se=d.getVideoTracks()[0];se&&(l=!0,t.onOverrideTrack(se))},y=!1;return(async()=>{let E=await cg(n,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>c});if(c)return;if(E==="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(E=>{if(f(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",E);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",E),w();return}o?.proceed(`negotiation unavailable: ${E instanceof Error?E.message:String(E)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",E),w()}),{activeTransport:()=>p.activeTransport,mediaTransportAttempted:()=>y,watchDownlinkStall(E){p.watchDownlinkStall(E)},dispose(){c=!0,m?.(),f(),b(),u(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var og,ag,ol=W(()=>{"use strict";el();tl();Wr();rl();sl();og="video",ag=45e3});function io(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function fg(n){return`${hg}:${n}`}function no(){return zt()}function mg(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 gg(n,e,t,r,s,i,o,a,c,d){let l=[],u=null,p=!1,m=null,g=!1,f,h,_=new Promise((k,K)=>{f=k,h=K});_.catch(()=>{});let v=o(),S=null,w=null,b=null,T=null,y=null,E=null,N=!0,J=()=>{b&&(clearTimeout(b),b=null),T&&(T(),T=null)},se=()=>{y&&(clearTimeout(y),y=null),E&&(E(),E=null)},$=!1,j=()=>{$||!g||($=!0,n.set({rpc:{[e]:null}}))},G=()=>{N=!1,J(),se(),S?.(),S=null,w?.(),w=null,a?.removeEventListener("abort",D),v.dispose(),j()},Z=()=>{if(u){if(l.length>0){let k=u;u=null,k.resolve({value:l.shift(),done:!1})}else if(m!==null){let k=u;u=null,k.reject(m)}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||(m=k,p=!0,h(k),G(),Z())},Me=k=>{p||(p=!0,f(k),G(),Z())},D=()=>{let k=a?.reason;ee(k instanceof He?k:new Qt(e))},U=k=>{if(!(p||!k||typeof k!="object"))switch(se(),j(),k.t){case"delta":typeof k.delta=="string"&&he(k.delta);break;case"response":Me(k.body);break;case"error":{let{message:K,code:q}=mg(k.body);ee(new He(K,{requestId:e,code:k.code??q}));break}}},H=()=>{let k=v.messages()[Symbol.asyncIterator]();S=()=>{k.return?.(void 0)};let K=()=>{N&&k.next().then(q=>{if(N){if(q.done){p||Me(void 0);return}U(q.value),K()}},q=>{N&&ee(q)})};K()},x=()=>{if(!g){if(g=!0,a){if(a.aborted){ee(new Qt(e));return}a.addEventListener("abort",D,{once:!0})}w=c?.(k=>ee(k))??null,H(),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 Lr(d,e))},d),T=n.onSynced(()=>J())),E=n.onSynced(()=>{E=null,!(p||$||y)&&(y=setTimeout(()=>{y=null,!(p||$)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(cl/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).`)},cl))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(x(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(m!==null){let k=m;return m=null,Promise.reject(k)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((k,K)=>{u={resolve:k,reject:K}})},return(){return p||(p=!0,f(void 0),G()),Promise.resolve({value:void 0,done:!0})},throw(k){return p||(p=!0,h(k),G()),Promise.reject(k)}}}},body:_,start:x}}function dl(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 _g(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=dl(i);c&&(a.rt=c);let d=dl(o);return d&&(a.br=d),a}var dg,lg,ug,ro,al,pg,cl,hg,so,us,ll=W(()=>{"use strict";Wr();wo();Ho();Vo();Ni();Ir();St();md();Gn();_d();wd();Sd();Td();Bi();Bn();bt();Ze();Fn();Id();ol();dg=new Set;lg="rpc",ug="$presence",ro=["control",gs],al=2e4,pg=3e4,cl=3e4,hg="rpc-resp";so=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=_g(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Mr(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??Dd;return xd(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)}},us=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new zn;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_gateDocUp={};_gate="open";_gateTimer=null;_gateDocUnsubs=[];_gateOff=!1;_gatedFrom;_gatedWith;_publicPhase;_phaseHandlers=new Set;_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=Bc(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Rd(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=bd({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new Jn({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(ug).awareness.setLocalState({role:"client"}),this._activation=new Fr({onPhase:a=>this.onPhase(a),hint:()=>this.doc(gs).get(_o)??this.doc("control").get(vo),onData:(a,c)=>this._streamData.onData(a,c)}),this._transport.on("phase",()=>this._applyLiveGate());for(let a of ro)this._gateDocUnsubs.push(this.doc(a).onConnectionState(c=>{this._gateDocUp[a]=c.connected,this._applyLiveGate()}))}_applyLiveGate(){let e=this._transport.phase;if(!e)return;let t=this._gateOff||!this._docConnector.connected||ro.every(i=>this._gateDocUp[i]);if(e.name!=="live"||t?(clearTimeout(this._gateTimer??void 0),this._gateTimer=null,this._gate="open"):this._gate==="open"&&(this._gate="connecting",this._gateTimer=setTimeout(()=>{this._gateTimer=null,this._gate="failed",this._applyLiveGate()},al)),e===this._gatedFrom&&this._gate===this._gatedWith)return;this._gatedFrom=e,this._gatedWith=this._gate;let r=ro.filter(i=>!this._gateDocUp[i]).join("/"),s=this._gate==="open"?e:this._gate==="connecting"?{...e,name:"connecting",reason:"docs_connecting"}:{...e,name:"error",reason:"doc_plane_unreachable",error:{kind:"transport-failed",code:"doc_plane_unreachable",reason:`the session's ${r} doc connection did not open within ${al/1e3}s (still retrying)`}};if(s!==this._publicPhase){this._publicPhase=s;for(let i of[...this._phaseHandlers])i(s)}}_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 $o({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 vt,o=new Gt({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,io(t),nr({...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),et()&&await yt();let c=t.getAccessToken,d=c?l=>!l?.redial&&s?s:Promise.resolve(c()).then(u=>u??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!==this._gatedFrom&&this._applyLiveGate(),this._publicPhase??this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){let e=this._transport.status,t=this.phase;return!e||!t||t===this._transport.phase?e:{...e,phase:t.name,...t.error?{error:t.error}:{}}}get region(){return this._transport.region}onPhase(e){return e(this.phase),this._phaseHandlers.add(e),()=>{this._phaseHandlers.delete(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 go(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=vd(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 Yr(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 rr(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new rr(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 so(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 Yn(e,this._sessionId,dg.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=gd(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=Kn(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",s=e.attach?`${e.attach.gen}:${e.attach.token}`:"",i=`${t}${r}${s}${this._sessionId}`;i!==this._docEndpointKey&&(this._docEndpointKey=i,this.connectDocs(hd({serverUrl:t,sessionId:this._sessionId,token:e.token,attach:e.attach,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=no(),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 Ar(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(lg),a=fg(e);return gg(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??pg)}requestStream(e,t={}){let r=no();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=no(),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=il(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 Xe)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Xe);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 Ur)}catch{}this._gateOff=!0,clearTimeout(this._gateTimer??void 0),this._gateTimer=null;for(let s of this._gateDocUnsubs.splice(0))s();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 ul(n){return`urun:session:v2:${n.orgId}:${n.app}:${n.functionName}`}function oo(){try{return globalThis.sessionStorage??null}catch{return null}}function ps(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 vg(n,e){return n!==void 0&&e!==void 0&&n!==e}function co(n,e){let t=oo(),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=ao.get(n)??r??null;return!s||vg(s.actor,e)?null:s}function pl(n,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};ao.set(n,t);let r=oo();if(r)try{r.setItem(n,JSON.stringify(t))}catch{}}function hs(n){ao.delete(n);let e=oo();if(e)try{e.removeItem(n)}catch{}}var ao,hl=W(()=>{"use strict";ao=new Map});function ml(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function yg(n){if(typeof n?.id!="string"||n.id.length===0)throw new Pe("[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"||!fl.has(n.state))throw new Pe(`[urun] session ${n.id} reported an unrecognized state ${JSON.stringify(n.state)} \u2014 this @urun-sh/core build knows only ${[...fl].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:ml(n.created_at),lastActiveAt:ml(n.last_active_at),archived:n.archived===!0,preview:typeof n.preview=="string"&&n.preview.length>0?n.preview:null,recordingsExpired:e,retention:wg.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 fl,wg,fs,gl=W(()=>{"use strict";Ze();St();fl=new Set(["paused","acquiring","live"]),wg=new Set(["24h","keep"]);fs=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await No({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(yg),nextCursor:r}}async end(e){await Wo({...this._request,sessionId:e})}async archive(e){await Rs({...this._request,sessionId:e,archived:!0})}async unarchive(e){await Rs({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await Fo({...this._request,sessionId:e,name:t,source:r.source})}}});var vl={};ms(vl,{App:()=>kg,sessionDirectory:()=>Sg});function _l(n,e,t){let r=ps(t);pl(n,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}function Sg(n,e){return new fs(n,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function kg(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(!(bg.has(r)||typeof r!="string"))return(s,i)=>{let o=s??{},a=ul({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,m=e.getAccessToken?async D=>{let U=await e.getAccessToken(D);return U&&(p=U),U}:void 0,g={...e,getAccessToken:m},f=new vt,h=new Gt({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 us(u,f,h,io(g),nr(g),{activity:i?.activity}),v,S=!1,w=!1,b,T,y=new Promise(D=>{T=D}),E,N=D=>{D.sessionId||b||(b="teardown",E="ticket",bs({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},J=D=>{b||D.sessionId||(b="abandon",bs({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider,reason:"client_abandoned"}))},se=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 Xe("[urun] session allocation failed before a releasable request was created",{cause:D.cause});let U=v??D.handle;return hs(a),b==="teardown"?U.sessionId?{status:"paused",sessionId:U.sessionId,reason:"client_ended"}:{status:"canceled",requestId:U.requestId}:(b="end",U.sessionId?ks({baseUrl:U.baseUrl,sessionId:U.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider}):Ss({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Xe("[urun] session allocation failed before a cancellable request was created",{cause:D.cause});let U=v??D.handle;if(U.sessionId)throw new _e(`[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 H=await Ss({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider});return hs(a),H}catch(H){throw b==="end"&&(b=void 0),H}});let $=async D=>{let U,H=i?.sessionId??e.sessionKey??d,x,F;if(H===void 0&&!c){let fe=co(a);if(fe?.sessionId){if(F=ps(p),fe.actor!==void 0&&F===void 0&&m){let _t=await Promise.resolve(m()).catch(()=>{});F=ps(_t??e.jwt)}x=fe.actor!==void 0&&F!==void 0&&fe.actor!==F?void 0:fe.sessionId}}let k=H??x,K=(fe,_t)=>Mo({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider,...e.shape?{shape:e.shape}:{},idempotencyKey:fe,sessionKey:_t,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:Se=>{h.reportAdmission(Se),Se.sessionId&&!d&&(d=Se.sessionId,U=Se.sessionId,v&&v.sessionId!==Se.sessionId&&se({...v,sessionId:Se.sessionId}),S||(e.sessionKey||_l(a,Se.sessionId,p),_.setSessionId(Se.sessionId)))},onRequest:se}),q;try{q=await K(D,k)}catch(fe){let _t=fe instanceof B&&fe.code==="session_name_not_yours"&&k!==void 0&&k===d&&i?.sessionId===void 0&&e.sessionKey===void 0;if(x===void 0&&!_t||!(fe instanceof B)||fe.code!=="session_name_not_yours")throw fe;let Se=x??k;if(Se===void 0)throw fe;console.warn(`[urun] session_name_not_yours: the control plane refused session ${Se} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),_t&&(d=void 0),co(a,F)?.sessionId===Se&&hs(a),q=await K(l(),void 0)}let bl=m?await m()??void 0:e.jwt;if(U&&U!==q.sessionId)throw v&&v.sessionId!==q.sessionId&&se({...v,sessionId:q.sessionId}),new B(`Gateway contract violation: admission minted session ${U} but allocation completed as ${q.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return d=q.sessionId,v&&v.sessionId!==q.sessionId&&se({...v,sessionId:q.sessionId}),S||(e.sessionKey||_l(a,q.sessionId,p),_.setSessionId(q.sessionId),Z=Vr(q.baseUrl)?{baseUrl:q.baseUrl,sessionId:q.sessionId}:null,_.setArtifactsAuth(nr({...g,baseUrl:q.baseUrl})),h.setEndsAt(q.endsAt),h.seedRegion(Es(q.response))),{url:q.wsUrl,sessionId:q.sessionId,jwt:bl,iceServers:q.response.ice_servers,endsAt:q.endsAt,sfuAttach:q.sfuAttach}},j,G,Z=null,he=m?D=>!D?.redial&&j?j:Promise.resolve(m(D?.redial?{forceRefresh:!0,reason:"background"}:void 0)).then(U=>j=U??j):()=>j,ee=()=>{let D=h.connectedUrl;return D?Kn(D):void 0};if(h.setConnectionResolver(async()=>{let D=await $(l());return j=D.jwt,G=D.sfuAttach,D}),h.setConnectionViewRefresher(async()=>Z?Uo({baseUrl:Z.baseUrl,sessionId:Z.sessionId,jwt:p}):null),h.on("connected",()=>{h.multiplexer&&f.setTarget(h.multiplexer);let D=h.connectedUrl;D&&_.setDocTransport({wsUrl:D,token:he,attach:G,resolveServerUrl:ee})}),(async D=>{let U;try{U=await $(D)}catch(H){if(S){T({status:"unavailable",cause:H});return}console.error(`[urun] Failed to create session for ${r}:`,H),v&&J(v);let x=H instanceof Error?H:new Error(String(H)),F=H instanceof B?H.httpStatus:void 0,k=H instanceof B?H.code:void 0,K=H instanceof B?H.retryAfterSeconds:void 0;h.reportAllocationFailure(x,F,k,K),T({status:"unavailable",cause:H});return}S||(h.setAuth({jwt:U.jwt,authProvider:e.authProvider,orgId:e.orgId}),h.setConnection({url:U.url,sessionId:U.sessionId,iceServers:U.iceServers,sfuAttach:U.sfuAttach}),et()&&await yt(),j=U.jwt,G=U.sfuAttach,_.setDocTransport({wsUrl:U.url,token:he,attach:G,resolveServerUrl:ee}),await h.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=Cd(()=>{if(S=!0,h.leaveLeg())return;if(h.connectedUrl!==null){h.disconnect();return}h.disconnect();let k=v;k?N(k):w=!0});_.onDisconnect(D);let U,H,x=!1,F=()=>{x||(x=!0,U?.(),H?.())};y.then(k=>{k.status!=="ready"||x||(U=Ed(()=>v!==void 0))}),H=_.onPhase(k=>{let K=k?.name;(K==="paused"||K==="error")&&F()}),x&&H(),_.onDisconnect(F)}return _}}})}var bg,wl=W(()=>{"use strict";Ir();ll();Ni();St();Ze();bt();Gn();Bi();hl();gl();bg=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive])});var Cg={};ms(Cg,{createSessionResolver:()=>yl});module.exports=uo(Cg);var Tg="serve";function yl(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(()=>(wl(),vl)),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
|
+
`;ss=class n{constructor(e,t){this.sink=e;this.seqState=t??{seq:0}}sink;stopped=!1;deadCb=null;seqState;static FLOW_WINDOW_MS=5e3;static FLOW_MIN_SENT_PER_WINDOW=25;sentCount=0;flowTimer=null;flowLastSent=0;flowLastDelivered=0;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()}sentDatagrams(){return this.sentCount}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=Wm(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),this.startFlowWatch())}}startFlowWatch(){this.flowTimer||this.stopped||(this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),this.flowTimer=setInterval(()=>{if(this.stopped)return;let e=this.sentCount-this.flowLastSent,t=this.sink.delivered()-this.flowLastDelivered;this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),e>0&&console.log(`[urun] WT mic uplink flow: wrote=${(e/(n.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s accepted=${(t/(n.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s`),!(e<n.FLOW_MIN_SENT_PER_WINDOW)&&(t*2>=e||console.error(`[urun] WT mic uplink flow STARVED: wrote ${e} datagrams in ${n.FLOW_WINDOW_MS/1e3}s but QUIC accepted only ${t}`))},n.FLOW_WINDOW_MS))}stop(){if(!this.stopped){this.stopped=!0,this.flowTimer!==null&&(clearInterval(this.flowTimer),this.flowTimer=null),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=Vd(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let s=await t.createAnswer();s.sdp=Vd(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([Nm],{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=Yi(this.seqState.seq,e,t,this.sink.maxDatagramSize()||Er);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.seqState.seq=this.seqState.seq+1>>>0;return}for(let s of r)this.sink.send(s),this.sentCount++;this.seqState.seq=this.seqState.seq+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 Hm(n){return Math.round(n*(Fm/1e6))%2**32>>>0}var Fm,$m,jm,qm,Bm,is,zd=W(()=>{"use strict";gt();Ji();Fm=9e4,$m="avc1.42E01F",jm=60,qm=3,Bm=1e4;is=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>=jm;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=Yi(this.frameSeq,Hm(e.timestamp),t,this.sink.maxDatagramSize()||Er,{lane:Md,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<Bm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=qm){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 Vm(n){return n.byteLength>=2&&n[0]===1&&n[1]===3}var os,Kd=W(()=>{"use strict";os=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),Vm(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 Gd,zm,Km,Gm,Qm,Ym,Jm,Xm,Zm,Qd,eg,tg,Xi,as,Yd=W(()=>{"use strict";gt();Nd();Wd();$d();gt();Hd();Ji();zd();Kd();Gd=250,zm=25,Km=2e3,Gm=15e3,Qm=1e3,Ym=45e3,Jm=5e3,Xm={llm:!0},Zm=500,Qd=10,eg=2,tg=2,Xi=2,as=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 rs({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&&Vi(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 Xn,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&&(Vi(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 ns(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 os({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(),Zm)),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 ${Gd}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Gm},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Qm))}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>=Qd&&d<=0?u="downlink":c!==null&&l>=Qd&&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 ${eg} 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<tg)){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=Xi}return}this.playoutStallStreak<Xi||(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 ${Xi} 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<=Jm&&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>=Ym&&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(Xm[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,Fd(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<Km),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<zm)&&(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;uplinkSeqState={seq:0};uplinkSink(e){this.datagramWriter();let t=0;return{send:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Er}}engageAudioUplink(){let e=new ss(this.uplinkSink("audio"),this.uplinkSeqState);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 is(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>=be&&t[11]===es){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(Ad(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(Ld(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(()=>{})},Gd)}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 Pr(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 Zd(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 ng(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 to(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 eo(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,Xd,rg,cs,el=W(()=>{"use strict";Yd();Jd=2500,Xd=["av01.0.08M.08","avc1.42E01F","avc1.640028"],rg=1e4,cs=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:Xd,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 eo(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 (${Pr(l)}) \u2014 dialed ${Zd(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}`+(ng(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:Xd,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let d=this.createWebTransportSession();try{await eo(d.start(),this.opts.quicDeadlineMs??Jd,"quic connect deadline")}catch(l){throw console.warn(`[urun] WT dial failed (${Pr(l)}) \u2014 dialed ${Zd(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 as(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.onWtLegDeath?.(t),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=to(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=Pr(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 eo(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??rg,"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 sg,ds,tl=W(()=>{"use strict";Fn();sg=1e4,ds=class{constructor(e,t=sg){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=zt();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 ig,ls,rl=W(()=>{"use strict";ig="video",ls=class{constructor(e,t=ig){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 nl(n){let e=n;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var sl=W(()=>{"use strict"});async function cg(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??ag;return new Promise(a=>{let c=!1,d,l=null,u=null,p=!1,m=_=>{c||(c=!0,h(),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 f=()=>{l===null&&!c&&(l=setTimeout(()=>m("unconfirmed"),o))},h=()=>{l!==null&&(clearTimeout(l),l=null)};d=e.subscribe(_=>{let v=_?.name;if(v==="live")return m("live");if(v==="error")return m("gone");h(),st(v)||f()}),st(s)||f()})}function il(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 E of d.getVideoTracks())try{E.stop()}catch{}d=null}l&&(l=!1,t.onOverrideTrack(null))},p=new cs(new ds(n),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new ls(n,t.streamName??og)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(E,N)=>n.dispatchQuicStreamData(E,N),onQuicLane:()=>n.markStreamDataLaneQuic(),onQuicLaneLost:E=>n.quicStreamDataLaneLost(E),onLaneError:E=>n.raiseQuicStreamDataError(E)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:E=>{c||(E&&n.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(E))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>w(),onMediaTransportLost:E=>{c||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(E),w())},onWtLegDeath:()=>{n.noteMediaLegDeath?.()},onTransportChange:(E,N)=>{c||(E==="webrtc"&&(u(),w()),t.onTransportChange?.(E,N))}}),m=n.onWtOnlyLegDeath?.(E=>p.failCurrentWtLeg(E)),g=null,f=()=>{g!==null&&(clearInterval(g),g=null)},h=t.wtRetryBaseMs??2e3,_=t.wtRetryCapMs??3e4,v=null,S=0,w=()=>{if(c||v!==null||p.activeTransport==="webtransport")return;let E=to(h,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: `+Pr(N)),w())})},E)},b=()=>{v!==null&&(clearTimeout(v),v=null)},T=async E=>{if(c||E.kind!=="webtransport")return;let N=t.pathHealthProbeMs??1e4;f();let J=!1;g=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let $=nl(E);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)"),f();return}let j=$.pathLiveness();if(!j.alive){let G=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${j.evidence}`+(G?" \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"),f(),$.fail(`path health: ${j.evidence}`);return}if(!J){if(J=!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 E.firstMedia}catch($){f(),console.debug("[urun] webtransport ended before any media flowed:",$);return}if(f(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;d=a.captureStream();let se=d.getVideoTracks()[0];se&&(l=!0,t.onOverrideTrack(se))},y=!1;return(async()=>{let E=await cg(n,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>c});if(c)return;if(E==="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(E=>{if(f(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",E);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",E),w();return}o?.proceed(`negotiation unavailable: ${E instanceof Error?E.message:String(E)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",E),w()}),{activeTransport:()=>p.activeTransport,mediaTransportAttempted:()=>y,watchDownlinkStall(E){p.watchDownlinkStall(E)},dispose(){c=!0,m?.(),f(),b(),u(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var og,ag,ol=W(()=>{"use strict";el();tl();Wr();rl();sl();og="video",ag=45e3});function io(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function fg(n){return`${hg}:${n}`}function no(){return zt()}function mg(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 gg(n,e,t,r,s,i,o,a,c,d){let l=[],u=null,p=!1,m=null,g=!1,f,h,_=new Promise((k,K)=>{f=k,h=K});_.catch(()=>{});let v=o(),S=null,w=null,b=null,T=null,y=null,E=null,N=!0,J=()=>{b&&(clearTimeout(b),b=null),T&&(T(),T=null)},se=()=>{y&&(clearTimeout(y),y=null),E&&(E(),E=null)},$=!1,j=()=>{$||!g||($=!0,n.set({rpc:{[e]:null}}))},G=()=>{N=!1,J(),se(),S?.(),S=null,w?.(),w=null,a?.removeEventListener("abort",D),v.dispose(),j()},Z=()=>{if(u){if(l.length>0){let k=u;u=null,k.resolve({value:l.shift(),done:!1})}else if(m!==null){let k=u;u=null,k.reject(m)}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||(m=k,p=!0,h(k),G(),Z())},Me=k=>{p||(p=!0,f(k),G(),Z())},D=()=>{let k=a?.reason;ee(k instanceof He?k:new Qt(e))},U=k=>{if(!(p||!k||typeof k!="object"))switch(se(),j(),k.t){case"delta":typeof k.delta=="string"&&he(k.delta);break;case"response":Me(k.body);break;case"error":{let{message:K,code:q}=mg(k.body);ee(new He(K,{requestId:e,code:k.code??q}));break}}},H=()=>{let k=v.messages()[Symbol.asyncIterator]();S=()=>{k.return?.(void 0)};let K=()=>{N&&k.next().then(q=>{if(N){if(q.done){p||Me(void 0);return}U(q.value),K()}},q=>{N&&ee(q)})};K()},x=()=>{if(!g){if(g=!0,a){if(a.aborted){ee(new Qt(e));return}a.addEventListener("abort",D,{once:!0})}w=c?.(k=>ee(k))??null,H(),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 Lr(d,e))},d),T=n.onSynced(()=>J())),E=n.onSynced(()=>{E=null,!(p||$||y)&&(y=setTimeout(()=>{y=null,!(p||$)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(cl/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).`)},cl))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(x(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(m!==null){let k=m;return m=null,Promise.reject(k)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((k,K)=>{u={resolve:k,reject:K}})},return(){return p||(p=!0,f(void 0),G()),Promise.resolve({value:void 0,done:!0})},throw(k){return p||(p=!0,h(k),G()),Promise.reject(k)}}}},body:_,start:x}}function dl(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 _g(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=dl(i);c&&(a.rt=c);let d=dl(o);return d&&(a.br=d),a}var dg,lg,ug,ro,al,pg,cl,hg,so,us,ll=W(()=>{"use strict";Wr();wo();Ho();Vo();Ni();Ir();St();md();Gn();_d();wd();Sd();Td();Bi();Bn();bt();Ze();Fn();Id();ol();dg=new Set;lg="rpc",ug="$presence",ro=["control",gs],al=2e4,pg=3e4,cl=3e4,hg="rpc-resp";so=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=_g(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Mr(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??Dd;return xd(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)}},us=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new zn;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_gateDocUp={};_gate="open";_gateTimer=null;_gateDocUnsubs=[];_gateOff=!1;_gatedFrom;_gatedWith;_publicPhase;_phaseHandlers=new Set;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_namedSessionIdProbe;_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=Bc(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Rd(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=bd({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new Jn({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(ug).awareness.setLocalState({role:"client"}),this._activation=new Fr({onPhase:a=>this.onPhase(a),hint:()=>this.doc(gs).get(_o)??this.doc("control").get(vo),onData:(a,c)=>this._streamData.onData(a,c)}),this._transport.on("phase",()=>this._applyLiveGate());for(let a of ro)this._gateDocUnsubs.push(this.doc(a).onConnectionState(c=>{this._gateDocUp[a]=c.connected,this._applyLiveGate()}))}_applyLiveGate(){let e=this._transport.phase;if(!e)return;let t=this._gateOff||!this._docConnector.connected||ro.every(i=>this._gateDocUp[i]);if(e.name!=="live"||t?(clearTimeout(this._gateTimer??void 0),this._gateTimer=null,this._gate="open"):this._gate==="open"&&(this._gate="connecting",this._gateTimer=setTimeout(()=>{this._gateTimer=null,this._gate="failed",this._applyLiveGate()},al)),e===this._gatedFrom&&this._gate===this._gatedWith)return;this._gatedFrom=e,this._gatedWith=this._gate;let r=ro.filter(i=>!this._gateDocUp[i]).join("/"),s=this._gate==="open"?e:this._gate==="connecting"?{...e,name:"connecting",reason:"docs_connecting"}:{...e,name:"error",reason:"doc_plane_unreachable",error:{kind:"transport-failed",code:"doc_plane_unreachable",reason:`the session's ${r} doc connection did not open within ${al/1e3}s (still retrying)`}};if(s!==this._publicPhase){this._publicPhase=s;for(let i of[...this._phaseHandlers])i(s)}}_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 $o({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 vt,o=new Gt({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,io(t),nr({...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),et()&&await yt();let c=t.getAccessToken,d=c?l=>!l?.redial&&s?s:Promise.resolve(c()).then(u=>u??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!==this._gatedFrom&&this._applyLiveGate(),this._publicPhase??this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){let e=this._transport.status,t=this.phase;return!e||!t||t===this._transport.phase?e:{...e,phase:t.name,...t.error?{error:t.error}:{}}}get region(){return this._transport.region}onPhase(e){return e(this.phase),this._phaseHandlers.add(e),()=>{this._phaseHandlers.delete(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 go(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=vd(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 Yr(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 rr(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new rr(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}setNamedSessionIdProbe(e){this._namedSessionIdProbe=e}namedSessionId(){return this._namedSessionIdProbe?.()}stream(e){let t=this._streams.get(e);return t||(t=new so(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 Yn(e,this._sessionId,dg.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=gd(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=Kn(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",s=e.attach?`${e.attach.gen}:${e.attach.token}`:"",i=`${t}${r}${s}${this._sessionId}`;i!==this._docEndpointKey&&(this._docEndpointKey=i,this.connectDocs(hd({serverUrl:t,sessionId:this._sessionId,token:e.token,attach:e.attach,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=no(),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 Ar(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(lg),a=fg(e);return gg(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??pg)}requestStream(e,t={}){let r=no();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=no(),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=il(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 Xe)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Xe);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 Ur)}catch{}this._gateOff=!0,clearTimeout(this._gateTimer??void 0),this._gateTimer=null;for(let s of this._gateDocUnsubs.splice(0))s();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 ul(n){return`urun:session:v2:${n.orgId}:${n.app}:${n.functionName}`}function oo(){try{return globalThis.sessionStorage??null}catch{return null}}function ps(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 vg(n,e){return n!==void 0&&e!==void 0&&n!==e}function co(n,e){let t=oo(),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=ao.get(n)??r??null;return!s||vg(s.actor,e)?null:s}function pl(n,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};ao.set(n,t);let r=oo();if(r)try{r.setItem(n,JSON.stringify(t))}catch{}}function hs(n){ao.delete(n);let e=oo();if(e)try{e.removeItem(n)}catch{}}var ao,hl=W(()=>{"use strict";ao=new Map});function ml(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function yg(n){if(typeof n?.id!="string"||n.id.length===0)throw new Pe("[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"||!fl.has(n.state))throw new Pe(`[urun] session ${n.id} reported an unrecognized state ${JSON.stringify(n.state)} \u2014 this @urun-sh/core build knows only ${[...fl].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:ml(n.created_at),lastActiveAt:ml(n.last_active_at),archived:n.archived===!0,preview:typeof n.preview=="string"&&n.preview.length>0?n.preview:null,recordingsExpired:e,retention:wg.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 fl,wg,fs,gl=W(()=>{"use strict";Ze();St();fl=new Set(["paused","acquiring","live"]),wg=new Set(["24h","keep"]);fs=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await No({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(yg),nextCursor:r}}async end(e){await Wo({...this._request,sessionId:e})}async archive(e){await Rs({...this._request,sessionId:e,archived:!0})}async unarchive(e){await Rs({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await Fo({...this._request,sessionId:e,name:t,source:r.source})}}});var vl={};ms(vl,{App:()=>kg,sessionDirectory:()=>Sg});function _l(n,e,t){let r=ps(t);pl(n,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}function Sg(n,e){return new fs(n,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function kg(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(!(bg.has(r)||typeof r!="string"))return(s,i)=>{let o=s??{},a=ul({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,m=e.getAccessToken?async D=>{let U=await e.getAccessToken(D);return U&&(p=U),U}:void 0,g={...e,getAccessToken:m},f=new vt,h=new Gt({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 us(u,f,h,io(g),nr(g),{activity:i?.activity}),v,S=!1,w=!1,b,T,y=new Promise(D=>{T=D}),E,N=D=>{D.sessionId||b||(b="teardown",E="ticket",bs({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},J=D=>{b||D.sessionId||(b="abandon",bs({baseUrl:D.baseUrl,requestId:D.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider,reason:"client_abandoned"}))},se=D=>{let U=D.sessionId||!d?D:{...D,sessionId:d};v=U,T({status:"ready",handle:U}),(w||b==="teardown")&&N(U)};_.setNamedSessionIdProbe(()=>v?.sessionId),_.setEndHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Xe("[urun] session allocation failed before a releasable request was created",{cause:D.cause});let U=v??D.handle;return hs(a),b==="teardown"?U.sessionId?{status:"paused",sessionId:U.sessionId,reason:"client_ended"}:{status:"canceled",requestId:U.requestId}:(b="end",U.sessionId?ks({baseUrl:U.baseUrl,sessionId:U.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider}):Ss({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let D=v?{status:"ready",handle:v}:await y;if(D.status==="unavailable")throw new Xe("[urun] session allocation failed before a cancellable request was created",{cause:D.cause});let U=v??D.handle;if(U.sessionId)throw new _e(`[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 H=await Ss({baseUrl:U.baseUrl,requestId:U.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider});return hs(a),H}catch(H){throw b==="end"&&(b=void 0),H}});let $=async D=>{let U,H=i?.sessionId??e.sessionKey??d,x,F;if(H===void 0&&!c){let fe=co(a);if(fe?.sessionId){if(F=ps(p),fe.actor!==void 0&&F===void 0&&m){let _t=await Promise.resolve(m()).catch(()=>{});F=ps(_t??e.jwt)}x=fe.actor!==void 0&&F!==void 0&&fe.actor!==F?void 0:fe.sessionId}}let k=H??x,K=(fe,_t)=>Mo({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider,...e.shape?{shape:e.shape}:{},idempotencyKey:fe,sessionKey:_t,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:Se=>{h.reportAdmission(Se),Se.sessionId&&!d&&(d=Se.sessionId,U=Se.sessionId,v&&v.sessionId!==Se.sessionId&&se({...v,sessionId:Se.sessionId}),S||(e.sessionKey||_l(a,Se.sessionId,p),_.setSessionId(Se.sessionId)))},onRequest:se}),q;try{q=await K(D,k)}catch(fe){let _t=fe instanceof B&&fe.code==="session_name_not_yours"&&k!==void 0&&k===d&&i?.sessionId===void 0&&e.sessionKey===void 0;if(x===void 0&&!_t||!(fe instanceof B)||fe.code!=="session_name_not_yours")throw fe;let Se=x??k;if(Se===void 0)throw fe;console.warn(`[urun] session_name_not_yours: the control plane refused session ${Se} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),_t&&(d=void 0),co(a,F)?.sessionId===Se&&hs(a),q=await K(l(),void 0)}let bl=m?await m()??void 0:e.jwt;if(U&&U!==q.sessionId)throw v&&v.sessionId!==q.sessionId&&se({...v,sessionId:q.sessionId}),new B(`Gateway contract violation: admission minted session ${U} but allocation completed as ${q.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return d=q.sessionId,v&&v.sessionId!==q.sessionId&&se({...v,sessionId:q.sessionId}),S||(e.sessionKey||_l(a,q.sessionId,p),_.setSessionId(q.sessionId),Z=Vr(q.baseUrl)?{baseUrl:q.baseUrl,sessionId:q.sessionId}:null,_.setArtifactsAuth(nr({...g,baseUrl:q.baseUrl})),h.setEndsAt(q.endsAt),h.seedRegion(Es(q.response))),{url:q.wsUrl,sessionId:q.sessionId,jwt:bl,iceServers:q.response.ice_servers,endsAt:q.endsAt,sfuAttach:q.sfuAttach}},j,G,Z=null,he=m?D=>!D?.redial&&j?j:Promise.resolve(m(D?.redial?{forceRefresh:!0,reason:"background"}:void 0)).then(U=>j=U??j):()=>j,ee=()=>{let D=h.connectedUrl;return D?Kn(D):void 0};if(h.setConnectionResolver(async()=>{let D=await $(l());return j=D.jwt,G=D.sfuAttach,D}),h.setConnectionViewRefresher(async()=>Z?Uo({baseUrl:Z.baseUrl,sessionId:Z.sessionId,jwt:p}):null),h.on("connected",()=>{h.multiplexer&&f.setTarget(h.multiplexer);let D=h.connectedUrl;D&&_.setDocTransport({wsUrl:D,token:he,attach:G,resolveServerUrl:ee})}),(async D=>{let U;try{U=await $(D)}catch(H){if(S){T({status:"unavailable",cause:H});return}console.error(`[urun] Failed to create session for ${r}:`,H),v&&J(v);let x=H instanceof Error?H:new Error(String(H)),F=H instanceof B?H.httpStatus:void 0,k=H instanceof B?H.code:void 0,K=H instanceof B?H.retryAfterSeconds:void 0;h.reportAllocationFailure(x,F,k,K),T({status:"unavailable",cause:H});return}S||(h.setAuth({jwt:U.jwt,authProvider:e.authProvider,orgId:e.orgId}),h.setConnection({url:U.url,sessionId:U.sessionId,iceServers:U.iceServers,sfuAttach:U.sfuAttach}),et()&&await yt(),j=U.jwt,G=U.sfuAttach,_.setDocTransport({wsUrl:U.url,token:he,attach:G,resolveServerUrl:ee}),await h.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=Cd(()=>{if(S=!0,h.leaveLeg())return;if(h.connectedUrl!==null){h.disconnect();return}h.disconnect();let k=v;k?N(k):w=!0});_.onDisconnect(D);let U,H,x=!1,F=()=>{x||(x=!0,U?.(),H?.())};y.then(k=>{k.status!=="ready"||x||(U=Ed(()=>v!==void 0))}),H=_.onPhase(k=>{let K=k?.name;(K==="paused"||K==="error")&&F()}),x&&H(),_.onDisconnect(F)}return _}}})}var bg,wl=W(()=>{"use strict";Ir();ll();Ni();St();Ze();bt();Gn();Bi();hl();gl();bg=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive])});var Cg={};ms(Cg,{createSessionResolver:()=>yl});module.exports=uo(Cg);var Tg="serve";function yl(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(()=>(wl(),vl)),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});
|