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