@urun-sh/core 0.6.4 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{$ as on,A as Je,B as Qr,C as Xr,D as Jr,E as Zr,F as en,G as tn,H as J,I as qt,J as _e,K as Ze,L as Bt,M as jt,N as Ht,O as et,P as Vt,Q as Kt,R as rn,S as Gt,T as Te,U as tt,V as nn,W as rt,Y as zt,_ as sn,a as $t,aa as an,b as ve,ba as cn,c as K,ca as Ae,d as Ge,e as we,ea as Ee,f as be,fa as Yt,g as ze,ga as Qt,h as Ye,ha as Xt,i as Qe,ia as Jt,j as $r,k as qr,l as ye,m as Xe,n as Br,o as jr,p as Hr,q as Vr,r as G,s as ke,v as Se,w as Kr,x as Gr,y as zr,z as Yr}from"./chunk-EPBFNUD2.mjs";var dn=15e3,ln=45e3,un=12e4,nt="platform",it="activation",st="desired.activation";function Zt(i){if(typeof i=="string"&&i.length>0)return i;if(i&&typeof i=="object"){let e=i.note;if(typeof e=="string"&&e.length>0)return e}}var pn=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],ne=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 n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));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 pn){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 n={state:t,elapsedMs:r,stream:e.name},s=Zt(this._options.hint());s!==void 0&&(n.hint=s),e.lastEvent=n;for(let o of Array.from(this._handlers))o(n)}};var D=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",n){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,n!==void 0&&(this.cause=n),Object.setPrototypeOf(this,new.target.prototype)}},Re=class extends D{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ce=class extends D{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function ie(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function hn(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=tr(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new D("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(er)}async getDownloadUrl(e,t){let r=tr(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!mn(n))throw new D("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:er(r.artifact),downloadUrl:n}}async _request(e,t){let r=qt(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let s of r)try{return await this._requestFromBase(s,e,t)}catch(o){if(n=o instanceof Error?o:new Error(String(o)),n instanceof D&&gn(n.status))throw n}throw n??new D("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${J(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,s=await this._resolveToken(),o=await fetch(n,{method:"GET",headers:this._headers(s)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await fetch(n,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:c}=await this._readError(o,e);throw vn(o.status,a,c)}try{return await o.json()}catch(a){throw new D(`[urun] runtime artifacts: invalid JSON response from ${J(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=J(t);try{let s=(await e.json()).error;if(s&&typeof s=="object"){let{code:o,message:a}=s;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 er(i){if(!i||typeof i!="object")throw new D("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=q(e,"artifact_id")||q(e,"id"),r=q(e,"filename"),n=q(e,"kind"),s=q(e,"status")||"ready",o=fn(e,"size_bytes"),a=q(e,"sha256");if(!t||!r||!n||o==null||!a)throw new D("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:q(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:s,createdAt:q(e,"created_at"),expiresAt:q(e,"expires_at")}}function q(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function fn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function mn(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function gn(i){return i===401||i===403}function vn(i,e,t){return i===401?new Re(t,e):i===404?new Ce(t,e):new D(t,i,e)}function tr(i){if(!i||typeof i!="object"||Array.isArray(i))throw new D("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var O=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)}},se=class extends O{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ie=class extends O{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},De=class extends O{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)}},Me=class extends O{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)}},Le=class extends O{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)}},Z=class extends O{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)}};function ot(i){return/^(\d+[smhdw])+$/.test(i)}function wn(i){if(i==="pin")return{action:"pin"};if(ot(i))return{action:"retain",duration:i};throw new Z(`[urun] recordings: "${i}" is not a duration or "pin"`)}function bn(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new se(r,e??"unauthorized");if(i===404)return new Ie(r,e??"not_found");if(i===400)return new Z(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new De(r,e);case"pin_requires_active_temp":return new Me(r,e);case"permanent_locked":return new Le(r,e)}return new O(r,{status:i,code:e??`http_${i}`})}var ee=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(!ot(t))throw new Z(`[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 O("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(n,e,s,r.body))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw bn(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:s};return n!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(n)),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 se("[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:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function yn(i){return new ee(i)}var kn=1e3,Sn=12e3;function at(i,e,t={}){let r=null,n=0,s=0,o=null,a=-1,c=()=>{let p=i.get("desired.billing.generationSeconds");if(typeof p!="number"||!Number.isFinite(p)||p<=0)return null;let y=i.get("desired.billing.epoch"),b=i.get("desired.billing.updatedAtMs");return{seconds:p,epoch:typeof y=="number"&&Number.isFinite(y)?y:0,updatedAtMs:typeof b=="number"&&Number.isFinite(b)?b:null}},d=()=>{if(r===null)return null;let p=Math.min(Math.max(0,Date.now()-n),s);return r+p/1e3},l=()=>{let p=t.creditsPerSecond;if(typeof p=="number"&&Number.isFinite(p)&&p>0)return p;let y=i.get("desired.billing.creditsPerSecond");return typeof y=="number"&&Number.isFinite(y)&&y>0?y:null},h=()=>{let p=d();if(p===null)return;let y=Math.floor(p);if(y<=a)return;a=y;let b={seconds:y},T=l();T!==null&&(b.estimatedCredits=y*T),e(b)},u=p=>{n=Date.now();let y=p===null?0:Math.max(0,n-p);s=Math.max(0,12e3-y)},f=()=>{let p=c();if(p!==null){if(o!==null&&p.epoch!==o){o=p.epoch,r=p.seconds,a=-1,u(p.updatedAtMs),h();return}r!==null&&p.seconds<=r||(o=p.epoch,r=p.seconds,u(p.updatedAtMs),h())}};f();let g=i.on("change",f),S=setInterval(h,1e3);return S.unref?.(),()=>{clearInterval(S),g()}}var rr="activity",nr="visibility",_n=15e3,ct=["pointerdown","pointermove","keydown","wheel","touchstart"];function dt(i){let e=i.now??Date.now,t=i.mode==="explicit",r=t?null:i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,n=t?null:i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let u=e();if(!(o!==void 0&&u-o<15e3)){o=u;try{i.awareness.setLocalStateField(rr,{at:u})}catch{}}},c=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(nr,n.visibilityState)}catch{}},d=()=>a(),l=()=>{c(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(r)for(let u of ct)r.addEventListener(u,d,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",l);let h=null;return!t&&i.isProducing&&(h=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),h.unref?.()),a(),c(),{touch:a,dispose(){if(!s){if(s=!0,r)for(let u of ct)r.removeEventListener(u,d,{capture:!0});n&&n.removeEventListener("visibilitychange",l),h&&(clearInterval(h),h=null)}}}}var sr="user_activity",or="focus",Tn=3e4;function ir(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var oe=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(ir(e.state));let t=e.on("stateChange",n=>{this._setState(ir(n))}),r=()=>{t(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(or,e)}catch{}}}_signal(){this._lastSignalAt=this._now();let e=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(e>=3e4){this._publishNow();return}if(this._trailing)return;let t=Math.max(3e4-e,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},t),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let e={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(e.visibility=this._visibility),this._focus!==void 0&&(e.focus=this._focus);try{this._awareness?.setLocalStateField(sr,e)}catch{}}dispose(){if(!this._disposed){for(let e of Array.from(this._transportUnsubs))e();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}};var An=250;function lt(i){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let r=Date.now();r-e<250||(e=r,i())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function ut(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,i())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function pt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{i()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var ar="video/mp4";function ht(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,s=!1,o=(a,c,d)=>{let l=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!l)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let h=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(ar)?ar:void 0),u=new MediaStream([a]),f=new l(u,h?{mimeType:h}:void 0);r=f;let g=Promise.resolve();f.ondataavailable=S=>{let p=S.data;s||!p||p.size===0||(g=g.then(async()=>{let y=new Uint8Array(await p.arrayBuffer());s||c(y)}))},f.onstop=()=>{g.then(()=>{s||d()})},f.onerror=()=>{g.then(()=>{s||d()})},f.start(t)};return{start(a,c){if(r||s)return;let d=i.track();if(d){o(d,a,c);return}n=i.onTrack(l=>{!l||r||s||(n?.(),n=null,o(l,a,c))})},stop(){if(s)return;s=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function En(i){let e=i;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=i.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function cr(i,e){let t=null,r=!1,n=!1,s=new ReadableStream({pull(o){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{o.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{o.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return En(s)}import{encode as Rn,decode as Cn}from"@msgpack/msgpack";var dr=65536;function mt(i){let e=Rn(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var ae=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>dr)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(Cn(n))}return t}},M=12,ft=1,In=0,Ue=1,lr=2;function ce(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&ft)===ft,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function gt(i){let e=new Uint8Array(M),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?ft:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??In),e}var Dn=100,ur=100,de=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Dn}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(e){if(e.byteLength<M)return;let t=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray(M),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-ur?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-ur}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((o,a)=>o+a.byteLength,0),n=new Uint8Array(r),s=0;for(let o of t.chunks)n.set(o,s),s+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Mn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Ln(i){return Mn.test(i)?null:`codec ${JSON.stringify(i)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function vt(i,e){let t=Ln(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var pr=1,Pe=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==pr)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let n=this.buf[1];if(n===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+n)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+n)),this.buf=this.buf.subarray(2+n)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let n=rt(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===tt&&(this.ended=!0),t.push({name:this.name,payload:n})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function wt(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&Un(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Un(i,e){let t=i.getReader(),r=new Pe;try{for(;;){let{value:n,done:s}=await t.read();if(s)break;if(!(!n||n.byteLength===0))for(let{name:o,payload:a}of r.push(n))e.onData(o,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var bt=40,kt=48e3,Pn=64,xn=100,yt=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<M)return;let t=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-xn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let r=this.pending.get(t.frameSeq);if(!r)for(r={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r);this.pending.size>Pn;){let a=1/0;for(let c of this.pending.keys())c<a&&(a=c);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(M),r.received++,r.received<r.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let n=r.chunks.reduce((a,c)=>a+(c?.byteLength??0),0),s=new Uint8Array(n),o=0;for(let a of r.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:s})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},xe=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??bt;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${bt}ms`),r=bt),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;assembler=new yt(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(r){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,r}}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){let t=new e({output:r=>this.schedule(r),error:r=>this.onDecoderError(r)});t.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=t}decodeFrame(e){let t=globalThis.EncodedAudioChunk;if(typeof t!="function"||this.stopped)return;if(!this.decoder){let n=globalThis.AudioDecoder;if(typeof n!="function")return;try{this.initDecoder(n)}catch{return}}let r=this.decoder;r&&r.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/kt)),data:e.data}))}schedule(e){let t=this.ctx,r=this.dest;if(!t||!r||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let l=r.stream.getAudioTracks()[0];l&&this.seam.onTrack(l)}let n=e.numberOfFrames,s=Math.max(1,e.numberOfChannels),o=t.createBuffer(s,n,e.sampleRate);for(let l=0;l<s;l++){let h=new Float32Array(n);e.copyTo(h,{planeIndex:l,format:"f32-planar"}),o.copyToChannel(h,l)}let a=n/e.sampleRate;e.close();let c=t.createBufferSource();c.buffer=o,c.connect(r);let d=Math.max(this.playhead,t.currentTime+this.targetS);c.start(d),this.playhead=d+a}onDecoderError(e){if(this.stopped)return;console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=globalThis.AudioDecoder;if(typeof t=="function")try{this.initDecoder(t)}catch(r){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}};function hr(i,e){let t=i.numberOfFrames;if(i.format==="f32-planar"){let r=new Float32Array(t);return i.copyTo(r,{planeIndex:e}),r}if(i.format==="f32"){let r=new Float32Array(t*i.numberOfChannels);i.copyTo(r,{planeIndex:0});let n=new Float32Array(t);for(let s=0;s<t;s++)n[s]=r[s*i.numberOfChannels+e];return n}if(i.format==="s16"){let r=new Int16Array(t*i.numberOfChannels);i.copyTo(r,{planeIndex:0});let n=new Float32Array(t);for(let s=0;s<t;s++)n[s]=r[s*i.numberOfChannels+e]/32768;return n}throw new Error(`unsupported AudioData format for mic uplink: ${i.format}`)}var We=class{srcRate;channels;pos=0;prevTail=null;rem=new Float32Array(0);outTs=0;outTsSeeded=!1;constructor(e,t){if(!Number.isFinite(e)||e<=0)throw new Error(`bad mic sample rate: ${e}`);if(!Number.isInteger(t)||t<=0)throw new Error(`bad mic channel count: ${t}`);this.srcRate=e,this.channels=t}push(e,t){let r=e[0].length;if(r===0)return null;let n;if(this.channels===1)n=e[0];else{n=new Float32Array(r);for(let u=0;u<r;u++){let f=0;for(let g of e)f+=g[u];n[u]=f/this.channels}}let s=this.srcRate/48e3,o=[],a=this.pos;for(;a<=r-1;){if(a<0){let u=a+1;o.push(this.prevTail===null?n[0]:this.prevTail*(1-u)+n[0]*u)}else{let u=Math.floor(a);if(u===r-1)o.push(n[u]);else{let f=a-u;o.push(n[u]*(1-f)+n[u+1]*f)}}a+=s}if(this.pos=a-r,this.prevTail=n[r-1],this.outTsSeeded||(this.outTsSeeded=!0,this.outTs=t),o.length===0)return null;let c=new Float32Array(this.rem.length+o.length);c.set(this.rem);for(let u=0;u<o.length;u++)c[this.rem.length+u]=o[u];let d=Math.floor(c.length/960);if(d===0)return this.rem=c,null;let l=new Float32Array(d*960);l.set(c.subarray(0,d*960)),this.rem=c.slice(d*960);let h=this.outTs;return this.outTs+=d*2e4,{samples:l,timestampMicros:h}}};var Y=1200,Wn=3,On=1e4;function Nn(i){return Math.round(i*(kt/1e6))%2**32>>>0}function Tt(i,e,t,r,n){let s=r-M;if(s<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/s));if(o>255)return null;let a=[];for(let c=0;c<o;c++){let d=t.subarray(c*s,Math.min((c+1)*s,t.byteLength)),l=gt({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:c,fragCount:o,lane:n?.lane??Ue}),h=new Uint8Array(M+d.byteLength);h.set(l,0),h.set(d,M),a.push(h)}return a}var Oe=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;normalizer=null;AudioDataCtor=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;lastInputAt=0;lastOutputAt=0;encoderQueueBacklog=!1;generation=0;cancelCapture=null;captureTrack=null;nodeBridge=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.captureTrack&&this.captureTrack.readyState==="live"||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}let n;if(Fn(e)){let c=e,d=c.context.createMediaStreamDestination();c.connect(d),this.nodeBridge={node:c,dest:d};let l=d.stream.getAudioTracks()[0];if(!l){this.die("AudioNode bridge produced no audio track");return}n=l}else n=e;let s=++this.generation,o=new r({track:n}).readable.getReader();this.captureTrack=n;let a=!1;this.cancelCapture=()=>{a=!0,o.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&s===this.generation;){let{value:c,done:d}=await o.read();if(d)break;if(c){if(a||this.stopped||s!==this.generation){c.close();break}this.feedAudioData(c)}}!a&&!this.stopped&&s===this.generation&&(this.captureTrack=null)})().catch(c=>{!a&&!this.stopped&&s===this.generation&&this.die(`capture: ${c instanceof Error?c.message:String(c)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){if(this.cancelCapture?.(),this.cancelCapture=null,this.captureTrack=null,this.normalizer=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}feedAudioData(e){if(this.lastInputAt=this.nowMs(),!this.encoder){let r=globalThis.AudioEncoder;if(typeof r!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:48e3,numberOfChannels:1};try{this.initEncoder(r)}catch(n){e.close(),this.encoder=null,this.die(`encoder configure: ${n instanceof Error?n.message:String(n)}`);return}}let t=this.encoder;if(!t){e.close();return}try{e.sampleRate===48e3&&e.numberOfChannels===1?t.encode(e):this.encodeNormalized(e)}catch(r){this.onEncoderError(r instanceof Error?r:new Error(String(r)))}e.close()}encodeNormalized(e){if(!this.normalizer&&(this.normalizer=new We(e.sampleRate,e.numberOfChannels),this.AudioDataCtor=globalThis.AudioData??null,typeof this.AudioDataCtor!="function")){this.die("AudioData is not available for mic shape normalization");return}let t;try{t=[];for(let s=0;s<e.numberOfChannels;s++)t.push(hr(e,s))}catch(s){this.die(`mic capture: ${s instanceof Error?s.message:String(s)}`);return}let r=this.normalizer.push(t,e.timestamp);if(r===null||r.samples.length===0)return;let n=new this.AudioDataCtor({format:"f32-planar",sampleRate:48e3,numberOfFrames:r.samples.length,numberOfChannels:1,timestamp:r.timestampMicros,data:r.samples});this.encoder.encode(n),n.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:n=>this.sendFrame(n),error:n=>this.onEncoderError(n)});let r={codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3,opus:{frameDuration:2e4,useinbandfec:!0,usedtx:!0,packetlossperc:5}};try{this.encoder.configure(r)}catch{console.warn("[urun] WT mic uplink: opus fec/dtx options unsupported \u2014 encoding without them"),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}}sendFrame(e){if(this.stopped)return;this.lastOutputAt=this.nowMs();let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=Tt(this.frameSeq,Nn(e.timestamp),t,this.sink.maxDatagramSize()||Y);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let n of r)this.sink.send(n);this.frameSeq=this.frameSeq+1>>>0}heartbeat(e){if(this.stopped||!this.encoder)return;let t=this.encoder.encodeQueueSize??0,r=2e3,n=e-this.lastInputAt<r,s=e-this.lastOutputAt>r,o=n&&s&&t>0&&this.encoderQueueBacklog;this.encoderQueueBacklog=t>0,o&&this.onEncoderError(new Error(`encoder wedged: ${t} frames queued, no output for ${r}ms`))}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}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(n=>t-n<On),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=Wn){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let r=globalThis.AudioEncoder;if(!(typeof r!="function"||!this.encoderConfig))try{this.initEncoder(r)}catch(n){this.die(`encoder re-init: ${n instanceof Error?n.message:String(n)}`)}}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 Fn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var fr="urun-mic-tap";var mr=`
1
+ import{$ as cn,A as Ze,B as Zr,C as en,D as tn,E as rn,F as nn,G as sn,H as J,I as Bt,J as Te,K as et,L as jt,M as Ht,N as Vt,O as tt,P as Kt,Q as Gt,R as on,S as zt,T as Ae,U as rt,V as an,W as nt,Y as Yt,_ as dn,a as qt,aa as ln,b as we,ba as un,c as K,ca as Ee,d as ze,e as be,ea as Re,f as ye,fa as Qt,g as Ye,ga as Xt,h as Qe,ha as Jt,i as Xe,ia as Zt,j as jr,k as Hr,l as ke,m as Je,n as Vr,o as Kr,p as Gr,q as zr,r as G,s as Se,v as _e,w as Yr,x as Qr,y as Xr,z as Jr}from"./chunk-EPBFNUD2.mjs";var pn=15e3,hn=45e3,fn=12e4,it="platform",st="activation",ot="desired.activation";function er(i){if(typeof i=="string"&&i.length>0)return i;if(i&&typeof i=="object"){let e=i.note;if(typeof e=="string"&&e.length>0)return e}}var mn=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],ne=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 n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));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 mn){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 n={state:t,elapsedMs:r,stream:e.name},s=er(this._options.hint());s!==void 0&&(n.hint=s),e.lastEvent=n;for(let o of Array.from(this._handlers))o(n)}};var I=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",n){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,n!==void 0&&(this.cause=n),Object.setPrototypeOf(this,new.target.prototype)}},Ce=class extends I{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},De=class extends I{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function ie(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function gn(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=rr(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new I("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(tr)}async getDownloadUrl(e,t){let r=rr(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!wn(n))throw new I("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:tr(r.artifact),downloadUrl:n}}async _request(e,t){let r=Bt(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let s of r)try{return await this._requestFromBase(s,e,t)}catch(o){if(n=o instanceof Error?o:new Error(String(o)),n instanceof I&&bn(n.status))throw n}throw n??new I("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${J(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,s=await this._resolveToken(),o=await fetch(n,{method:"GET",headers:this._headers(s)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await fetch(n,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw yn(o.status,a,d)}try{return await o.json()}catch(a){throw new I(`[urun] runtime artifacts: invalid JSON response from ${J(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=J(t);try{let s=(await e.json()).error;if(s&&typeof s=="object"){let{code:o,message:a}=s;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 tr(i){if(!i||typeof i!="object")throw new I("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=q(e,"artifact_id")||q(e,"id"),r=q(e,"filename"),n=q(e,"kind"),s=q(e,"status")||"ready",o=vn(e,"size_bytes"),a=q(e,"sha256");if(!t||!r||!n||o==null||!a)throw new I("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:q(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:s,createdAt:q(e,"created_at"),expiresAt:q(e,"expires_at")}}function q(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function vn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function wn(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function bn(i){return i===401||i===403}function yn(i,e,t){return i===401?new Ce(t,e):i===404?new De(t,e):new I(t,i,e)}function rr(i){if(!i||typeof i!="object"||Array.isArray(i))throw new I("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var O=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)}},se=class extends O{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ie=class extends O{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Me=class extends O{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)}},Le=class extends O{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)}},xe=class extends O{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)}},Z=class extends O{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)}};function at(i){return/^(\d+[smhdw])+$/.test(i)}function kn(i){if(i==="pin")return{action:"pin"};if(at(i))return{action:"retain",duration:i};throw new Z(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Sn(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new se(r,e??"unauthorized");if(i===404)return new Ie(r,e??"not_found");if(i===400)return new Z(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Me(r,e);case"pin_requires_active_temp":return new Le(r,e);case"permanent_locked":return new xe(r,e)}return new O(r,{status:i,code:e??`http_${i}`})}var ee=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(!at(t))throw new Z(`[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 O("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(n,e,s,r.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw Sn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:s};return n!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(n)),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 se("[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:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function _n(i){return new ee(i)}var Tn=1e3,An=12e3;function dt(i,e,t={}){let r=null,n=0,s=0,o=null,a=-1,d=()=>{let h=i.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let b=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},c=()=>{if(r===null)return null;let h=Math.min(Math.max(0,Date.now()-n),s);return r+h/1e3},l=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let b=i.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},p=()=>{let h=c();if(h===null)return;let b=Math.floor(h);if(b<=a)return;a=b;let w={seconds:b},T=l();T!==null&&(w.estimatedCredits=b*T),e(w)},u=h=>{n=Date.now();let b=h===null?0:Math.max(0,n-h);s=Math.max(0,12e3-b)},f=()=>{let h=d();if(h!==null){if(o!==null&&h.epoch!==o){o=h.epoch,r=h.seconds,a=-1,u(h.updatedAtMs),p();return}r!==null&&h.seconds<=r||(o=h.epoch,r=h.seconds,u(h.updatedAtMs),p())}};f();let m=i.on("change",f),k=setInterval(p,1e3);return k.unref?.(),()=>{clearInterval(k),m()}}var nr="activity",ir="visibility",En=15e3,ct=["pointerdown","pointermove","keydown","wheel","touchstart"];function lt(i){let e=i.now??Date.now,t=i.mode==="explicit",r=t?null:i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,n=t?null:i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let u=e();if(!(o!==void 0&&u-o<15e3)){o=u;try{i.awareness.setLocalStateField(nr,{at:u})}catch{}}},d=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(ir,n.visibilityState)}catch{}},c=()=>a(),l=()=>{d(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(r)for(let u of ct)r.addEventListener(u,c,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",l);let p=null;return!t&&i.isProducing&&(p=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),p.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,r)for(let u of ct)r.removeEventListener(u,c,{capture:!0});n&&n.removeEventListener("visibilitychange",l),p&&(clearInterval(p),p=null)}}}}var or="user_activity",ar="focus",Rn=3e4;function sr(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var oe=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(sr(e.state));let t=e.on("stateChange",n=>{this._setState(sr(n))}),r=()=>{t(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(ar,e)}catch{}}}_signal(){this._lastSignalAt=this._now();let e=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(e>=3e4){this._publishNow();return}if(this._trailing)return;let t=Math.max(3e4-e,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},t),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let e={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(e.visibility=this._visibility),this._focus!==void 0&&(e.focus=this._focus);try{this._awareness?.setLocalStateField(or,e)}catch{}}dispose(){if(!this._disposed){for(let e of Array.from(this._transportUnsubs))e();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}};var Cn=250;function ut(i){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let r=Date.now();r-e<250||(e=r,i())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function pt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,i())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function ht(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{i()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var dr="video/mp4";function ft(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,s=!1,o=(a,d,c)=>{let l=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!l)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let p=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(dr)?dr:void 0),u=new MediaStream([a]),f=new l(u,p?{mimeType:p}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=k=>{let h=k.data;s||!h||h.size===0||(m=m.then(async()=>{let b=new Uint8Array(await h.arrayBuffer());s||d(b)}))},f.onstop=()=>{m.then(()=>{s||c()})},f.onerror=()=>{m.then(()=>{s||c()})},f.start(t)};return{start(a,d){if(r||s)return;let c=i.track();if(c){o(c,a,d);return}n=i.onTrack(l=>{!l||r||s||(n?.(),n=null,o(l,a,d))})},stop(){if(s)return;s=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Dn(i){let e=i;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=i.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function cr(i,e){let t=null,r=!1,n=!1,s=new ReadableStream({pull(o){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{o.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{o.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Dn(s)}import{encode as In,decode as Mn}from"@msgpack/msgpack";var lr=65536;function gt(i){let e=In(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var de=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>lr)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(Object.assign(Mn(n),{raw:n}))}return t}};function ur(i,e){let t=new DataView(i.buffer,i.byteOffset,i.byteLength),r=t.getUint8(0),n=(r&240)===128,s=r===222;if(!n&&!s&&!(r===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=n?r&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=n?1:s?3:5,c=[];c.push(i.subarray(0,d));for(let f=0;f<a;f++){let m=d,k=ae(i,t,d);d=k.end;let b=ae(i,t,d).end;if(Ln(t.getUint8(m))){let w=t.getUint8(m),T=(w&224)===160?1:w===217?2:w===218?3:5;if(new TextDecoder().decode(i.subarray(m+T,k.end))==="t"){c.push(i.subarray(m,k.end));let A=new TextEncoder().encode(e);if(A.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");c.push(new Uint8Array([160|A.byteLength]),A)}else c.push(i.subarray(m,b))}else c.push(i.subarray(m,b));d=b}let l=c.reduce((f,m)=>f+m.byteLength,0),p=new Uint8Array(l),u=0;for(let f of c)p.set(f,u),u+=f.byteLength;return p}function Ln(i){return(i&224)===160?!0:i===217||i===218||i===219}function ae(i,e,t){let r=e.getUint8(t),n=t;if(r<=127||r>=224)return{start:n,end:t+1};if((r&224)===160)return{start:n,end:t+1+(r&31)};if((r&240)===128||(r&240)===144){let o=r&15;t+=1;let a=(r&240)===128?o*2:o;for(let d=0;d<a;d++)t=ae(i,e,t).end;return{start:n,end:t}}let s={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(s[r]!==void 0)return{start:n,end:t+1+s[r]};if(r===217||r===196)return{start:n,end:t+2+e.getUint8(t+1)};if(r===218||r===197)return{start:n,end:t+3+e.getUint16(t+1,!1)};if(r===219||r===198)return{start:n,end:t+5+e.getUint32(t+1,!1)};if(r===220||r===221){let o=r===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===220?3:5;for(let a=0;a<o;a++)t=ae(i,e,t).end;return{start:n,end:t}}if(r===222||r===223){let o=r===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===222?3:5;for(let a=0;a<o*2;a++)t=ae(i,e,t).end;return{start:n,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${r.toString(16)} at byte ${n}`)}var M=12,mt=1,xn=0,Ue=1,pr=2;function ce(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&mt)===mt,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function vt(i){let e=new Uint8Array(M),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?mt:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??xn),e}var Un=100,hr=100,le=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Un}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(e){if(e.byteLength<M)return;let t=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray(M),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-hr?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-hr}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((o,a)=>o+a.byteLength,0),n=new Uint8Array(r),s=0;for(let o of t.chunks)n.set(o,s),s+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Pn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Wn(i){return Pn.test(i)?null:`codec ${JSON.stringify(i)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function wt(i,e){let t=Wn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var fr=1,Pe=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==fr)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let n=this.buf[1];if(n===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+n)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+n)),this.buf=this.buf.subarray(2+n)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let n=nt(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===rt&&(this.ended=!0),t.push({name:this.name,payload:n})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function bt(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&On(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function On(i,e){let t=i.getReader(),r=new Pe;try{for(;;){let{value:n,done:s}=await t.read();if(s)break;if(!(!n||n.byteLength===0))for(let{name:o,payload:a}of r.push(n))e.onData(o,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var yt=40,St=48e3,Nn=64,Fn=100,kt=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<M)return;let t=ce(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Fn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let r=this.pending.get(t.frameSeq);if(!r)for(r={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r);this.pending.size>Nn;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(M),r.received++,r.received<r.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let n=r.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(n),o=0;for(let a of r.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:s})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},We=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??yt;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${yt}ms`),r=yt),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;assembler=new kt(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(r){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,r}}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){let t=new e({output:r=>this.schedule(r),error:r=>this.onDecoderError(r)});t.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=t}decodeFrame(e){let t=globalThis.EncodedAudioChunk;if(typeof t!="function"||this.stopped)return;if(!this.decoder){let n=globalThis.AudioDecoder;if(typeof n!="function")return;try{this.initDecoder(n)}catch{return}}let r=this.decoder;r&&r.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/St)),data:e.data}))}schedule(e){let t=this.ctx,r=this.dest;if(!t||!r||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let l=r.stream.getAudioTracks()[0];l&&(this.armBridgeEndedWatch(l),this.seam.onTrack(l))}let n=e.numberOfFrames,s=Math.max(1,e.numberOfChannels),o=t.createBuffer(s,n,e.sampleRate);for(let l=0;l<s;l++){let p=new Float32Array(n);e.copyTo(p,{planeIndex:l,format:"f32-planar"}),o.copyToChannel(p,l)}let a=n/e.sampleRate;e.close();let d=t.createBufferSource();d.buffer=o,d.connect(r);let c=Math.max(this.playhead,t.currentTime+this.targetS);d.start(c),this.playhead=c+a}armBridgeEndedWatch(e){e.addEventListener?.("ended",()=>{if(!this.stopped){console.warn("[urun] WT audio bridge track ENDED while the lane is live \u2014 rebuilding the WebAudio playout surface and re-delivering the bridge track");try{this.rebuildSurface()}catch(t){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${t instanceof Error?t.message:String(t)}`)}}},{once:!0})}rebuildSurface(){let e=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let t=this.ctx,r=new e({sampleRate:this.config.sampleRate});this.ctx=r,this.dest=r.createMediaStreamDestination(),this.playhead=0,this.trackSurfaced=!0;let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] rebuilt playout produced no bridge track");this.armBridgeEndedWatch(n),t?.close().catch(()=>{}),this.seam.onTrack(n)}onDecoderError(e){if(this.stopped)return;console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=globalThis.AudioDecoder;if(typeof t=="function")try{this.initDecoder(t)}catch(r){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}};function mr(i,e){let t=i.numberOfFrames;if(i.format==="f32-planar"){let r=new Float32Array(t);return i.copyTo(r,{planeIndex:e}),r}if(i.format==="f32"){let r=new Float32Array(t*i.numberOfChannels);i.copyTo(r,{planeIndex:0});let n=new Float32Array(t);for(let s=0;s<t;s++)n[s]=r[s*i.numberOfChannels+e];return n}if(i.format==="s16"){let r=new Int16Array(t*i.numberOfChannels);i.copyTo(r,{planeIndex:0});let n=new Float32Array(t);for(let s=0;s<t;s++)n[s]=r[s*i.numberOfChannels+e]/32768;return n}throw new Error(`unsupported AudioData format for mic uplink: ${i.format}`)}var Oe=class{srcRate;channels;pos=0;prevTail=null;rem=new Float32Array(0);outTs=0;outTsSeeded=!1;constructor(e,t){if(!Number.isFinite(e)||e<=0)throw new Error(`bad mic sample rate: ${e}`);if(!Number.isInteger(t)||t<=0)throw new Error(`bad mic channel count: ${t}`);this.srcRate=e,this.channels=t}push(e,t){let r=e[0].length;if(r===0)return null;let n;if(this.channels===1)n=e[0];else{n=new Float32Array(r);for(let u=0;u<r;u++){let f=0;for(let m of e)f+=m[u];n[u]=f/this.channels}}let s=this.srcRate/48e3,o=[],a=this.pos;for(;a<=r-1;){if(a<0){let u=a+1;o.push(this.prevTail===null?n[0]:this.prevTail*(1-u)+n[0]*u)}else{let u=Math.floor(a);if(u===r-1)o.push(n[u]);else{let f=a-u;o.push(n[u]*(1-f)+n[u+1]*f)}}a+=s}if(this.pos=a-r,this.prevTail=n[r-1],this.outTsSeeded||(this.outTsSeeded=!0,this.outTs=t),o.length===0)return null;let d=new Float32Array(this.rem.length+o.length);d.set(this.rem);for(let u=0;u<o.length;u++)d[this.rem.length+u]=o[u];let c=Math.floor(d.length/960);if(c===0)return this.rem=d,null;let l=new Float32Array(c*960);l.set(d.subarray(0,c*960)),this.rem=d.slice(c*960);let p=this.outTs;return this.outTs+=c*2e4,{samples:l,timestampMicros:p}}};var Y=1200,$n=3,qn=1e4;function Bn(i){return Math.round(i*(St/1e6))%2**32>>>0}function At(i,e,t,r,n){let s=r-M;if(s<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/s));if(o>255)return null;let a=[];for(let d=0;d<o;d++){let c=t.subarray(d*s,Math.min((d+1)*s,t.byteLength)),l=vt({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:d,fragCount:o,lane:n?.lane??Ue}),p=new Uint8Array(M+c.byteLength);p.set(l,0),p.set(c,M),a.push(p)}return a}var Ne=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;normalizer=null;AudioDataCtor=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;lastInputAt=0;lastOutputAt=0;encoderQueueBacklog=!1;generation=0;cancelCapture=null;captureTrack=null;nodeBridge=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.captureTrack&&this.captureTrack.readyState==="live"||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}let n;if(jn(e)){let d=e,c=d.context.createMediaStreamDestination();d.connect(c),this.nodeBridge={node:d,dest:c};let l=c.stream.getAudioTracks()[0];if(!l){this.die("AudioNode bridge produced no audio track");return}n=l}else n=e;let s=++this.generation,o=new r({track:n}).readable.getReader();this.captureTrack=n;let a=!1;this.cancelCapture=()=>{a=!0,o.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&s===this.generation;){let{value:d,done:c}=await o.read();if(c)break;if(d){if(a||this.stopped||s!==this.generation){d.close();break}this.feedAudioData(d)}}!a&&!this.stopped&&s===this.generation&&(this.captureTrack=null)})().catch(d=>{!a&&!this.stopped&&s===this.generation&&this.die(`capture: ${d instanceof Error?d.message:String(d)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){if(this.cancelCapture?.(),this.cancelCapture=null,this.captureTrack=null,this.normalizer=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}feedAudioData(e){if(this.lastInputAt=this.nowMs(),!this.encoder){let r=globalThis.AudioEncoder;if(typeof r!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:48e3,numberOfChannels:1};try{this.initEncoder(r)}catch(n){e.close(),this.encoder=null,this.die(`encoder configure: ${n instanceof Error?n.message:String(n)}`);return}}let t=this.encoder;if(!t){e.close();return}try{e.sampleRate===48e3&&e.numberOfChannels===1?t.encode(e):this.encodeNormalized(e)}catch(r){this.onEncoderError(r instanceof Error?r:new Error(String(r)))}e.close()}encodeNormalized(e){if(!this.normalizer&&(this.normalizer=new Oe(e.sampleRate,e.numberOfChannels),this.AudioDataCtor=globalThis.AudioData??null,typeof this.AudioDataCtor!="function")){this.die("AudioData is not available for mic shape normalization");return}let t;try{t=[];for(let s=0;s<e.numberOfChannels;s++)t.push(mr(e,s))}catch(s){this.die(`mic capture: ${s instanceof Error?s.message:String(s)}`);return}let r=this.normalizer.push(t,e.timestamp);if(r===null||r.samples.length===0)return;let n=new this.AudioDataCtor({format:"f32-planar",sampleRate:48e3,numberOfFrames:r.samples.length,numberOfChannels:1,timestamp:r.timestampMicros,data:r.samples});this.encoder.encode(n),n.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:n=>this.sendFrame(n),error:n=>this.onEncoderError(n)});let r={codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3,opus:{frameDuration:2e4,useinbandfec:!0,usedtx:!0,packetlossperc:5}};try{this.encoder.configure(r)}catch{console.warn("[urun] WT mic uplink: opus fec/dtx options unsupported \u2014 encoding without them"),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}}sendFrame(e){if(this.stopped)return;this.lastOutputAt=this.nowMs();let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=At(this.frameSeq,Bn(e.timestamp),t,this.sink.maxDatagramSize()||Y);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let n of r)this.sink.send(n);this.frameSeq=this.frameSeq+1>>>0}heartbeat(e){if(this.stopped||!this.encoder)return;let t=this.encoder.encodeQueueSize??0,r=2e3,n=e-this.lastInputAt<r,s=e-this.lastOutputAt>r,o=n&&s&&t>0&&this.encoderQueueBacklog;this.encoderQueueBacklog=t>0,o&&this.onEncoderError(new Error(`encoder wedged: ${t} frames queued, no output for ${r}ms`))}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}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(n=>t-n<qn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=$n){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let r=globalThis.AudioEncoder;if(!(typeof r!="function"||!this.encoderConfig))try{this.initEncoder(r)}catch(n){this.die(`encoder re-init: ${n instanceof Error?n.message:String(n)}`)}}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 jn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var gr="urun-mic-tap";var vr=`
2
2
  class UrunMicTap extends AudioWorkletProcessor {
3
3
  constructor(options) {
4
4
  super(options)
@@ -29,4 +29,4 @@ class UrunMicTap extends AudioWorkletProcessor {
29
29
  }
30
30
  }
31
31
  registerProcessor('urun-mic-tap', UrunMicTap)
32
- `.trim();var gr='"use strict";(()=>{var O=Object.defineProperty;var F=(r,e,t)=>e in r?O(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var a=(r,e,t)=>F(r,typeof e!="symbol"?e+"":e,t);var A=12,P=1,N=0,R=1;function L(r){let e=new Uint8Array(A),t=new DataView(e.buffer);return t.setUint32(0,r.groupId,!0),t.setUint32(4,r.frameSeq,!0),t.setUint8(8,r.keyframe?P:0),t.setUint8(9,r.fragIndex),t.setUint8(10,r.fragCount),t.setUint8(11,r.lane??N),e}var U=48e3;function _(r,e){let t=r.numberOfFrames;if(r.format==="f32-planar"){let n=new Float32Array(t);return r.copyTo(n,{planeIndex:e}),n}if(r.format==="f32"){let n=new Float32Array(t*r.numberOfChannels);r.copyTo(n,{planeIndex:0});let o=new Float32Array(t);for(let i=0;i<t;i++)o[i]=n[i*r.numberOfChannels+e];return o}if(r.format==="s16"){let n=new Int16Array(t*r.numberOfChannels);r.copyTo(n,{planeIndex:0});let o=new Float32Array(t);for(let i=0;i<t;i++)o[i]=n[i*r.numberOfChannels+e]/32768;return o}throw new Error(`unsupported AudioData format for mic uplink: ${r.format}`)}var v=class{constructor(e,t){a(this,"srcRate");a(this,"channels");a(this,"pos",0);a(this,"prevTail",null);a(this,"rem",new Float32Array(0));a(this,"outTs",0);a(this,"outTsSeeded",!1);if(!Number.isFinite(e)||e<=0)throw new Error(`bad mic sample rate: ${e}`);if(!Number.isInteger(t)||t<=0)throw new Error(`bad mic channel count: ${t}`);this.srcRate=e,this.channels=t}push(e,t){let n=e[0].length;if(n===0)return null;let o;if(this.channels===1)o=e[0];else{o=new Float32Array(n);for(let l=0;l<n;l++){let g=0;for(let y of e)g+=y[l];o[l]=g/this.channels}}let i=this.srcRate/48e3,c=[],u=this.pos;for(;u<=n-1;){if(u<0){let l=u+1;c.push(this.prevTail===null?o[0]:this.prevTail*(1-l)+o[0]*l)}else{let l=Math.floor(u);if(l===n-1)c.push(o[l]);else{let g=u-l;c.push(o[l]*(1-g)+o[l+1]*g)}}u+=i}if(this.pos=u-n,this.prevTail=o[n-1],this.outTsSeeded||(this.outTsSeeded=!0,this.outTs=t),c.length===0)return null;let s=new Float32Array(this.rem.length+c.length);s.set(this.rem);for(let l=0;l<c.length;l++)s[this.rem.length+l]=c[l];let p=Math.floor(s.length/960);if(p===0)return this.rem=s,null;let h=new Float32Array(p*960);h.set(s.subarray(0,p*960)),this.rem=s.slice(p*960);let b=this.outTs;return this.outTs+=p*2e4,{samples:h,timestampMicros:b}}};var B=1200,z=3,q=1e4;function $(r){return Math.round(r*(U/1e6))%2**32>>>0}function H(r,e,t,n,o){let i=n-A;if(i<=0)return null;let c=Math.max(1,Math.ceil(t.byteLength/i));if(c>255)return null;let u=[];for(let s=0;s<c;s++){let p=t.subarray(s*i,Math.min((s+1)*i,t.byteLength)),h=L({groupId:e>>>0,frameSeq:r>>>0,keyframe:o?.keyframe??!0,fragIndex:s,fragCount:c,lane:o?.lane??R}),b=new Uint8Array(A+p.byteLength);b.set(h,0),b.set(p,A),u.push(b)}return u}var M=class{constructor(e){a(this,"sink",e);a(this,"encoder",null);a(this,"encoderConfig",null);a(this,"normalizer",null);a(this,"AudioDataCtor",null);a(this,"encoderErrorsAt",[]);a(this,"frameSeq",0);a(this,"stopped",!1);a(this,"deadCb",null);a(this,"lastInputAt",0);a(this,"lastOutputAt",0);a(this,"encoderQueueBacklog",!1);a(this,"generation",0);a(this,"cancelCapture",null);a(this,"captureTrack",null);a(this,"nodeBridge",null)}deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.captureTrack&&this.captureTrack.readyState==="live"||(this.teardownCapture(),e===null))return;let n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}let o;if(G(e)){let s=e,p=s.context.createMediaStreamDestination();s.connect(p),this.nodeBridge={node:s,dest:p};let h=p.stream.getAudioTracks()[0];if(!h){this.die("AudioNode bridge produced no audio track");return}o=h}else o=e;let i=++this.generation,c=new n({track:o}).readable.getReader();this.captureTrack=o;let u=!1;this.cancelCapture=()=>{u=!0,c.cancel().catch(()=>{})},(async()=>{for(;!u&&!this.stopped&&i===this.generation;){let{value:s,done:p}=await c.read();if(p)break;if(s){if(u||this.stopped||i!==this.generation){s.close();break}this.feedAudioData(s)}}!u&&!this.stopped&&i===this.generation&&(this.captureTrack=null)})().catch(s=>{!u&&!this.stopped&&i===this.generation&&this.die(`capture: ${s instanceof Error?s.message:String(s)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){if(this.cancelCapture?.(),this.cancelCapture=null,this.captureTrack=null,this.normalizer=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}feedAudioData(e){if(this.lastInputAt=this.nowMs(),!this.encoder){let n=globalThis.AudioEncoder;if(typeof n!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:48e3,numberOfChannels:1};try{this.initEncoder(n)}catch(o){e.close(),this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let t=this.encoder;if(!t){e.close();return}try{e.sampleRate===48e3&&e.numberOfChannels===1?t.encode(e):this.encodeNormalized(e)}catch(n){this.onEncoderError(n instanceof Error?n:new Error(String(n)))}e.close()}encodeNormalized(e){if(!this.normalizer&&(this.normalizer=new v(e.sampleRate,e.numberOfChannels),this.AudioDataCtor=globalThis.AudioData??null,typeof this.AudioDataCtor!="function")){this.die("AudioData is not available for mic shape normalization");return}let t;try{t=[];for(let i=0;i<e.numberOfChannels;i++)t.push(_(e,i))}catch(i){this.die(`mic capture: ${i instanceof Error?i.message:String(i)}`);return}let n=this.normalizer.push(t,e.timestamp);if(n===null||n.samples.length===0)return;let o=new this.AudioDataCtor({format:"f32-planar",sampleRate:48e3,numberOfFrames:n.samples.length,numberOfChannels:1,timestamp:n.timestampMicros,data:n.samples});this.encoder.encode(o),o.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)});let n={codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3,opus:{frameDuration:2e4,useinbandfec:!0,usedtx:!0,packetlossperc:5}};try{this.encoder.configure(n)}catch{console.warn("[urun] WT mic uplink: opus fec/dtx options unsupported \\u2014 encoding without them"),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}}sendFrame(e){if(this.stopped)return;this.lastOutputAt=this.nowMs();let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=H(this.frameSeq,$(e.timestamp),t,this.sink.maxDatagramSize()||B);if(n===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \\u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let o of n)this.sink.send(o);this.frameSeq=this.frameSeq+1>>>0}heartbeat(e){if(this.stopped||!this.encoder)return;let t=this.encoder.encodeQueueSize??0,n=2e3,o=e-this.lastInputAt<n,i=e-this.lastOutputAt>n,c=o&&i&&t>0&&this.encoderQueueBacklog;this.encoderQueueBacklog=t>0,c&&this.onEncoderError(new Error(`encoder wedged: ${t} frames queued, no output for ${n}ms`))}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}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(o=>t-o<q),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=z){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \\u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let n=globalThis.AudioEncoder;if(!(typeof n!="function"||!this.encoderConfig))try{this.initEncoder(n)}catch(o){this.die(`encoder re-init: ${o instanceof Error?o.message:String(o)}`)}}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 G(r){let e=r;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var V=4,j=6e4,K=1500;function Q(r){let e=r.now??(()=>performance.now()),t=r.writable.getWriter(),n=r.maxDatagramSize,o=!1,i=null,c=!1,u=[],s=0,p=[],h=!1,b=d=>console.warn(`[urun] WT mic uplink worker: ${d}`),l=0,g=0,y=()=>performance.timeOrigin+performance.now(),k=[],x=setInterval(()=>{r.control.postMessage({type:"stats",fed:l,blocks:k.length,accepted:g,writeTimes:k.slice(-8192),pcmTimes:u.slice(-8192),lastPcmAt:i})},5e3);function W(d,m){let f=e();for(;p.length>0&&f-p[0]>j;)p.shift();p.push(f),b(`STALL (${d}): ${m} \\u2014 the session host rebuilds the capture path`),r.control.postMessage({type:"stall",kind:d,detail:m}),p.length>=V&&!h&&(h=!0,b("stall budget exhausted \\u2014 the lane dies loudly (the transport reverts the mic)"),r.control.postMessage({type:"dead",reason:`mic uplink ${d} stalls repeating: ${m}`}))}let w=new M({send:d=>{k.push(y()),k.length>8192&&k.splice(0,k.length-8192),t.write(d).then(()=>{g++,r.control.postMessage({type:"accepted",lane:"audio",n:1})},m=>r.control.postMessage({type:"failed",lane:"audio",error:m instanceof Error?m.message:String(m)}))},delivered:()=>0,maxDatagramSize:()=>n}),E=null,I=setInterval(()=>{let d=e();if(w.heartbeat(d),o&&!c){let m=i===null?d-s:d-i;m>K&&(c=!0,W("capture",`no pcm blocks for ${Math.round(m)}ms with a source armed`))}},r.watchdogIntervalMs??500),S={onControl(d){switch(d.type){case"max-dgram":n=d.n;break;case"pcm-port":{let m=d.port;if(!m)return;m.onmessage=f=>{let C=f.data;C?.type==="pcm"&&E?.(C)};break}case"mic-reset":w.setSource(null),o=!1,i=null,c=!1,s=e();break;case"mic-arm":o=!0,c=!1,s=e();break;case"video":t.write(d.dgram).then(()=>r.control.postMessage({type:"accepted",lane:"video",n:1}),m=>r.control.postMessage({type:"failed",lane:"video",error:m instanceof Error?m.message:String(m)}));break;case"stats":r.control.postMessage({type:"stats",fed:l,blocks:k.length,accepted:g,writeTimes:k.slice(-8192),pcmTimes:u.slice(-8192),lastPcmAt:i});break;case"mic-stop":w.stop(),o=!1;break}},onPcm(d){if(!o)return;i=e(),u.push(y()),u.length>8192&&u.splice(0,u.length-8192),l++,c=!1;let m;try{let f=globalThis.AudioData;if(typeof f!="function"){r.control.postMessage({type:"dead",reason:"AudioData is not available in the mic uplink worker"});return}m=new f({format:"f32-planar",sampleRate:d.rate,numberOfFrames:d.samples.length,numberOfChannels:1,timestamp:d.micros,data:d.samples})}catch(f){r.control.postMessage({type:"dead",reason:`mic uplink worker: AudioData construction failed: ${f instanceof Error?f.message:String(f)}`});return}w.feedAudioData(m)},dispose(){clearInterval(I),clearInterval(x),w.stop();try{t.releaseLock?.()}catch{}}};return E=d=>S.onPcm(d),S}if(typeof document>"u"&&typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope){let r=globalThis,e=null;r.onmessage=t=>{let n=t.data;if(n.type==="probe"){r.postMessage({type:"supported",detail:typeof globalThis.AudioEncoder=="function"&&typeof globalThis.AudioData=="function"?"ok":"missing AudioEncoder/AudioData"});return}if(n.type==="init"){let o=n.writable,i=n.pcmPort??t.ports?.[0];e=Q({control:{postMessage:c=>r.postMessage(c)},writable:o,maxDatagramSize:n.maxDatagramSize}),e.onControl({type:"pcm-port",port:i}),r.postMessage({type:"ready"});return}if(e){n.type==="video"&&n.dgram instanceof Uint8Array,e.onControl(n);return}r.postMessage({type:"unsupported",detail:`message before init: ${n.type}`})}}})();\n';var Ne=class{constructor(e){this.deps=e}deps;worker=null;workerUrl=null;workletUrl=null;workletsLoaded=new WeakSet;active=!1;lastSource=null;graph=null;ctx=null;deliveredByLane={audio:0,video:0};lastWorkerStats=null;audioDeadCb=null;delivered(e){return this.deliveredByLane[e]}isActive(){return this.active}audioLane(){return{setSource:e=>this.setMicSource(e),deliveredDatagrams:()=>this.delivered("audio"),onDead:e=>{this.audioDeadCb=e},stop:()=>this.stopMic()}}async start(){if(this.active||this.worker)return this.active;let e=this.deps.writable();if(!e)return console.warn("[urun] WT uplink worker: no datagram writable \u2014 staying on the main-thread uplink pipeline"),!1;let t;try{this.workerUrl=URL.createObjectURL(new Blob([gr],{type:"text/javascript"})),t=new Worker(this.workerUrl)}catch(n){return console.warn(`[urun] WT uplink worker: could not start (${n instanceof Error?n.message:String(n)}) \u2014 staying on the main-thread uplink pipeline`),!1}if(!await this.probe(t))return t.terminate(),!1;this.worker=t,t.onmessage=n=>this.handleMessage(n.data),t.onerror=n=>{console.error(`[urun] WT uplink worker CRASHED (${n.message||"worker error"}) \u2014 the datagram writable died with it; the send-failure budget owns the revert`),this.active=!1,this.worker=null,this.deps.onSendFailed("uplink worker crashed")};try{t.postMessage({type:"init",writable:e,maxDatagramSize:this.deps.maxDatagramSize()},[e])}catch(n){return console.warn(`[urun] WT uplink worker: writable transfer refused (${n instanceof Error?n.message:String(n)}) \u2014 staying on the main-thread uplink pipeline`),t.terminate(),this.worker=null,!1}return this.active=!0,!0}probe(e){return new Promise(t=>{let r,n=()=>{e.removeEventListener("message",s),e.removeEventListener("error",o),clearTimeout(r)},s=a=>{let c=a.data;c?.type==="supported"?(n(),t(!0)):c.type==="unsupported"&&(console.warn(`[urun] WT uplink worker: unsupported in this worker (${c.detail??"unknown"}) \u2014 staying on the main-thread uplink pipeline`),n(),t(!1))},o=()=>{n(),t(!1)};e.addEventListener("message",s),e.addEventListener("error",o),r=setTimeout(()=>{n(),t(!1)},3e3),e.postMessage({type:"probe"})})}handleMessage(e){switch(e.type){case"accepted":this.deliveredByLane[e.lane]+=e.n;break;case"failed":this.deps.onSendFailed(e.error);break;case"dead":this.audioDeadCb?this.audioDeadCb(e.reason):this.deps.onAudioDead(e.reason);break;case"stall":console.error(`[urun] WT mic uplink STALL (${e.kind}): ${e.detail} \u2014 rebuilding the capture path`),this.rebuildCapture();break;case"stats":this.lastWorkerStats=e;break}}setMicSource(e){this.active&&(e!==null&&e===this.lastSource&&this.graph!==null&&this.graph.track===e&&e.readyState==="live"||(this.post({type:"mic-reset"}),this.teardownGraph(),this.lastSource=e,e!==null&&this.wireSource(e).catch(t=>{console.error(`[urun] WT mic uplink capture wiring FAILED (${t instanceof Error?t.message:String(t)}) \u2014 the stall watchdog escalates if the lane never produces`)})))}async wireSource(e){let t=await this.ensureCaptureContext(e);await this.loadWorklet(t);let r=this.createWorklet(t),n=t.createGain();n.channelCount=1,n.channelCountMode="explicit",n.channelInterpretation="speakers",n.gain.value=1;let s=t.createMediaStreamDestination();r.connect(s),n.connect(r);let o={ctx:t,worklet:r,gain:n,sinkGain:s,srcNode:null,appNode:null,track:null,onended:null};if(vr(e)){let c=e;c.connect(n),o.appNode=c}else{let c=e,d=t.createMediaStreamSource(new MediaStream([c]));d.connect(n);let l=()=>{this.graph?.track===c&&(console.error("[urun] WT mic uplink: the mic track ENDED while the lane was engaged \u2014 dying loudly so the transport republishes the mic intent"),this.audioDeadCb?.("mic track ended"))};c.addEventListener("ended",l),o.srcNode=d,o.track=c,o.onended=l}this.graph=o;let a=new MessageChannel;r.port.postMessage({port:a.port2},[a.port2]),this.worker?.postMessage({type:"pcm-port",port:a.port1},[a.port1]),this.post({type:"mic-arm"})}async ensureCaptureContext(e){if(vr(e))return e.context;if(!this.ctx){if(typeof AudioContext!="function")throw new Error("AudioContext is not available");this.ctx=new AudioContext({sampleRate:48e3})}return this.ctx.state==="suspended"&&await this.ctx.resume().catch(()=>{}),this.ctx}async loadWorklet(e){this.workletsLoaded.has(e)||(this.workletUrl||(this.workletUrl=URL.createObjectURL(new Blob([mr],{type:"text/javascript"}))),await e.audioWorklet.addModule(this.workletUrl),this.workletsLoaded.add(e))}createWorklet(e){if(typeof AudioWorkletNode!="function")throw new Error("AudioWorkletNode is not available");return new AudioWorkletNode(e,fr)}teardownGraph(){let e=this.graph;if(e){try{e.worklet.disconnect()}catch{}try{e.sinkGain.disconnect()}catch{}try{e.gain.disconnect()}catch{}try{e.srcNode?.disconnect()}catch{}if(e.appNode)try{e.appNode.disconnect(e.gain)}catch{}e.track&&e.onended&&e.track.removeEventListener("ended",e.onended),this.graph=null}}async rebuildCapture(){let e=this.lastSource;if(this.teardownGraph(),e!==null)try{let t=await this.ensureCaptureContext(e);t.state==="suspended"&&await t.resume().catch(()=>{}),await this.loadWorklet(t),await this.wireSource(e)}catch(t){console.error(`[urun] WT mic uplink capture rebuild FAILED (${t instanceof Error?t.message:String(t)}) \u2014 the stall watchdog escalates if the stall repeats`)}}stopMic(){this.post({type:"mic-stop"}),this.teardownGraph(),this.lastSource=null}send(e,t){if(!this.active||!this.worker)throw new Error("uplink worker host is not active");this.worker.postMessage({type:"video",dgram:t},[t.buffer])}terminate(){this.worker?.terminate(),this.worker=null,this.active=!1,this.teardownGraph(),this.ctx&&(this.ctx.close().catch(()=>{}),this.ctx=null)}post(e){this.worker?.postMessage(e)}};function vr(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var $n=9e4,qn="avc1.42E01F",Bn=60,jn=3,Hn=1e4;function Vn(i){return Math.round(i*($n/1e6))%2**32>>>0}var Fe=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 n=++this.generation,s=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,s.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&n===this.generation;){let{value:a,done:c}=await s.read();if(c)break;if(a){if(o||this.stopped||n!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&n===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 s=globalThis.VideoEncoder;if(typeof s!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new s({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:qn,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 n=this.keyframeWanted||this.framesSinceKeyframe>=Bn;this.keyframeWanted=!1,this.framesSinceKeyframe=n?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:n})}catch(s){this.onEncoderError(s instanceof Error?s:new Error(String(s)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=Tt(this.frameSeq,Vn(e.timestamp),t,this.sink.maxDatagramSize()||Y,{lane:lr,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 n of r)this.sink.send(n);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<Hn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=jn){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 Kn(i){return i.byteLength>=2&&i[0]===1&&i[1]===3}var $e=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 n=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let s=this.streams.get(e);if(!s){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),s={writer:a},this.streams.set(e,s)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await s.writer.write(o),Kn(t)&&(this.streams.delete(e),await s.writer.close().catch(()=>{}))}catch(s){throw this.die(s instanceof Error?s.message:String(s)),s}});return this.chain=n.catch(()=>{}),n}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 wr=250,Gn=25,zn=2e3,Yn=15e3,Qn=1e3,Xn=45e3,le=class i{constructor(e,t,r,n,s,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=n;this.audioUplink=s;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;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new de({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;audioUplinkLane=null;uplinkWorkerHost=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&&vt(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(d=>({algorithm:"sha-256",value:Uint8Array.from(atob(d),l=>l.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready,this.startUplinkWorker();let n=await this.wt.createBidirectionalStream();this.writer=n.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=n.readable.getReader(),o=new ae,a=[],c=await this.readControl(s,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");if(this.lastInboundControlAt=performance.now(),typeof c.pingIntervalMs=="number"&&c.pingIntervalMs>0?this.advertisedPingIntervalMs=c.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&&(vt(c.codec,"hello-ack"),this.initDecoder(c.codec,c.width,c.height)),this.offer.audio&&this.audioLane){let d=new xe(this.offer.audio,this.audioLane);try{d.start(),this.audioPlayout=d}catch(l){console.warn(`[urun] WT audio lane failed to start (${l instanceof Error?l.message:String(l)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),d.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 d=this.wt.createUnidirectionalStream?.bind(this.wt);if(!d)throw new Error("WebTransport uni streams are not creatable in this environment");let l=new $e({openUniStream:async()=>(await d()).getWriter()});l.onDead(h=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(h)}),this.dataUplinkSender=l,this.dataUplink.onUplink(l)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT data uplink failed to engage (${l}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(l)}this.controlLoop(s,o,a).catch(d=>this.die(`control loop: ${d}`)),this.datagramLoop().catch(d=>this.die(`datagram loop: ${d}`)),this.feedbackLoop(),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(d=>{this.closedReason=`connection error: ${d}`,this.die(`connection error: ${d}`)})}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 ${wr}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Yn},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Qn))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}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(),n=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,s=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=n===null&&s===null?!0:(n===null||n>=e.stallMs)&&(s===null||s>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&s!==null&&s>=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(s/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}o&&s!==null&&s>=Xn&&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(s/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.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.uplinkWorkerHost?.terminate(),this.uplinkWorkerHost=null,this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e))}dropDatagramUplinks(e){this.clearUplinkRetryTimers(),(this.audioUplinkLane!==null||this.audioUplinkRetry!==null)&&(this.audioUplinkLane?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e)),(this.videoUplinkLane!==null||this.videoUplinkRetry!==null)&&(this.videoUplinkLane?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e))}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)");this.dataLaneSink=e,wt(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,r){let n=globalThis.VideoDecoder;if(typeof n!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let s=this.canvas.getContext("2d");if(!s)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r};let o=new n({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,s.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,n=>this.onUplinkSendError(n))}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(n=>r-n<zn),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<Gn)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){let t=this.uplinkWorkerHost;if(t?.isActive())return{send:n=>{if(!(this.stopped||this.deadFired))try{t.send(e,n)}catch(s){this.onUplinkSendError(s)}},delivered:()=>t.delivered(e),maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Y};this.datagramWriter();let r=0;return{send:n=>this.uplinkSend(n,()=>{r++}),delivered:()=>r,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Y}}async startUplinkWorker(){let e=new Ne({writable:()=>this.wt?.datagrams.writable??null,maxDatagramSize:()=>this.wt?.datagrams.maxDatagramSize??Y,onSendFailed:r=>this.onUplinkSendError(new Error(r)),onAudioDead:r=>this.onUplinkLaneDead("audio",r)});await e.start()&&(this.uplinkWorkerHost=e)}engageAudioUplink(){let e=this.uplinkWorkerHost,t=e?.isActive()?e.audioLane():new Oe(this.uplinkSink("audio"));t.onDead(r=>this.onUplinkLaneDead("audio",r)),this.audioUplinkLane=t,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(t)}engageVideoUplink(){let e=new Fe(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t)),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 n=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${n}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,n)}}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){if(e==="audio"?this.audioUplinkLane=null:this.videoUplinkLane=null,this.stopped||this.deadFired)return;let r=e==="audio"?"mic":"video",n=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,o=n?.builtAt!=null&&Date.now()-n.builtAt>=i.UPLINK_LANE_HEALTHY_MS?1:(n?.count??0)+1;if(o>i.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${r} uplink lane dead (${t}) \u2014 ${i.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 ${i.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`);return}console.warn(`[urun] WT ${r} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${o}/${i.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let a={count:o,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=a:this.videoUplinkRetry=a,a.timer=setTimeout(()=>{a.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},i.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t){e==="audio"?this.audioUplink.onUplinkLost(t):this.videoUplink.onUplinkLost(t)}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>=M&&t[11]===Ue){this.audioLaneLastArrivalAt=performance.now(),this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let n=performance.now();if(this.lastArrivalTs>0){let s=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(s-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;if(typeof n=="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 n({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(mt(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 readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;let{value:s,done:o}=await e.read();if(o)return null;s&&r.push(...t.push(s))}}async controlLoop(e,t,r){for(;!this.stopped;){let n=await this.readControl(e,t,r);if(!n)break;this.lastInboundControlAt=performance.now(),n.t==="ping"&&(this.gatewayPings++,this.sendControl(n.id!==void 0?{t:"pong",ts:n.ts,id:n.id}:{t:"pong",ts:n.ts}).catch(()=>{})),n.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 n=this.reassembler.drainWindow(),s=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:s>0?100*n.abandoned/s:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},wr)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),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)}}};var br=2500,yr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Jn=1e4,ue=class i{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;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",n=this.opts.allowWebTransport??!0,s={webtransport:t&&r&&n,webcodecs:r,codecs:yr,wtData:t&&r&&n&&this.opts.dataLane!==void 0,wtAudio:t&&r&&n&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&r&&n&&this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtVideoUp:t&&r&&n&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&n&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:s});let o=s.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"),s.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 At(d.start(),this.opts.quicDeadlineMs??br,"quic connect deadline"),this.engageQuicDataLane(d,s.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(d?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let h=String(l instanceof Error?l.message:l);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${h}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(h),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()}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,n=this.opts.dataLane!==void 0,s=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="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:yr,wtData:n,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;let d=this.createWebTransportSession();try{await At(d.start(),this.opts.quicDeadlineMs??br,"quic connect deadline")}catch(l){throw d.stop().catch(()=>{}),l}if(this.session!==r)return d.stop().catch(()=>{}),null;try{this.engageQuicDataLane(d,n)}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:(n,s)=>r.onData(n,s),onLaneError:n=>r.onLaneError(n)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new le(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; retrying WT`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.opts.onWtRequiredOutage?.(t);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);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,r)})}redialWtAfterDeath(e){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures+=1,this.wtRedialFailures===i.WT_REDIAL_MAX+1){console.error(`[urun] WT re-dial failed ${i.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 t=this.wtRedialFailures,r=Rt(i.WT_REDIAL_BASE_MS,t,i.WT_REDIAL_CAP_MS,t===1?0:void 0);console.warn(`[urun] WT re-dial attempt ${t} scheduled in ${Math.round(r)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},r)}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}try{if(await this.retryWebTransport()!==null){console.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let r=Et(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${i.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 n=this.createWebRtc();try{let s=await At(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Jn,"webrtc failover produced no media transport");if(this.session!==e){s.stop().catch(()=>{});return}this.session=s,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(s){if(n.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=s instanceof Error?s.message:String(s),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})}};function Et(i){if(i instanceof Error)return i.message;if(typeof i=="string")return i;if(i&&typeof i=="object"){try{let e=JSON.stringify(i);if(e!==void 0&&e!=="{}")return e}catch{}return i.constructor?.name??Object.prototype.toString.call(i).slice(8,-1)}return String(i)}function Rt(i,e,t,r){if(r!==void 0)return r;let n=Math.min(i*2**Math.max(0,e-2),t);return Math.round(n*(.75+Math.random()*.5))}function At(i,e,t){return new Promise((r,n)=>{let s=setTimeout(()=>n(new Error(t)),e);i.then(o=>{clearTimeout(s),r(o)},o=>{clearTimeout(s),n(o)})})}var Zn=1e4,pe=class{constructor(e,t=Zn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=Te();return new Promise((n,s)=>{let o=setTimeout(()=>{a(),s(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){s(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:d,requestId:l,...h}=c;n(h)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(o),a(),s(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 ei="video",he=class{constructor(e,t=ei){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,n)=>{this.firstMediaResolve=r,this.firstMediaReject=n}),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 kr(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var ti="video";function Sr(i,e,t){let r=globalThis,n=r.document;if(!(typeof n?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=i.holdWebRtcDial?.(),a=n.createElement("canvas"),c=!1,d=null,l=!1,h=()=>{if(d){for(let w of d.getVideoTracks())try{w.stop()}catch{}d=null}l&&(l=!1,t.onOverrideTrack(null))},u=new ue(new pe(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new he(i,t.streamName??ti)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(w,A)=>i.dispatchQuicStreamData(w,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:w=>i.quicStreamDataLaneLost(w),onLaneError:w=>i.raiseQuicStreamDataError(w)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:w=>{c||t.onOverrideAudioTrack(w)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>C(),onMediaTransportLost:w=>{c||(h(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(w),C())},onTransportChange:(w,A)=>{c||(w==="webrtc"&&(h(),C()),t.onTransportChange?.(w,A))}}),f=i.onWtOnlyLegDeath?.(w=>u.failCurrentWtLeg(w)),g=null,S=()=>{g!==null&&(clearInterval(g),g=null)},p=t.wtRetryBaseMs??2e3,y=t.wtRetryCapMs??3e4,b=null,T=0,C=()=>{if(c||b!==null||u.activeTransport==="webtransport")return;let w=Rt(p,T+2,y);b=setTimeout(()=>{b=null,T+=1,u.retryWebTransport().then(A=>{if(c){A&&u.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${T})`),T=0,W(A);C()}).catch(A=>{c||(console.debug(`[urun] webtransport background retry ${T} failed: `+Et(A)),C())})},w)},E=()=>{b!==null&&(clearTimeout(b),b=null)},W=async w=>{if(c||w.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;S();let N=!1;g=setInterval(()=>{if(c||u.activeTransport!=="webtransport")return;let L=kr(w);if(!L){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)"),S();return}let U=L.pathLiveness();if(!U.alive){let $=u.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${U.evidence}`+($?" \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"),S(),L.fail(`path health: ${U.evidence}`);return}if(!N){if(N=!0,u.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${A}ms \u2014 the QUIC PATH IS HEALTHY (${U.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 ${A}ms \u2014 no media datagrams reached this client (path healthy: ${U.evidence}); webrtc track remains authoritative`)}},A);try{await w.firstMedia}catch(L){S(),console.debug("[urun] webtransport ended before any media flowed:",L);return}if(S(),c||u.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;d=a.captureStream();let H=d.getVideoTracks()[0];H&&(l=!0,t.onOverrideTrack(H))};return(async()=>{let w=await u.connect();if(c){u.disconnect().catch(()=>{});return}await W(w)})().catch(w=>{if(S(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",w);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",w),C();return}o?.proceed(`negotiation unavailable: ${w instanceof Error?w.message:String(w)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",w),C()}),{activeTransport:()=>u.activeTransport,watchDownlinkStall(w){u.watchDownlinkStall(w)},dispose(){c=!0,f?.(),S(),E(),h(),t.onOverrideAudioTrack?.(null),u.disconnect().catch(()=>{})}}}var ri=new Set;function Dt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var ni="rpc",ii="$presence",Ar=3e4,_r=3e4,si="rpc-resp";function oi(i){return`${si}:${i}`}function Ct(){return Te()}function ai(i){if(i&&typeof i=="object"){let e=i.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 i=="string"?i:JSON.stringify(i)}}function ci(i,e,t,r,n,s,o,a,c,d){let l=[],h=null,u=!1,f=null,g=!1,S,p,y=new Promise((m,F)=>{S=m,p=F});y.catch(()=>{});let b=o(),T=null,C=null,E=null,W=null,w=null,A=null,N=!0,H=()=>{E&&(clearTimeout(E),E=null),W&&(W(),W=null)},L=()=>{w&&(clearTimeout(w),w=null),A&&(A(),A=null)},U=!1,$=()=>{U||!g||(U=!0,i.set({rpc:{[e]:null}}))},V=()=>{N=!1,H(),L(),T?.(),T=null,C?.(),C=null,a?.removeEventListener("abort",_),b.dispose(),$()},X=()=>{if(h){if(l.length>0){let m=h;h=null,m.resolve({value:l.shift(),done:!1})}else if(f!==null){let m=h;h=null,m.reject(f)}else if(u){let m=h;h=null,m.resolve({value:void 0,done:!0})}}},Ft=m=>{u||(l.push(m),X())},v=m=>{u||(f=m,u=!0,p(m),V(),X())},k=m=>{u||(u=!0,S(m),V(),X())},_=()=>{let m=a?.reason;v(m instanceof be?m:new ye(e))},I=m=>{if(!(u||!m||typeof m!="object"))switch(L(),$(),m.t){case"delta":typeof m.delta=="string"&&Ft(m.delta);break;case"response":k(m.body);break;case"error":{let{message:F,code:R}=ai(m.body);v(new be(F,{requestId:e,code:m.code??R}));break}}},P=()=>{let m=b.messages()[Symbol.asyncIterator]();T=()=>{m.return?.(void 0)};let F=()=>{N&&m.next().then(R=>{if(N){if(R.done){u||k(void 0);return}I(R.value),F()}},R=>{N&&v(R)})};F()},x=()=>{if(!g){if(g=!0,a){if(a.aborted){v(new ye(e));return}a.addEventListener("abort",_,{once:!0})}C=c?.(m=>v(m))??null,P(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:s}}}),d&&d>0&&!i.synced&&(E=setTimeout(()=>{E=null,!u&&!i.synced&&v(new Ye(d,e))},d),W=i.onSynced(()=>H())),A=i.onSynced(()=>{A=null,!(u||U||w)&&(w=setTimeout(()=>{w=null,!(u||U)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(_r/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).`)},_r))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(x(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(f!==null){let m=f;return f=null,Promise.reject(m)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((m,F)=>{h={resolve:m,reject:F}})},return(){return u||(u=!0,S(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(m){return u||(u=!0,p(m),V()),Promise.reject(m)}}}},body:y,start:x}}function Tr(i){if(i&&typeof i=="object"){let{epoch:e,by:t}=i,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function di(i,e){let r=i.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:s,br:o}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let c=Tr(s);c&&(a.rt=c);let d=Tr(o);return d&&(a.br=d),a}var It=class{constructor(e,t,r,n,s){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,s=null,o={push(c){if(!n)if(r){let d=r;r=null,d.resolve({value:c,done:!1})}else t.push(c)},end(){if(n=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{n=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||n)&&(s=e._streamConsumeUnavailableError(c),a(),r)){let d=r;r=null,d.reject(s)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.reject(s):n?Promise.resolve({value:void 0,done:!0}):new Promise((c,d)=>{r={resolve:c,reject:d}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=di(t,this._name),n=r?.br;if(n?.by==="runtime")throw new Qe(this._name,"runtime","browser");if(n)return;let s={br:{epoch:1}};r?.rt&&(s.rt=r.rt);let o=r?.kind??e;o&&(s.kind=o),t.set({streams:{[this._name]:s}})}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??ht;return cr(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}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)}},fe=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Qt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,n,s,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=s,this._streamData=zt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=lt(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=dt({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new oe({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(ii).awareness.setLocalState({role:"client"}),this._activation=new ne({onPhase:a=>this.onPhase(a),hint:()=>this.doc(nt).get(it)??this.doc("control").get(st),onData:(a,c)=>this._streamData.onData(a,c)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await Kt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,s=new ve,o=new Ae({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new i(e,s,o,Dt(t),ie({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&s.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),ke()&&await Se();let c=t.getAccessToken,d=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:d}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return Je(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=at(this.doc("control"),r=>{for(let n of Array.from(this._generationTickHandlers))try{n(r)}catch(s){console.warn("[urun] generationTick handler failed:",s)}})),()=>{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 ee(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,n)=>t.retain(r,n),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 z(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new z(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 It(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 Xt(e,this._sessionId,ri.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Jt(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=Ee(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${t}\0${r}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(Yt({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=Ct(),n=new AbortController;t.signal&&(t.signal.aborted?n.abort(t.signal.reason):t.signal.addEventListener("abort",()=>n.abort(t.signal.reason),{once:!0}));let s=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;s=setTimeout(()=>n.abort(new ze(c,r)),c)}let o=this._consumeResponse(r,e,!1,n.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{s&&clearTimeout(s),a?.()})}_consumeResponse(e,t,r,n,s){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(ni),a=oi(e);return ci(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),s??Ar)}requestStream(e,t={}){let r=Ct();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Ct(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.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)}}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=Sr(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}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 K)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new K);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 n of t)try{n()}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 n of r)try{n(new Xe)}catch{}for(let n of this._docs.values())n.dispose();this._docs.clear();for(let n of this._streams.values())n.dispose();this._streams.clear(),this._transport.disconnect(e)}};function Er(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function Mt(){try{return globalThis.sessionStorage??null}catch{return null}}var Lt=new Map;function qe(i){if(!i)return;let e=i.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 li(i,e){return i!==void 0&&e!==void 0&&i!==e}function Ut(i,e){let t=Mt(),r=null;if(t)try{let s=t.getItem(i);if(s){let o=JSON.parse(s);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 n=Lt.get(i)??r??null;return!n||li(n.actor,e)?null:n}function Rr(i,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};Lt.set(i,t);let r=Mt();if(r)try{r.setItem(i,JSON.stringify(t))}catch{}}function Be(i){Lt.delete(i);let e=Mt();if(e)try{e.removeItem(i)}catch{}}var Cr=new Set(["paused","acquiring","live"]),ui=new Set(["24h","keep"]);function Ir(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function pi(i){if(typeof i?.id!="string"||i.id.length===0)throw new we("[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 i.state!="string"||!Cr.has(i.state))throw new we(`[urun] session ${i.id} reported an unrecognized state ${JSON.stringify(i.state)} \u2014 this @urun-sh/core build knows only ${[...Cr].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 i.recordings_expired=="boolean"?e=i.recordings_expired:console.warn(`[urun] session ${i.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:i.id,label:typeof i.label=="string"&&i.label.length>0?i.label:null,state:i.state,app:typeof i.app=="string"?i.app:"",functionName:typeof i.function=="string"?i.function:"",createdAt:Ir(i.created_at),lastActiveAt:Ir(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:ui.has(i.retention)?i.retention:(i.retention!==void 0&&console.warn(`[urun] session ${i.id} reported an unrecognized retention ${JSON.stringify(i.retention)} \u2014 defaulting to '24h'`),"24h")}}var me=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await Ht({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(pi),nextCursor:r}}async end(e){await Vt({...this._request,sessionId:e})}async archive(e){await et({...this._request,sessionId:e,archived:!0})}async unarchive(e){await et({...this._request,sessionId:e,archived:!1})}};function Dr(i,e,t){let r=qe(t);Rr(i,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var hi=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function fi(i,e){return new me(i,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function mi(i,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(!(hi.has(r)||typeof r!="string"))return(n,s)=>{let o=n??{},a=Er({orgId:e.orgId,app:i,functionName:r}),c=!s?.sessionId&&!e.sessionKey&&!!s?.label,d,l=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,h=l(),u=e.jwt,f=e.getAccessToken?async v=>{let k=await e.getAccessToken(v);return k&&(u=k),k}:void 0,g={...e,getAccessToken:f},S=new ve,p=new Ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:h,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),y=new fe(h,S,p,Dt(g),ie(g),{activity:s?.activity}),b,T=!1,C=!1,E,W,w=new Promise(v=>{W=v}),A,N=v=>{v.sessionId||E||(E="teardown",A="ticket",_e({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},H=v=>{E||v.sessionId||(E="abandon",_e({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider,reason:"client_abandoned"}))},L=v=>{let k=v.sessionId||!d?v:{...v,sessionId:d};b=k,W({status:"ready",handle:k}),(C||E==="teardown")&&N(k)};y.setEndHandler(async()=>{let v=b?{status:"ready",handle:b}:await w;if(v.status==="unavailable")throw new K("[urun] session allocation failed before a releasable request was created",{cause:v.cause});let k=b??v.handle;return Be(a),E==="teardown"?k.sessionId?{status:"paused",sessionId:k.sessionId,reason:"client_ended"}:{status:"canceled",requestId:k.requestId}:(E="end",k.sessionId?Bt({baseUrl:k.baseUrl,sessionId:k.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):Ze({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),y.setCancelHandler(async()=>{let v=b?{status:"ready",handle:b}:await w;if(v.status==="unavailable")throw new K("[urun] session allocation failed before a cancellable request was created",{cause:v.cause});let k=b??v.handle;if(k.sessionId)throw new Ge(`[urun] cancel() is for a queued admission request, but this call already has session ${k.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:k.sessionId,code:"cancel_on_live_session"});E="end";try{let _=await Ze({baseUrl:k.baseUrl,requestId:k.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return Be(a),_}catch(_){throw E==="end"&&(E=void 0),_}});let U=async v=>{let k,_=s?.sessionId??e.sessionKey??d,I,P;if(_===void 0&&!c){let R=Ut(a);if(R?.sessionId){if(P=qe(u),R.actor!==void 0&&P===void 0&&f){let Ke=await Promise.resolve(f()).catch(()=>{});P=qe(Ke??e.jwt)}I=R.actor!==void 0&&P!==void 0&&R.actor!==P?void 0:R.sessionId}}let x=_??I,B=(R,Ke)=>jt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:R,sessionKey:Ke,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},priority:e.priority,onAdmission:j=>{p.reportAdmission(j),j.sessionId&&!d&&(d=j.sessionId,k=j.sessionId,b&&b.sessionId!==j.sessionId&&L({...b,sessionId:j.sessionId}),T||(e.sessionKey||Dr(a,j.sessionId,u),y.setSessionId(j.sessionId)))},onRequest:L}),m;try{m=await B(v,x)}catch(R){if(I===void 0||!(R instanceof G)||R.code!=="session_name_not_yours")throw R;console.warn(`[urun] session_name_not_yours: the control plane refused session ${I} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),Ut(a,P)?.sessionId===I&&Be(a),m=await B(l(),void 0)}let F=f?await f()??void 0:e.jwt;if(k&&k!==m.sessionId)throw b&&b.sessionId!==m.sessionId&&L({...b,sessionId:m.sessionId}),new G(`Gateway contract violation: admission minted session ${k} but allocation completed as ${m.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return d=m.sessionId,b&&b.sessionId!==m.sessionId&&L({...b,sessionId:m.sessionId}),T||(e.sessionKey||Dr(a,m.sessionId,u),y.setSessionId(m.sessionId),y.setArtifactsAuth(ie({...g,baseUrl:m.baseUrl})),p.setEndsAt(m.endsAt),p.seedRegion(Gt(m.response))),{url:m.wsUrl,sessionId:m.sessionId,jwt:F,iceServers:m.response.ice_servers,endsAt:m.endsAt}},$,V=f?async()=>await f()??$:()=>$,X=()=>{let v=p.connectedUrl;return v?Ee(v):void 0};if(p.setConnectionResolver(async()=>{let v=await U(l());return $=v.jwt,v}),p.on("connected",()=>{p.multiplexer&&S.setTarget(p.multiplexer);let v=p.connectedUrl;v&&y.setDocTransport({wsUrl:v,token:V,resolveServerUrl:X})}),(async v=>{let k;try{k=await U(v)}catch(_){if(T){W({status:"unavailable",cause:_});return}console.error(`[urun] Failed to create session for ${r}:`,_),b&&H(b);let I=_ instanceof Error?_:new Error(String(_)),P=_ instanceof G?_.httpStatus:void 0,x=_ instanceof G?_.code:void 0,B=_ instanceof G?_.retryAfterSeconds:void 0;p.reportAllocationFailure(I,P,x,B),W({status:"unavailable",cause:_});return}T||(p.setAuth({jwt:k.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:k.url,sessionId:k.sessionId,iceServers:k.iceServers}),ke()&&await Se(),$=k.jwt,y.setDocTransport({wsUrl:k.url,token:V,resolveServerUrl:X}),await p.connect({app:i,functionName:r,args:o}),y.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(h).catch(v=>{console.error(`[urun] Failed to connect session for ${r}:`,v)}),e.releaseOnLeave!==!1){let v=ut(()=>{if(T=!0,p.leaveLeg())return;if(p.connectedUrl!==null){p.disconnect();return}p.disconnect();let x=b;x?N(x):C=!0});y.onDisconnect(v);let k,_,I=!1,P=()=>{I||(I=!0,k?.(),_?.())};w.then(x=>{x.status!=="ready"||I||(k=pt(()=>b!==void 0))}),_=y.onPhase(x=>{let B=x?.name;(B==="paused"||B==="error")&&P()}),I&&_(),y.onDisconnect(P)}return y}}})}var Mr="https://api.urun.sh",Lr="URUN_DEV";function gi(){if(typeof process>"u")return!1;let i=process.env?.[Lr];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var Q=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function vi(i,e={}){if(!i)throw new Q("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=J(e.baseUrl??Mr),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),e.sharedApp&&(n.shared_app=!0),(e.dev??gi())&&(n.dev=!0);let s;try{s=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(n)})}catch(u){throw new Q(`[urun] client token mint request failed: ${u instanceof Error?u.message:String(u)}`)}let o={};try{o=await s.json()}catch{}if(!s.ok){let u=typeof o.message=="string"?o.message:`HTTP ${s.status}`;throw new Q(`[urun] client token mint failed: ${u}`,s.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",d=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,l=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new Q("[urun] client token mint returned no token (control-plane contract violation)",s.status);let h=Number.isFinite(d)?new Date(d):new Date(Date.now()+(l??60)*1e3);return{token:a,expiresAt:h,orgId:c}}var Ur=3e4,Pr="stream:",Pt=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let s=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(s.timer),n.error?s.reject(new Error(n.error)):s.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${Pr}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Pr}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let s=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(s)&&(this._pendingRpc.delete(s),n(new Error(`RPC request "${e}" timed out after ${Ur}ms`)))},Ur);this._pendingRpc.set(s,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function wi(i){let r=`${i.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(i.orgId)}`,n=new WebSocket(r);(i.jwt||i.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:i.orgId,jwt:i.jwt,authProvider:i.authProvider,apiKey:i.apiKey}))});let s=new $t(n);return new Pt(n,s)}var bi='video/mp4; codecs="avc1.42E01E"';function yi(i,e){let t=e?.codec??bi,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,s=URL.createObjectURL(n);r.src=s,n.addEventListener("sourceopen",()=>{let u;try{u=n.addSourceBuffer(t)}catch(p){throw p instanceof DOMException&&p.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):p}let f=i.getReader();function g(){return u.updating?new Promise(p=>{u.addEventListener("updateend",()=>p(),{once:!0})}):Promise.resolve()}async function S(){try{for(;;){let{done:p,value:y}=await f.read();if(p){await g(),n.readyState==="open"&&n.endOfStream();return}await g();try{u.appendBuffer(y)}catch(b){if(b instanceof DOMException&&b.name==="QuotaExceededError"){let T=u.buffered;if(T.length>0){let C=T.start(T.length-1);u.remove(0,C),await g(),u.appendBuffer(y)}else throw b}else throw b}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}S()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),d=c.getTracks(),l=0,h=d.length;if(h===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let u of d)u.addEventListener("ended",()=>{l++,l>=h&&URL.revokeObjectURL(s)});return c}function ki(i){return i.status.startsWith("pending_")}var te=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},ge=class extends te{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Si(i,e,t){let r=t||e||`HTTP ${i}`;return i===401?new ge(r,e??"unauthorized"):new te(r,{status:i,code:e??`http_${i}`})}var je=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new te("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let r=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(r)?r:[]}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(n,e,s))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw Si(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r){let n={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(n["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:n})}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 ge("[urun] credits: 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:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function _i(i){return new je(i)}var He=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function xr(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function Ti(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Ai(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function xt(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var Ve=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,xt(r,new Error(`${e} capture claim superseded by a newer claim`)));let n=this.createState(e,t);return this.claims.set(e,n),await this.converge(n),n.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new He;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},n;try{n=await t(r)}catch(o){let a=`one-capture getUserMedia(${xr(r)}) failed`,c=o instanceof Error?o.message:String(o);for(let d of[...this.claims.values()])if(this.claims.delete(d.kind),d.released=!0,d!==e){let l=new Error(`${a} \u2014 ${d.kind} capture lost: ${c||o}`);l.cause=o,xt(d,l)}throw o}let s=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of s){let a=Ti(n,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${xr(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw c;xt(o,c);continue}if(o.track=a,o.stream=Ai(n,a),o!==e)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(e,t){let r=this,n={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return n.track},get stream(){return n.stream},update(s){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=s,await r.converge(n),!n.track)throw new Error(`${e} capture update yielded no track`);return n.track})},release(){n.released||(n.released=!0,r.claims.get(e)===n&&r.claims.delete(e),n.track?.stop(),n.track=null,n.stream=null)},onTrack(s){return n.trackListeners.add(s),()=>n.trackListeners.delete(s)},onLost(s){return n.lostListeners.add(s),()=>n.lostListeners.delete(s)}}};return n}},Ei=null;function Ri(){return Ei??=new Ve}var Wr="input",Ci=30;function Ii(i){let e=i.now??Date.now,t=i.field??Wr,r=1e3/Math.max(i.hz??30,.001),n=new Set,s=0,o=0,a=0,c=0,d,l=null,h=!1,u=()=>{if(h)return;d=e(),c+=1;let g={keys:[...n],buttons:s,pointer:{x:o,y:a},seq:c,at:d};try{i.awareness.setLocalStateField(t,g)}catch{}},f=()=>{if(h)return;let g=e();if(d===void 0||g-d>=r){l&&(clearTimeout(l),l=null),u();return}if(l)return;let S=Math.max(r-(g-d),0);l=setTimeout(()=>{l=null,u()},S),l.unref?.()};return{keyDown(g){let S=String(g).toLowerCase();n.has(S)||(n.add(S),f())},keyUp(g){let S=String(g).toLowerCase();n.delete(S)&&f()},setButtons(g){let S=Number.isFinite(g)?Number(g):0;S!==s&&(s=S,f())},movePointer(g,S){let p=Number.isFinite(g)?Number(g):0,y=Number.isFinite(S)?Number(S):0;p===0&&y===0||(o+=p,a+=y,f())},heldKeys(){return[...n]},clear(){h||(n.clear(),s=0,l&&(clearTimeout(l),l=null),u())},dispose(){if(h)return;let g=n.size>0||s!==0;n.clear(),s=0,l&&(clearTimeout(l),l=null),g&&u(),h=!0}}}var Di=1024,Mi=.92,Li=262144,Ui=256e3,Wt=[.9,.8,.7,.6,.5],Or=.8,Pi=8;function Nt(i,e,t){if(!(i>0)||!(e>0))throw new Error(`reference image has no pixels (${i}x${e})`);let r=Math.min(1,t/Math.max(i,e));return{width:Math.max(1,Math.round(i*r)),height:Math.max(1,Math.round(e*r))}}async function xi(i){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(i,{imageOrientation:"from-image"})}async function Fr(i,e,t){let r=await new Promise(n=>{i.toBlob(n,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function Nr(i,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${i} -> ${e} bytes`)}async function Ot(i,e,t,r,n){let s=document.createElement("canvas");s.width=e,s.height=t;let o=s.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(i,0,0,e,t),await Fr(s,r,n)}async function Wi(i,e,t,r){let{width:n,height:s}=e,o=await Ot(i,n,s,t,r);if(o.size<=256e3)return{blob:o,width:n,height:s};if(t==="image/jpeg"){for(let c of Wt)if(!(c>=r)&&(o=await Ot(i,n,s,t,c),o.size<=256e3))return Nr(`quality ${r} -> ${c}`,o.size),{blob:o,width:n,height:s}}let a=t==="image/jpeg"?Wt[Wt.length-1]:r;for(let c=0;c<Pi;c++)if(n=Math.max(16,Math.round(n*Or)),s=Math.max(16,Math.round(s*Or)),o=await Ot(i,n,s,t,a),o.size<=256e3)return Nr(`downscaled to ${n}x${s} @ q${a}`,o.size),{blob:o,width:n,height:s};throw new Error(`this image cannot be sent: even at ${n}x${s} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function Oi(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:s}=e,o=await xi(i);try{let a=Nt(o.width,o.height,t),c=await Wi(o,a,r,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:s}}finally{o.close()}}function Ni(i){let e=i instanceof Error?i.name:"",t=i instanceof Error?i.message:String(i);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function Fi(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function $i(i,e){let t=i.videoWidth,r=i.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:s="image/jpeg",quality:o=.92}=e??{},a=Nt(t,r,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let d=c.getContext("2d");if(!d)throw new Error("could not prepare the reference image (no 2d canvas context)");s==="image/jpeg"&&(d.fillStyle="#fff",d.fillRect(0,0,a.width,a.height)),d.drawImage(i,0,0,a.width,a.height);let l=await Fr(c,s,o);return{bytes:new Uint8Array(await l.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var qi=new Set(["w","a","s","d"]),re=(i,e)=>Math.min(e,Math.max(-e,i));function Bi(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:s=.06,maxPan:o=.12,maxLogZoom:a=.22}=i,c=0,d=0,l=0,h=null,u=new Set;return{pointerDelta(f,g){c=re(c-f*e,o),d=re(d-g*e,o)},keyDown(f){let g=f.toLowerCase();qi.has(g)&&u.add(g)},keyUp(f){u.delete(f.toLowerCase())},clearKeys(){u.clear()},frameArrived(){let f=1-s;c*=f,d*=f,l*=f},tick(f){if(h===null){h=f;return}let g=Math.max(0,Math.min(100,f-h))/1e3;h=f,u.has("w")&&(l=re(l+t*g,a)),u.has("s")&&(l=re(l-t*g,a)),u.has("a")&&(c=re(c+r*g,o)),u.has("d")&&(c=re(c-r*g,o));let S=Math.exp(-g*1e3/n);c*=S,d*=S,l*=S},transform(){return{translateX:c,translateY:d,scale:Math.exp(l)}},isIdentity(f=5e-4){return Math.abs(c)<f&&Math.abs(d)<f&&Math.abs(l)<f},reset(){c=0,d=0,l=0,u.clear()}}}export{ln as ACTIVATION_COLD_BOOT_AFTER_MS,un as ACTIVATION_DEGRADED_AFTER_MS,it as ACTIVATION_HINT_PATH,dn as ACTIVATION_STILL_AFTER_MS,ct as ACTIVITY_DOM_EVENTS,rr as ACTIVITY_FIELD,_n as ACTIVITY_STAMP_MIN_INTERVAL_MS,ne as ActivationMonitor,mi as App,Xr as BACKOFF_BASE_MS,Zr as BACKOFF_MAX_ATTEMPTS,Jr as BACKOFF_MAX_MS,Yr as COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,Ve as CaptureController,He as CaptureUnavailableError,Q as ClientTokenError,je as CreditsClient,te as CreditsError,ge as CreditsUnauthorizedError,Li as DATA_CHANNEL_MESSAGE_CEILING,Ar as DEFAULT_DOC_SYNC_TIMEOUT_MS,Mr as DEFAULT_GATEWAY_URL,$r as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Mi as DEFAULT_REFERENCE_JPEG_QUALITY,Di as DEFAULT_REFERENCE_MAX_SIZE,zr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,sn as DERIVED_LEG_SEP,M as DGRAM_HEADER_BYTES,or as FOCUS_FIELD,An as FOREGROUND_COALESCE_MS,de as FrameReassembler,kn as GENERATION_TICK_EMIT_INTERVAL_MS,Sn as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Ci as INPUT_PRESENCE_DEFAULT_HZ,Wr as INPUT_PRESENCE_FIELD,Z as InvalidDurationError,st as LEGACY_ACTIVATION_HINT_PATH,nt as PLATFORM_DOC_NAME,Le as PermanentLockedError,Me as PinRequiresActiveTempError,oe as PresenceTracker,qr as ProduceAckTimeoutError,Ie as RecordingNotFoundError,ee as RecordingsClient,O as RecordingsError,se as RecordingsUnauthorizedError,ye as RequestAbortError,Xe as RequestCancelledError,Ye as RequestDocSyncError,be as RequestError,ze as RequestTimeoutError,De as RetainNotTempError,Ce as RuntimeArtifactNotFoundError,z as RuntimeArtifactsClient,D as RuntimeArtifactsError,Re as RuntimeArtifactsUnauthorizedError,cn as SIGNALING_PROTOCOL_VERSION,tt as STREAM_END,fe as Session,G as SessionAllocationError,me as SessionDirectory,we as SessionDirectoryError,Ge as SessionEndError,K as SessionEndUnavailableError,jr as SessionFailedError,Qe as StreamDirectionConflict,ue as TransportNegotiator,Vr as TransportSessionMismatchError,pe as TransportSessionSignaling,Lr as URUN_DEV_ENV,sr as USER_ACTIVITY_FIELD,Tn as USER_ACTIVITY_MIN_INTERVAL_MS,nr as VISIBILITY_FIELD,Ui as WIRE_MESSAGE_BUDGET,dr as WT_CONTROL_FRAME_MAX,pr as WT_DATA_STREAM_VERSION,he as WebRtcSession,le as WebTransportSession,ae as WtControlDecoder,Pe as WtDataStreamParser,Zt as activationHintFrom,Fi as cameraCaptureAvailable,$i as captureStillFromVideo,en as computeBackoffDelay,wt as consumeWtDataStreams,dt as createActivityTracker,Bi as createCameraWarp,vi as createClientToken,_i as createCreditsClient,Ii as createInputPresencePublisher,yn as createRecordingsClient,hn as createRuntimeArtifactsClient,wi as createStore,rt as decodeStreamEnvelope,an as derivedLegName,on as derivedLegRole,Br as describeSessionFailure,Qr as describeSessionPhase,nn as encodeStreamEnvelope,mt as encodeWtControlFrame,Nt as fitWithin,ot as isDurationString,Gr as isPausedPhase,ki as isPendingRecording,tn as isRetryableSessionError,Kr as isWakingPhase,ht as mediaRecorderChunkSource,Oi as normalizeReferenceImage,wn as normalizeRetention,pt as observeLeaveConfirm,lt as observePageLifecycle,ut as observePageTeardown,ce as parseDgramHeader,rn as prewake,Ni as referenceImageErrorMessage,_e as releaseSessionBeacon,fi as sessionDirectory,Hr as sessionFailureFromMediaError,Ri as sharedCaptureController,yi as videoStream,at as watchGenerationTick,Je as whenLive,gt as writeDgramHeader};
32
+ `.trim();var wr='"use strict";(()=>{var F=Object.defineProperty;var O=(r,e,t)=>e in r?F(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var s=(r,e,t)=>O(r,typeof e!="symbol"?e+"":e,t);var w=12,P=1,B=0,S=1;function U(r){let e=new Uint8Array(w),t=new DataView(e.buffer);return t.setUint32(0,r.groupId,!0),t.setUint32(4,r.frameSeq,!0),t.setUint8(8,r.keyframe?P:0),t.setUint8(9,r.fragIndex),t.setUint8(10,r.fragCount),t.setUint8(11,r.lane??B),e}var L=48e3;function R(r,e){let t=r.numberOfFrames;if(r.format==="f32-planar"){let n=new Float32Array(t);return r.copyTo(n,{planeIndex:e}),n}if(r.format==="f32"){let n=new Float32Array(t*r.numberOfChannels);r.copyTo(n,{planeIndex:0});let o=new Float32Array(t);for(let i=0;i<t;i++)o[i]=n[i*r.numberOfChannels+e];return o}if(r.format==="s16"){let n=new Int16Array(t*r.numberOfChannels);r.copyTo(n,{planeIndex:0});let o=new Float32Array(t);for(let i=0;i<t;i++)o[i]=n[i*r.numberOfChannels+e]/32768;return o}throw new Error(`unsupported AudioData format for mic uplink: ${r.format}`)}var v=class{constructor(e,t){s(this,"srcRate");s(this,"channels");s(this,"pos",0);s(this,"prevTail",null);s(this,"rem",new Float32Array(0));s(this,"outTs",0);s(this,"outTsSeeded",!1);if(!Number.isFinite(e)||e<=0)throw new Error(`bad mic sample rate: ${e}`);if(!Number.isInteger(t)||t<=0)throw new Error(`bad mic channel count: ${t}`);this.srcRate=e,this.channels=t}push(e,t){let n=e[0].length;if(n===0)return null;let o;if(this.channels===1)o=e[0];else{o=new Float32Array(n);for(let l=0;l<n;l++){let g=0;for(let A of e)g+=A[l];o[l]=g/this.channels}}let i=this.srcRate/48e3,c=[],d=this.pos;for(;d<=n-1;){if(d<0){let l=d+1;c.push(this.prevTail===null?o[0]:this.prevTail*(1-l)+o[0]*l)}else{let l=Math.floor(d);if(l===n-1)c.push(o[l]);else{let g=d-l;c.push(o[l]*(1-g)+o[l+1]*g)}}d+=i}if(this.pos=d-n,this.prevTail=o[n-1],this.outTsSeeded||(this.outTsSeeded=!0,this.outTs=t),c.length===0)return null;let a=new Float32Array(this.rem.length+c.length);a.set(this.rem);for(let l=0;l<c.length;l++)a[this.rem.length+l]=c[l];let p=Math.floor(a.length/960);if(p===0)return this.rem=a,null;let h=new Float32Array(p*960);h.set(a.subarray(0,p*960)),this.rem=a.slice(p*960);let b=this.outTs;return this.outTs+=p*2e4,{samples:h,timestampMicros:b}}};var N=1200,z=3,q=1e4;function $(r){return Math.round(r*(L/1e6))%2**32>>>0}function G(r,e,t,n,o){let i=n-w;if(i<=0)return null;let c=Math.max(1,Math.ceil(t.byteLength/i));if(c>255)return null;let d=[];for(let a=0;a<c;a++){let p=t.subarray(a*i,Math.min((a+1)*i,t.byteLength)),h=U({groupId:e>>>0,frameSeq:r>>>0,keyframe:o?.keyframe??!0,fragIndex:a,fragCount:c,lane:o?.lane??S}),b=new Uint8Array(w+p.byteLength);b.set(h,0),b.set(p,w),d.push(b)}return d}var x=class{constructor(e){s(this,"sink",e);s(this,"encoder",null);s(this,"encoderConfig",null);s(this,"normalizer",null);s(this,"AudioDataCtor",null);s(this,"encoderErrorsAt",[]);s(this,"frameSeq",0);s(this,"stopped",!1);s(this,"deadCb",null);s(this,"lastInputAt",0);s(this,"lastOutputAt",0);s(this,"encoderQueueBacklog",!1);s(this,"generation",0);s(this,"cancelCapture",null);s(this,"captureTrack",null);s(this,"nodeBridge",null)}deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.captureTrack&&this.captureTrack.readyState==="live"||(this.teardownCapture(),e===null))return;let n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}let o;if(H(e)){let a=e,p=a.context.createMediaStreamDestination();a.connect(p),this.nodeBridge={node:a,dest:p};let h=p.stream.getAudioTracks()[0];if(!h){this.die("AudioNode bridge produced no audio track");return}o=h}else o=e;let i=++this.generation,c=new n({track:o}).readable.getReader();this.captureTrack=o;let d=!1;this.cancelCapture=()=>{d=!0,c.cancel().catch(()=>{})},(async()=>{for(;!d&&!this.stopped&&i===this.generation;){let{value:a,done:p}=await c.read();if(p)break;if(a){if(d||this.stopped||i!==this.generation){a.close();break}this.feedAudioData(a)}}!d&&!this.stopped&&i===this.generation&&(this.captureTrack=null)})().catch(a=>{!d&&!this.stopped&&i===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(){if(this.cancelCapture?.(),this.cancelCapture=null,this.captureTrack=null,this.normalizer=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}feedAudioData(e){if(this.lastInputAt=this.nowMs(),!this.encoder){let n=globalThis.AudioEncoder;if(typeof n!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:48e3,numberOfChannels:1};try{this.initEncoder(n)}catch(o){e.close(),this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let t=this.encoder;if(!t){e.close();return}try{e.sampleRate===48e3&&e.numberOfChannels===1?t.encode(e):this.encodeNormalized(e)}catch(n){this.onEncoderError(n instanceof Error?n:new Error(String(n)))}e.close()}encodeNormalized(e){if(!this.normalizer&&(this.normalizer=new v(e.sampleRate,e.numberOfChannels),this.AudioDataCtor=globalThis.AudioData??null,typeof this.AudioDataCtor!="function")){this.die("AudioData is not available for mic shape normalization");return}let t;try{t=[];for(let i=0;i<e.numberOfChannels;i++)t.push(R(e,i))}catch(i){this.die(`mic capture: ${i instanceof Error?i.message:String(i)}`);return}let n=this.normalizer.push(t,e.timestamp);if(n===null||n.samples.length===0)return;let o=new this.AudioDataCtor({format:"f32-planar",sampleRate:48e3,numberOfFrames:n.samples.length,numberOfChannels:1,timestamp:n.timestampMicros,data:n.samples});this.encoder.encode(o),o.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)});let n={codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3,opus:{frameDuration:2e4,useinbandfec:!0,usedtx:!0,packetlossperc:5}};try{this.encoder.configure(n)}catch{console.warn("[urun] WT mic uplink: opus fec/dtx options unsupported \\u2014 encoding without them"),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}}sendFrame(e){if(this.stopped)return;this.lastOutputAt=this.nowMs();let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=G(this.frameSeq,$(e.timestamp),t,this.sink.maxDatagramSize()||N);if(n===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \\u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let o of n)this.sink.send(o);this.frameSeq=this.frameSeq+1>>>0}heartbeat(e){if(this.stopped||!this.encoder)return;let t=this.encoder.encodeQueueSize??0,n=2e3,o=e-this.lastInputAt<n,i=e-this.lastOutputAt>n,c=o&&i&&t>0&&this.encoderQueueBacklog;this.encoderQueueBacklog=t>0,c&&this.onEncoderError(new Error(`encoder wedged: ${t} frames queued, no output for ${n}ms`))}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}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(o=>t-o<q),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=z){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \\u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let n=globalThis.AudioEncoder;if(!(typeof n!="function"||!this.encoderConfig))try{this.initEncoder(n)}catch(o){this.die(`encoder re-init: ${o instanceof Error?o.message:String(o)}`)}}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 H(r){let e=r;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var V=4,j=6e4,K=1500;function Q(r){let e=r.now??(()=>performance.now()),t=r.writable.getWriter(),n=r.maxDatagramSize,o=!1,i=null,c=!1,d=[],a=0,p=[],h=!1,b=u=>console.warn(`[urun] WT mic uplink worker: ${u}`),l=0,g=0,A=()=>performance.timeOrigin+performance.now(),k=[],_=setInterval(()=>{r.control.postMessage({type:"stats",fed:l,blocks:k.length,accepted:g,writeTimes:k.slice(-8192),pcmTimes:d.slice(-8192),lastPcmAt:i})},5e3);function W(u,m){let f=e();for(;p.length>0&&f-p[0]>j;)p.shift();p.push(f),b(`STALL (${u}): ${m} \\u2014 the session host rebuilds the capture path`),r.control.postMessage({type:"stall",kind:u,detail:m}),p.length>=V&&!h&&(h=!0,b("stall budget exhausted \\u2014 the lane dies loudly (the transport reverts the mic)"),r.control.postMessage({type:"dead",reason:`mic uplink ${u} stalls repeating: ${m}`}))}let y=new x({send:u=>{k.push(A()),k.length>8192&&k.splice(0,k.length-8192),t.write(u).then(()=>{g++,r.control.postMessage({type:"accepted",lane:"audio",n:1})},m=>r.control.postMessage({type:"failed",lane:"audio",error:m instanceof Error?m.message:String(m)}))},delivered:()=>0,maxDatagramSize:()=>n}),E=null,I=setInterval(()=>{let u=e();if(y.heartbeat(u),o&&!c){let m=i===null?u-a:u-i;m>K&&(c=!0,W("capture",`no pcm blocks for ${Math.round(m)}ms with a source armed`))}},r.watchdogIntervalMs??500),T={onControl(u){switch(u.type){case"max-dgram":n=u.n;break;case"pcm-port":{let m=u.port;if(!m)return;m.onmessage=f=>{let C=f.data;C?.type==="pcm"&&E?.(C)};break}case"mic-reset":y.setSource(null),o=!1,i=null,c=!1,a=e();break;case"mic-arm":o=!0,c=!1,a=e();break;case"video":t.write(u.dgram).then(()=>r.control.postMessage({type:"accepted",lane:"video",n:1}),m=>r.control.postMessage({type:"failed",lane:"video",error:m instanceof Error?m.message:String(m)}));break;case"stats":r.control.postMessage({type:"stats",fed:l,blocks:k.length,accepted:g,writeTimes:k.slice(-8192),pcmTimes:d.slice(-8192),lastPcmAt:i});break;case"mic-stop":y.stop(),o=!1;break}},onPcm(u){if(!o)return;i=e(),d.push(A()),d.length>8192&&d.splice(0,d.length-8192),l++,c=!1;let m;try{let f=globalThis.AudioData;if(typeof f!="function"){r.control.postMessage({type:"dead",reason:"AudioData is not available in the mic uplink worker"});return}m=new f({format:"f32-planar",sampleRate:u.rate,numberOfFrames:u.samples.length,numberOfChannels:1,timestamp:u.micros,data:u.samples})}catch(f){r.control.postMessage({type:"dead",reason:`mic uplink worker: AudioData construction failed: ${f instanceof Error?f.message:String(f)}`});return}y.feedAudioData(m)},dispose(){clearInterval(I),clearInterval(_),y.stop();try{t.releaseLock?.()}catch{}}};return E=u=>T.onPcm(u),T}if(typeof document>"u"&&typeof globalThis.WorkerGlobalScope<"u"&&globalThis instanceof globalThis.WorkerGlobalScope){let r=globalThis,e=null;r.onmessage=t=>{let n=t.data;if(n.type==="probe"){r.postMessage({type:"supported",detail:typeof globalThis.AudioEncoder=="function"&&typeof globalThis.AudioData=="function"?"ok":"missing AudioEncoder/AudioData"});return}if(n.type==="init"){let o=n.writable,i=n.pcmPort??t.ports?.[0];e=Q({control:{postMessage:c=>r.postMessage(c)},writable:o,maxDatagramSize:n.maxDatagramSize}),e.onControl({type:"pcm-port",port:i}),r.postMessage({type:"ready"});return}if(e){n.type==="video"&&n.dgram instanceof Uint8Array,e.onControl(n);return}r.postMessage({type:"unsupported",detail:`message before init: ${n.type}`})}}})();\n';var Fe=class{constructor(e){this.deps=e}deps;worker=null;workerUrl=null;workletUrl=null;workletsLoaded=new WeakSet;active=!1;lastSource=null;graph=null;ctx=null;deliveredByLane={audio:0,video:0};lastWorkerStats=null;audioDeadCb=null;delivered(e){return this.deliveredByLane[e]}isActive(){return this.active}audioLane(){return{setSource:e=>this.setMicSource(e),deliveredDatagrams:()=>this.delivered("audio"),onDead:e=>{this.audioDeadCb=e},stop:()=>this.stopMic()}}async start(){if(this.active||this.worker)return this.active;let e=this.deps.writable();if(!e)return console.warn("[urun] WT uplink worker: no datagram writable \u2014 staying on the main-thread uplink pipeline"),!1;let t;try{this.workerUrl=URL.createObjectURL(new Blob([wr],{type:"text/javascript"})),t=new Worker(this.workerUrl)}catch(n){return console.warn(`[urun] WT uplink worker: could not start (${n instanceof Error?n.message:String(n)}) \u2014 staying on the main-thread uplink pipeline`),!1}if(!await this.probe(t))return t.terminate(),!1;this.worker=t,t.onmessage=n=>this.handleMessage(n.data),t.onerror=n=>{console.error(`[urun] WT uplink worker CRASHED (${n.message||"worker error"}) \u2014 the datagram writable died with it; the send-failure budget owns the revert`),this.active=!1,this.worker=null,this.deps.onSendFailed("uplink worker crashed")};try{t.postMessage({type:"init",writable:e,maxDatagramSize:this.deps.maxDatagramSize()},[e])}catch(n){return console.warn(`[urun] WT uplink worker: writable transfer refused (${n instanceof Error?n.message:String(n)}) \u2014 staying on the main-thread uplink pipeline`),t.terminate(),this.worker=null,!1}return this.active=!0,!0}probe(e){return new Promise(t=>{let r,n=()=>{e.removeEventListener("message",s),e.removeEventListener("error",o),clearTimeout(r)},s=a=>{let d=a.data;d?.type==="supported"?(n(),t(!0)):d.type==="unsupported"&&(console.warn(`[urun] WT uplink worker: unsupported in this worker (${d.detail??"unknown"}) \u2014 staying on the main-thread uplink pipeline`),n(),t(!1))},o=()=>{n(),t(!1)};e.addEventListener("message",s),e.addEventListener("error",o),r=setTimeout(()=>{n(),t(!1)},3e3),e.postMessage({type:"probe"})})}handleMessage(e){switch(e.type){case"accepted":this.deliveredByLane[e.lane]+=e.n;break;case"failed":this.deps.onSendFailed(e.error);break;case"dead":this.audioDeadCb?this.audioDeadCb(e.reason):this.deps.onAudioDead(e.reason);break;case"stall":console.error(`[urun] WT mic uplink STALL (${e.kind}): ${e.detail} \u2014 rebuilding the capture path`),this.rebuildCapture();break;case"stats":this.lastWorkerStats=e;break}}setMicSource(e){this.active&&(e!==null&&e===this.lastSource&&this.graph!==null&&this.graph.track===e&&e.readyState==="live"||(this.post({type:"mic-reset"}),this.teardownGraph(),this.lastSource=e,e!==null&&this.wireSource(e).catch(t=>{console.error(`[urun] WT mic uplink capture wiring FAILED (${t instanceof Error?t.message:String(t)}) \u2014 the stall watchdog escalates if the lane never produces`)})))}async wireSource(e){let t=await this.ensureCaptureContext(e);await this.loadWorklet(t);let r=this.createWorklet(t),n=t.createGain();n.channelCount=1,n.channelCountMode="explicit",n.channelInterpretation="speakers",n.gain.value=1;let s=t.createMediaStreamDestination();r.connect(s),n.connect(r);let o={ctx:t,worklet:r,gain:n,sinkGain:s,srcNode:null,appNode:null,track:null,onended:null};if(br(e)){let d=e;d.connect(n),o.appNode=d}else{let d=e,c=t.createMediaStreamSource(new MediaStream([d]));c.connect(n);let l=()=>{this.graph?.track===d&&(console.error("[urun] WT mic uplink: the mic track ENDED while the lane was engaged \u2014 dying loudly so the transport republishes the mic intent"),this.audioDeadCb?.("mic track ended"))};d.addEventListener("ended",l),o.srcNode=c,o.track=d,o.onended=l}this.graph=o;let a=new MessageChannel;r.port.postMessage({port:a.port2},[a.port2]),this.worker?.postMessage({type:"pcm-port",port:a.port1},[a.port1]),this.post({type:"mic-arm"})}async ensureCaptureContext(e){if(br(e))return e.context;if(!this.ctx){if(typeof AudioContext!="function")throw new Error("AudioContext is not available");this.ctx=new AudioContext({sampleRate:48e3})}return this.ctx.state==="suspended"&&await this.ctx.resume().catch(()=>{}),this.ctx}async loadWorklet(e){this.workletsLoaded.has(e)||(this.workletUrl||(this.workletUrl=URL.createObjectURL(new Blob([vr],{type:"text/javascript"}))),await e.audioWorklet.addModule(this.workletUrl),this.workletsLoaded.add(e))}createWorklet(e){if(typeof AudioWorkletNode!="function")throw new Error("AudioWorkletNode is not available");return new AudioWorkletNode(e,gr)}teardownGraph(){let e=this.graph;if(e){try{e.worklet.disconnect()}catch{}try{e.sinkGain.disconnect()}catch{}try{e.gain.disconnect()}catch{}try{e.srcNode?.disconnect()}catch{}if(e.appNode)try{e.appNode.disconnect(e.gain)}catch{}e.track&&e.onended&&e.track.removeEventListener("ended",e.onended),this.graph=null}}async rebuildCapture(){let e=this.lastSource;if(this.teardownGraph(),e!==null)try{let t=await this.ensureCaptureContext(e);t.state==="suspended"&&await t.resume().catch(()=>{}),await this.loadWorklet(t),await this.wireSource(e)}catch(t){console.error(`[urun] WT mic uplink capture rebuild FAILED (${t instanceof Error?t.message:String(t)}) \u2014 the stall watchdog escalates if the stall repeats`)}}stopMic(){this.post({type:"mic-stop"}),this.teardownGraph(),this.lastSource=null}send(e,t){if(!this.active||!this.worker)throw new Error("uplink worker host is not active");this.worker.postMessage({type:"video",dgram:t},[t.buffer])}terminate(){this.worker?.terminate(),this.worker=null,this.active=!1,this.teardownGraph(),this.ctx&&(this.ctx.close().catch(()=>{}),this.ctx=null)}post(e){this.worker?.postMessage(e)}};function br(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Hn=9e4,Vn="avc1.42E01F",Kn=60,Gn=3,zn=1e4;function Yn(i){return Math.round(i*(Hn/1e6))%2**32>>>0}var $e=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 n=++this.generation,s=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,s.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&n===this.generation;){let{value:a,done:d}=await s.read();if(d)break;if(a){if(o||this.stopped||n!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&n===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 s=globalThis.VideoEncoder;if(typeof s!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new s({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:Vn,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 n=this.keyframeWanted||this.framesSinceKeyframe>=Kn;this.keyframeWanted=!1,this.framesSinceKeyframe=n?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:n})}catch(s){this.onEncoderError(s instanceof Error?s:new Error(String(s)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=At(this.frameSeq,Yn(e.timestamp),t,this.sink.maxDatagramSize()||Y,{lane:pr,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 n of r)this.sink.send(n);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<zn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=Gn){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 Qn(i){return i.byteLength>=2&&i[0]===1&&i[1]===3}var qe=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 n=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let s=this.streams.get(e);if(!s){let a=await this.transport.openUniStream(),d=new Uint8Array(2+r.byteLength);d[0]=1,d[1]=r.byteLength,d.set(r,2),await a.write(d),s={writer:a},this.streams.set(e,s)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await s.writer.write(o),Qn(t)&&(this.streams.delete(e),await s.writer.close().catch(()=>{}))}catch(s){throw this.die(s instanceof Error?s.message:String(s)),s}});return this.chain=n.catch(()=>{}),n}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 yr=250,Xn=25,Jn=2e3,Zn=15e3,ei=1e3,ti=45e3,ri=500,kr=10,ni=2,ue=class i{constructor(e,t,r,n,s,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=n;this.audioUplink=s;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((d,c)=>{this.firstFrameResolve=d,this.firstFrameReject=c}),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;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new le({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";gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;audioUplinkLane=null;uplinkWorkerHost=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&&wt(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(l=>({algorithm:"sha-256",value:Uint8Array.from(atob(l),p=>p.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready,this.startUplinkWorker();let n=await this.wt.createBidirectionalStream();this.writer=n.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=n.readable.getReader(),o=new de,a=[],d=await this.readControl(s,o,a);if(d?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let c=d;if(this.lastInboundControlAt=performance.now(),typeof c.pingIntervalMs=="number"&&c.pingIntervalMs>0?this.advertisedPingIntervalMs=c.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&&(wt(c.codec,"hello-ack"),this.initDecoder(c.codec,c.width,c.height)),this.offer.audio&&this.audioLane){let l=new We(this.offer.audio,this.audioLane);try{l.start(),this.audioPlayout=l}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`),l.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 p=new qe({openUniStream:async()=>(await l()).getWriter()});p.onDead(u=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(u)}),this.dataUplinkSender=p,this.dataUplink.onUplink(p)}catch(l){let p=l instanceof Error?l.message:String(l);console.warn(`[urun] WT data uplink failed to engage (${p}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(p)}this.controlLoop(s,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(),ri)),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 ${yr}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Zn},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),ei))}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"}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 n=this.audioDgramsReceived,s=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:r,recvDownlink:n,sentUplink:s},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,d=r!==null&&o.ur!==null?r-o.ur:null,c=n-o.recvDownlink,l=s-o.sentUplink,p="none";if(a!==null&&a>=kr&&c<=0?p="downlink":d!==null&&l>=kr&&d<=0&&(p="uplink"),p==="none"){this.severedStreak="none";return}if(this.severedStreak!==p){this.severedStreak=p;return}this.severedStreak="none";let u=p==="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: "+u+` (gateway flow counters ds=${t} ur=${r}, client received=${n} accepted=${s}, confirmed on ${ni} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}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(),n=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,s=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=n===null&&s===null?!0:(n===null||n>=e.stallMs)&&(s===null||s>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&s!==null&&s>=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(s/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}o&&s!==null&&s>=ti&&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(s/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.uplinkWorkerHost?.terminate(),this.uplinkWorkerHost=null,this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e))}dropDatagramUplinks(e){this.clearUplinkRetryTimers(),(this.audioUplinkLane!==null||this.audioUplinkRetry!==null)&&(this.audioUplinkLane?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e)),(this.videoUplinkLane!==null||this.videoUplinkRetry!==null)&&(this.videoUplinkLane?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e))}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)");this.dataLaneSink=e,bt(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,r){let n=globalThis.VideoDecoder;if(typeof n!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let s=this.canvas.getContext("2d");if(!s)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r};let o=new n({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,s.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,n=>this.onUplinkSendError(n))}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(n=>r-n<Jn),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<Xn)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){let t=this.uplinkWorkerHost;if(t?.isActive())return{send:n=>{if(!(this.stopped||this.deadFired))try{t.send(e,n)}catch(s){this.onUplinkSendError(s)}},delivered:()=>t.delivered(e),maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Y};this.datagramWriter();let r=0;return{send:n=>this.uplinkSend(n,()=>{r++}),delivered:()=>r,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Y}}async startUplinkWorker(){let e=new Fe({writable:()=>this.wt?.datagrams.writable??null,maxDatagramSize:()=>this.wt?.datagrams.maxDatagramSize??Y,onSendFailed:r=>this.onUplinkSendError(new Error(r)),onAudioDead:r=>this.onUplinkLaneDead("audio",r)});await e.start()&&(this.uplinkWorkerHost=e)}engageAudioUplink(){let e=this.uplinkWorkerHost,t=e?.isActive()?e.audioLane():new Ne(this.uplinkSink("audio"));t.onDead(r=>this.onUplinkLaneDead("audio",r)),this.audioUplinkLane=t,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(t)}engageVideoUplink(){let e=new $e(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t)),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 n=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${n}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,n)}}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){if(e==="audio"?this.audioUplinkLane=null:this.videoUplinkLane=null,this.stopped||this.deadFired)return;let r=e==="audio"?"mic":"video",n=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,o=n?.builtAt!=null&&Date.now()-n.builtAt>=i.UPLINK_LANE_HEALTHY_MS?1:(n?.count??0)+1;if(o>i.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${r} uplink lane dead (${t}) \u2014 ${i.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 ${i.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`);return}console.warn(`[urun] WT ${r} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${o}/${i.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let a={count:o,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=a:this.videoUplinkRetry=a,a.timer=setTimeout(()=>{a.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},i.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t){e==="audio"?this.audioUplink.onUplinkLost(t):this.videoUplink.onUplinkLost(t)}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>=M&&t[11]===Ue){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let n=performance.now();if(this.lastArrivalTs>0){let s=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(s-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;if(typeof n=="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 n({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(gt(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 n=r.shift();if(n)return n;let{value:s,done:o}=await e.read();if(o)return null;s&&r.push(...t.push(s))}}async controlLoop(e,t,r){for(;!this.stopped;){let n=await this.readControl(e,t,r);if(!n)break;let s=n;if(this.lastInboundControlAt=performance.now(),s.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(ur(n.raw,"pong"))}catch{}}(s.t==="ping"||s.t==="pong")&&this.observeFlowCounters(s),s.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 n=this.reassembler.drainWindow(),s=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:s>0?100*n.abandoned/s:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},yr)}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)}}};var Sr=2500,_r=["av01.0.08M.08","avc1.42E01F","avc1.640028"],ii=1e4,pe=class i{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;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",n=this.opts.allowWebTransport??!0,s={webtransport:t&&r&&n,webcodecs:r,codecs:_r,wtData:t&&r&&n&&this.opts.dataLane!==void 0,wtAudio:t&&r&&n&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&r&&n&&this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtVideoUp:t&&r&&n&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&n&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:s});let o=s.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,d=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(d||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),s.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let c=null;try{return c=this.createWebTransportSession(),await Et(c.start(),this.opts.quicDeadlineMs??Sr,"quic connect deadline"),this.engageQuicDataLane(c,s.wtData===!0),this.session=c,d&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(l){if(c?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let p=String(l instanceof Error?l.message:l);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${p}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(p),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 c=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${c} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(c),new Error(`[urun] WT required but unavailable: ${c}`)}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()}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,n=this.opts.dataLane!==void 0,s=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",d=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:_r,wtData:n,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;let c=this.createWebTransportSession();try{await Et(c.start(),this.opts.quicDeadlineMs??Sr,"quic connect deadline")}catch(l){throw c.stop().catch(()=>{}),l}if(this.session!==r)return c.stop().catch(()=>{}),null;try{this.engageQuicDataLane(c,n)}catch(l){throw c.stop().catch(()=>{}),l}if(this.disconnected)return c.stop().catch(()=>{}),null;this.session=c;{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(()=>{}),c}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:(n,s)=>r.onData(n,s),onLaneError:n=>r.onLaneError(n)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new ue(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t);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);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,r)})}redialWtAfterDeath(e){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures+=1,this.wtRedialFailures===i.WT_REDIAL_MAX+1){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${i.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 ${i.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 t=this.wtRedialFailures,r=Ct(i.WT_REDIAL_BASE_MS,t,i.WT_REDIAL_CAP_MS,t===1?0:void 0);console.warn(`[urun] WT re-dial attempt ${t} scheduled in ${Math.round(r)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},r)}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}try{if(await this.retryWebTransport()!==null){console.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${i.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let r=Rt(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${i.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 n=this.createWebRtc();try{let s=await Et(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??ii,"webrtc failover produced no media transport");if(this.session!==e){s.stop().catch(()=>{});return}this.session=s,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(s){if(n.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=s instanceof Error?s.message:String(s),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})}};function Rt(i){if(i instanceof Error)return i.message;if(typeof i=="string")return i;if(i&&typeof i=="object"){try{let e=JSON.stringify(i);if(e!==void 0&&e!=="{}")return e}catch{}return i.constructor?.name??Object.prototype.toString.call(i).slice(8,-1)}return String(i)}function Ct(i,e,t,r){if(r!==void 0)return r;let n=Math.min(i*2**Math.max(0,e-2),t);return Math.round(n*(.75+Math.random()*.5))}function Et(i,e,t){return new Promise((r,n)=>{let s=setTimeout(()=>n(new Error(t)),e);i.then(o=>{clearTimeout(s),r(o)},o=>{clearTimeout(s),n(o)})})}var si=1e4,he=class{constructor(e,t=si){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=Ae();return new Promise((n,s)=>{let o=setTimeout(()=>{a(),s(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(d=>{if(d.type!==`${e}.response`||d.requestId!==r)return;if(clearTimeout(o),a(),d.error){s(new Error(`[urun] ${e} failed: ${String(d.error)}`));return}let{type:c,requestId:l,...p}=d;n(p)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(o),a(),s(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 oi="video",fe=class{constructor(e,t=oi){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,n)=>{this.firstMediaResolve=r,this.firstMediaReject=n}),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 Tr(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var ai="video";function Ar(i,e,t){let r=globalThis,n=r.document;if(!(typeof n?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=i.holdWebRtcDial?.(),a=n.createElement("canvas"),d=!1,c=null,l=!1,p=()=>{if(c){for(let y of c.getVideoTracks())try{y.stop()}catch{}c=null}l&&(l=!1,t.onOverrideTrack(null))},u=new pe(new he(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new fe(i,t.streamName??ai)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(y,E)=>i.dispatchQuicStreamData(y,E),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:y=>i.quicStreamDataLaneLost(y),onLaneError:y=>i.raiseQuicStreamDataError(y)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:y=>{d||t.onOverrideAudioTrack(y)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>C(),onMediaTransportLost:y=>{d||(p(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(y),C())},onTransportChange:(y,E)=>{d||(y==="webrtc"&&(p(),C()),t.onTransportChange?.(y,E))}}),f=i.onWtOnlyLegDeath?.(y=>u.failCurrentWtLeg(y)),m=null,k=()=>{m!==null&&(clearInterval(m),m=null)},h=t.wtRetryBaseMs??2e3,b=t.wtRetryCapMs??3e4,w=null,T=0,C=()=>{if(d||w!==null||u.activeTransport==="webtransport")return;let y=Ct(h,T+2,b);w=setTimeout(()=>{w=null,T+=1,u.retryWebTransport().then(E=>{if(d){E&&u.disconnect().catch(()=>{});return}if(E)return console.debug(`[urun] webtransport upgraded in background (retry ${T})`),T=0,W(E);C()}).catch(E=>{d||(console.debug(`[urun] webtransport background retry ${T} failed: `+Rt(E)),C())})},y)},A=()=>{w!==null&&(clearTimeout(w),w=null)},W=async y=>{if(d||y.kind!=="webtransport")return;let E=t.pathHealthProbeMs??1e4;k();let N=!1;m=setInterval(()=>{if(d||u.activeTransport!=="webtransport")return;let L=Tr(y);if(!L){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)"),k();return}let x=L.pathLiveness();if(!x.alive){let $=u.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${x.evidence}`+($?" \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"),k(),L.fail(`path health: ${x.evidence}`);return}if(!N){if(N=!0,u.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${E}ms \u2014 the QUIC PATH IS HEALTHY (${x.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 ${E}ms \u2014 no media datagrams reached this client (path healthy: ${x.evidence}); webrtc track remains authoritative`)}},E);try{await y.firstMedia}catch(L){k(),console.debug("[urun] webtransport ended before any media flowed:",L);return}if(k(),d||u.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;c=a.captureStream();let H=c.getVideoTracks()[0];H&&(l=!0,t.onOverrideTrack(H))};return(async()=>{let y=await u.connect();if(d){u.disconnect().catch(()=>{});return}await W(y)})().catch(y=>{if(k(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",y);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",y),C();return}o?.proceed(`negotiation unavailable: ${y instanceof Error?y.message:String(y)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",y),C()}),{activeTransport:()=>u.activeTransport,watchDownlinkStall(y){u.watchDownlinkStall(y)},dispose(){d=!0,f?.(),k(),A(),p(),t.onOverrideAudioTrack?.(null),u.disconnect().catch(()=>{})}}}var di=new Set;function Mt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var ci="rpc",li="$presence",Cr=3e4,Er=3e4,ui="rpc-resp";function pi(i){return`${ui}:${i}`}function Dt(){return Ae()}function hi(i){if(i&&typeof i=="object"){let e=i.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 i=="string"?i:JSON.stringify(i)}}function fi(i,e,t,r,n,s,o,a,d,c){let l=[],p=null,u=!1,f=null,m=!1,k,h,b=new Promise((g,F)=>{k=g,h=F});b.catch(()=>{});let w=o(),T=null,C=null,A=null,W=null,y=null,E=null,N=!0,H=()=>{A&&(clearTimeout(A),A=null),W&&(W(),W=null)},L=()=>{y&&(clearTimeout(y),y=null),E&&(E(),E=null)},x=!1,$=()=>{x||!m||(x=!0,i.set({rpc:{[e]:null}}))},V=()=>{N=!1,H(),L(),T?.(),T=null,C?.(),C=null,a?.removeEventListener("abort",_),w.dispose(),$()},X=()=>{if(p){if(l.length>0){let g=p;p=null,g.resolve({value:l.shift(),done:!1})}else if(f!==null){let g=p;p=null,g.reject(f)}else if(u){let g=p;p=null,g.resolve({value:void 0,done:!0})}}},$t=g=>{u||(l.push(g),X())},v=g=>{u||(f=g,u=!0,h(g),V(),X())},S=g=>{u||(u=!0,k(g),V(),X())},_=()=>{let g=a?.reason;v(g instanceof ye?g:new ke(e))},D=g=>{if(!(u||!g||typeof g!="object"))switch(L(),$(),g.t){case"delta":typeof g.delta=="string"&&$t(g.delta);break;case"response":S(g.body);break;case"error":{let{message:F,code:R}=hi(g.body);v(new ye(F,{requestId:e,code:g.code??R}));break}}},U=()=>{let g=w.messages()[Symbol.asyncIterator]();T=()=>{g.return?.(void 0)};let F=()=>{N&&g.next().then(R=>{if(N){if(R.done){u||S(void 0);return}D(R.value),F()}},R=>{N&&v(R)})};F()},P=()=>{if(!m){if(m=!0,a){if(a.aborted){v(new ke(e));return}a.addEventListener("abort",_,{once:!0})}C=d?.(g=>v(g))??null,U(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:s}}}),c&&c>0&&!i.synced&&(A=setTimeout(()=>{A=null,!u&&!i.synced&&v(new Qe(c,e))},c),W=i.onSynced(()=>H())),E=i.onSynced(()=>{E=null,!(u||x||y)&&(y=setTimeout(()=>{y=null,!(u||x)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(Er/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).`)},Er))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(P(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(f!==null){let g=f;return f=null,Promise.reject(g)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((g,F)=>{p={resolve:g,reject:F}})},return(){return u||(u=!0,k(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(g){return u||(u=!0,h(g),V()),Promise.reject(g)}}}},body:b,start:P}}function Rr(i){if(i&&typeof i=="object"){let{epoch:e,by:t}=i,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function mi(i,e){let r=i.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:s,br:o}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let d=Rr(s);d&&(a.rt=d);let c=Rr(o);return c&&(a.br=c),a}var It=class{constructor(e,t,r,n,s){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,s=null,o={push(d){if(!n)if(r){let c=r;r=null,c.resolve({value:d,done:!1})}else t.push(d)},end(){if(n=!0,r){let d=r;r=null,d.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{n=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||n)&&(s=e._streamConsumeUnavailableError(d),a(),r)){let c=r;r=null,c.reject(s)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.reject(s):n?Promise.resolve({value:void 0,done:!0}):new Promise((d,c)=>{r={resolve:d,reject:c}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=mi(t,this._name),n=r?.br;if(n?.by==="runtime")throw new Xe(this._name,"runtime","browser");if(n)return;let s={br:{epoch:1}};r?.rt&&(s.rt=r.rt);let o=r?.kind??e;o&&(s.kind=o),t.set({streams:{[this._name]:s}})}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??ft;return cr(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}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)}},me=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Xt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,n,s,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=s,this._streamData=Yt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=ut(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=lt({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new oe({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(li).awareness.setLocalState({role:"client"}),this._activation=new ne({onPhase:a=>this.onPhase(a),hint:()=>this.doc(it).get(st)??this.doc("control").get(ot),onData:(a,d)=>this._streamData.onData(a,d)})}_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 Gt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,s=new we,o=new Ee({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new i(e,s,o,Mt(t),ie({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&s.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),Se()&&await _e();let d=t.getAccessToken,c=d?async()=>await d()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:c}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return Ze(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=dt(this.doc("control"),r=>{for(let n of Array.from(this._generationTickHandlers))try{n(r)}catch(s){console.warn("[urun] generationTick handler failed:",s)}})),()=>{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 ee(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,n)=>t.retain(r,n),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 z(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new z(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 It(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 Jt(e,this._sessionId,di.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Zt(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=Re(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${t}\0${r}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(Qt({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=Dt(),n=new AbortController;t.signal&&(t.signal.aborted?n.abort(t.signal.reason):t.signal.addEventListener("abort",()=>n.abort(t.signal.reason),{once:!0}));let s=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;s=setTimeout(()=>n.abort(new Ye(d,r)),d)}let o=this._consumeResponse(r,e,!1,n.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{s&&clearTimeout(s),a?.()})}_consumeResponse(e,t,r,n,s){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(ci),a=pi(e);return fi(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??Cr)}requestStream(e,t={}){let r=Dt();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Dt(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.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)}}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=Ar(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}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 K)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new K);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 n of t)try{n()}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 n of r)try{n(new Je)}catch{}for(let n of this._docs.values())n.dispose();this._docs.clear();for(let n of this._streams.values())n.dispose();this._streams.clear(),this._transport.disconnect(e)}};function Dr(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function Lt(){try{return globalThis.sessionStorage??null}catch{return null}}var xt=new Map;function Be(i){if(!i)return;let e=i.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 gi(i,e){return i!==void 0&&e!==void 0&&i!==e}function Ut(i,e){let t=Lt(),r=null;if(t)try{let s=t.getItem(i);if(s){let o=JSON.parse(s);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 n=xt.get(i)??r??null;return!n||gi(n.actor,e)?null:n}function Ir(i,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};xt.set(i,t);let r=Lt();if(r)try{r.setItem(i,JSON.stringify(t))}catch{}}function je(i){xt.delete(i);let e=Lt();if(e)try{e.removeItem(i)}catch{}}var Mr=new Set(["paused","acquiring","live"]),vi=new Set(["24h","keep"]);function Lr(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function wi(i){if(typeof i?.id!="string"||i.id.length===0)throw new be("[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 i.state!="string"||!Mr.has(i.state))throw new be(`[urun] session ${i.id} reported an unrecognized state ${JSON.stringify(i.state)} \u2014 this @urun-sh/core build knows only ${[...Mr].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 i.recordings_expired=="boolean"?e=i.recordings_expired:console.warn(`[urun] session ${i.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:i.id,label:typeof i.label=="string"&&i.label.length>0?i.label:null,state:i.state,app:typeof i.app=="string"?i.app:"",functionName:typeof i.function=="string"?i.function:"",createdAt:Lr(i.created_at),lastActiveAt:Lr(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:vi.has(i.retention)?i.retention:(i.retention!==void 0&&console.warn(`[urun] session ${i.id} reported an unrecognized retention ${JSON.stringify(i.retention)} \u2014 defaulting to '24h'`),"24h")}}var ge=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await Vt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(wi),nextCursor:r}}async end(e){await Kt({...this._request,sessionId:e})}async archive(e){await tt({...this._request,sessionId:e,archived:!0})}async unarchive(e){await tt({...this._request,sessionId:e,archived:!1})}};function xr(i,e,t){let r=Be(t);Ir(i,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var bi=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function yi(i,e){return new ge(i,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function ki(i,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(!(bi.has(r)||typeof r!="string"))return(n,s)=>{let o=n??{},a=Dr({orgId:e.orgId,app:i,functionName:r}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,c,l=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,p=l(),u=e.jwt,f=e.getAccessToken?async v=>{let S=await e.getAccessToken(v);return S&&(u=S),S}:void 0,m={...e,getAccessToken:f},k=new we,h=new Ee({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:p,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),b=new me(p,k,h,Mt(m),ie(m),{activity:s?.activity}),w,T=!1,C=!1,A,W,y=new Promise(v=>{W=v}),E,N=v=>{v.sessionId||A||(A="teardown",E="ticket",Te({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},H=v=>{A||v.sessionId||(A="abandon",Te({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider,reason:"client_abandoned"}))},L=v=>{let S=v.sessionId||!c?v:{...v,sessionId:c};w=S,W({status:"ready",handle:S}),(C||A==="teardown")&&N(S)};b.setEndHandler(async()=>{let v=w?{status:"ready",handle:w}:await y;if(v.status==="unavailable")throw new K("[urun] session allocation failed before a releasable request was created",{cause:v.cause});let S=w??v.handle;return je(a),A==="teardown"?S.sessionId?{status:"paused",sessionId:S.sessionId,reason:"client_ended"}:{status:"canceled",requestId:S.requestId}:(A="end",S.sessionId?jt({baseUrl:S.baseUrl,sessionId:S.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):et({baseUrl:S.baseUrl,requestId:S.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),b.setCancelHandler(async()=>{let v=w?{status:"ready",handle:w}:await y;if(v.status==="unavailable")throw new K("[urun] session allocation failed before a cancellable request was created",{cause:v.cause});let S=w??v.handle;if(S.sessionId)throw new ze(`[urun] cancel() is for a queued admission request, but this call already has session ${S.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:S.sessionId,code:"cancel_on_live_session"});A="end";try{let _=await et({baseUrl:S.baseUrl,requestId:S.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return je(a),_}catch(_){throw A==="end"&&(A=void 0),_}});let x=async v=>{let S,_=s?.sessionId??e.sessionKey??c,D,U;if(_===void 0&&!d){let R=Ut(a);if(R?.sessionId){if(U=Be(u),R.actor!==void 0&&U===void 0&&f){let Ge=await Promise.resolve(f()).catch(()=>{});U=Be(Ge??e.jwt)}D=R.actor!==void 0&&U!==void 0&&R.actor!==U?void 0:R.sessionId}}let P=_??D,B=(R,Ge)=>Ht({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:R,sessionKey:Ge,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},priority:e.priority,onAdmission:j=>{h.reportAdmission(j),j.sessionId&&!c&&(c=j.sessionId,S=j.sessionId,w&&w.sessionId!==j.sessionId&&L({...w,sessionId:j.sessionId}),T||(e.sessionKey||xr(a,j.sessionId,u),b.setSessionId(j.sessionId)))},onRequest:L}),g;try{g=await B(v,P)}catch(R){if(D===void 0||!(R instanceof G)||R.code!=="session_name_not_yours")throw R;console.warn(`[urun] session_name_not_yours: the control plane refused session ${D} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),Ut(a,U)?.sessionId===D&&je(a),g=await B(l(),void 0)}let F=f?await f()??void 0:e.jwt;if(S&&S!==g.sessionId)throw w&&w.sessionId!==g.sessionId&&L({...w,sessionId:g.sessionId}),new G(`Gateway contract violation: admission minted session ${S} but allocation completed as ${g.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return c=g.sessionId,w&&w.sessionId!==g.sessionId&&L({...w,sessionId:g.sessionId}),T||(e.sessionKey||xr(a,g.sessionId,u),b.setSessionId(g.sessionId),b.setArtifactsAuth(ie({...m,baseUrl:g.baseUrl})),h.setEndsAt(g.endsAt),h.seedRegion(zt(g.response))),{url:g.wsUrl,sessionId:g.sessionId,jwt:F,iceServers:g.response.ice_servers,endsAt:g.endsAt}},$,V=f?async()=>await f()??$:()=>$,X=()=>{let v=h.connectedUrl;return v?Re(v):void 0};if(h.setConnectionResolver(async()=>{let v=await x(l());return $=v.jwt,v}),h.on("connected",()=>{h.multiplexer&&k.setTarget(h.multiplexer);let v=h.connectedUrl;v&&b.setDocTransport({wsUrl:v,token:V,resolveServerUrl:X})}),(async v=>{let S;try{S=await x(v)}catch(_){if(T){W({status:"unavailable",cause:_});return}console.error(`[urun] Failed to create session for ${r}:`,_),w&&H(w);let D=_ instanceof Error?_:new Error(String(_)),U=_ instanceof G?_.httpStatus:void 0,P=_ instanceof G?_.code:void 0,B=_ instanceof G?_.retryAfterSeconds:void 0;h.reportAllocationFailure(D,U,P,B),W({status:"unavailable",cause:_});return}T||(h.setAuth({jwt:S.jwt,authProvider:e.authProvider,orgId:e.orgId}),h.setConnection({url:S.url,sessionId:S.sessionId,iceServers:S.iceServers}),Se()&&await _e(),$=S.jwt,b.setDocTransport({wsUrl:S.url,token:V,resolveServerUrl:X}),await h.connect({app:i,functionName:r,args:o}),b.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(p).catch(v=>{console.error(`[urun] Failed to connect session for ${r}:`,v)}),e.releaseOnLeave!==!1){let v=pt(()=>{if(T=!0,h.leaveLeg())return;if(h.connectedUrl!==null){h.disconnect();return}h.disconnect();let P=w;P?N(P):C=!0});b.onDisconnect(v);let S,_,D=!1,U=()=>{D||(D=!0,S?.(),_?.())};y.then(P=>{P.status!=="ready"||D||(S=ht(()=>w!==void 0))}),_=b.onPhase(P=>{let B=P?.name;(B==="paused"||B==="error")&&U()}),D&&_(),b.onDisconnect(U)}return b}}})}var Ur="https://api.urun.sh",Pr="URUN_DEV";function Si(){if(typeof process>"u")return!1;let i=process.env?.[Pr];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var Q=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function _i(i,e={}){if(!i)throw new Q("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=J(e.baseUrl??Ur),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),e.sharedApp&&(n.shared_app=!0),(e.dev??Si())&&(n.dev=!0);let s;try{s=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(n)})}catch(u){throw new Q(`[urun] client token mint request failed: ${u instanceof Error?u.message:String(u)}`)}let o={};try{o=await s.json()}catch{}if(!s.ok){let u=typeof o.message=="string"?o.message:`HTTP ${s.status}`;throw new Q(`[urun] client token mint failed: ${u}`,s.status)}let a=typeof o.token=="string"?o.token:"",d=typeof o.org_id=="string"?o.org_id:"",c=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,l=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new Q("[urun] client token mint returned no token (control-plane contract violation)",s.status);let p=Number.isFinite(c)?new Date(c):new Date(Date.now()+(l??60)*1e3);return{token:a,expiresAt:p,orgId:d}}var Wr=3e4,Or="stream:",Pt=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let s=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(s.timer),n.error?s.reject(new Error(n.error)):s.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${Or}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Or}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let s=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(s)&&(this._pendingRpc.delete(s),n(new Error(`RPC request "${e}" timed out after ${Wr}ms`)))},Wr);this._pendingRpc.set(s,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function Ti(i){let r=`${i.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(i.orgId)}`,n=new WebSocket(r);(i.jwt||i.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:i.orgId,jwt:i.jwt,authProvider:i.authProvider,apiKey:i.apiKey}))});let s=new qt(n);return new Pt(n,s)}var Ai='video/mp4; codecs="avc1.42E01E"';function Ei(i,e){let t=e?.codec??Ai,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,s=URL.createObjectURL(n);r.src=s,n.addEventListener("sourceopen",()=>{let u;try{u=n.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):h}let f=i.getReader();function m(){return u.updating?new Promise(h=>{u.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function k(){try{for(;;){let{done:h,value:b}=await f.read();if(h){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{u.appendBuffer(b)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let T=u.buffered;if(T.length>0){let C=T.start(T.length-1);u.remove(0,C),await m(),u.appendBuffer(b)}else throw w}else throw w}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}k()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let d=a.call(r),c=d.getTracks(),l=0,p=c.length;if(p===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let u of c)u.addEventListener("ended",()=>{l++,l>=p&&URL.revokeObjectURL(s)});return d}function Ri(i){return i.status.startsWith("pending_")}var te=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},ve=class extends te{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Ci(i,e,t){let r=t||e||`HTTP ${i}`;return i===401?new ve(r,e??"unauthorized"):new te(r,{status:i,code:e??`http_${i}`})}var He=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new te("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let r=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(r)?r:[]}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),s=await this._resolveToken(),o=await this._fetch(n,e,s);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(n,e,s))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw Ci(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r){let n={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(n["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:n})}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 ve("[urun] credits: 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:n,message:s}=r;return{code:typeof n=="string"?n:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Di(i){return new He(i)}var Ve=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function Nr(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function Ii(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Mi(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function Wt(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var Ke=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,Wt(r,new Error(`${e} capture claim superseded by a newer claim`)));let n=this.createState(e,t);return this.claims.set(e,n),await this.converge(n),n.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new Ve;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},n;try{n=await t(r)}catch(o){let a=`one-capture getUserMedia(${Nr(r)}) failed`,d=o instanceof Error?o.message:String(o);for(let c of[...this.claims.values()])if(this.claims.delete(c.kind),c.released=!0,c!==e){let l=new Error(`${a} \u2014 ${c.kind} capture lost: ${d||o}`);l.cause=o,Wt(c,l)}throw o}let s=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of s){let a=Ii(n,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let d=Object.assign(new Error(`one-capture getUserMedia(${Nr(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw d;Wt(o,d);continue}if(o.track=a,o.stream=Mi(n,a),o!==e)for(let d of[...o.trackListeners])try{d(a,o.stream)}catch{}}}createState(e,t){let r=this,n={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return n.track},get stream(){return n.stream},update(s){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=s,await r.converge(n),!n.track)throw new Error(`${e} capture update yielded no track`);return n.track})},release(){n.released||(n.released=!0,r.claims.get(e)===n&&r.claims.delete(e),n.track?.stop(),n.track=null,n.stream=null)},onTrack(s){return n.trackListeners.add(s),()=>n.trackListeners.delete(s)},onLost(s){return n.lostListeners.add(s),()=>n.lostListeners.delete(s)}}};return n}},Li=null;function xi(){return Li??=new Ke}var Fr="input",Ui=30;function Pi(i){let e=i.now??Date.now,t=i.field??Fr,r=1e3/Math.max(i.hz??30,.001),n=new Set,s=0,o=0,a=0,d=0,c,l=null,p=!1,u=()=>{if(p)return;c=e(),d+=1;let m={keys:[...n],buttons:s,pointer:{x:o,y:a},seq:d,at:c};try{i.awareness.setLocalStateField(t,m)}catch{}},f=()=>{if(p)return;let m=e();if(c===void 0||m-c>=r){l&&(clearTimeout(l),l=null),u();return}if(l)return;let k=Math.max(r-(m-c),0);l=setTimeout(()=>{l=null,u()},k),l.unref?.()};return{keyDown(m){let k=String(m).toLowerCase();n.has(k)||(n.add(k),f())},keyUp(m){let k=String(m).toLowerCase();n.delete(k)&&f()},setButtons(m){let k=Number.isFinite(m)?Number(m):0;k!==s&&(s=k,f())},movePointer(m,k){let h=Number.isFinite(m)?Number(m):0,b=Number.isFinite(k)?Number(k):0;h===0&&b===0||(o+=h,a+=b,f())},heldKeys(){return[...n]},clear(){p||(n.clear(),s=0,l&&(clearTimeout(l),l=null),u())},dispose(){if(p)return;let m=n.size>0||s!==0;n.clear(),s=0,l&&(clearTimeout(l),l=null),m&&u(),p=!0}}}var Wi=1024,Oi=.92,Ni=262144,Fi=256e3,Ot=[.9,.8,.7,.6,.5],$r=.8,$i=8;function Ft(i,e,t){if(!(i>0)||!(e>0))throw new Error(`reference image has no pixels (${i}x${e})`);let r=Math.min(1,t/Math.max(i,e));return{width:Math.max(1,Math.round(i*r)),height:Math.max(1,Math.round(e*r))}}async function qi(i){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(i,{imageOrientation:"from-image"})}async function Br(i,e,t){let r=await new Promise(n=>{i.toBlob(n,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function qr(i,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${i} -> ${e} bytes`)}async function Nt(i,e,t,r,n){let s=document.createElement("canvas");s.width=e,s.height=t;let o=s.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(i,0,0,e,t),await Br(s,r,n)}async function Bi(i,e,t,r){let{width:n,height:s}=e,o=await Nt(i,n,s,t,r);if(o.size<=256e3)return{blob:o,width:n,height:s};if(t==="image/jpeg"){for(let d of Ot)if(!(d>=r)&&(o=await Nt(i,n,s,t,d),o.size<=256e3))return qr(`quality ${r} -> ${d}`,o.size),{blob:o,width:n,height:s}}let a=t==="image/jpeg"?Ot[Ot.length-1]:r;for(let d=0;d<$i;d++)if(n=Math.max(16,Math.round(n*$r)),s=Math.max(16,Math.round(s*$r)),o=await Nt(i,n,s,t,a),o.size<=256e3)return qr(`downscaled to ${n}x${s} @ q${a}`,o.size),{blob:o,width:n,height:s};throw new Error(`this image cannot be sent: even at ${n}x${s} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function ji(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:s}=e,o=await qi(i);try{let a=Ft(o.width,o.height,t),d=await Bi(o,a,r,n);return{bytes:new Uint8Array(await d.blob.arrayBuffer()),type:r,width:d.width,height:d.height,source:s}}finally{o.close()}}function Hi(i){let e=i instanceof Error?i.name:"",t=i instanceof Error?i.message:String(i);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function Vi(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Ki(i,e){let t=i.videoWidth,r=i.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:s="image/jpeg",quality:o=.92}=e??{},a=Ft(t,r,n),d=document.createElement("canvas");d.width=a.width,d.height=a.height;let c=d.getContext("2d");if(!c)throw new Error("could not prepare the reference image (no 2d canvas context)");s==="image/jpeg"&&(c.fillStyle="#fff",c.fillRect(0,0,a.width,a.height)),c.drawImage(i,0,0,a.width,a.height);let l=await Br(d,s,o);return{bytes:new Uint8Array(await l.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var Gi=new Set(["w","a","s","d"]),re=(i,e)=>Math.min(e,Math.max(-e,i));function zi(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:s=.06,maxPan:o=.12,maxLogZoom:a=.22}=i,d=0,c=0,l=0,p=null,u=new Set;return{pointerDelta(f,m){d=re(d-f*e,o),c=re(c-m*e,o)},keyDown(f){let m=f.toLowerCase();Gi.has(m)&&u.add(m)},keyUp(f){u.delete(f.toLowerCase())},clearKeys(){u.clear()},frameArrived(){let f=1-s;d*=f,c*=f,l*=f},tick(f){if(p===null){p=f;return}let m=Math.max(0,Math.min(100,f-p))/1e3;p=f,u.has("w")&&(l=re(l+t*m,a)),u.has("s")&&(l=re(l-t*m,a)),u.has("a")&&(d=re(d+r*m,o)),u.has("d")&&(d=re(d-r*m,o));let k=Math.exp(-m*1e3/n);d*=k,c*=k,l*=k},transform(){return{translateX:d,translateY:c,scale:Math.exp(l)}},isIdentity(f=5e-4){return Math.abs(d)<f&&Math.abs(c)<f&&Math.abs(l)<f},reset(){d=0,c=0,l=0,u.clear()}}}export{hn as ACTIVATION_COLD_BOOT_AFTER_MS,fn as ACTIVATION_DEGRADED_AFTER_MS,st as ACTIVATION_HINT_PATH,pn as ACTIVATION_STILL_AFTER_MS,ct as ACTIVITY_DOM_EVENTS,nr as ACTIVITY_FIELD,En as ACTIVITY_STAMP_MIN_INTERVAL_MS,ne as ActivationMonitor,ki as App,en as BACKOFF_BASE_MS,rn as BACKOFF_MAX_ATTEMPTS,tn as BACKOFF_MAX_MS,Jr as COLD_BOOT_WHEN_LIVE_TIMEOUT_MS,Ke as CaptureController,Ve as CaptureUnavailableError,Q as ClientTokenError,He as CreditsClient,te as CreditsError,ve as CreditsUnauthorizedError,Ni as DATA_CHANNEL_MESSAGE_CEILING,Cr as DEFAULT_DOC_SYNC_TIMEOUT_MS,Ur as DEFAULT_GATEWAY_URL,jr as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Oi as DEFAULT_REFERENCE_JPEG_QUALITY,Wi as DEFAULT_REFERENCE_MAX_SIZE,Xr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,dn as DERIVED_LEG_SEP,M as DGRAM_HEADER_BYTES,ar as FOCUS_FIELD,Cn as FOREGROUND_COALESCE_MS,le as FrameReassembler,Tn as GENERATION_TICK_EMIT_INTERVAL_MS,An as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Ui as INPUT_PRESENCE_DEFAULT_HZ,Fr as INPUT_PRESENCE_FIELD,Z as InvalidDurationError,ot as LEGACY_ACTIVATION_HINT_PATH,it as PLATFORM_DOC_NAME,xe as PermanentLockedError,Le as PinRequiresActiveTempError,oe as PresenceTracker,Hr as ProduceAckTimeoutError,Ie as RecordingNotFoundError,ee as RecordingsClient,O as RecordingsError,se as RecordingsUnauthorizedError,ke as RequestAbortError,Je as RequestCancelledError,Qe as RequestDocSyncError,ye as RequestError,Ye as RequestTimeoutError,Me as RetainNotTempError,De as RuntimeArtifactNotFoundError,z as RuntimeArtifactsClient,I as RuntimeArtifactsError,Ce as RuntimeArtifactsUnauthorizedError,un as SIGNALING_PROTOCOL_VERSION,rt as STREAM_END,me as Session,G as SessionAllocationError,ge as SessionDirectory,be as SessionDirectoryError,ze as SessionEndError,K as SessionEndUnavailableError,Kr as SessionFailedError,Xe as StreamDirectionConflict,pe as TransportNegotiator,zr as TransportSessionMismatchError,he as TransportSessionSignaling,Pr as URUN_DEV_ENV,or as USER_ACTIVITY_FIELD,Rn as USER_ACTIVITY_MIN_INTERVAL_MS,ir as VISIBILITY_FIELD,Fi as WIRE_MESSAGE_BUDGET,lr as WT_CONTROL_FRAME_MAX,fr as WT_DATA_STREAM_VERSION,fe as WebRtcSession,ue as WebTransportSession,de as WtControlDecoder,Pe as WtDataStreamParser,er as activationHintFrom,Vi as cameraCaptureAvailable,Ki as captureStillFromVideo,nn as computeBackoffDelay,bt as consumeWtDataStreams,lt as createActivityTracker,zi as createCameraWarp,_i as createClientToken,Di as createCreditsClient,Pi as createInputPresencePublisher,_n as createRecordingsClient,gn as createRuntimeArtifactsClient,Ti as createStore,nt as decodeStreamEnvelope,ln as derivedLegName,cn as derivedLegRole,Vr as describeSessionFailure,Zr as describeSessionPhase,an as encodeStreamEnvelope,gt as encodeWtControlFrame,Ft as fitWithin,at as isDurationString,Qr as isPausedPhase,Ri as isPendingRecording,sn as isRetryableSessionError,Yr as isWakingPhase,ft as mediaRecorderChunkSource,ji as normalizeReferenceImage,kn as normalizeRetention,ht as observeLeaveConfirm,ut as observePageLifecycle,pt as observePageTeardown,ce as parseDgramHeader,on as prewake,Hi as referenceImageErrorMessage,Te as releaseSessionBeacon,yi as sessionDirectory,Gr as sessionFailureFromMediaError,xi as sharedCaptureController,Ei as videoStream,dt as watchGenerationTick,Ze as whenLive,vt as writeDgramHeader};