@urun-sh/core 0.6.16 → 0.6.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/index.js +7 -7
- package/dist/adapter/index.mjs +1 -1
- package/dist/{app-JQES6MVY.mjs → app-7M5NBLQS.mjs} +1 -1
- package/dist/{stream-data-BHDuPKhI.d.mts → backoff-CUwly6E_.d.mts} +13 -1
- package/dist/{stream-data-BHDuPKhI.d.ts → backoff-CUwly6E_.d.ts} +13 -1
- package/dist/{stream-data-gthI5aJp.d.mts → backoff-DxQ5__tj.d.mts} +13 -1
- package/dist/{stream-data-gthI5aJp.d.ts → backoff-DxQ5__tj.d.ts} +13 -1
- package/dist/{chunk-F2X3TCVZ.mjs → chunk-5KH6VNMJ.mjs} +2 -2
- package/dist/{chunk-GEHV47FN.mjs → chunk-D65T46UC.mjs} +3 -3
- package/dist/{chunk-6NLEURUP.mjs → chunk-THU4G74G.mjs} +5 -5
- package/dist/index.browser.d.mts +7 -13
- package/dist/index.browser.d.ts +7 -13
- package/dist/index.browser.js +4 -4
- package/dist/index.browser.mjs +3 -3
- package/dist/index.d.mts +7 -13
- package/dist/index.d.ts +7 -13
- package/dist/index.js +7 -7
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.d.mts +1 -1
- package/dist/internal.browser.d.ts +1 -1
- package/dist/internal.browser.js +2 -2
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +5 -5
- package/dist/internal.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
|
|
2
|
-
import{B as ie,H as se,I as lt,J as Ce,K as Pe,L as ut,M as ht,N as pt,O as We,P as ft,Q as mt,S as gt,T as oe,U as vt,W as wt,Y as bt,b as ne,c as Q,ca as ae,d as it,e as Le,ea as de,f as Ue,fa as yt,g as st,ga as kt,h as ot,ha as St,i as at,ia as _t,l as Ie,m as dt,r as Y,w as ct,y as re}from"./chunk-6NLEURUP.mjs";var hr=15e3,pr=45e3,fr=12e4,Tt="platform",At="activation",Rt="desired.activation";function dn(r){if(typeof r=="string"&&r.length>0)return r;if(r&&typeof r=="object"){let e=r.note;if(typeof e=="string"&&e.length>0)return e}}var cn=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],ce=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 n of this._watches.values())this._arm(n)}}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 n={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,n),this._hookFirstMediaSignals(n),!n.done&&this._liveAt!==null&&this._arm(n)}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=n=>{if(!(!n||e.done)){if(n.muted===!0&&typeof n.addEventListener=="function"){let i=()=>this._firstMedia(e);n.addEventListener("unmute",i,{once:!0}),e.cleanups.push(()=>n.removeEventListener?.("unmute",i));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",n=>t(n))),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 cn){let n=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);n.unref?.(),e.timers.push(n)}}}_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,n){let i={state:t,elapsedMs:n,stream:e.name},s=dn(this._options.hint());s!==void 0&&(i.hint=s),e.lastEvent=i;for(let o of Array.from(this._handlers))o(i)}};var W=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",i){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,i!==void 0&&(this.cause=i),Object.setPrototypeOf(this,new.target.prototype)}},Me=class extends W{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},xe=class extends W{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function X(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function vr(r){return new z(r)}var z=class{_options;constructor(e){this._options=e}async list(e){let n=Dt(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new W("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(Et)}async getDownloadUrl(e,t){let n=Dt(await this._request(t,`/${encodeURIComponent(e)}/download`)),i=n.download_url;if(typeof i!="string"||!un(i))throw new W("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Et(n.artifact),downloadUrl:i}}async _request(e,t){let n=lt(this._options.baseUrl,this._options.fallbackUrls),i=null;for(let s of n)try{return await this._requestFromBase(s,e,t)}catch(o){if(i=o instanceof Error?o:new Error(String(o)),i instanceof W&&hn(i.status))throw i}throw i??new W("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let i=`${se(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,s=await this._resolveToken(),o=await fetch(i,{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(i,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw pn(o.status,a,d)}try{return await o.json()}catch(a){throw new W(`[urun] runtime artifacts: invalid JSON response from ${se(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 n=se(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 ${n}: ${a}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function Et(r){if(!r||typeof r!="object")throw new W("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=q(e,"artifact_id")||q(e,"id"),n=q(e,"filename"),i=q(e,"kind"),s=q(e,"status")||"ready",o=ln(e,"size_bytes"),a=q(e,"sha256");if(!t||!n||!i||o==null||!a)throw new W("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:i,filename:n,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(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function ln(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function un(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function hn(r){return r===401||r===403}function pn(r,e,t){return r===401?new Me(t,e):r===404?new xe(t,e):new W(t,r,e)}function Dt(r){if(!r||typeof r!="object"||Array.isArray(r))throw new W("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var F=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)}},le=class extends F{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Oe=class extends F{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Ne=class extends F{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)}},Fe=class extends F{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)}},$e=class extends F{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)}},J=class extends F{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function Lt(r){return/^(\d+[smhdw])+$/.test(r)}function br(r){if(r==="pin")return{action:"pin"};if(Lt(r))return{action:"retain",duration:r};throw new J(`[urun] recordings: "${r}" is not a duration or "pin"`)}function fn(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new le(n,e??"unauthorized");if(r===404)return new Oe(n,e??"not_found");if(r===400)return new J(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new Ne(n,e);case"pin_requires_active_temp":return new Fe(n,e);case"permanent_locked":return new $e(n,e)}return new F(n,{status:r,code:e??`http_${r}`})}var Z=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!Lt(t))throw new J(`[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 F("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let i=this._buildUrl(t,n.params),s=await this._resolveToken(),o=await this._fetch(i,e,s,n.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(i,e,s,n.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw fn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,i=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return i&&(n+=`?${i}`),n}_fetch(e,t,n,i){let s={Authorization:`Bearer ${n}`,apikey:n,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 i!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(i)),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 le("[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 n=(await e.json()).error;if(n&&typeof n=="object"){let{code:i,message:s}=n;return{code:typeof i=="string"?i:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function yr(r){return new Z(r)}var Sr=1e3,_r=12e3;function Ut(r,e,t={}){let n=null,i=0,s=0,o=null,a=-1,d=()=>{let p=r.get("desired.billing.generationSeconds");if(typeof p!="number"||!Number.isFinite(p)||p<=0)return null;let b=r.get("desired.billing.epoch"),v=r.get("desired.billing.updatedAtMs");return{seconds:p,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof v=="number"&&Number.isFinite(v)?v:null}},c=()=>{if(n===null)return null;let p=Math.min(Math.max(0,Date.now()-i),s);return n+p/1e3},l=()=>{let p=t.creditsPerSecond;if(typeof p=="number"&&Number.isFinite(p)&&p>0)return p;let b=r.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},u=()=>{let p=c();if(p===null)return;let b=Math.floor(p);if(b<=a)return;a=b;let v={seconds:b},R=l();R!==null&&(v.estimatedCredits=b*R),e(v)},h=p=>{i=Date.now();let b=p===null?0:Math.max(0,i-p);s=Math.max(0,12e3-b)},y=()=>{let p=d();if(p!==null){if(o!==null&&p.epoch!==o){o=p.epoch,n=p.seconds,a=-1,h(p.updatedAtMs),u();return}n!==null&&p.seconds<=n||(o=p.epoch,n=p.seconds,h(p.updatedAtMs),u())}};y();let k=r.on("change",y),_=setInterval(u,1e3);return _.unref?.(),()=>{clearInterval(_),k()}}var mn="activity",gn="visibility",Ar=15e3,It=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ct(r){let e=r.now??Date.now,t=r.mode==="explicit",n=t?null:r.windowTarget!==void 0?r.windowTarget:typeof window<"u"?window:null,i=t?null:r.documentTarget!==void 0?r.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let h=e();if(!(o!==void 0&&h-o<15e3)){o=h;try{r.awareness.setLocalStateField(mn,{at:h})}catch{}}},d=()=>{if(!(s||!i||i.visibilityState===void 0))try{r.awareness.setLocalStateField(gn,i.visibilityState)}catch{}},c=()=>a(),l=()=>{d(),(!i||i.visibilityState===void 0||i.visibilityState==="visible")&&a()};if(n)for(let h of It)n.addEventListener(h,c,{passive:!0,capture:!0});i&&i.addEventListener("visibilitychange",l);let u=null;return!t&&r.isProducing&&(u=setInterval(()=>{if(!s)try{r.isProducing?.()&&a()}catch{}},15e3),u.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,n)for(let h of It)n.removeEventListener(h,c,{capture:!0});i&&i.removeEventListener("visibilitychange",l),u&&(clearInterval(u),u=null)}}}}var vn="user_activity",wn="focus",Er=3e4;function Pt(r){switch(r){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var ue=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(Pt(e.state));let t=e.on("stateChange",i=>{this._setState(Pt(i))}),n=()=>{t(),this._transportUnsubs.delete(n)};return this._transportUnsubs.add(n),n}_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(wn,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(vn,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 Lr=250;function Wt(r){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 n=Date.now();n-e<250||(e=n,r())};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 Mt(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=n=>{n.persisted||e||(e=!0,r())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function xt(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{r()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Ot="video/mp4";function Nt(r,e={}){let t=e.timesliceMs??1e3,n=null,i=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 u=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(Ot)?Ot:void 0),h=new MediaStream([a]),y=new l(h,u?{mimeType:u}:void 0);n=y;let k=Promise.resolve();y.ondataavailable=_=>{let p=_.data;s||!p||p.size===0||(k=k.then(async()=>{let b=new Uint8Array(await p.arrayBuffer());s||d(b)}))},y.onstop=()=>{k.then(()=>{s||c()})},y.onerror=()=>{k.then(()=>{s||c()})},y.start(t)};return{start(a,d){if(n||s)return;let c=r.track();if(c){o(c,a,d);return}i=r.onTrack(l=>{!l||n||s||(i?.(),i=null,o(l,a,d))})},stop(){if(s)return;s=!0,i?.(),i=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function bn(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.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 Ft(r,e){let t=null,n=!1,i=!1,s=new ReadableStream({pull(o){n||(n=!0,t=r(e),t.start(a=>{if(!i)try{o.enqueue(a)}catch{}},()=>{if(!i){i=!0;try{o.close()}catch{}}}))},cancel(){i=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return bn(s)}import{encode as yn,decode as kn}from"@msgpack/msgpack";var Sn=65536;function $t(r){let e=yn(r),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var he=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(n>Sn)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+n)break;let i=this.buf.subarray(4,4+n);this.buf=this.buf.subarray(4+n),t.push(Object.assign(kn(i),{raw:i}))}return t}};function qt(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=t.getUint8(0),i=(n&240)===128,s=n===222;if(!i&&!s&&!(n===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=i?n&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=i?1:s?3:5,c=[];c.push(r.subarray(0,d));for(let y=0;y<a;y++){let k=d,_=ee(r,t,d);d=_.end;let b=ee(r,t,d).end;if(_n(t.getUint8(k))){let v=t.getUint8(k),R=(v&224)===160?1:v===217?2:v===218?3:5;if(new TextDecoder().decode(r.subarray(k+R,_.end))==="t"){c.push(r.subarray(k,_.end));let T=new TextEncoder().encode(e);if(T.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");c.push(new Uint8Array([160|T.byteLength]),T)}else c.push(r.subarray(k,b))}else c.push(r.subarray(k,b));d=b}let l=c.reduce((y,k)=>y+k.byteLength,0),u=new Uint8Array(l),h=0;for(let y of c)u.set(y,h),h+=y.byteLength;return u}function _n(r){return(r&224)===160?!0:r===217||r===218||r===219}function ee(r,e,t){let n=e.getUint8(t),i=t;if(n<=127||n>=224)return{start:i,end:t+1};if((n&224)===160)return{start:i,end:t+1+(n&31)};if((n&240)===128||(n&240)===144){let o=n&15;t+=1;let a=(n&240)===128?o*2:o;for(let d=0;d<a;d++)t=ee(r,e,t).end;return{start:i,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[n]!==void 0)return{start:i,end:t+1+s[n]};if(n===217||n===196)return{start:i,end:t+2+e.getUint8(t+1)};if(n===218||n===197)return{start:i,end:t+3+e.getUint16(t+1,!1)};if(n===219||n===198)return{start:i,end:t+5+e.getUint32(t+1,!1)};if(n===220||n===221){let o=n===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===220?3:5;for(let a=0;a<o;a++)t=ee(r,e,t).end;return{start:i,end:t}}if(n===222||n===223){let o=n===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===222?3:5;for(let a=0;a<o*2;a++)t=ee(r,e,t).end;return{start:i,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${n.toString(16)} at byte ${i}`)}var M=12,qe=1,Tn=0,pe=1,Bt=2;function fe(r){let e=r.getUint8(8);return{groupId:r.getUint32(0,!0),frameSeq:r.getUint32(4,!0),keyframe:(e&qe)===qe,fragIndex:r.getUint8(9),fragCount:r.getUint8(10),lane:r.getUint8(11)}}function Ht(r){let e=new Uint8Array(M),t=new DataView(e.buffer);return t.setUint32(0,r.groupId,!0),t.setUint32(4,r.frameSeq,!0),t.setUint8(8,r.keyframe?qe:0),t.setUint8(9,r.fragIndex),t.setUint8(10,r.fragCount),t.setUint8(11,r.lane??Tn),e}var An=100,jt=100,me=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??An}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=fe(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 n=this.pending.get(t.frameSeq);if(n||(n={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n)),!n.chunks[t.fragIndex]){n.chunks[t.fragIndex]=e.subarray(M),n.received++,n.received===n.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,n));for(let i of this.pending.keys())i<t.frameSeq-1&&(this.pending.delete(i),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-jt?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-jt}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 n=t.chunks.reduce((o,a)=>o+a.byteLength,0),i=new Uint8Array(n),s=0;for(let o of t.chunks)i.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:i})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Rn=/^avc[13]\.[0-9a-fA-F]{6}$/;function En(r){return Rn.test(r)?null:`codec ${JSON.stringify(r)} 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 Be(r,e){let t=En(r);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var Dn=1,He=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}if(this.name===null){if(this.buf.byteLength<2)return[];let n=this.buf[0];if(n!==Dn)throw new Error(`[urun] wt data stream: unknown header version 0x${n.toString(16)} \u2014 rejecting stream`);let i=this.buf[1];if(i===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+i)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+i)),this.buf=this.buf.subarray(2+i)}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+n)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let i=wt(this.buf.subarray(4,4+n));this.buf=this.buf.subarray(4+n),i===vt&&(this.ended=!0),t.push({name:this.name,payload:i})}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 Vt(r,e){let t=r.getReader();for(;;){let{value:n,done:i}=await t.read();if(i)return;n&&Ln(n,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Ln(r,e){let t=r.getReader(),n=new He;try{for(;;){let{value:i,done:s}=await t.read();if(s)break;if(!(!i||i.byteLength===0))for(let{name:o,payload:a}of n.push(i))e.onData(o,a)}n.finish()}catch(i){try{await t.cancel?.(i)}catch{}throw i}}var je=40,Kt=2,K=48e3,Un=64,In=100,Ve=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=fe(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-In)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let n=this.pending.get(t.frameSeq);if(!n)for(n={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n);this.pending.size>Un;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=n.fragCount||n.chunks[t.fragIndex]||(n.chunks[t.fragIndex]=e.subarray(M),n.received++,n.received<n.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let i=n.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(i),o=0;for(let a of n.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:n.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}},ge=class{constructor(e,t){this.config=e;this.seam=t;let n=this.seam.jitterBufferTargetMs??je;Number.isFinite(n)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${n} is not finite \u2014 using default ${je}ms`),n=je),this.targetS=Math.max(0,n)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;contentBaseS=null;wallBaseS=0;reanchorLogged=!1;lastTsS=null;pendingTs=[];bridgeTrack=null;scheduledCount=0;lastScheduledAt=0;rebuildGen=0;rebuildTimes=[];rebuildBudgetLoggedAt=-1e4;lastRemote=null;assembler=new Ve(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(i){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,i}this.trackSurfaced=!0,this.ctx.resume?.().catch(()=>{});let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] playout start produced no bridge track");this.surfaceTrack(n)}stop(){if(!this.stopped){this.stopped=!0;try{this.seam.renderHop?.setSource(null)}catch{}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:n=>this.schedule(n,this.pendingTs.shift()),error:n=>this.onDecoderError(n)});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 i=globalThis.AudioDecoder;if(typeof i!="function")return;try{this.initDecoder(i)}catch{return}}let n=this.decoder;n&&(this.pendingTs.push(e.timestamp),n.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/K)),data:e.data})))}schedule(e,t){let n=this.ctx,i=this.dest;if(!n||!i||this.stopped){e.close();return}let s=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),a=n.createBuffer(o,s,e.sampleRate);for(let u=0;u<o;u++){let h=new Float32Array(s);e.copyTo(h,{planeIndex:u,format:"f32-planar"}),a.copyToChannel(h,u)}let d=s/e.sampleRate;e.close();let c=n.createBufferSource();c.buffer=a,c.connect(i);let l;if(t===void 0)l=Math.max(this.playhead,n.currentTime+this.targetS);else{this.contentBaseS===null&&(this.contentBaseS=t/K,this.wallBaseS=n.currentTime+this.targetS),l=this.wallBaseS+t/K-this.contentBaseS;let u=null;this.lastTsS!==null&&(t<this.lastTsS?(l=n.currentTime+this.targetS,u=`backward ts step ${(this.lastTsS-t/K).toFixed(3)}s (producer clock reset)`):l>n.currentTime+this.targetS+Math.max(d,this.targetS)&&(u=`forward jump ${(l-n.currentTime).toFixed(3)}s out (lead + ${d.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),u&&(this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${u} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=t/K,this.wallBaseS=n.currentTime+this.targetS,l=this.wallBaseS)),l<n.currentTime&&(this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored ${(n.currentTime-l).toFixed(3)}s past its content position (arrival deficit exceeded the lead) \u2014 the gap is honest silence at rate 1.0, never a catch-up stretch`)),this.contentBaseS=t/K,this.wallBaseS=n.currentTime+this.targetS,l=this.wallBaseS)}c.start(l),this.scheduledCount++,this.lastScheduledAt=performance.now(),t!==void 0&&(this.lastTsS=t/K),this.playhead=l+d}armBridgeEndedWatch(e){let t=this.rebuildGen;e.addEventListener?.("ended",()=>{if(!this.stopped&&!(t!==this.rebuildGen||this.bridgeTrack!==e)){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(n){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${n instanceof Error?n.message:String(n)}`)}}},{once:!0})}playoutProgress(){return{scheduled:this.scheduledCount,lastScheduledAt:this.lastScheduledAt,surfaced:this.trackSurfaced&&this.bridgeTrack?.readyState!=="ended"}}rebuildSurface(){if(this.stopped)return;let e=performance.now();if(this.rebuildTimes=this.rebuildTimes.filter(s=>e-s<1e4),this.rebuildTimes.length>=Kt){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${Kt} in 10s) \u2014 standing down; the media-dead playout-progress verdict escalates to a re-dial if the surface stays dead`));return}this.rebuildTimes.push(e),this.rebuildGen++;let t=globalThis.AudioContext;if(typeof t!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let n=new t({sampleRate:this.config.sampleRate});this.ctx=n,n.resume?.().catch(()=>{}),this.dest=n.createMediaStreamDestination(),this.playhead=0,this.contentBaseS=null,this.lastTsS=null,this.trackSurfaced=!0;let i=this.dest.stream.getAudioTracks()[0];if(!i)throw new Error("[urun] rebuilt playout produced no bridge track");this.surfaceTrack(i)}surfaceTrack(e){this.bridgeTrack=e,this.armBridgeEndedWatch(e),this.lastRemote&&this.lastRemote.readyState==="live"?this.seam.onTrack(this.lastRemote):this.seam.onTrack(e);let t=this.seam.renderHop;t&&(t.onRemote(n=>{if(this.stopped)return;if(n?this.lastRemote=n:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),n){this.seam.onTrack(n);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.seam.onTrack(this.lastRemote);return}let i=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.seam.onTrack(i)}),t.setSource(e))}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(n){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${n instanceof Error?n.message:String(n)}`)}}};var te=1200;function Ke(r,e,t,n,i){let s=n-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=Ht({groupId:e>>>0,frameSeq:r>>>0,keyframe:i?.keyframe??!0,fragIndex:d,fragCount:o,lane:i?.lane??pe}),u=new Uint8Array(M+c.byteLength);u.set(l,0),u.set(c,M),a.push(u)}return a}var Cn=`
|
|
2
|
+
import{B as ie,H as se,I as lt,J as Ce,K as Pe,L as ut,M as ht,N as pt,O as We,P as ft,Q as mt,R as gt,T as vt,U as oe,V as wt,X as bt,Z as yt,b as ne,c as Q,d as it,da as ae,e as Le,f as Ue,fa as de,g as st,ga as kt,h as ot,ha as St,i as at,ia as _t,ja as Tt,l as Ie,m as dt,r as Y,w as ct,y as re}from"./chunk-THU4G74G.mjs";var pr=15e3,fr=45e3,mr=12e4,At="platform",Rt="activation",Et="desired.activation";function cn(r){if(typeof r=="string"&&r.length>0)return r;if(r&&typeof r=="object"){let e=r.note;if(typeof e=="string"&&e.length>0)return e}}var ln=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],ce=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 n of this._watches.values())this._arm(n)}}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 n={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,n),this._hookFirstMediaSignals(n),!n.done&&this._liveAt!==null&&this._arm(n)}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=n=>{if(!(!n||e.done)){if(n.muted===!0&&typeof n.addEventListener=="function"){let i=()=>this._firstMedia(e);n.addEventListener("unmute",i,{once:!0}),e.cleanups.push(()=>n.removeEventListener?.("unmute",i));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",n=>t(n))),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 ln){let n=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);n.unref?.(),e.timers.push(n)}}}_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,n){let i={state:t,elapsedMs:n,stream:e.name},s=cn(this._options.hint());s!==void 0&&(i.hint=s),e.lastEvent=i;for(let o of Array.from(this._handlers))o(i)}};var W=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",i){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,i!==void 0&&(this.cause=i),Object.setPrototypeOf(this,new.target.prototype)}},Me=class extends W{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},xe=class extends W{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function X(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function wr(r){return new z(r)}var z=class{_options;constructor(e){this._options=e}async list(e){let n=Lt(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new W("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(Dt)}async getDownloadUrl(e,t){let n=Lt(await this._request(t,`/${encodeURIComponent(e)}/download`)),i=n.download_url;if(typeof i!="string"||!hn(i))throw new W("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Dt(n.artifact),downloadUrl:i}}async _request(e,t){let n=lt(this._options.baseUrl,this._options.fallbackUrls),i=null;for(let s of n)try{return await this._requestFromBase(s,e,t)}catch(o){if(i=o instanceof Error?o:new Error(String(o)),i instanceof W&&pn(i.status))throw i}throw i??new W("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let i=`${se(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,s=await this._resolveToken(),o=await fetch(i,{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(i,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw fn(o.status,a,d)}try{return await o.json()}catch(a){throw new W(`[urun] runtime artifacts: invalid JSON response from ${se(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 n=se(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 ${n}: ${a}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function Dt(r){if(!r||typeof r!="object")throw new W("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=q(e,"artifact_id")||q(e,"id"),n=q(e,"filename"),i=q(e,"kind"),s=q(e,"status")||"ready",o=un(e,"size_bytes"),a=q(e,"sha256");if(!t||!n||!i||o==null||!a)throw new W("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:i,filename:n,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(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function un(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function hn(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function pn(r){return r===401||r===403}function fn(r,e,t){return r===401?new Me(t,e):r===404?new xe(t,e):new W(t,r,e)}function Lt(r){if(!r||typeof r!="object"||Array.isArray(r))throw new W("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var F=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)}},le=class extends F{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Oe=class extends F{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Ne=class extends F{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)}},Fe=class extends F{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)}},$e=class extends F{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)}},J=class extends F{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function Ut(r){return/^(\d+[smhdw])+$/.test(r)}function yr(r){if(r==="pin")return{action:"pin"};if(Ut(r))return{action:"retain",duration:r};throw new J(`[urun] recordings: "${r}" is not a duration or "pin"`)}function mn(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new le(n,e??"unauthorized");if(r===404)return new Oe(n,e??"not_found");if(r===400)return new J(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new Ne(n,e);case"pin_requires_active_temp":return new Fe(n,e);case"permanent_locked":return new $e(n,e)}return new F(n,{status:r,code:e??`http_${r}`})}var Z=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!Ut(t))throw new J(`[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 F("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let i=this._buildUrl(t,n.params),s=await this._resolveToken(),o=await this._fetch(i,e,s,n.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(i,e,s,n.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw mn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,i=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return i&&(n+=`?${i}`),n}_fetch(e,t,n,i){let s={Authorization:`Bearer ${n}`,apikey:n,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 i!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(i)),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 le("[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 n=(await e.json()).error;if(n&&typeof n=="object"){let{code:i,message:s}=n;return{code:typeof i=="string"?i:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function kr(r){return new Z(r)}var _r=1e3,Tr=12e3;function It(r,e,t={}){let n=null,i=0,s=0,o=null,a=-1,d=()=>{let p=r.get("desired.billing.generationSeconds");if(typeof p!="number"||!Number.isFinite(p)||p<=0)return null;let b=r.get("desired.billing.epoch"),v=r.get("desired.billing.updatedAtMs");return{seconds:p,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof v=="number"&&Number.isFinite(v)?v:null}},c=()=>{if(n===null)return null;let p=Math.min(Math.max(0,Date.now()-i),s);return n+p/1e3},l=()=>{let p=t.creditsPerSecond;if(typeof p=="number"&&Number.isFinite(p)&&p>0)return p;let b=r.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},u=()=>{let p=c();if(p===null)return;let b=Math.floor(p);if(b<=a)return;a=b;let v={seconds:b},R=l();R!==null&&(v.estimatedCredits=b*R),e(v)},h=p=>{i=Date.now();let b=p===null?0:Math.max(0,i-p);s=Math.max(0,12e3-b)},y=()=>{let p=d();if(p!==null){if(o!==null&&p.epoch!==o){o=p.epoch,n=p.seconds,a=-1,h(p.updatedAtMs),u();return}n!==null&&p.seconds<=n||(o=p.epoch,n=p.seconds,h(p.updatedAtMs),u())}};y();let k=r.on("change",y),_=setInterval(u,1e3);return _.unref?.(),()=>{clearInterval(_),k()}}var gn="activity",vn="visibility",Rr=15e3,Ct=["pointerdown","pointermove","keydown","wheel","touchstart"];function Pt(r){let e=r.now??Date.now,t=r.mode==="explicit",n=t?null:r.windowTarget!==void 0?r.windowTarget:typeof window<"u"?window:null,i=t?null:r.documentTarget!==void 0?r.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let h=e();if(!(o!==void 0&&h-o<15e3)){o=h;try{r.awareness.setLocalStateField(gn,{at:h})}catch{}}},d=()=>{if(!(s||!i||i.visibilityState===void 0))try{r.awareness.setLocalStateField(vn,i.visibilityState)}catch{}},c=()=>a(),l=()=>{d(),(!i||i.visibilityState===void 0||i.visibilityState==="visible")&&a()};if(n)for(let h of Ct)n.addEventListener(h,c,{passive:!0,capture:!0});i&&i.addEventListener("visibilitychange",l);let u=null;return!t&&r.isProducing&&(u=setInterval(()=>{if(!s)try{r.isProducing?.()&&a()}catch{}},15e3),u.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,n)for(let h of Ct)n.removeEventListener(h,c,{capture:!0});i&&i.removeEventListener("visibilitychange",l),u&&(clearInterval(u),u=null)}}}}var wn="user_activity",bn="focus",Dr=3e4;function Wt(r){switch(r){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var ue=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(Wt(e.state));let t=e.on("stateChange",i=>{this._setState(Wt(i))}),n=()=>{t(),this._transportUnsubs.delete(n)};return this._transportUnsubs.add(n),n}_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(bn,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(wn,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 Ur=250;function Mt(r){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 n=Date.now();n-e<250||(e=n,r())};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 xt(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=n=>{n.persisted||e||(e=!0,r())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function Ot(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{r()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Nt="video/mp4";function Ft(r,e={}){let t=e.timesliceMs??1e3,n=null,i=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 u=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(Nt)?Nt:void 0),h=new MediaStream([a]),y=new l(h,u?{mimeType:u}:void 0);n=y;let k=Promise.resolve();y.ondataavailable=_=>{let p=_.data;s||!p||p.size===0||(k=k.then(async()=>{let b=new Uint8Array(await p.arrayBuffer());s||d(b)}))},y.onstop=()=>{k.then(()=>{s||c()})},y.onerror=()=>{k.then(()=>{s||c()})},y.start(t)};return{start(a,d){if(n||s)return;let c=r.track();if(c){o(c,a,d);return}i=r.onTrack(l=>{!l||n||s||(i?.(),i=null,o(l,a,d))})},stop(){if(s)return;s=!0,i?.(),i=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function yn(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.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 $t(r,e){let t=null,n=!1,i=!1,s=new ReadableStream({pull(o){n||(n=!0,t=r(e),t.start(a=>{if(!i)try{o.enqueue(a)}catch{}},()=>{if(!i){i=!0;try{o.close()}catch{}}}))},cancel(){i=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return yn(s)}import{encode as kn,decode as Sn}from"@msgpack/msgpack";var _n=65536;function qt(r){let e=kn(r),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var he=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(n>_n)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+n)break;let i=this.buf.subarray(4,4+n);this.buf=this.buf.subarray(4+n),t.push(Object.assign(Sn(i),{raw:i}))}return t}};function Bt(r,e){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),n=t.getUint8(0),i=(n&240)===128,s=n===222;if(!i&&!s&&!(n===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=i?n&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=i?1:s?3:5,c=[];c.push(r.subarray(0,d));for(let y=0;y<a;y++){let k=d,_=ee(r,t,d);d=_.end;let b=ee(r,t,d).end;if(Tn(t.getUint8(k))){let v=t.getUint8(k),R=(v&224)===160?1:v===217?2:v===218?3:5;if(new TextDecoder().decode(r.subarray(k+R,_.end))==="t"){c.push(r.subarray(k,_.end));let T=new TextEncoder().encode(e);if(T.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");c.push(new Uint8Array([160|T.byteLength]),T)}else c.push(r.subarray(k,b))}else c.push(r.subarray(k,b));d=b}let l=c.reduce((y,k)=>y+k.byteLength,0),u=new Uint8Array(l),h=0;for(let y of c)u.set(y,h),h+=y.byteLength;return u}function Tn(r){return(r&224)===160?!0:r===217||r===218||r===219}function ee(r,e,t){let n=e.getUint8(t),i=t;if(n<=127||n>=224)return{start:i,end:t+1};if((n&224)===160)return{start:i,end:t+1+(n&31)};if((n&240)===128||(n&240)===144){let o=n&15;t+=1;let a=(n&240)===128?o*2:o;for(let d=0;d<a;d++)t=ee(r,e,t).end;return{start:i,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[n]!==void 0)return{start:i,end:t+1+s[n]};if(n===217||n===196)return{start:i,end:t+2+e.getUint8(t+1)};if(n===218||n===197)return{start:i,end:t+3+e.getUint16(t+1,!1)};if(n===219||n===198)return{start:i,end:t+5+e.getUint32(t+1,!1)};if(n===220||n===221){let o=n===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===220?3:5;for(let a=0;a<o;a++)t=ee(r,e,t).end;return{start:i,end:t}}if(n===222||n===223){let o=n===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===222?3:5;for(let a=0;a<o*2;a++)t=ee(r,e,t).end;return{start:i,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${n.toString(16)} at byte ${i}`)}var M=12,qe=1,An=0,pe=1,Ht=2;function fe(r){let e=r.getUint8(8);return{groupId:r.getUint32(0,!0),frameSeq:r.getUint32(4,!0),keyframe:(e&qe)===qe,fragIndex:r.getUint8(9),fragCount:r.getUint8(10),lane:r.getUint8(11)}}function jt(r){let e=new Uint8Array(M),t=new DataView(e.buffer);return t.setUint32(0,r.groupId,!0),t.setUint32(4,r.frameSeq,!0),t.setUint8(8,r.keyframe?qe:0),t.setUint8(9,r.fragIndex),t.setUint8(10,r.fragCount),t.setUint8(11,r.lane??An),e}var Rn=100,Vt=100,me=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Rn}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=fe(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 n=this.pending.get(t.frameSeq);if(n||(n={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n)),!n.chunks[t.fragIndex]){n.chunks[t.fragIndex]=e.subarray(M),n.received++,n.received===n.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,n));for(let i of this.pending.keys())i<t.frameSeq-1&&(this.pending.delete(i),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-Vt?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Vt}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 n=t.chunks.reduce((o,a)=>o+a.byteLength,0),i=new Uint8Array(n),s=0;for(let o of t.chunks)i.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:i})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var En=/^avc[13]\.[0-9a-fA-F]{6}$/;function Dn(r){return En.test(r)?null:`codec ${JSON.stringify(r)} 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 Be(r,e){let t=Dn(r);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var Ln=1,He=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}if(this.name===null){if(this.buf.byteLength<2)return[];let n=this.buf[0];if(n!==Ln)throw new Error(`[urun] wt data stream: unknown header version 0x${n.toString(16)} \u2014 rejecting stream`);let i=this.buf[1];if(i===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+i)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+i)),this.buf=this.buf.subarray(2+i)}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+n)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let i=bt(this.buf.subarray(4,4+n));this.buf=this.buf.subarray(4+n),i===wt&&(this.ended=!0),t.push({name:this.name,payload:i})}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 Kt(r,e){let t=r.getReader();for(;;){let{value:n,done:i}=await t.read();if(i)return;n&&Un(n,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Un(r,e){let t=r.getReader(),n=new He;try{for(;;){let{value:i,done:s}=await t.read();if(s)break;if(!(!i||i.byteLength===0))for(let{name:o,payload:a}of n.push(i))e.onData(o,a)}n.finish()}catch(i){try{await t.cancel?.(i)}catch{}throw i}}var je=40,Gt=2,K=48e3,In=64,Cn=100,Ve=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=fe(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Cn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let n=this.pending.get(t.frameSeq);if(!n)for(n={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n);this.pending.size>In;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=n.fragCount||n.chunks[t.fragIndex]||(n.chunks[t.fragIndex]=e.subarray(M),n.received++,n.received<n.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let i=n.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(i),o=0;for(let a of n.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:n.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}},ge=class{constructor(e,t){this.config=e;this.seam=t;let n=this.seam.jitterBufferTargetMs??je;Number.isFinite(n)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${n} is not finite \u2014 using default ${je}ms`),n=je),this.targetS=Math.max(0,n)/1e3}config;seam;decoder=null;ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;contentBaseS=null;wallBaseS=0;reanchorLogged=!1;lastTsS=null;pendingTs=[];bridgeTrack=null;scheduledCount=0;lastScheduledAt=0;rebuildGen=0;rebuildTimes=[];rebuildBudgetLoggedAt=-1e4;lastRemote=null;assembler=new Ve(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(i){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,i}this.trackSurfaced=!0,this.ctx.resume?.().catch(()=>{});let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] playout start produced no bridge track");this.surfaceTrack(n)}stop(){if(!this.stopped){this.stopped=!0;try{this.seam.renderHop?.setSource(null)}catch{}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:n=>this.schedule(n,this.pendingTs.shift()),error:n=>this.onDecoderError(n)});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 i=globalThis.AudioDecoder;if(typeof i!="function")return;try{this.initDecoder(i)}catch{return}}let n=this.decoder;n&&(this.pendingTs.push(e.timestamp),n.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/K)),data:e.data})))}schedule(e,t){let n=this.ctx,i=this.dest;if(!n||!i||this.stopped){e.close();return}let s=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),a=n.createBuffer(o,s,e.sampleRate);for(let u=0;u<o;u++){let h=new Float32Array(s);e.copyTo(h,{planeIndex:u,format:"f32-planar"}),a.copyToChannel(h,u)}let d=s/e.sampleRate;e.close();let c=n.createBufferSource();c.buffer=a,c.connect(i);let l;if(t===void 0)l=Math.max(this.playhead,n.currentTime+this.targetS);else{this.contentBaseS===null&&(this.contentBaseS=t/K,this.wallBaseS=n.currentTime+this.targetS),l=this.wallBaseS+t/K-this.contentBaseS;let u=null;this.lastTsS!==null&&(t<this.lastTsS?(l=n.currentTime+this.targetS,u=`backward ts step ${(this.lastTsS-t/K).toFixed(3)}s (producer clock reset)`):l>n.currentTime+this.targetS+Math.max(d,this.targetS)&&(u=`forward jump ${(l-n.currentTime).toFixed(3)}s out (lead + ${d.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),u&&(this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${u} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=t/K,this.wallBaseS=n.currentTime+this.targetS,l=this.wallBaseS)),l<n.currentTime&&(this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored ${(n.currentTime-l).toFixed(3)}s past its content position (arrival deficit exceeded the lead) \u2014 the gap is honest silence at rate 1.0, never a catch-up stretch`)),this.contentBaseS=t/K,this.wallBaseS=n.currentTime+this.targetS,l=this.wallBaseS)}c.start(l),this.scheduledCount++,this.lastScheduledAt=performance.now(),t!==void 0&&(this.lastTsS=t/K),this.playhead=l+d}armBridgeEndedWatch(e){let t=this.rebuildGen;e.addEventListener?.("ended",()=>{if(!this.stopped&&!(t!==this.rebuildGen||this.bridgeTrack!==e)){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(n){console.error(`[urun] WT audio bridge rebuild failed \u2014 the reply stays silent until the next lane death re-delivers: ${n instanceof Error?n.message:String(n)}`)}}},{once:!0})}playoutProgress(){return{scheduled:this.scheduledCount,lastScheduledAt:this.lastScheduledAt,surfaced:this.trackSurfaced&&this.bridgeTrack?.readyState!=="ended"}}rebuildSurface(){if(this.stopped)return;let e=performance.now();if(this.rebuildTimes=this.rebuildTimes.filter(s=>e-s<1e4),this.rebuildTimes.length>=Gt){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${Gt} in 10s) \u2014 standing down; the media-dead playout-progress verdict escalates to a re-dial if the surface stays dead`));return}this.rebuildTimes.push(e),this.rebuildGen++;let t=globalThis.AudioContext;if(typeof t!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");let n=new t({sampleRate:this.config.sampleRate});this.ctx=n,n.resume?.().catch(()=>{}),this.dest=n.createMediaStreamDestination(),this.playhead=0,this.contentBaseS=null,this.lastTsS=null,this.trackSurfaced=!0;let i=this.dest.stream.getAudioTracks()[0];if(!i)throw new Error("[urun] rebuilt playout produced no bridge track");this.surfaceTrack(i)}surfaceTrack(e){this.bridgeTrack=e,this.armBridgeEndedWatch(e),this.lastRemote&&this.lastRemote.readyState==="live"?this.seam.onTrack(this.lastRemote):this.seam.onTrack(e);let t=this.seam.renderHop;t&&(t.onRemote(n=>{if(this.stopped)return;if(n?this.lastRemote=n:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),n){this.seam.onTrack(n);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.seam.onTrack(this.lastRemote);return}let i=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.seam.onTrack(i)}),t.setSource(e))}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(n){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${n instanceof Error?n.message:String(n)}`)}}};var te=1200;function Ke(r,e,t,n,i){let s=n-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=jt({groupId:e>>>0,frameSeq:r>>>0,keyframe:i?.keyframe??!0,fragIndex:d,fragCount:o,lane:i?.lane??pe}),u=new Uint8Array(M+c.byteLength);u.set(l,0),u.set(c,M),a.push(u)}return a}var Pn=`
|
|
3
3
|
self.onrtctransform = (event) => {
|
|
4
4
|
const transformer = event.transformer
|
|
5
5
|
if (transformer.options?.role === 'sender') {
|
|
@@ -25,6 +25,6 @@ self.onrtctransform = (event) => {
|
|
|
25
25
|
self.postMessage({ type: 'err', detail: String(e) }))
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
`;function
|
|
28
|
+
`;function Qt(r){let e=r.match(/a=rtpmap:(\d+) opus\/48000\/2/)?.[1];if(!e)return r;let t="usedtx=1;useinbandfec=1;maxaveragebitrate=32000",n=!1,i=r.split(`\r
|
|
29
29
|
`).map(s=>s.startsWith(`a=fmtp:${e} `)&&!s.includes("usedtx=")?(n=!0,`${s};${t}`):s);if(!n){let s=i.findIndex(o=>o===`a=rtpmap:${e} opus/48000/2`);s>=0&&i.splice(s+1,0,`a=fmtp:${e} ${t}`)}return i.join(`\r
|
|
30
|
-
`)}var ve=class{constructor(e){this.sink=e}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=Pn(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(n){this.die(`replaceTrack: ${n instanceof Error?n.message:String(n)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&this.engage(t)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let n;try{n=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let i=this.sendPc.addTrack(e);this.sender=i,this.currentTrack=e,this.wireTrackLiveness(e);let s=t.RTCRtpScriptTransform;i.transform=new s(n,{role:"sender"}),!this.negotiatedOnce&&this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=n=>{if(!n.candidate)return;let i=this.candQueue;i!==null&&(i.toRecv.push(n.candidate),this.flushCandidates())},this.recvPc.onicecandidate=n=>{if(!n.candidate)return;let i=this.candQueue;i!==null&&(i.toSend.push(n.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(n=>this.die(`loopback renegotiate: ${n instanceof Error?n.message:String(n)}`))},this.recvPc.ontrack=n=>{let i=n.transceiver?.mid??null;i!==null&&i===this.renderMidOf()&&this.renderRemoteCb?.(n.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),this.negotiatedOnce||this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let n=await e.createOffer();n.sdp=Gt(n.sdp??""),await e.setLocalDescription(n),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:n.sdp});let i=await t.createAnswer();i.sdp=Gt(i.sdp??""),await t.setLocalDescription(i),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:i.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let n=t.context.createMediaStreamDestination();t.connect(n);let i=n.stream.getAudioTracks()[0]??null;return i?(this.nodeBridge={node:t,dest:n},i):(this.die("AudioNode bridge produced no audio track"),null)}catch(n){return this.die(`AudioNode bridge: ${n instanceof Error?n.message:String(n)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([Cn],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let n=t.data;n?.type==="enc"&&n.payload instanceof ArrayBuffer?this.onEncodedFrame(n.rtpTimestamp??0,new Uint8Array(n.payload)):n?.type==="err"&&this.die(`transform: ${n.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let n=Ke(this.frameSeq,e,t,this.sink.maxDatagramSize()||te);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 i of n)this.sink.send(i);this.frameSeq=this.frameSeq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Pn(r){let e=r;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Wn=9e4,Mn="avc1.42E01F",xn=60,On=3,Nn=1e4;function Fn(r){return Math.round(r*(Wn/1e6))%2**32>>>0}var we=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 n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let i=++this.generation,s=new n({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,s.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&i===this.generation;){let{value:a,done:d}=await s.read();if(d)break;if(a){if(o||this.stopped||i!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!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(){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:Mn,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 i=this.keyframeWanted||this.framesSinceKeyframe>=xn;this.keyframeWanted=!1,this.framesSinceKeyframe=i?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:i})}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 n=Ke(this.frameSeq,Fn(e.timestamp),t,this.sink.maxDatagramSize()||te,{lane:Bt,keyframe:e.type==="key"});if(n===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 i of n)this.sink.send(i);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(n=>t-n<Nn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=On){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 $n(r){return r.byteLength>=2&&r[0]===1&&r[1]===3}var be=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 n=new TextEncoder().encode(e);if(n.byteLength===0||n.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${n.byteLength})`));let i=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+n.byteLength);d[0]=1,d[1]=n.byteLength,d.set(n,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),$n(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=i.catch(()=>{}),i}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 Qt=250,qn=25,Bn=2e3,Hn=15e3,jn=1e3,Vn=45e3,Kn=500,Yt=10,Gn=2,Qn=2,Ge=2,ye=class r{constructor(e,t,n,i,s,o,a){this.offer=e;this.sessionId=t;this.canvas=n;this.audioLane=i;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 me({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,n=t!==void 0&&t!=="";this.hasVideoLane=n,n&&Be(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(l=>({algorithm:"sha-256",value:Uint8Array.from(atob(l),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let i=await this.wt.createBidirectionalStream();this.writer=i.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=i.readable.getReader(),o=new he,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")),n&&(Be(c.codec,"hello-ack"),this.initDecoder(c.codec,c.width,c.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let l={setSource:h=>{this.renderSource=h,this.audioUplinkLane?.setRenderSource?.(h)},onRemote:h=>{this.renderRemoteCb=h}},u=new ge(this.offer.audio,{...this.audioLane,renderHop:l});try{u.start(),this.audioPlayout=u}catch(h){console.warn(`[urun] WT audio lane failed to start (${h instanceof Error?h.message:String(h)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),u.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let l=this.wt.createUnidirectionalStream?.bind(this.wt);if(!l)throw new Error("WebTransport uni streams are not creatable in this environment");let u=new be({openUniStream:async()=>(await l()).getWriter()});u.onDead(h=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(h)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(l){let u=l instanceof Error?l.message:String(l);console.warn(`[urun] WT data uplink failed to engage (${u}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(u)}this.controlLoop(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(),Kn)),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 ${Qt}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Hn},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),jn))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,n=typeof e.ur=="number"?e.ur:null;if(t===null&&n===null)return;this.gatewayExposesCounters=!0;let i=this.audioDgramsReceived,s=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:n,recvDownlink:i,sentUplink:s},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,d=n!==null&&o.ur!==null?n-o.ur:null,c=i-o.recvDownlink,l=s-o.sentUplink,u="none";if(a!==null&&a>=Yt&&c<=0?u="downlink":d!==null&&l>=Yt&&d<=0&&(u="uplink"),u==="none"){this.severedStreak="none",this.observePlayoutProgress(c,t);return}if(this.severedStreak!==u){this.severedStreak=u;return}this.severedStreak="none";let h=u==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${l} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+h+` (gateway flow counters ds=${t} ur=${n}, client received=${i} accepted=${s}, confirmed on ${Gn} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let n=this.audioPlayout;if(!n){this.playoutScheduledSeen=null;return}let i=n.playoutProgress(),s=i.surfaced;if(this.playoutScheduledSeen!==null&&i.scheduled>this.playoutScheduledSeen&&s){this.playoutScheduledSeen=i.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=i.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Qn)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,console.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${i.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{n.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=Ge}return}this.playoutStallStreak<Ge||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${i.scheduled} on ${Ge} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let n=performance.now(),i=this.audioLaneLastArrivalAt===null?null:n-this.audioLaneLastArrivalAt,s=this.lastInboundControlAt===null?null:n-this.lastInboundControlAt,o=i===null&&s===null?!0:(i===null||i>=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>=Vn&&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.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,Vt(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,n){let i=globalThis.VideoDecoder;if(typeof i!="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:n};let o=new i({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&&n>0?{codedWidth:t,codedHeight:n}:{},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(n){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${n instanceof Error?n.message:String(n)}`));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,i=>this.onUplinkSendError(i))}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 n=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(i=>n-i<Bn),this.uplinkSendErrorsAt.push(n),!(this.uplinkSendErrorsAt.length<qn)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let t=0;return{send:n=>this.uplinkSend(n,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??te}}engageAudioUplink(){let e=new ve(this.uplinkSink("audio"));e.onDead(t=>this.onUplinkLaneDead("audio",t)),e.onRenderTrack?.(t=>this.renderRemoteCb?.(t)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new we(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(n){let i=n instanceof Error?n.message:String(n);console.warn(`[urun] WT ${t} uplink failed to engage (${i}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,i)}}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.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let n=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,o=i?.builtAt!=null&&Date.now()-i.builtAt>=r.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(o>r.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${n} uplink lane dead (${t}) \u2014 ${r.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 ${r.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`);return}console.warn(`[urun] WT ${n} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${o}/${r.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)},r.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:n}=await e.read();if(n)break;if(!t)continue;if(t.byteLength>=M&&t[11]===pe){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let i=performance.now();if(this.lastArrivalTs>0){let s=i-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(s-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=i,this.reassembler.push(t)}}decodeFrame(e,t,n){let i=globalThis.EncodedVideoChunk;if(typeof i=="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 i({type:t?"key":"delta",timestamp:e*(1e6/24),data:n})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write($t(e)),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),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 n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async readControl(e,t,n=[]){for(;;){let i=n.shift();if(i)return i;let{value:s,done:o}=await e.read();if(o)return null;s&&n.push(...t.push(s))}}async controlLoop(e,t,n){for(;!this.stopped;){let i=await this.readControl(e,t,n);if(!i)break;let s=i;if(this.lastInboundControlAt=performance.now(),s.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(qt(i.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(),n=(t-e)/1e3;e=t;let i=this.reassembler.drainWindow(),s=i.delivered+i.abandoned;this.lastStats={recvBps:n>0?i.bytes*8/n:0,lossPct:s>0?100*i.abandoned/s:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Qt)}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 zt=2500,Xt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Yn=1e4,ke=class r{constructor(e,t,n){this.signaling=e;this.sessionId=t;this.opts=n}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",n=typeof e.VideoDecoder=="function",i=this.opts.allowWebTransport??!0,s={webtransport:t&&n&&i,webcodecs:n,codecs:Xt,wtData:t&&n&&i&&this.opts.dataLane!==void 0,wtAudio:t&&n&&i&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&i&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&n&&i&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&n&&i&&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 Qe(c.start(),this.opts.quicDeadlineMs??zt,"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 u=String(l instanceof Error?l.message:l);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${u}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(u),l}console.warn("[urun] webtransport failed, falling back to webrtc:",l),this.proceedWebRtcDial(`wt failed: ${String(l instanceof Error?l.message:l)}`),this.notifyEstablished("webrtc",String(l instanceof Error?l.message:l))}}if(this.opts.allowWebRtcFallback===!1){let 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 n=this.session,i=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.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="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:Xt,wtData:i,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;let c=this.createWebTransportSession();try{await Qe(c.start(),this.opts.quicDeadlineMs??zt,"quic connect deadline")}catch(l){throw c.stop().catch(()=>{}),l}if(this.session!==n)return c.stop().catch(()=>{}),null;try{this.engageQuicDataLane(c,i)}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"),n?.stop().catch(()=>{}),c}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let n=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:(i,s)=>n.onData(i,s),onLaneError:i=>n.onLaneError(i)}),n.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 ye(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 n=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),n){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,n)})}redialWtAfterDeath(e){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures+=1,this.wtRedialFailures===r.WT_REDIAL_MAX+1){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${r.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 ${r.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,n=ze(r.WT_REDIAL_BASE_MS,t,r.WT_REDIAL_CAP_MS,t===1?0:void 0);console.warn(`[urun] WT re-dial attempt ${t} scheduled in ${Math.round(n)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},n)}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}/${r.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let n=Ye(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${r.WT_REDIAL_MAX} failed (${n}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${n}`)}}}lateWebRtcFailover(e,t,n){this.disconnected||(async()=>{let i=this.createWebRtc();try{let s=await Qe(this.startWebRtcOn(i),this.opts.webRtcFailoverDeadlineMs??Yn,"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(i.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=s instanceof Error?s.message:String(s),a=n?`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 Ye(r){if(r instanceof Error)return r.message;if(typeof r=="string")return r;if(r&&typeof r=="object"){try{let e=JSON.stringify(r);if(e!==void 0&&e!=="{}")return e}catch{}return r.constructor?.name??Object.prototype.toString.call(r).slice(8,-1)}return String(r)}function ze(r,e,t,n){if(n!==void 0)return n;let i=Math.min(r*2**Math.max(0,e-2),t);return Math.round(i*(.75+Math.random()*.5))}function Qe(r,e,t){return new Promise((n,i)=>{let s=setTimeout(()=>i(new Error(t)),e);r.then(o=>{clearTimeout(s),n(o)},o=>{clearTimeout(s),i(o)})})}var zn=1e4,Se=class{constructor(e,t=zn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let n=oe();return new Promise((i,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!==n)return;if(clearTimeout(o),a(),d.error){s(new Error(`[urun] ${e} failed: ${String(d.error)}`));return}let{type:c,requestId:l,...u}=d;i(u)});this.carrier.sendSignal({type:e,requestId:n,...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(n=>{n.type===e&&t(n)})}};var Xn="video",_e=class{constructor(e,t=Xn){this.transport=e;this.streamName=t;this.firstMedia=new Promise((n,i)=>{this.firstMediaResolve=n,this.firstMediaReject=i}),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 n=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(n(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(n)})}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 Jt(r){let e=r;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Jn="video";function Zt(r,e,t){let n=globalThis,i=n.document;if(!(typeof i?.createElement=="function"&&typeof n.WebTransport=="function"&&typeof n.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=r.holdWebRtcDial?.(),a=i.createElement("canvas"),d=!1,c=null,l=!1,u=()=>{if(c){for(let g of c.getVideoTracks())try{g.stop()}catch{}c=null}l&&(l=!1,t.onOverrideTrack(null))},h=new ke(new Se(r),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new _e(r,t.streamName??Jn)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(g,A)=>r.dispatchQuicStreamData(g,A),onQuicLane:()=>r.markStreamDataLaneQuic(),onQuicLaneLost:g=>r.quicStreamDataLaneLost(g),onLaneError:g=>r.raiseQuicStreamDataError(g)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:g=>{d||t.onOverrideAudioTrack(g)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>D(),onMediaTransportLost:g=>{d||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(g),D())},onTransportChange:(g,A)=>{d||(g==="webrtc"&&(u(),D()),t.onTransportChange?.(g,A))}}),y=r.onWtOnlyLegDeath?.(g=>h.failCurrentWtLeg(g)),k=null,_=()=>{k!==null&&(clearInterval(k),k=null)},p=t.wtRetryBaseMs??2e3,b=t.wtRetryCapMs??3e4,v=null,R=0,D=()=>{if(d||v!==null||h.activeTransport==="webtransport")return;let g=ze(p,R+2,b);v=setTimeout(()=>{v=null,R+=1,h.retryWebTransport().then(A=>{if(d){A&&h.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${R})`),R=0,x(A);D()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${R} failed: `+Ye(A)),D())})},g)},T=()=>{v!==null&&(clearTimeout(v),v=null)},x=async g=>{if(d||g.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;_();let O=!1;k=setInterval(()=>{if(d||h.activeTransport!=="webtransport")return;let U=Jt(g);if(!U){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)"),_();return}let I=U.pathLiveness();if(!I.alive){let $=h.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${I.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"),_(),U.fail(`path health: ${I.evidence}`);return}if(!O){if(O=!0,h.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${A}ms \u2014 the QUIC PATH IS HEALTHY (${I.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: ${I.evidence}); webrtc track remains authoritative`)}},A);try{await g.firstMedia}catch(U){_(),console.debug("[urun] webtransport ended before any media flowed:",U);return}if(_(),d||h.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;c=a.captureStream();let j=c.getVideoTracks()[0];j&&(l=!0,t.onOverrideTrack(j))};return(async()=>{let g=await h.connect();if(d){h.disconnect().catch(()=>{});return}await x(g)})().catch(g=>{if(_(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",g);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",g),D();return}o?.proceed(`negotiation unavailable: ${g instanceof Error?g.message:String(g)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",g),D()}),{activeTransport:()=>h.activeTransport,watchDownlinkStall(g){h.watchDownlinkStall(g)},dispose(){d=!0,y?.(),_(),T(),u(),t.onOverrideAudioTrack?.(null),h.disconnect().catch(()=>{})}}}var Zn=new Set;function Ze(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var er="rpc",tr="$presence",nr=3e4,en=3e4,rr="rpc-resp";function ir(r){return`${rr}:${r}`}function Xe(){return oe()}function sr(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function or(r,e,t,n,i,s,o,a,d,c){let l=[],u=null,h=!1,y=null,k=!1,_,p,b=new Promise((f,N)=>{_=f,p=N});b.catch(()=>{});let v=o(),R=null,D=null,T=null,x=null,g=null,A=null,O=!0,j=()=>{T&&(clearTimeout(T),T=null),x&&(x(),x=null)},U=()=>{g&&(clearTimeout(g),g=null),A&&(A(),A=null)},I=!1,$=()=>{I||!k||(I=!0,r.set({rpc:{[e]:null}}))},V=()=>{O=!1,j(),U(),R?.(),R=null,D?.(),D=null,a?.removeEventListener("abort",S),v.dispose(),$()},G=()=>{if(u){if(l.length>0){let f=u;u=null,f.resolve({value:l.shift(),done:!1})}else if(y!==null){let f=u;u=null,f.reject(y)}else if(h){let f=u;u=null,f.resolve({value:void 0,done:!0})}}},rt=f=>{h||(l.push(f),G())},m=f=>{h||(y=f,h=!0,p(f),V(),G())},w=f=>{h||(h=!0,_(f),V(),G())},S=()=>{let f=a?.reason;m(f instanceof Ue?f:new Ie(e))},L=f=>{if(!(h||!f||typeof f!="object"))switch(U(),$(),f.t){case"delta":typeof f.delta=="string"&&rt(f.delta);break;case"response":w(f.body);break;case"error":{let{message:N,code:E}=sr(f.body);m(new Ue(N,{requestId:e,code:f.code??E}));break}}},C=()=>{let f=v.messages()[Symbol.asyncIterator]();R=()=>{f.return?.(void 0)};let N=()=>{O&&f.next().then(E=>{if(O){if(E.done){h||w(void 0);return}L(E.value),N()}},E=>{O&&m(E)})};N()},P=()=>{if(!k){if(k=!0,a){if(a.aborted){m(new Ie(e));return}a.addEventListener("abort",S,{once:!0})}D=d?.(f=>m(f))??null,C(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:i,stream:s}}}),c&&c>0&&!r.synced&&(T=setTimeout(()=>{T=null,!h&&!r.synced&&m(new ot(c,e))},c),x=r.onSynced(()=>j())),A=r.onSynced(()=>{A=null,!(h||I||g)&&(g=setTimeout(()=>{g=null,!(h||I)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(en/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).`)},en))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(P(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(y!==null){let f=y;return y=null,Promise.reject(f)}return h?Promise.resolve({value:void 0,done:!0}):new Promise((f,N)=>{u={resolve:f,reject:N}})},return(){return h||(h=!0,_(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(f){return h||(h=!0,p(f),V()),Promise.reject(f)}}}},body:b,start:P}}function tn(r){if(r&&typeof r=="object"){let{epoch:e,by:t}=r,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function ar(r,e){let n=r.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:i,rt:s,br:o}=n,a={};(i==="audio"||i==="video"||i==="data")&&(a.kind=i);let d=tn(s);d&&(a.rt=d);let c=tn(o);return c&&(a.br=c),a}var Je=class{constructor(e,t,n,i,s){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=i;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],n=null,i=!1,s=null,o={push(d){if(!i)if(n){let c=n;n=null,c.resolve({value:d,done:!1})}else t.push(d)},end(){if(i=!0,n){let d=n;n=null,d.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{i=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||i)&&(s=e._streamConsumeUnavailableError(d),a(),n)){let c=n;n=null,c.reject(s)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.reject(s):i?Promise.resolve({value:void 0,done:!0}):new Promise((d,c)=>{n={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,n=this._handlers.get("track");if(n)for(let i of n)i(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=ar(t,this._name),i=n?.br;if(i?.by==="runtime")throw new at(this._name,"runtime","browser");if(i)return;let s={br:{epoch:1}};n?.rt&&(s.rt=n.rt);let o=n?.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??Nt;return Ft(t,{track:()=>this.track,onTrack:i=>this.on("track",i)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.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 n of t)n(e)}},Te=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new kt;_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,n,i,s,o){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=i,this._artifactsAuth=s,this._streamData=bt(n),this._wireControlDocIncarnation(),this._lifecycleUnsub=Wt(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=Ct({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new ue({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(tr).awareness.setLocalState({role:"client"}),this._activation=new ce({onPhase:a=>this.onPhase(a),hint:()=>this.doc(Tt).get(At)??this.doc("control").get(Rt),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 n=await mt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),i=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,s=new ne,o=new ae({url:n.wsUrl,orgId:t.orgId,jwt:i,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,s,o,Ze(t),X({...t,baseUrl:n.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&s.setTarget(o.multiplexer)}),o.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),o.setEndsAt(n.endsAt),re()&&await ie();let d=t.getAccessToken,c=d?async()=>await d()??i:i;return a.setDocTransport({wsUrl:n.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 ct(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=Ut(this.doc("control"),n=>{for(let i of Array.from(this._generationTickHandlers))try{i(n)}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 Z(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,i)=>t.retain(n,i),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},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 n of this._docs.values())n.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Je(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 St(e,this._sessionId,Zn.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=_t(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=de(e.wsUrl),n=typeof e.token=="function"?"<token-supplier>":e.token??"",i=`${t}\0${n}\0${this._sessionId}`;i!==this._docEndpointKey&&(this._docEndpointKey=i,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 n=Xe(),i=new AbortController;t.signal&&(t.signal.aborted?i.abort(t.signal.reason):t.signal.addEventListener("abort",()=>i.abort(t.signal.reason),{once:!0}));let s=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;s=setTimeout(()=>i.abort(new st(d,n)),d)}let o=this._consumeResponse(n,e,!1,i.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{s&&clearTimeout(s),a?.()})}_consumeResponse(e,t,n,i,s){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(er),a=ir(e);return or(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),i,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??nr)}requestStream(e,t={}){let n=Xe();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=Xe(),i=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return i.start(),i.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=Zt(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 Q)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Q);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 i of t)try{i()}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 n=Array.from(this._activeRequests);this._activeRequests.clear();for(let i of n)try{i(new dt)}catch{}for(let i of this._docs.values())i.dispose();this._docs.clear();for(let i of this._streams.values())i.dispose();this._streams.clear(),this._transport.disconnect(e)}};function nn(r){return`urun:session:v2:${r.orgId}:${r.app}:${r.functionName}`}function et(){try{return globalThis.sessionStorage??null}catch{return null}}var tt=new Map;function Ae(r){if(!r)return;let e=r.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof n?.sub=="string"&&n.sub.length>0?n.sub:void 0}catch{return}}function dr(r,e){return r!==void 0&&e!==void 0&&r!==e}function nt(r,e){let t=et(),n=null;if(t)try{let s=t.getItem(r);if(s){let o=JSON.parse(s);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(n={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{n=null}let i=tt.get(r)??n??null;return!i||dr(i.actor,e)?null:i}function rn(r,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};tt.set(r,t);let n=et();if(n)try{n.setItem(r,JSON.stringify(t))}catch{}}function Re(r){tt.delete(r);let e=et();if(e)try{e.removeItem(r)}catch{}}var sn=new Set(["paused","acquiring","live"]),cr=new Set(["24h","keep"]);function on(r){if(typeof r!="string"||r.length===0)return null;let e=new Date(r);return Number.isFinite(e.getTime())?e:null}function lr(r){if(typeof r?.id!="string"||r.id.length===0)throw new Le("[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 r.state!="string"||!sn.has(r.state))throw new Le(`[urun] session ${r.id} reported an unrecognized state ${JSON.stringify(r.state)} \u2014 this @urun-sh/core build knows only ${[...sn].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 r.recordings_expired=="boolean"?e=r.recordings_expired:console.warn(`[urun] session ${r.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:r.id,label:typeof r.label=="string"&&r.label.length>0?r.label:null,state:r.state,app:typeof r.app=="string"?r.app:"",functionName:typeof r.function=="string"?r.function:"",createdAt:on(r.created_at),lastActiveAt:on(r.last_active_at),archived:r.archived===!0,preview:typeof r.preview=="string"&&r.preview.length>0?r.preview:null,recordingsExpired:e,retention:cr.has(r.retention)?r.retention:(r.retention!==void 0&&console.warn(`[urun] session ${r.id} reported an unrecognized retention ${JSON.stringify(r.retention)} \u2014 defaulting to '24h'`),"24h")}}var Ee=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:n}=await pt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(lr),nextCursor:n}}async end(e){await ft({...this._request,sessionId:e})}async archive(e){await We({...this._request,sessionId:e,archived:!0})}async unarchive(e){await We({...this._request,sessionId:e,archived:!1})}};function an(r,e,t){let n=Ae(t);rn(r,n!==void 0?{sessionId:e,actor:n}:{sessionId:e})}var ur=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Yi(r,e){return new Ee(r,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function zi(r,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,n){if(!(ur.has(n)||typeof n!="string"))return(i,s)=>{let o=i??{},a=nn({orgId:e.orgId,app:r,functionName:n}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,c,l=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,u=l(),h=e.jwt,y=e.getAccessToken?async m=>{let w=await e.getAccessToken(m);return w&&(h=w),w}:void 0,k={...e,getAccessToken:y},_=new ne,p=new ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:u,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),b=new Te(u,_,p,Ze(k),X(k),{activity:s?.activity}),v,R=!1,D=!1,T,x,g=new Promise(m=>{x=m}),A,O=m=>{m.sessionId||T||(T="teardown",A="ticket",Ce({baseUrl:m.baseUrl,requestId:m.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider}))},j=m=>{T||m.sessionId||(T="abandon",Ce({baseUrl:m.baseUrl,requestId:m.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider,reason:"client_abandoned"}))},U=m=>{let w=m.sessionId||!c?m:{...m,sessionId:c};v=w,x({status:"ready",handle:w}),(D||T==="teardown")&&O(w)};b.setEndHandler(async()=>{let m=v?{status:"ready",handle:v}:await g;if(m.status==="unavailable")throw new Q("[urun] session allocation failed before a releasable request was created",{cause:m.cause});let w=v??m.handle;return Re(a),T==="teardown"?w.sessionId?{status:"paused",sessionId:w.sessionId,reason:"client_ended"}:{status:"canceled",requestId:w.requestId}:(T="end",w.sessionId?ut({baseUrl:w.baseUrl,sessionId:w.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:y,authProvider:e.authProvider}):Pe({baseUrl:w.baseUrl,requestId:w.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:y,authProvider:e.authProvider}))}),b.setCancelHandler(async()=>{let m=v?{status:"ready",handle:v}:await g;if(m.status==="unavailable")throw new Q("[urun] session allocation failed before a cancellable request was created",{cause:m.cause});let w=v??m.handle;if(w.sessionId)throw new it(`[urun] cancel() is for a queued admission request, but this call already has session ${w.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:w.sessionId,code:"cancel_on_live_session"});T="end";try{let S=await Pe({baseUrl:w.baseUrl,requestId:w.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:y,authProvider:e.authProvider});return Re(a),S}catch(S){throw T==="end"&&(T=void 0),S}});let I=async m=>{let w,S=s?.sessionId??e.sessionKey??c,L,C;if(S===void 0&&!d){let E=nt(a);if(E?.sessionId){if(C=Ae(h),E.actor!==void 0&&C===void 0&&y){let De=await Promise.resolve(y()).catch(()=>{});C=Ae(De??e.jwt)}L=E.actor!==void 0&&C!==void 0&&E.actor!==C?void 0:E.sessionId}}let P=S??L,B=(E,De)=>ht({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:y,authProvider:e.authProvider,idempotencyKey:E,sessionKey:De,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},priority:e.priority,onAdmission:H=>{p.reportAdmission(H),H.sessionId&&!c&&(c=H.sessionId,w=H.sessionId,v&&v.sessionId!==H.sessionId&&U({...v,sessionId:H.sessionId}),R||(e.sessionKey||an(a,H.sessionId,h),b.setSessionId(H.sessionId)))},onRequest:U}),f;try{f=await B(m,P)}catch(E){if(L===void 0||!(E instanceof Y)||E.code!=="session_name_not_yours")throw E;console.warn(`[urun] session_name_not_yours: the control plane refused session ${L} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),nt(a,C)?.sessionId===L&&Re(a),f=await B(l(),void 0)}let N=y?await y()??void 0:e.jwt;if(w&&w!==f.sessionId)throw v&&v.sessionId!==f.sessionId&&U({...v,sessionId:f.sessionId}),new Y(`Gateway contract violation: admission minted session ${w} but allocation completed as ${f.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return c=f.sessionId,v&&v.sessionId!==f.sessionId&&U({...v,sessionId:f.sessionId}),R||(e.sessionKey||an(a,f.sessionId,h),b.setSessionId(f.sessionId),b.setArtifactsAuth(X({...k,baseUrl:f.baseUrl})),p.setEndsAt(f.endsAt),p.seedRegion(gt(f.response))),{url:f.wsUrl,sessionId:f.sessionId,jwt:N,iceServers:f.response.ice_servers,endsAt:f.endsAt}},$,V=y?async()=>await y()??$:()=>$,G=()=>{let m=p.connectedUrl;return m?de(m):void 0};if(p.setConnectionResolver(async()=>{let m=await I(l());return $=m.jwt,m}),p.on("connected",()=>{p.multiplexer&&_.setTarget(p.multiplexer);let m=p.connectedUrl;m&&b.setDocTransport({wsUrl:m,token:V,resolveServerUrl:G})}),(async m=>{let w;try{w=await I(m)}catch(S){if(R){x({status:"unavailable",cause:S});return}console.error(`[urun] Failed to create session for ${n}:`,S),v&&j(v);let L=S instanceof Error?S:new Error(String(S)),C=S instanceof Y?S.httpStatus:void 0,P=S instanceof Y?S.code:void 0,B=S instanceof Y?S.retryAfterSeconds:void 0;p.reportAllocationFailure(L,C,P,B),x({status:"unavailable",cause:S});return}R||(p.setAuth({jwt:w.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:w.url,sessionId:w.sessionId,iceServers:w.iceServers}),re()&&await ie(),$=w.jwt,b.setDocTransport({wsUrl:w.url,token:V,resolveServerUrl:G}),await p.connect({app:r,functionName:n,args:o}),b.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(u).catch(m=>{console.error(`[urun] Failed to connect session for ${n}:`,m)}),e.releaseOnLeave!==!1){let m=Mt(()=>{if(R=!0,p.leaveLeg())return;if(p.connectedUrl!==null){p.disconnect();return}p.disconnect();let P=v;P?O(P):D=!0});b.onDisconnect(m);let w,S,L=!1,C=()=>{L||(L=!0,w?.(),S?.())};g.then(P=>{P.status!=="ready"||L||(w=xt(()=>v!==void 0))}),S=b.onPhase(P=>{let B=P?.name;(B==="paused"||B==="error")&&C()}),L&&S(),b.onDisconnect(C)}return b}}})}export{hr as a,pr as b,fr as c,Tt as d,At as e,Rt as f,dn as g,ce as h,W as i,Me as j,xe as k,vr as l,z as m,F as n,le as o,Oe as p,Ne as q,Fe as r,$e as s,J as t,Lt as u,br as v,Z as w,yr as x,Sr as y,_r as z,Ut as A,mn as B,gn as C,Ar as D,It as E,Ct as F,vn as G,wn as H,Er as I,ue as J,Lr as K,Wt as L,Mt as M,xt as N,Nt as O,Sn as P,$t as Q,he as R,M as S,fe as T,Ht as U,me as V,Dn as W,He as X,Vt as Y,ye as Z,ke as _,Se as $,_e as aa,nr as ba,Te as ca,Ee as da,Yi as ea,zi as fa};
|
|
30
|
+
`)}var ve=class{constructor(e){this.sink=e}sink;frameSeq=0;stopped=!1;deadCb=null;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=Wn(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(n){this.die(`replaceTrack: ${n instanceof Error?n.message:String(n)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&this.engage(t)}}stop(){if(!this.stopped){this.stopped=!0,this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let n;try{n=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let i=this.sendPc.addTrack(e);this.sender=i,this.currentTrack=e,this.wireTrackLiveness(e);let s=t.RTCRtpScriptTransform;i.transform=new s(n,{role:"sender"}),!this.negotiatedOnce&&this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=n=>{if(!n.candidate)return;let i=this.candQueue;i!==null&&(i.toRecv.push(n.candidate),this.flushCandidates())},this.recvPc.onicecandidate=n=>{if(!n.candidate)return;let i=this.candQueue;i!==null&&(i.toSend.push(n.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(n=>this.die(`loopback renegotiate: ${n instanceof Error?n.message:String(n)}`))},this.recvPc.ontrack=n=>{let i=n.transceiver?.mid??null;i!==null&&i===this.renderMidOf()&&this.renderRemoteCb?.(n.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),this.negotiatedOnce||this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let n=await e.createOffer();n.sdp=Qt(n.sdp??""),await e.setLocalDescription(n),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:n.sdp});let i=await t.createAnswer();i.sdp=Qt(i.sdp??""),await t.setLocalDescription(i),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:i.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let n=t.context.createMediaStreamDestination();t.connect(n);let i=n.stream.getAudioTracks()[0]??null;return i?(this.nodeBridge={node:t,dest:n},i):(this.die("AudioNode bridge produced no audio track"),null)}catch(n){return this.die(`AudioNode bridge: ${n instanceof Error?n.message:String(n)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([Pn],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let n=t.data;n?.type==="enc"&&n.payload instanceof ArrayBuffer?this.onEncodedFrame(n.rtpTimestamp??0,new Uint8Array(n.payload)):n?.type==="err"&&this.die(`transform: ${n.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let n=Ke(this.frameSeq,e,t,this.sink.maxDatagramSize()||te);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 i of n)this.sink.send(i);this.frameSeq=this.frameSeq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Wn(r){let e=r;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Mn=9e4,xn="avc1.42E01F",On=60,Nn=3,Fn=1e4;function $n(r){return Math.round(r*(Mn/1e6))%2**32>>>0}var we=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 n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let i=++this.generation,s=new n({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,s.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&i===this.generation;){let{value:a,done:d}=await s.read();if(d)break;if(a){if(o||this.stopped||i!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!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(){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:xn,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 i=this.keyframeWanted||this.framesSinceKeyframe>=On;this.keyframeWanted=!1,this.framesSinceKeyframe=i?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:i})}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 n=Ke(this.frameSeq,$n(e.timestamp),t,this.sink.maxDatagramSize()||te,{lane:Ht,keyframe:e.type==="key"});if(n===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 i of n)this.sink.send(i);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(n=>t-n<Fn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=Nn){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(r){return r.byteLength>=2&&r[0]===1&&r[1]===3}var be=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 n=new TextEncoder().encode(e);if(n.byteLength===0||n.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${n.byteLength})`));let i=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+n.byteLength);d[0]=1,d[1]=n.byteLength,d.set(n,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=i.catch(()=>{}),i}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 Yt=250,Bn=25,Hn=2e3,jn=15e3,Vn=1e3,Kn=45e3,Gn=500,zt=10,Qn=2,Yn=2,Ge=2,ye=class r{constructor(e,t,n,i,s,o,a){this.offer=e;this.sessionId=t;this.canvas=n;this.audioLane=i;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 me({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,n=t!==void 0&&t!=="";this.hasVideoLane=n,n&&Be(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(l=>({algorithm:"sha-256",value:Uint8Array.from(atob(l),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let i=await this.wt.createBidirectionalStream();this.writer=i.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=i.readable.getReader(),o=new he,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")),n&&(Be(c.codec,"hello-ack"),this.initDecoder(c.codec,c.width,c.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let l={setSource:h=>{this.renderSource=h,this.audioUplinkLane?.setRenderSource?.(h)},onRemote:h=>{this.renderRemoteCb=h}},u=new ge(this.offer.audio,{...this.audioLane,renderHop:l});try{u.start(),this.audioPlayout=u}catch(h){console.warn(`[urun] WT audio lane failed to start (${h instanceof Error?h.message:String(h)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),u.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let l=this.wt.createUnidirectionalStream?.bind(this.wt);if(!l)throw new Error("WebTransport uni streams are not creatable in this environment");let u=new be({openUniStream:async()=>(await l()).getWriter()});u.onDead(h=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(h)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(l){let u=l instanceof Error?l.message:String(l);console.warn(`[urun] WT data uplink failed to engage (${u}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(u)}this.controlLoop(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(),Gn)),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 ${Yt}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??jn},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Vn))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,n=typeof e.ur=="number"?e.ur:null;if(t===null&&n===null)return;this.gatewayExposesCounters=!0;let i=this.audioDgramsReceived,s=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:n,recvDownlink:i,sentUplink:s},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,d=n!==null&&o.ur!==null?n-o.ur:null,c=i-o.recvDownlink,l=s-o.sentUplink,u="none";if(a!==null&&a>=zt&&c<=0?u="downlink":d!==null&&l>=zt&&d<=0&&(u="uplink"),u==="none"){this.severedStreak="none",this.observePlayoutProgress(c,t);return}if(this.severedStreak!==u){this.severedStreak=u;return}this.severedStreak="none";let h=u==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${l} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+h+` (gateway flow counters ds=${t} ur=${n}, client received=${i} accepted=${s}, confirmed on ${Qn} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let n=this.audioPlayout;if(!n){this.playoutScheduledSeen=null;return}let i=n.playoutProgress(),s=i.surfaced;if(this.playoutScheduledSeen!==null&&i.scheduled>this.playoutScheduledSeen&&s){this.playoutScheduledSeen=i.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=i.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Yn)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,console.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${i.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{n.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=Ge}return}this.playoutStallStreak<Ge||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${i.scheduled} on ${Ge} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let n=performance.now(),i=this.audioLaneLastArrivalAt===null?null:n-this.audioLaneLastArrivalAt,s=this.lastInboundControlAt===null?null:n-this.lastInboundControlAt,o=i===null&&s===null?!0:(i===null||i>=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>=Kn&&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.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,Kt(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,n){let i=globalThis.VideoDecoder;if(typeof i!="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:n};let o=new i({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&&n>0?{codedWidth:t,codedHeight:n}:{},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(n){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${n instanceof Error?n.message:String(n)}`));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,i=>this.onUplinkSendError(i))}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 n=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(i=>n-i<Hn),this.uplinkSendErrorsAt.push(n),!(this.uplinkSendErrorsAt.length<Bn)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSink(e){this.datagramWriter();let t=0;return{send:n=>this.uplinkSend(n,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??te}}engageAudioUplink(){let e=new ve(this.uplinkSink("audio"));e.onDead(t=>this.onUplinkLaneDead("audio",t)),e.onRenderTrack?.(t=>this.renderRemoteCb?.(t)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new we(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(n){let i=n instanceof Error?n.message:String(n);console.warn(`[urun] WT ${t} uplink failed to engage (${i}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,i)}}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.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let n=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,o=i?.builtAt!=null&&Date.now()-i.builtAt>=r.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(o>r.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${n} uplink lane dead (${t}) \u2014 ${r.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 ${r.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`);return}console.warn(`[urun] WT ${n} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${o}/${r.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)},r.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:n}=await e.read();if(n)break;if(!t)continue;if(t.byteLength>=M&&t[11]===pe){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let i=performance.now();if(this.lastArrivalTs>0){let s=i-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(s-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=i,this.reassembler.push(t)}}decodeFrame(e,t,n){let i=globalThis.EncodedVideoChunk;if(typeof i=="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 i({type:t?"key":"delta",timestamp:e*(1e6/24),data:n})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(qt(e)),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),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 n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async readControl(e,t,n=[]){for(;;){let i=n.shift();if(i)return i;let{value:s,done:o}=await e.read();if(o)return null;s&&n.push(...t.push(s))}}async controlLoop(e,t,n){for(;!this.stopped;){let i=await this.readControl(e,t,n);if(!i)break;let s=i;if(this.lastInboundControlAt=performance.now(),s.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(Bt(i.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(),n=(t-e)/1e3;e=t;let i=this.reassembler.drainWindow(),s=i.delivered+i.abandoned;this.lastStats={recvBps:n>0?i.bytes*8/n:0,lossPct:s>0?100*i.abandoned/s:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Yt)}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 Xt=2500,Jt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],zn=1e4,ke=class r{constructor(e,t,n){this.signaling=e;this.sessionId=t;this.opts=n}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",n=typeof e.VideoDecoder=="function",i=this.opts.allowWebTransport??!0,s={webtransport:t&&n&&i,webcodecs:n,codecs:Jt,wtData:t&&n&&i&&this.opts.dataLane!==void 0,wtAudio:t&&n&&i&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&i&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&n&&i&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&n&&i&&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 Qe(c.start(),this.opts.quicDeadlineMs??Xt,"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 u=String(l instanceof Error?l.message:l);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${u}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(u),l}console.warn("[urun] webtransport failed, falling back to webrtc:",l),this.proceedWebRtcDial(`wt failed: ${String(l instanceof Error?l.message:l)}`),this.notifyEstablished("webrtc",String(l instanceof Error?l.message:l))}}if(this.opts.allowWebRtcFallback===!1){let 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 n=this.session,i=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.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="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:Jt,wtData:i,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;let c=this.createWebTransportSession();try{await Qe(c.start(),this.opts.quicDeadlineMs??Xt,"quic connect deadline")}catch(l){throw c.stop().catch(()=>{}),l}if(this.session!==n)return c.stop().catch(()=>{}),null;try{this.engageQuicDataLane(c,i)}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"),n?.stop().catch(()=>{}),c}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let n=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:(i,s)=>n.onData(i,s),onLaneError:i=>n.onLaneError(i)}),n.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 ye(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 n=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),n){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,n)})}redialWtAfterDeath(e){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures+=1,this.wtRedialFailures===r.WT_REDIAL_MAX+1){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${r.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 ${r.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,n=ze(r.WT_REDIAL_BASE_MS,t,r.WT_REDIAL_CAP_MS,t===1?0:void 0);console.warn(`[urun] WT re-dial attempt ${t} scheduled in ${Math.round(n)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},n)}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}/${r.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let n=Ye(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${r.WT_REDIAL_MAX} failed (${n}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${n}`)}}}lateWebRtcFailover(e,t,n){this.disconnected||(async()=>{let i=this.createWebRtc();try{let s=await Qe(this.startWebRtcOn(i),this.opts.webRtcFailoverDeadlineMs??zn,"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(i.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=s instanceof Error?s.message:String(s),a=n?`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 Ye(r){if(r instanceof Error)return r.message;if(typeof r=="string")return r;if(r&&typeof r=="object"){try{let e=JSON.stringify(r);if(e!==void 0&&e!=="{}")return e}catch{}return r.constructor?.name??Object.prototype.toString.call(r).slice(8,-1)}return String(r)}function ze(r,e,t,n){if(n!==void 0)return n;let i=Math.min(r*2**Math.max(0,e-2),t);return Math.round(i*(.75+Math.random()*.5))}function Qe(r,e,t){return new Promise((n,i)=>{let s=setTimeout(()=>i(new Error(t)),e);r.then(o=>{clearTimeout(s),n(o)},o=>{clearTimeout(s),i(o)})})}var Xn=1e4,Se=class{constructor(e,t=Xn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let n=oe();return new Promise((i,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!==n)return;if(clearTimeout(o),a(),d.error){s(new Error(`[urun] ${e} failed: ${String(d.error)}`));return}let{type:c,requestId:l,...u}=d;i(u)});this.carrier.sendSignal({type:e,requestId:n,...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(n=>{n.type===e&&t(n)})}};var Jn="video",_e=class{constructor(e,t=Jn){this.transport=e;this.streamName=t;this.firstMedia=new Promise((n,i)=>{this.firstMediaResolve=n,this.firstMediaReject=i}),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 n=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(n(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(n)})}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 Zt(r){let e=r;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Zn="video";function en(r,e,t){let n=globalThis,i=n.document;if(!(typeof i?.createElement=="function"&&typeof n.WebTransport=="function"&&typeof n.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=r.holdWebRtcDial?.(),a=i.createElement("canvas"),d=!1,c=null,l=!1,u=()=>{if(c){for(let g of c.getVideoTracks())try{g.stop()}catch{}c=null}l&&(l=!1,t.onOverrideTrack(null))},h=new ke(new Se(r),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new _e(r,t.streamName??Zn)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(g,A)=>r.dispatchQuicStreamData(g,A),onQuicLane:()=>r.markStreamDataLaneQuic(),onQuicLaneLost:g=>r.quicStreamDataLaneLost(g),onLaneError:g=>r.raiseQuicStreamDataError(g)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:g=>{d||t.onOverrideAudioTrack(g)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>D(),onMediaTransportLost:g=>{d||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(g),D())},onTransportChange:(g,A)=>{d||(g==="webrtc"&&(u(),D()),t.onTransportChange?.(g,A))}}),y=r.onWtOnlyLegDeath?.(g=>h.failCurrentWtLeg(g)),k=null,_=()=>{k!==null&&(clearInterval(k),k=null)},p=t.wtRetryBaseMs??2e3,b=t.wtRetryCapMs??3e4,v=null,R=0,D=()=>{if(d||v!==null||h.activeTransport==="webtransport")return;let g=ze(p,R+2,b);v=setTimeout(()=>{v=null,R+=1,h.retryWebTransport().then(A=>{if(d){A&&h.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${R})`),R=0,x(A);D()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${R} failed: `+Ye(A)),D())})},g)},T=()=>{v!==null&&(clearTimeout(v),v=null)},x=async g=>{if(d||g.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;_();let O=!1;k=setInterval(()=>{if(d||h.activeTransport!=="webtransport")return;let U=Zt(g);if(!U){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)"),_();return}let I=U.pathLiveness();if(!I.alive){let $=h.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${I.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"),_(),U.fail(`path health: ${I.evidence}`);return}if(!O){if(O=!0,h.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${A}ms \u2014 the QUIC PATH IS HEALTHY (${I.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: ${I.evidence}); webrtc track remains authoritative`)}},A);try{await g.firstMedia}catch(U){_(),console.debug("[urun] webtransport ended before any media flowed:",U);return}if(_(),d||h.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;c=a.captureStream();let j=c.getVideoTracks()[0];j&&(l=!0,t.onOverrideTrack(j))};return(async()=>{let g=await h.connect();if(d){h.disconnect().catch(()=>{});return}await x(g)})().catch(g=>{if(_(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",g);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",g),D();return}o?.proceed(`negotiation unavailable: ${g instanceof Error?g.message:String(g)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",g),D()}),{activeTransport:()=>h.activeTransport,watchDownlinkStall(g){h.watchDownlinkStall(g)},dispose(){d=!0,y?.(),_(),T(),u(),t.onOverrideAudioTrack?.(null),h.disconnect().catch(()=>{})}}}var er=new Set;function Ze(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var tr="rpc",nr="$presence",rr=3e4,tn=3e4,ir="rpc-resp";function sr(r){return`${ir}:${r}`}function Xe(){return oe()}function or(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function ar(r,e,t,n,i,s,o,a,d,c){let l=[],u=null,h=!1,y=null,k=!1,_,p,b=new Promise((f,N)=>{_=f,p=N});b.catch(()=>{});let v=o(),R=null,D=null,T=null,x=null,g=null,A=null,O=!0,j=()=>{T&&(clearTimeout(T),T=null),x&&(x(),x=null)},U=()=>{g&&(clearTimeout(g),g=null),A&&(A(),A=null)},I=!1,$=()=>{I||!k||(I=!0,r.set({rpc:{[e]:null}}))},V=()=>{O=!1,j(),U(),R?.(),R=null,D?.(),D=null,a?.removeEventListener("abort",S),v.dispose(),$()},G=()=>{if(u){if(l.length>0){let f=u;u=null,f.resolve({value:l.shift(),done:!1})}else if(y!==null){let f=u;u=null,f.reject(y)}else if(h){let f=u;u=null,f.resolve({value:void 0,done:!0})}}},rt=f=>{h||(l.push(f),G())},m=f=>{h||(y=f,h=!0,p(f),V(),G())},w=f=>{h||(h=!0,_(f),V(),G())},S=()=>{let f=a?.reason;m(f instanceof Ue?f:new Ie(e))},L=f=>{if(!(h||!f||typeof f!="object"))switch(U(),$(),f.t){case"delta":typeof f.delta=="string"&&rt(f.delta);break;case"response":w(f.body);break;case"error":{let{message:N,code:E}=or(f.body);m(new Ue(N,{requestId:e,code:f.code??E}));break}}},C=()=>{let f=v.messages()[Symbol.asyncIterator]();R=()=>{f.return?.(void 0)};let N=()=>{O&&f.next().then(E=>{if(O){if(E.done){h||w(void 0);return}L(E.value),N()}},E=>{O&&m(E)})};N()},P=()=>{if(!k){if(k=!0,a){if(a.aborted){m(new Ie(e));return}a.addEventListener("abort",S,{once:!0})}D=d?.(f=>m(f))??null,C(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:i,stream:s}}}),c&&c>0&&!r.synced&&(T=setTimeout(()=>{T=null,!h&&!r.synced&&m(new ot(c,e))},c),x=r.onSynced(()=>j())),A=r.onSynced(()=>{A=null,!(h||I||g)&&(g=setTimeout(()=>{g=null,!(h||I)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(tn/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).`)},tn))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(P(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(y!==null){let f=y;return y=null,Promise.reject(f)}return h?Promise.resolve({value:void 0,done:!0}):new Promise((f,N)=>{u={resolve:f,reject:N}})},return(){return h||(h=!0,_(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(f){return h||(h=!0,p(f),V()),Promise.reject(f)}}}},body:b,start:P}}function nn(r){if(r&&typeof r=="object"){let{epoch:e,by:t}=r,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function dr(r,e){let n=r.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:i,rt:s,br:o}=n,a={};(i==="audio"||i==="video"||i==="data")&&(a.kind=i);let d=nn(s);d&&(a.rt=d);let c=nn(o);return c&&(a.br=c),a}var Je=class{constructor(e,t,n,i,s){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=i;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],n=null,i=!1,s=null,o={push(d){if(!i)if(n){let c=n;n=null,c.resolve({value:d,done:!1})}else t.push(d)},end(){if(i=!0,n){let d=n;n=null,d.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{i=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||i)&&(s=e._streamConsumeUnavailableError(d),a(),n)){let c=n;n=null,c.reject(s)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.reject(s):i?Promise.resolve({value:void 0,done:!0}):new Promise((d,c)=>{n={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,n=this._handlers.get("track");if(n)for(let i of n)i(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=dr(t,this._name),i=n?.br;if(i?.by==="runtime")throw new at(this._name,"runtime","browser");if(i)return;let s={br:{epoch:1}};n?.rt&&(s.rt=n.rt);let o=n?.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 $t(t,{track:()=>this.track,onTrack:i=>this.on("track",i)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.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 n of t)n(e)}},Te=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new St;_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,n,i,s,o){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=i,this._artifactsAuth=s,this._streamData=yt(n),this._wireControlDocIncarnation(),this._lifecycleUnsub=Mt(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=Pt({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new ue({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(nr).awareness.setLocalState({role:"client"}),this._activation=new ce({onPhase:a=>this.onPhase(a),hint:()=>this.doc(At).get(Rt)??this.doc("control").get(Et),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 n=await gt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),i=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,s=new ne,o=new ae({url:n.wsUrl,orgId:t.orgId,jwt:i,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,s,o,Ze(t),X({...t,baseUrl:n.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&s.setTarget(o.multiplexer)}),o.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),o.setEndsAt(n.endsAt),re()&&await ie();let d=t.getAccessToken,c=d?async()=>await d()??i:i;return a.setDocTransport({wsUrl:n.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 ct(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=It(this.doc("control"),n=>{for(let i of Array.from(this._generationTickHandlers))try{i(n)}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 Z(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,i)=>t.retain(n,i),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},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 n of this._docs.values())n.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new Je(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 _t(e,this._sessionId,er.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Tt(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=de(e.wsUrl),n=typeof e.token=="function"?"<token-supplier>":e.token??"",i=`${t}\0${n}\0${this._sessionId}`;i!==this._docEndpointKey&&(this._docEndpointKey=i,this.connectDocs(kt({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 n=Xe(),i=new AbortController;t.signal&&(t.signal.aborted?i.abort(t.signal.reason):t.signal.addEventListener("abort",()=>i.abort(t.signal.reason),{once:!0}));let s=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;s=setTimeout(()=>i.abort(new st(d,n)),d)}let o=this._consumeResponse(n,e,!1,i.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{s&&clearTimeout(s),a?.()})}_consumeResponse(e,t,n,i,s){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(tr),a=sr(e);return ar(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),i,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??rr)}requestStream(e,t={}){let n=Xe();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=Xe(),i=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return i.start(),i.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=en(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 Q)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Q);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 i of t)try{i()}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 n=Array.from(this._activeRequests);this._activeRequests.clear();for(let i of n)try{i(new dt)}catch{}for(let i of this._docs.values())i.dispose();this._docs.clear();for(let i of this._streams.values())i.dispose();this._streams.clear(),this._transport.disconnect(e)}};function rn(r){return`urun:session:v2:${r.orgId}:${r.app}:${r.functionName}`}function et(){try{return globalThis.sessionStorage??null}catch{return null}}var tt=new Map;function Ae(r){if(!r)return;let e=r.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof n?.sub=="string"&&n.sub.length>0?n.sub:void 0}catch{return}}function cr(r,e){return r!==void 0&&e!==void 0&&r!==e}function nt(r,e){let t=et(),n=null;if(t)try{let s=t.getItem(r);if(s){let o=JSON.parse(s);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(n={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{n=null}let i=tt.get(r)??n??null;return!i||cr(i.actor,e)?null:i}function sn(r,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};tt.set(r,t);let n=et();if(n)try{n.setItem(r,JSON.stringify(t))}catch{}}function Re(r){tt.delete(r);let e=et();if(e)try{e.removeItem(r)}catch{}}var on=new Set(["paused","acquiring","live"]),lr=new Set(["24h","keep"]);function an(r){if(typeof r!="string"||r.length===0)return null;let e=new Date(r);return Number.isFinite(e.getTime())?e:null}function ur(r){if(typeof r?.id!="string"||r.id.length===0)throw new Le("[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 r.state!="string"||!on.has(r.state))throw new Le(`[urun] session ${r.id} reported an unrecognized state ${JSON.stringify(r.state)} \u2014 this @urun-sh/core build knows only ${[...on].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 r.recordings_expired=="boolean"?e=r.recordings_expired:console.warn(`[urun] session ${r.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:r.id,label:typeof r.label=="string"&&r.label.length>0?r.label:null,state:r.state,app:typeof r.app=="string"?r.app:"",functionName:typeof r.function=="string"?r.function:"",createdAt:an(r.created_at),lastActiveAt:an(r.last_active_at),archived:r.archived===!0,preview:typeof r.preview=="string"&&r.preview.length>0?r.preview:null,recordingsExpired:e,retention:lr.has(r.retention)?r.retention:(r.retention!==void 0&&console.warn(`[urun] session ${r.id} reported an unrecognized retention ${JSON.stringify(r.retention)} \u2014 defaulting to '24h'`),"24h")}}var Ee=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:n}=await pt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(ur),nextCursor:n}}async end(e){await ft({...this._request,sessionId:e})}async archive(e){await We({...this._request,sessionId:e,archived:!0})}async unarchive(e){await We({...this._request,sessionId:e,archived:!1})}async setName(e,t,n={}){await mt({...this._request,sessionId:e,name:t,source:n.source})}};function dn(r,e,t){let n=Ae(t);sn(r,n!==void 0?{sessionId:e,actor:n}:{sessionId:e})}var hr=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function zi(r,e){return new Ee(r,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function Xi(r,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,n){if(!(hr.has(n)||typeof n!="string"))return(i,s)=>{let o=i??{},a=rn({orgId:e.orgId,app:r,functionName:n}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,c,l=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,u=l(),h=e.jwt,y=e.getAccessToken?async m=>{let w=await e.getAccessToken(m);return w&&(h=w),w}:void 0,k={...e,getAccessToken:y},_=new ne,p=new ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:u,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),b=new Te(u,_,p,Ze(k),X(k),{activity:s?.activity}),v,R=!1,D=!1,T,x,g=new Promise(m=>{x=m}),A,O=m=>{m.sessionId||T||(T="teardown",A="ticket",Ce({baseUrl:m.baseUrl,requestId:m.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider}))},j=m=>{T||m.sessionId||(T="abandon",Ce({baseUrl:m.baseUrl,requestId:m.requestId,orgId:e.orgId,jwt:h,authProvider:e.authProvider,reason:"client_abandoned"}))},U=m=>{let w=m.sessionId||!c?m:{...m,sessionId:c};v=w,x({status:"ready",handle:w}),(D||T==="teardown")&&O(w)};b.setEndHandler(async()=>{let m=v?{status:"ready",handle:v}:await g;if(m.status==="unavailable")throw new Q("[urun] session allocation failed before a releasable request was created",{cause:m.cause});let w=v??m.handle;return Re(a),T==="teardown"?w.sessionId?{status:"paused",sessionId:w.sessionId,reason:"client_ended"}:{status:"canceled",requestId:w.requestId}:(T="end",w.sessionId?ut({baseUrl:w.baseUrl,sessionId:w.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:y,authProvider:e.authProvider}):Pe({baseUrl:w.baseUrl,requestId:w.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:y,authProvider:e.authProvider}))}),b.setCancelHandler(async()=>{let m=v?{status:"ready",handle:v}:await g;if(m.status==="unavailable")throw new Q("[urun] session allocation failed before a cancellable request was created",{cause:m.cause});let w=v??m.handle;if(w.sessionId)throw new it(`[urun] cancel() is for a queued admission request, but this call already has session ${w.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:w.sessionId,code:"cancel_on_live_session"});T="end";try{let S=await Pe({baseUrl:w.baseUrl,requestId:w.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:y,authProvider:e.authProvider});return Re(a),S}catch(S){throw T==="end"&&(T=void 0),S}});let I=async m=>{let w,S=s?.sessionId??e.sessionKey??c,L,C;if(S===void 0&&!d){let E=nt(a);if(E?.sessionId){if(C=Ae(h),E.actor!==void 0&&C===void 0&&y){let De=await Promise.resolve(y()).catch(()=>{});C=Ae(De??e.jwt)}L=E.actor!==void 0&&C!==void 0&&E.actor!==C?void 0:E.sessionId}}let P=S??L,B=(E,De)=>ht({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:y,authProvider:e.authProvider,idempotencyKey:E,sessionKey:De,label:s?.label,...s?.sharedApp?{sharedApp:!0}:{},priority:e.priority,onAdmission:H=>{p.reportAdmission(H),H.sessionId&&!c&&(c=H.sessionId,w=H.sessionId,v&&v.sessionId!==H.sessionId&&U({...v,sessionId:H.sessionId}),R||(e.sessionKey||dn(a,H.sessionId,h),b.setSessionId(H.sessionId)))},onRequest:U}),f;try{f=await B(m,P)}catch(E){if(L===void 0||!(E instanceof Y)||E.code!=="session_name_not_yours")throw E;console.warn(`[urun] session_name_not_yours: the control plane refused session ${L} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),nt(a,C)?.sessionId===L&&Re(a),f=await B(l(),void 0)}let N=y?await y()??void 0:e.jwt;if(w&&w!==f.sessionId)throw v&&v.sessionId!==f.sessionId&&U({...v,sessionId:f.sessionId}),new Y(`Gateway contract violation: admission minted session ${w} but allocation completed as ${f.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return c=f.sessionId,v&&v.sessionId!==f.sessionId&&U({...v,sessionId:f.sessionId}),R||(e.sessionKey||dn(a,f.sessionId,h),b.setSessionId(f.sessionId),b.setArtifactsAuth(X({...k,baseUrl:f.baseUrl})),p.setEndsAt(f.endsAt),p.seedRegion(vt(f.response))),{url:f.wsUrl,sessionId:f.sessionId,jwt:N,iceServers:f.response.ice_servers,endsAt:f.endsAt}},$,V=y?async()=>await y()??$:()=>$,G=()=>{let m=p.connectedUrl;return m?de(m):void 0};if(p.setConnectionResolver(async()=>{let m=await I(l());return $=m.jwt,m}),p.on("connected",()=>{p.multiplexer&&_.setTarget(p.multiplexer);let m=p.connectedUrl;m&&b.setDocTransport({wsUrl:m,token:V,resolveServerUrl:G})}),(async m=>{let w;try{w=await I(m)}catch(S){if(R){x({status:"unavailable",cause:S});return}console.error(`[urun] Failed to create session for ${n}:`,S),v&&j(v);let L=S instanceof Error?S:new Error(String(S)),C=S instanceof Y?S.httpStatus:void 0,P=S instanceof Y?S.code:void 0,B=S instanceof Y?S.retryAfterSeconds:void 0;p.reportAllocationFailure(L,C,P,B),x({status:"unavailable",cause:S});return}R||(p.setAuth({jwt:w.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:w.url,sessionId:w.sessionId,iceServers:w.iceServers}),re()&&await ie(),$=w.jwt,b.setDocTransport({wsUrl:w.url,token:V,resolveServerUrl:G}),await p.connect({app:r,functionName:n,args:o}),b.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(u).catch(m=>{console.error(`[urun] Failed to connect session for ${n}:`,m)}),e.releaseOnLeave!==!1){let m=xt(()=>{if(R=!0,p.leaveLeg())return;if(p.connectedUrl!==null){p.disconnect();return}p.disconnect();let P=v;P?O(P):D=!0});b.onDisconnect(m);let w,S,L=!1,C=()=>{L||(L=!0,w?.(),S?.())};g.then(P=>{P.status!=="ready"||L||(w=Ot(()=>v!==void 0))}),S=b.onPhase(P=>{let B=P?.name;(B==="paused"||B==="error")&&C()}),L&&S(),b.onDisconnect(C)}return b}}})}export{pr as a,fr as b,mr as c,At as d,Rt as e,Et as f,cn as g,ce as h,W as i,Me as j,xe as k,wr as l,z as m,F as n,le as o,Oe as p,Ne as q,Fe as r,$e as s,J as t,Ut as u,yr as v,Z as w,kr as x,_r as y,Tr as z,It as A,gn as B,vn as C,Rr as D,Ct as E,Pt as F,wn as G,bn as H,Dr as I,ue as J,Ur as K,Mt as L,xt as M,Ot as N,Ft as O,_n as P,qt as Q,he as R,M as S,fe as T,jt as U,me as V,Ln as W,He as X,Kt as Y,ye as Z,ke as _,Se as $,_e as aa,rr as ba,Te as ca,Ee as da,zi as ea,Xi as fa};
|