@urun-sh/core 0.5.5 → 0.6.0
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/CHANGELOG.md +19 -0
- package/dist/adapter/index.d.mts +41 -0
- package/dist/adapter/index.d.ts +41 -0
- package/dist/adapter/index.js +7 -0
- package/dist/adapter/index.mjs +2 -0
- package/dist/adapter/test-util.d.mts +32 -0
- package/dist/adapter/test-util.d.ts +32 -0
- package/dist/adapter/test-util.js +1 -0
- package/dist/adapter/test-util.mjs +2 -0
- package/dist/app-7GEM2YU2.mjs +2 -0
- package/dist/{chunk-STXAJ5OB.mjs → chunk-6UCN2ZJF.mjs} +5 -5
- package/dist/chunk-AL3FYYQK.mjs +3 -0
- package/dist/chunk-NLAOQUYQ.mjs +2 -0
- package/dist/chunk-NYZRQF75.mjs +2 -0
- package/dist/index.browser.d.mts +27 -12
- package/dist/index.browser.d.ts +27 -12
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +27 -12
- package/dist/index.d.ts +27 -12
- package/dist/index.js +5 -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 +2 -2
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +5 -5
- package/dist/internal.mjs +1 -1
- package/dist/stream-data-Cewea7lG.d.mts +1717 -0
- package/dist/stream-data-Cewea7lG.d.ts +1717 -0
- package/dist/{stream-data-77pUfFQK.d.mts → stream-data-s7maju0w.d.mts} +5 -0
- package/dist/{stream-data-77pUfFQK.d.ts → stream-data-s7maju0w.d.ts} +5 -0
- package/package.json +12 -2
- package/dist/chunk-JFRHVRUS.mjs +0 -3
package/dist/index.browser.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as Hr,A as Fr,B as qr,C as X,D as xt,E as Se,F as Ye,G as Ot,H as Wt,I as Nt,J as Qe,K as Ft,L as qt,M as $r,N as $t,O as ke,R as _e,S as Te,T as Xe,U as jr,V as Je,X as jt,Z as Br,_ as Vr,a as Mt,aa as Gr,b as ve,ba as Ae,c as G,d as Be,da as Ee,e as be,ea as Bt,f as we,fa as Vt,g as Ve,ga as Ht,h as He,ha as Gt,i as Ge,j as Er,k as Rr,l as ye,m as Ke,n as Ir,o as Cr,p as Dr,q as Pr,r as K,s as Ur,t as Lr,u as Mr,v as ze,w as xr,x as Or,y as Wr,z as Nr}from"./chunk-JFRHVRUS.mjs";var Kr=15e3,zr=45e3,Yr=12e4,Ze="platform",et="activation",tt="desired.activation";function Kt(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 Qr=[{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 Qr){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=Kt(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)}},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 Xr(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=Yt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new D("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(zt)}async getDownloadUrl(e,t){let r=Yt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!Zr(n))throw new D("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:zt(r.artifact),downloadUrl:n}}async _request(e,t){let r=xt(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&&en(n.status))throw n}throw n??new D("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${X(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 tn(o.status,a,d)}try{return await o.json()}catch(a){throw new D(`[urun] runtime artifacts: invalid JSON response from ${X(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=X(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 zt(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=Jr(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 Jr(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function Zr(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function en(i){return i===401||i===403}function tn(i,e,t){return i===401?new Re(t,e):i===404?new Ie(t,e):new D(t,i,e)}function Yt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new D("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var x=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 x{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 x{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 x{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 x{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)}},Ue=class extends x{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 x{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 rt(i){return/^(\d+[smhdw])+$/.test(i)}function rn(i){if(i==="pin")return{action:"pin"};if(rt(i))return{action:"retain",duration:i};throw new J(`[urun] recordings: "${i}" is not a duration or "pin"`)}function nn(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 Ue(r,e)}return new x(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(!rt(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 x("[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 nn(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 sn(i){return new Z(i)}var on=1e3,an=12e3;function nt(i,e,t={}){let r=null,n=0,s=0,o=null,a=-1,d=()=>{let f=i.get("desired.billing.generationSeconds");if(typeof f!="number"||!Number.isFinite(f)||f<=0)return null;let v=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:f,epoch:typeof v=="number"&&Number.isFinite(v)?v:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},u=()=>{if(r===null)return null;let f=Math.min(Math.max(0,Date.now()-n),s);return r+f/1e3},c=()=>{let f=t.creditsPerSecond;if(typeof f=="number"&&Number.isFinite(f)&&f>0)return f;let v=i.get("desired.billing.creditsPerSecond");return typeof v=="number"&&Number.isFinite(v)&&v>0?v:null},l=()=>{let f=u();if(f===null)return;let v=Math.floor(f);if(v<=a)return;a=v;let w={seconds:v},T=c();T!==null&&(w.estimatedCredits=v*T),e(w)},p=f=>{n=Date.now();let v=f===null?0:Math.max(0,n-f);s=Math.max(0,12e3-v)},m=()=>{let f=d();if(f!==null){if(o!==null&&f.epoch!==o){o=f.epoch,r=f.seconds,a=-1,p(f.updatedAtMs),l();return}r!==null&&f.seconds<=r||(o=f.epoch,r=f.seconds,p(f.updatedAtMs),l())}};m();let h=i.on("change",m),k=setInterval(l,1e3);return k.unref?.(),()=>{clearInterval(k),h()}}var Qt="activity",Xt="visibility",dn=15e3,it=["pointerdown","pointermove","keydown","wheel","touchstart"];function st(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 p=e();if(!(o!==void 0&&p-o<15e3)){o=p;try{i.awareness.setLocalStateField(Qt,{at:p})}catch{}}},d=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(Xt,n.visibilityState)}catch{}},u=()=>a(),c=()=>{d(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(r)for(let p of it)r.addEventListener(p,u,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",c);let l=null;return!t&&i.isProducing&&(l=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),l.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,r)for(let p of it)r.removeEventListener(p,u,{capture:!0});n&&n.removeEventListener("visibilitychange",c),l&&(clearInterval(l),l=null)}}}}var Zt="user_activity",er="focus",cn=3e4;function Jt(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(Jt(e.state));let t=e.on("stateChange",n=>{this._setState(Jt(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(er,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(Zt,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 un=250;function ot(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 at(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 dt(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 tr="video/mp4";function ct(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,s=!1,o=(a,d,u)=>{let c=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!c)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 l=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(tr)?tr:void 0),p=new MediaStream([a]),m=new c(p,l?{mimeType:l}:void 0);r=m;let h=Promise.resolve();m.ondataavailable=k=>{let f=k.data;s||!f||f.size===0||(h=h.then(async()=>{let v=new Uint8Array(await f.arrayBuffer());s||d(v)}))},m.onstop=()=>{h.then(()=>{s||u()})},m.onerror=()=>{h.then(()=>{s||u()})},m.start(t)};return{start(a,d){if(r||s)return;let u=i.track();if(u){o(u,a,d);return}n=i.onTrack(c=>{!c||r||s||(n?.(),n=null,o(c,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 ln(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 rr(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 ln(s)}import{encode as pn,decode as fn}from"@msgpack/msgpack";var nr=65536;function lt(i){let e=pn(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>nr)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(fn(n))}return t}},P=12,ut=1,mn=0,Le=1,ir=2;function ae(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&ut)===ut,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function pt(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?ut:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??mn),e}var hn=100,sr=100,de=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??hn}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-sr?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-sr}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 gn=/^avc[13]\.[0-9a-fA-F]{6}$/;function vn(i){return gn.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 ft(i,e){let t=vn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var or=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!==or)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=Je(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===Xe&&(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 mt(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&bn(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function bn(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 ht=40,vt=48e3,wn=64,yn=100,gt=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-yn)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>wn;){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}},Sn=3,kn=1e4,xe=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??ht;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${ht}ms`),r=ht),this.targetS=Math.max(0,r)/1e3}config;seam;decoder=null;decoderErrorsAt=[];ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;deadCb=null;assembler=new gt(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}}onDead(e){this.deadCb=e}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){this.decoder=new e({output:t=>this.schedule(t),error:t=>this.onDecoderError(t)}),this.decoder.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels})}decodeFrame(e){let t=globalThis.EncodedAudioChunk;!this.decoder||typeof t!="function"||this.stopped||this.decoder.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/vt)),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 c=r.stream.getAudioTracks()[0];c&&this.seam.onTrack(c)}let n=e.numberOfFrames,s=Math.max(1,e.numberOfChannels),o=t.createBuffer(s,n,e.sampleRate);for(let c=0;c<s;c++){let l=new Float32Array(n);e.copyTo(l,{planeIndex:c,format:"f32-planar"}),o.copyToChannel(l,c)}let a=n/e.sampleRate;e.close();let d=t.createBufferSource();d.buffer=o,d.connect(r);let u=Math.max(this.playhead,t.currentTime+this.targetS);d.start(u),this.playhead=u+a}onDecoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(n=>t-n<kn),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=Sn){let n=`audio decoder: ${e.message}`;console.warn(`[urun] WT audio lane dead (${n}) \u2014 audio reverts to the WebRTC track`),this.stop(),this.deadCb?.(n);return}console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=globalThis.AudioDecoder;typeof r=="function"&&this.initDecoder(r)}};var ce=1200,_n=3,Tn=1e4;function An(i){return Math.round(i*(vt/1e6))%2**32>>>0}function bt(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 u=t.subarray(d*s,Math.min((d+1)*s,t.byteLength)),c=pt({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:d,fragCount:o,lane:n?.lane??Le}),l=new Uint8Array(P+u.byteLength);l.set(c,0),l.set(u,P),a.push(l)}return a}var Oe=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(En(e)){let d=e,u=d.context.createMediaStreamDestination();d.connect(u),this.nodeBridge={node:d,dest:u};let c=u.stream.getAudioTracks()[0];if(!c){this.die("AudioNode bridge produced no audio track");return}n=c}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:u}=await o.read();if(u)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=bt(this.frameSeq,An(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<Tn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=_n){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let r=globalThis.AudioEncoder;if(!(typeof r!="function"||!this.encoderConfig))try{this.initEncoder(r)}catch(n){this.die(`encoder re-init: ${n instanceof Error?n.message:String(n)}`)}}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function En(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Rn=9e4,In="avc1.42E01F",Cn=60,Dn=3,Pn=1e4;function Un(i){return Math.round(i*(Rn/1e6))%2**32>>>0}var We=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let 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:In,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>=Cn;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=bt(this.frameSeq,Un(e.timestamp),t,this.sink.maxDatagramSize()||ce,{lane:ir,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<Pn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=Dn){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 Ln(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),Ln(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 wt=250,Mn=3,xn=1e4,yt=2500,On=25,Wn=2e3,ue=class{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,u)=>{this.firstFrameResolve=d,this.firstFrameReject=u}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;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;videoArrivedEver=!1;videoArrivalsInWindow=0;frameOutputEver=!1;frameOutputsInWindow=0;decodeStalledMs=0;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&&ft(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&&(ft(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);c.onDead(()=>{this.audioPlayout=null});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()}}let u=()=>{this.datagramWriter();let c=0;return{send:l=>this.uplinkSend(l,()=>{c++}),delivered:()=>c,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??ce}};if(this.offer.audioUp===!0&&this.audioUplink)try{let c=new Oe(u());c.onDead(l=>{this.audioUplinkLane=null,this.audioUplink.onUplinkLost(l)}),this.audioUplinkLane=c,this.audioUplink.onUplink(c)}catch(c){let l=c instanceof Error?c.message:String(c);console.warn(`[urun] WT mic uplink failed to engage (${l}) \u2014 keeping the WT session; the mic stays on the WebRTC produce path`),this.audioUplink.onUplinkLost(l)}if(this.offer.videoUp===!0&&this.videoUplink)try{let c=new We(u());c.onDead(l=>{this.videoUplinkLane=null,this.videoUplink.onUplinkLost(l)}),this.videoUplinkLane=c,this.videoUplink.onUplink(c)}catch(c){let l=c instanceof Error?c.message:String(c);console.warn(`[urun] WT video uplink failed to engage (${l}) \u2014 keeping the WT session; the camera stays on the WebRTC produce path`),this.videoUplink.onUplinkLost(l)}if(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(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p)}),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 ${wt}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}async stop(){this.stopped=!0,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){let t=this.audioUplinkLane;t&&(this.audioUplinkLane=null,t.stop(),this.audioUplink?.onUplinkLost(e));let r=this.videoUplinkLane;r&&(this.videoUplinkLane=null,r.stop(),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,mt(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},this.decoder=new n({output:o=>{this.frameOutputEver=!0,this.frameOutputsInWindow++,this.canvas.width=o.displayWidth,this.canvas.height=o.displayHeight,s.drawImage(o,0,0),o.close()},error:o=>this.onDecoderError(o)}),this.decoder.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(e){if(this.stopped||this.deadFired)return;let t=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(n=>t-n<xn),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=Mn){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(n){this.die(`decoder re-init: ${n instanceof Error?n.message:String(n)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}evaluateDecodeLiveness(e,t){if(!this.videoArrivedEver)return!1;if(t>0)return this.decodeStalledMs=0,!1;if(e>0||!this.frameOutputEver)this.decodeStalledMs+=wt;else return this.decodeStalledMs=0,!1;return this.decodeStalledMs<yt?!1:(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${yt}ms \u2014 broken WT media leg; failing over LOUDLY`),this.die(`decode-stall: datagrams flowing but nothing decoded within ${yt}ms`),!0)}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<Wn),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<On)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}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]===Le){this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;this.videoArrivedEver=!0,this.videoArrivalsInWindow++;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;!this.decoder||typeof n!="function"||(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(lt(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;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=this.videoArrivalsInWindow,o=this.frameOutputsInWindow;if(this.videoArrivalsInWindow=0,this.frameOutputsInWindow=0,this.evaluateDecodeLiveness(s,o))return;let a=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:a>0?100*n.abandoned/a:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},wt)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,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 ar=2500,dr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Nn=1e4,le=class{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;get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,s={webtransport:t&&r&&n,webcodecs:r,codecs:dr,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 u=null;try{return u=this.createWebTransportSession(),await St(u.start(),this.opts.quicDeadlineMs??ar,"quic connect deadline"),this.engageQuicDataLane(u,s.wtData===!0),this.session=u,d&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){if(u?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let l=String(c instanceof Error?c.message:c);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${l}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(l),c}console.warn("[urun] webtransport failed, falling back to webrtc:",c),this.proceedWebRtcDial(`wt failed: ${String(c instanceof Error?c.message:c)}`),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}if(this.opts.allowWebRtcFallback===!1){let u=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${u} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(u),new Error(`[urun] WT required but unavailable: ${u}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){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:dr,wtData:n,wtAudio:s,wtAudioUp:o,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;let u=this.createWebTransportSession();try{await St(u.start(),this.opts.quicDeadlineMs??ar,"quic connect deadline")}catch(c){throw u.stop().catch(()=>{}),c}if(this.session!==r)return u.stop().catch(()=>{}),null;try{this.engageQuicDataLane(u,n)}catch(c){throw u.stop().catch(()=>{}),c}this.session=u;{let c=this.offer.webtransport;c&&(this.opts.audioLane===void 0||c.audio!==void 0)&&(this.opts.audioUplink===void 0||c.audioUp===!0)&&(this.opts.videoUplink===void 0||c.videoUp===!0)&&(this.opts.dataLane===void 0||c.data===!0)&&(this.opts.dataUplink===void 0||c.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(()=>{}),u}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(n,s)=>r.onData(n,s),onLaneError:n=>r.onLaneError(n)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new ue(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;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;r&&this.proceedWebRtcDial(`failover: ${t}`),console.warn(r?"[urun] quic died mid-session on a WT-only leg (no RTCPeerConnection) \u2014 attempting a late WebRTC dial from scratch:":"[urun] quic died mid-session, failing over to webrtc:",t),this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),(async()=>{let n=this.createWebRtc();try{let s=await St(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Nn,"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){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 Fn=1e4,pe=class{constructor(e,t=Fn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;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:u,requestId:c,...l}=d;n(l)});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 qn="video",fe=class{constructor(e,t=qn){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 cr(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var $n="video";function ur(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,u=null,c=!1,l=()=>{if(u){for(let S of u.getVideoTracks())try{S.stop()}catch{}u=null}c&&(c=!1,t.onOverrideTrack(null))},p=new le(new pe(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new fe(i,t.streamName??$n)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(S,A)=>i.dispatchQuicStreamData(S,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:S=>i.quicStreamDataLaneLost(S),onLaneError:S=>i.raiseQuicStreamDataError(S)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:S=>{d||t.onOverrideAudioTrack(S)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>T(),onMediaTransportLost:S=>{d||(l(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(S),T())},onTransportChange:(S,A)=>{d||(S==="webrtc"&&(l(),T()),t.onTransportChange?.(S,A))}}),m=null,h=()=>{m!==null&&(clearInterval(m),m=null)},k=t.wtRetryBaseMs??2e3,f=t.wtRetryCapMs??3e4,v=null,w=0,T=()=>{if(d||v!==null||p.activeTransport==="webtransport")return;let S=Math.min(k*2**w,f);v=setTimeout(()=>{v=null,w+=1,p.retryWebTransport().then(A=>{if(d){A&&p.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${w})`),w=0,R(A);T()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${w} failed:`,A),T())})},S)},O=()=>{v!==null&&(clearTimeout(v),v=null)},R=async S=>{if(d||S.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;h();let M=!1;m=setInterval(()=>{if(d||p.activeTransport!=="webtransport")return;let N=cr(S);if(!N){console.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),h();return}let U=N.pathLiveness();if(!U.alive){let F=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${U.evidence}`+(F?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),h(),N.fail(`path health: ${U.evidence}`);return}if(!M){if(M=!0,p.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 S.firstMedia}catch(N){h(),console.debug("[urun] webtransport ended before any media flowed:",N);return}if(h(),d||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;u=a.captureStream();let W=u.getVideoTracks()[0];W&&(c=!0,t.onOverrideTrack(W))};return(async()=>{let S=await p.connect();if(d){p.disconnect().catch(()=>{});return}await R(S)})().catch(S=>{if(h(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",S);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",S),T();return}o?.proceed(`negotiation unavailable: ${S instanceof Error?S.message:String(S)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",S),T()}),{activeTransport:()=>p.activeTransport,dispose(){d=!0,h(),O(),l(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var jn=new Set;function Tt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var Bn="rpc",fr=3e4,lr=3e4,Vn="rpc-resp";function Hn(i){return`${Vn}:${i}`}function kt(){return Te()}function Gn(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 Kn(i,e,t,r,n,s,o,a,d,u){let c=[],l=null,p=!1,m=null,h=!1,k,f,v=new Promise((y,C)=>{k=y,f=C});v.catch(()=>{});let w=o(),T=null,O=null,R=null,S=null,A=null,M=null,W=!0,N=()=>{R&&(clearTimeout(R),R=null),S&&(S(),S=null)},U=()=>{A&&(clearTimeout(A),A=null),M&&(M(),M=null)},F=!1,V=()=>{F||!h||(F=!0,i.set({rpc:{[e]:null}}))},H=()=>{W=!1,N(),U(),T?.(),T=null,O?.(),O=null,a?.removeEventListener("abort",_),w.dispose(),V()},Q=()=>{if(l){if(c.length>0){let y=l;l=null,y.resolve({value:c.shift(),done:!1})}else if(m!==null){let y=l;l=null,y.reject(m)}else if(p){let y=l;l=null,y.resolve({value:void 0,done:!0})}}},Lt=y=>{p||(c.push(y),Q())},g=y=>{p||(m=y,p=!0,f(y),H(),Q())},b=y=>{p||(p=!0,k(y),H(),Q())},_=()=>{let y=a?.reason;g(y instanceof we?y:new ye(e))},L=y=>{if(!(p||!y||typeof y!="object"))switch(U(),V(),y.t){case"delta":typeof y.delta=="string"&&Lt(y.delta);break;case"response":b(y.body);break;case"error":{let{message:C,code:j}=Gn(y.body);g(new we(C,{requestId:e,code:y.code??j}));break}}},$=()=>{let y=w.messages()[Symbol.asyncIterator]();T=()=>{y.return?.(void 0)};let C=()=>{W&&y.next().then(j=>{if(W){if(j.done){p||b(void 0);return}L(j.value),C()}},j=>{W&&g(j)})};C()},I=()=>{if(!h){if(h=!0,a){if(a.aborted){g(new ye(e));return}a.addEventListener("abort",_,{once:!0})}O=d?.(y=>g(y))??null,$(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:s}}}),u&&u>0&&!i.synced&&(R=setTimeout(()=>{R=null,!p&&!i.synced&&g(new He(u,e))},u),S=i.onSynced(()=>N())),M=i.onSynced(()=>{M=null,!(p||F||A)&&(A=setTimeout(()=>{A=null,!(p||F)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(lr/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).`)},lr))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(I(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(m!==null){let y=m;return m=null,Promise.reject(y)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((y,C)=>{l={resolve:y,reject:C}})},return(){return p||(p=!0,k(void 0),H()),Promise.resolve({value:void 0,done:!0})},throw(y){return p||(p=!0,f(y),H()),Promise.reject(y)}}}},body:v,start:I}}function pr(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 zn(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=pr(s);d&&(a.rt=d);let u=pr(o);return u&&(a.br=u),a}var _t=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 u=r;r=null,u.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 u=r;r=null,u.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,u)=>{r={resolve:d,reject:u}})},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=zn(t,this._name),n=r?.br;if(n?.by==="runtime")throw new Ge(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??ct;return rr(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},me=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new 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;_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=ot(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=st({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._activation=new re({onPhase:a=>this.onPhase(a),hint:()=>this.doc(Ze).get(et)??this.doc("control").get(tt),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 qt({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,Tt(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 _e();let d=t.getAccessToken,u=d?async()=>await d()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:u}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return ze(this,e)}on(e,t){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(t),this._generationTickStop||(this._generationTickStop=nt(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 _t(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 Ht(e,this._sessionId,jn.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=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(Bt({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=kt(),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 Ve(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(Bn),a=Hn(e);return Kn(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??fr)}requestStream(e,t={}){let r=kt();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=kt(),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=ur(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}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??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 G)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new G);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 Ke)}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 mr(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function At(){try{return globalThis.sessionStorage??null}catch{return null}}function Et(i){let e=At();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let r=JSON.parse(t);return typeof r?.sessionId!="string"||r.sessionId.length===0?null:{sessionId:r.sessionId}}catch{return null}}function Rt(i,e){let t=At();if(t)try{t.setItem(i,JSON.stringify({sessionId:e.sessionId}))}catch{}}function Fe(i){let e=At();if(e)try{e.removeItem(i)}catch{}}var hr=new Set(["paused","acquiring","live"]),Yn=new Set(["24h","keep"]);function gr(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function Qn(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"||!hr.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 ${[...hr].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:gr(i.created_at),lastActiveAt:gr(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:Yn.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 he=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await Nt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(Qn),nextCursor:r}}async end(e){await Ft({...this._request,sessionId:e})}async archive(e){await Qe({...this._request,sessionId:e,archived:!0})}async unarchive(e){await Qe({...this._request,sessionId:e,archived:!1})}};var Xn=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Jn(i,e){return new he(i,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function Zn(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(!(Xn.has(r)||typeof r!="string"))return(n,s)=>{let o=n??{},a=mr({orgId:e.orgId,app:i,functionName:r}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,u,c=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,l=c(),p=e.jwt,m=e.getAccessToken?async g=>{let b=await e.getAccessToken(g);return b&&(p=b),b}:void 0,h={...e,getAccessToken:m},k=new ve,f=new Ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:l,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),v=new me(l,k,f,Tt(h),ne(h),{activity:s?.activity}),w,T=!1,O=!1,R,S,A=new Promise(g=>{S=g}),M,W=g=>{let b=g.sessionId?"session":"ticket";R&&!(R==="teardown"&&M==="ticket"&&b==="session")||(R="teardown",M=b,Se({baseUrl:g.baseUrl,requestId:g.requestId,...g.sessionId?{sessionId:g.sessionId}:{},orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},N=g=>{R||(R="abandon",Se({baseUrl:g.baseUrl,requestId:g.requestId,...g.sessionId?{sessionId:g.sessionId}:{},orgId:e.orgId,jwt:p,authProvider:e.authProvider,...g.sessionId?{}:{reason:"client_abandoned"}}))},U=g=>{let b=g.sessionId||!u?g:{...g,sessionId:u};w=b,S({status:"ready",handle:b}),(O||R==="teardown")&&W(b)};v.setEndHandler(async()=>{let g=w?{status:"ready",handle:w}:await A;if(g.status==="unavailable")throw new G("[urun] session allocation failed before a releasable request was created",{cause:g.cause});let b=w??g.handle;return Fe(a),R==="teardown"?b.sessionId?{status:"paused",sessionId:b.sessionId,reason:"client_ended"}:{status:"canceled",requestId:b.requestId}:(R="end",b.sessionId?Ot({baseUrl:b.baseUrl,sessionId:b.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider}):Ye({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider}))}),v.setCancelHandler(async()=>{let g=w?{status:"ready",handle:w}:await A;if(g.status==="unavailable")throw new G("[urun] session allocation failed before a cancellable request was created",{cause:g.cause});let b=w??g.handle;if(b.sessionId)throw new Be(`[urun] cancel() is for a queued admission request, but this call already has session ${b.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:b.sessionId,code:"cancel_on_live_session"});R="end";try{let _=await Ye({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider});return Fe(a),_}catch(_){throw R==="end"&&(R=void 0),_}});let F=async g=>{let b,_=s?.sessionId??e.sessionKey??u,L=_===void 0&&!d?Et(a)?.sessionId:void 0,$=_??L,I=(C,j)=>Wt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:m,authProvider:e.authProvider,idempotencyKey:C,sessionKey:j,label:s?.label,priority:e.priority,onAdmission:B=>{f.reportAdmission(B),B.sessionId&&!u&&(u=B.sessionId,b=B.sessionId,w&&w.sessionId!==B.sessionId&&U({...w,sessionId:B.sessionId}),T||(e.sessionKey||Rt(a,{sessionId:B.sessionId}),v.setSessionId(B.sessionId)))},onRequest:U}),E;try{E=await I(g,$)}catch(C){if(L===void 0||!(C instanceof K)||C.code!=="session_name_not_yours")throw C;Et(a)?.sessionId===L&&Fe(a),E=await I(c(),void 0)}let y=m?await m()??void 0:e.jwt;if(b&&b!==E.sessionId)throw w&&w.sessionId!==E.sessionId&&U({...w,sessionId:E.sessionId}),new K(`Gateway contract violation: admission minted session ${b} but allocation completed as ${E.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return u=E.sessionId,w&&w.sessionId!==E.sessionId&&U({...w,sessionId:E.sessionId}),T||(e.sessionKey||Rt(a,{sessionId:E.sessionId}),v.setSessionId(E.sessionId),v.setArtifactsAuth(ne({...h,baseUrl:E.baseUrl})),f.setEndsAt(E.endsAt),f.seedRegion($t(E.response))),{url:E.wsUrl,sessionId:E.sessionId,jwt:y,iceServers:E.response.ice_servers,endsAt:E.endsAt}},V,H=m?async()=>await m()??V:()=>V,Q=()=>{let g=f.connectedUrl;return g?Ee(g):void 0};if(f.setConnectionResolver(async()=>{let g=await F(c());return V=g.jwt,g}),f.on("connected",()=>{f.multiplexer&&k.setTarget(f.multiplexer);let g=f.connectedUrl;g&&v.setDocTransport({wsUrl:g,token:H,resolveServerUrl:Q})}),(async g=>{let b;try{b=await F(g)}catch(_){if(T){S({status:"unavailable",cause:_});return}console.error(`[urun] Failed to create session for ${r}:`,_),w&&N(w);let L=_ instanceof Error?_:new Error(String(_)),$=_ instanceof K?_.httpStatus:void 0,I=_ instanceof K?_.code:void 0,E=_ instanceof K?_.retryAfterSeconds:void 0;f.reportAllocationFailure(L,$,I,E),S({status:"unavailable",cause:_});return}T||(f.setAuth({jwt:b.jwt,authProvider:e.authProvider,orgId:e.orgId}),f.setConnection({url:b.url,sessionId:b.sessionId,iceServers:b.iceServers}),ke()&&await _e(),V=b.jwt,v.setDocTransport({wsUrl:b.url,token:H,resolveServerUrl:Q}),await f.connect({app:i,functionName:r,args:o}),v.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(l).catch(g=>{console.error(`[urun] Failed to connect session for ${r}:`,g)}),e.releaseOnLeave!==!1){let g=at(()=>{if(T=!0,f.leaveLeg())return;if(f.connectedUrl!==null){f.disconnect();return}f.disconnect();let I=w;I?W(I):O=!0});v.onDisconnect(g);let b,_,L=!1,$=()=>{L||(L=!0,b?.(),_?.())};A.then(I=>{I.status!=="ready"||L||(b=dt(()=>w!==void 0))}),_=v.onPhase(I=>{let E=I?.name;(E==="paused"||E==="error")&&$()}),L&&_(),v.onDisconnect($)}return v}}})}var vr="https://api.urun.sh",br="URUN_DEV";function ei(){if(typeof process>"u")return!1;let i=process.env?.[br];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 ti(i,e={}){if(!i)throw new Y("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=X(e.baseUrl??vr),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.dev??ei())&&(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(p){throw new Y(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let o={};try{o=await s.json()}catch{}if(!s.ok){let p=typeof o.message=="string"?o.message:`HTTP ${s.status}`;throw new Y(`[urun] client token mint failed: ${p}`,s.status)}let a=typeof o.token=="string"?o.token:"",d=typeof o.org_id=="string"?o.org_id:"",u=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,c=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 l=Number.isFinite(u)?new Date(u):new Date(Date.now()+(c??60)*1e3);return{token:a,expiresAt:l,orgId:d}}var wr=3e4,yr="stream:",It=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=`${yr}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${yr}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let s=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(s)&&(this._pendingRpc.delete(s),n(new Error(`RPC request "${e}" timed out after ${wr}ms`)))},wr);this._pendingRpc.set(s,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function ri(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 Mt(n);return new It(n,s)}var ni='video/mp4; codecs="avc1.42E01E"';function ii(i,e){let t=e?.codec??ni,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 p;try{p=n.addSourceBuffer(t)}catch(f){throw f instanceof DOMException&&f.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).`):f}let m=i.getReader();function h(){return p.updating?new Promise(f=>{p.addEventListener("updateend",()=>f(),{once:!0})}):Promise.resolve()}async function k(){try{for(;;){let{done:f,value:v}=await m.read();if(f){await h(),n.readyState==="open"&&n.endOfStream();return}await h();try{p.appendBuffer(v)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let T=p.buffered;if(T.length>0){let O=T.start(T.length-1);p.remove(0,O),await h(),p.appendBuffer(v)}else throw w}else throw w}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}k()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let d=a.call(r),u=d.getTracks(),c=0,l=u.length;if(l===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{c++,c>=l&&URL.revokeObjectURL(s)});return d}function si(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 oi(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 qe=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 oi(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 ai(i){return new qe(i)}var $e=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 Sr(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function di(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function ci(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function Ct(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,Ct(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 $e;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(${Sr(r)}) failed`,d=o instanceof Error?o.message:String(o);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let c=new Error(`${a} \u2014 ${u.kind} capture lost: ${d||o}`);c.cause=o,Ct(u,c)}throw o}let s=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of s){let a=di(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(${Sr(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw d;Ct(o,d);continue}if(o.track=a,o.stream=ci(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}},ui=null;function li(){return ui??=new je}var kr="input",pi=30;function fi(i){let e=i.now??Date.now,t=i.field??kr,r=1e3/Math.max(i.hz??30,.001),n=new Set,s=0,o=0,a=0,d=0,u,c=null,l=!1,p=()=>{if(l)return;u=e(),d+=1;let h={keys:[...n],buttons:s,pointer:{x:o,y:a},seq:d,at:u};try{i.awareness.setLocalStateField(t,h)}catch{}},m=()=>{if(l)return;let h=e();if(u===void 0||h-u>=r){c&&(clearTimeout(c),c=null),p();return}if(c)return;let k=Math.max(r-(h-u),0);c=setTimeout(()=>{c=null,p()},k),c.unref?.()};return{keyDown(h){let k=String(h).toLowerCase();n.has(k)||(n.add(k),m())},keyUp(h){let k=String(h).toLowerCase();n.delete(k)&&m()},setButtons(h){let k=Number.isFinite(h)?Number(h):0;k!==s&&(s=k,m())},movePointer(h,k){let f=Number.isFinite(h)?Number(h):0,v=Number.isFinite(k)?Number(k):0;f===0&&v===0||(o+=f,a+=v,m())},heldKeys(){return[...n]},clear(){l||(n.clear(),s=0,c&&(clearTimeout(c),c=null),p())},dispose(){if(l)return;let h=n.size>0||s!==0;n.clear(),s=0,c&&(clearTimeout(c),c=null),h&&p(),l=!0}}}var mi=1024,hi=.92,gi=262144,vi=256e3,Dt=[.9,.8,.7,.6,.5],_r=.8,bi=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 wi(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 Ar(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 Tr(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 Pt(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 Ar(s,r,n)}async function yi(i,e,t,r){let{width:n,height:s}=e,o=await Pt(i,n,s,t,r);if(o.size<=256e3)return{blob:o,width:n,height:s};if(t==="image/jpeg"){for(let d of Dt)if(!(d>=r)&&(o=await Pt(i,n,s,t,d),o.size<=256e3))return Tr(`quality ${r} -> ${d}`,o.size),{blob:o,width:n,height:s}}let a=t==="image/jpeg"?Dt[Dt.length-1]:r;for(let d=0;d<bi;d++)if(n=Math.max(16,Math.round(n*_r)),s=Math.max(16,Math.round(s*_r)),o=await Pt(i,n,s,t,a),o.size<=256e3)return Tr(`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 Si(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:s}=e,o=await wi(i);try{let a=Ut(o.width,o.height,t),d=await yi(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 ki(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 _i(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Ti(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 u=d.getContext("2d");if(!u)throw new Error("could not prepare the reference image (no 2d canvas context)");s==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(i,0,0,a.width,a.height);let c=await Ar(d,s,o);return{bytes:new Uint8Array(await c.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var Ai=new Set(["w","a","s","d"]),te=(i,e)=>Math.min(e,Math.max(-e,i));function Ei(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,u=0,c=0,l=null,p=new Set;return{pointerDelta(m,h){d=te(d-m*e,o),u=te(u-h*e,o)},keyDown(m){let h=m.toLowerCase();Ai.has(h)&&p.add(h)},keyUp(m){p.delete(m.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let m=1-s;d*=m,u*=m,c*=m},tick(m){if(l===null){l=m;return}let h=Math.max(0,Math.min(100,m-l))/1e3;l=m,p.has("w")&&(c=te(c+t*h,a)),p.has("s")&&(c=te(c-t*h,a)),p.has("a")&&(d=te(d+r*h,o)),p.has("d")&&(d=te(d-r*h,o));let k=Math.exp(-h*1e3/n);d*=k,u*=k,c*=k},transform(){return{translateX:d,translateY:u,scale:Math.exp(c)}},isIdentity(m=5e-4){return Math.abs(d)<m&&Math.abs(u)<m&&Math.abs(c)<m},reset(){d=0,u=0,c=0,p.clear()}}}export{zr as ACTIVATION_COLD_BOOT_AFTER_MS,Yr as ACTIVATION_DEGRADED_AFTER_MS,et as ACTIVATION_HINT_PATH,Kr as ACTIVATION_STILL_AFTER_MS,it as ACTIVITY_DOM_EVENTS,Qt as ACTIVITY_FIELD,dn as ACTIVITY_STAMP_MIN_INTERVAL_MS,re as ActivationMonitor,Zn as App,Or as BACKOFF_BASE_MS,Nr as BACKOFF_MAX_ATTEMPTS,Wr as BACKOFF_MAX_MS,je as CaptureController,$e as CaptureUnavailableError,Y as ClientTokenError,qe as CreditsClient,ee as CreditsError,ge as CreditsUnauthorizedError,gi as DATA_CHANNEL_MESSAGE_CEILING,fr as DEFAULT_DOC_SYNC_TIMEOUT_MS,vr as DEFAULT_GATEWAY_URL,Er as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,hi as DEFAULT_REFERENCE_JPEG_QUALITY,mi as DEFAULT_REFERENCE_MAX_SIZE,Mr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Br as DERIVED_LEG_SEP,P as DGRAM_HEADER_BYTES,er as FOCUS_FIELD,un as FOREGROUND_COALESCE_MS,de as FrameReassembler,on as GENERATION_TICK_EMIT_INTERVAL_MS,an as GENERATION_TICK_MAX_EXTRAPOLATION_MS,pi as INPUT_PRESENCE_DEFAULT_HZ,kr as INPUT_PRESENCE_FIELD,J as InvalidDurationError,tt as LEGACY_ACTIVATION_HINT_PATH,Ze as PLATFORM_DOC_NAME,Ue as PermanentLockedError,Pe as PinRequiresActiveTempError,se as PresenceTracker,Rr as ProduceAckTimeoutError,Ce as RecordingNotFoundError,Z as RecordingsClient,x as RecordingsError,ie as RecordingsUnauthorizedError,ye as RequestAbortError,Ke as RequestCancelledError,He as RequestDocSyncError,we as RequestError,Ve as RequestTimeoutError,De as RetainNotTempError,Ie as RuntimeArtifactNotFoundError,z as RuntimeArtifactsClient,D as RuntimeArtifactsError,Re as RuntimeArtifactsUnauthorizedError,Gr as SIGNALING_PROTOCOL_VERSION,Xe as STREAM_END,me as Session,K as SessionAllocationError,he as SessionDirectory,be as SessionDirectoryError,Be as SessionEndError,G as SessionEndUnavailableError,Cr as SessionFailedError,Ge as StreamDirectionConflict,le as TransportNegotiator,Pr as TransportSessionMismatchError,pe as TransportSessionSignaling,br as URUN_DEV_ENV,Zt as USER_ACTIVITY_FIELD,cn as USER_ACTIVITY_MIN_INTERVAL_MS,Xt as VISIBILITY_FIELD,vi as WIRE_MESSAGE_BUDGET,nr as WT_CONTROL_FRAME_MAX,or as WT_DATA_STREAM_VERSION,fe as WebRtcSession,ue as WebTransportSession,oe as WtControlDecoder,Me as WtDataStreamParser,Kt as activationHintFrom,_i as cameraCaptureAvailable,Ti as captureStillFromVideo,Fr as computeBackoffDelay,mt as consumeWtDataStreams,st as createActivityTracker,Ei as createCameraWarp,ti as createClientToken,ai as createCreditsClient,fi as createInputPresencePublisher,sn as createRecordingsClient,Xr as createRuntimeArtifactsClient,ri as createStore,Je as decodeStreamEnvelope,Hr as derivedLegName,Vr as derivedLegRole,Ir as describeSessionFailure,xr as describeSessionPhase,jr as encodeStreamEnvelope,lt as encodeWtControlFrame,Ut as fitWithin,rt as isDurationString,Lr as isPausedPhase,si as isPendingRecording,qr as isRetryableSessionError,Ur as isWakingPhase,ct as mediaRecorderChunkSource,Si as normalizeReferenceImage,rn as normalizeRetention,dt as observeLeaveConfirm,ot as observePageLifecycle,at as observePageTeardown,ae as parseDgramHeader,$r as prewake,ki as referenceImageErrorMessage,Se as releaseSessionBeacon,Jn as sessionDirectory,Dr as sessionFailureFromMediaError,li as sharedCaptureController,ii as videoStream,nt as watchGenerationTick,ze as whenLive,pt as writeDgramHeader};
|
|
1
|
+
import{$ as zr,A as Qe,B as Fr,C as qr,D as $r,E as Br,F as jr,G as Hr,H as X,I as xt,J as _e,K as Xe,L as Ot,M as Wt,N as Nt,O as Je,P as Ft,Q as qt,R as Vr,S as $t,T as Te,U as Ze,V as Kr,W as et,Y as Bt,_ as Gr,a as Mt,aa as Yr,b as ve,ba as Qr,c as K,ca as Ae,d as Ve,e as be,ea as Re,f as ye,fa as jt,g as Ke,ga as Ht,h as Ge,ha as Vt,i as ze,ia as Kt,j as Cr,k as Pr,l as we,m as Ye,n as Dr,o as Ur,p as Lr,q as Mr,r as G,s as ke,v as Se,w as xr,x as Or,y as Wr,z as Nr}from"./chunk-AL3FYYQK.mjs";var Xr=15e3,Jr=45e3,Zr=12e4,tt="platform",rt="activation",nt="desired.activation";function Gt(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 en=[{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 en){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=Gt(this._options.hint());s!==void 0&&(n.hint=s),e.lastEvent=n;for(let o of Array.from(this._handlers))o(n)}};var C=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 C{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ie=class extends C{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 tn(i){return new z(i)}var z=class{_options;constructor(e){this._options=e}async list(e){let r=Yt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new C("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(zt)}async getDownloadUrl(e,t){let r=Yt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!nn(n))throw new C("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:zt(r.artifact),downloadUrl:n}}async _request(e,t){let r=xt(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 C&&sn(n.status))throw n}throw n??new C("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${X(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 on(o.status,a,d)}try{return await o.json()}catch(a){throw new C(`[urun] runtime artifacts: invalid JSON response from ${X(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=X(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 zt(i){if(!i||typeof i!="object")throw new C("[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=rn(e,"size_bytes"),a=$(e,"sha256");if(!t||!r||!n||o==null||!a)throw new C("[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 rn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function nn(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function sn(i){return i===401||i===403}function on(i,e,t){return i===401?new Ee(t,e):i===404?new Ie(t,e):new C(t,i,e)}function Yt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new C("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var M=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 M{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 M{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Pe=class extends M{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)}},De=class extends M{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)}},Ue=class extends M{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 M{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 an(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 dn(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 Pe(r,e);case"pin_requires_active_temp":return new De(r,e);case"permanent_locked":return new Ue(r,e)}return new M(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 M("[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 dn(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 cn(i){return new Z(i)}var un=1e3,ln=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 b=i.get("desired.billing.epoch"),y=i.get("desired.billing.updatedAtMs");return{seconds:p,epoch:typeof b=="number"&&Number.isFinite(b)?b:0,updatedAtMs:typeof y=="number"&&Number.isFinite(y)?y:null}},c=()=>{if(r===null)return null;let p=Math.min(Math.max(0,Date.now()-n),s);return r+p/1e3},u=()=>{let p=t.creditsPerSecond;if(typeof p=="number"&&Number.isFinite(p)&&p>0)return p;let b=i.get("desired.billing.creditsPerSecond");return typeof b=="number"&&Number.isFinite(b)&&b>0?b:null},f=()=>{let p=c();if(p===null)return;let b=Math.floor(p);if(b<=a)return;a=b;let y={seconds:b},T=u();T!==null&&(y.estimatedCredits=b*T),e(y)},l=p=>{n=Date.now();let b=p===null?0:Math.max(0,n-p);s=Math.max(0,12e3-b)},h=()=>{let p=d();if(p!==null){if(o!==null&&p.epoch!==o){o=p.epoch,r=p.seconds,a=-1,l(p.updatedAtMs),f();return}r!==null&&p.seconds<=r||(o=p.epoch,r=p.seconds,l(p.updatedAtMs),f())}};h();let g=i.on("change",h),S=setInterval(f,1e3);return S.unref?.(),()=>{clearInterval(S),g()}}var Qt="activity",Xt="visibility",pn=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 l=e();if(!(o!==void 0&&l-o<15e3)){o=l;try{i.awareness.setLocalStateField(Qt,{at:l})}catch{}}},d=()=>{if(!(s||!n||n.visibilityState===void 0))try{i.awareness.setLocalStateField(Xt,n.visibilityState)}catch{}},c=()=>a(),u=()=>{d(),(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&a()};if(r)for(let l of ot)r.addEventListener(l,c,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",u);let f=null;return!t&&i.isProducing&&(f=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),f.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,r)for(let l of ot)r.removeEventListener(l,c,{capture:!0});n&&n.removeEventListener("visibilitychange",u),f&&(clearInterval(f),f=null)}}}}var Zt="user_activity",er="focus",fn=3e4;function Jt(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(Jt(e.state));let t=e.on("stateChange",n=>{this._setState(Jt(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(er,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(Zt,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 hn=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 ut(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 tr="video/mp4";function lt(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,s=!1,o=(a,d,c)=>{let u=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!u)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 f=e.mimeType??(typeof u.isTypeSupported=="function"&&u.isTypeSupported(tr)?tr:void 0),l=new MediaStream([a]),h=new u(l,f?{mimeType:f}:void 0);r=h;let g=Promise.resolve();h.ondataavailable=S=>{let p=S.data;s||!p||p.size===0||(g=g.then(async()=>{let b=new Uint8Array(await p.arrayBuffer());s||d(b)}))},h.onstop=()=>{g.then(()=>{s||c()})},h.onerror=()=>{g.then(()=>{s||c()})},h.start(t)};return{start(a,d){if(r||s)return;let c=i.track();if(c){o(c,a,d);return}n=i.onTrack(u=>{!u||r||s||(n?.(),n=null,o(u,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 mn(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 rr(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 mn(s)}import{encode as gn,decode as vn}from"@msgpack/msgpack";var nr=65536;function ft(i){let e=gn(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>nr)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(vn(n))}return t}},P=12,pt=1,bn=0,Le=1,ir=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 ht(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??bn),e}var yn=100,sr=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-sr?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-sr}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 wn=/^avc[13]\.[0-9a-fA-F]{6}$/;function kn(i){return wn.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=kn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var or=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!==or)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&&Sn(r,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function Sn(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,yt=48e3,_n=64,Tn=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-Tn)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>_n;){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/yt)),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 u=r.stream.getAudioTracks()[0];u&&this.seam.onTrack(u)}let n=e.numberOfFrames,s=Math.max(1,e.numberOfChannels),o=t.createBuffer(s,n,e.sampleRate);for(let u=0;u<s;u++){let f=new Float32Array(n);e.copyTo(f,{planeIndex:u,format:"f32-planar"}),o.copyToChannel(f,u)}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,An=3,Rn=1e4;function En(i){return Math.round(i*(yt/1e6))%2**32>>>0}function wt(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)),u=ht({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:d,fragCount:o,lane:n?.lane??Le}),f=new Uint8Array(P+c.byteLength);f.set(u,0),f.set(c,P),a.push(f)}return a}var Oe=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(In(e)){let d=e,c=d.context.createMediaStreamDestination();d.connect(c),this.nodeBridge={node:d,dest:c};let u=c.stream.getAudioTracks()[0];if(!u){this.die("AudioNode bridge produced no audio track");return}n=u}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=wt(this.frameSeq,En(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<Rn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=An){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 In(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var Cn=9e4,Pn="avc1.42E01F",Dn=60,Un=3,Ln=1e4;function Mn(i){return Math.round(i*(Cn/1e6))%2**32>>>0}var We=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let 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>=Dn;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=wt(this.frameSeq,Mn(e.timestamp),t,this.sink.maxDatagramSize()||ce,{lane:ir,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<Ln),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 xn(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),xn(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 ar=250,On=25,Wn=2e3,ue=class i{constructor(e,t,r,n,s,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=n;this.audioUplink=s;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((d,c)=>{this.firstFrameResolve=d,this.firstFrameReject=c}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;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),u=>u.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(u){console.warn(`[urun] WT audio lane failed to start (${u instanceof Error?u.message:String(u)}) \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 u=new Ne({openUniStream:async()=>(await c()).getWriter()});u.onDead(f=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(f)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(c){let u=c instanceof Error?c.message:String(c);console.warn(`[urun] WT data uplink failed to engage (${u}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(u)}this.controlLoop(s,o,a).catch(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 ${ar}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}async stop(){this.stopped=!0,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<Wn),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 Oe(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 We(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]===Le){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(ft(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;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(()=>{})},ar)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,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 dr=2500,cr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Nn=1e4,le=class{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;get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,s={webtransport:t&&r&&n,webcodecs:r,codecs:cr,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??dr,"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(u){if(c?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let f=String(u instanceof Error?u.message:u);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${f}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(f),u}console.warn("[urun] webtransport failed, falling back to webrtc:",u),this.proceedWebRtcDial(`wt failed: ${String(u instanceof Error?u.message:u)}`),this.notifyEstablished("webrtc",String(u instanceof Error?u.message:u))}}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.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:cr,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??dr,"quic connect deadline")}catch(u){throw c.stop().catch(()=>{}),u}if(this.session!==r)return c.stop().catch(()=>{}),null;try{this.engageQuicDataLane(c,n)}catch(u){throw c.stop().catch(()=>{}),u}this.session=c;{let u=this.offer.webtransport;u&&(this.opts.audioLane===void 0||u.audio!==void 0)&&(this.opts.audioUplink===void 0||u.audioUp===!0)&&(this.opts.videoUplink===void 0||u.videoUp===!0)&&(this.opts.dataLane===void 0||u.data===!0)&&(this.opts.dataUplink===void 0||u.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),c}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(n,s)=>r.onData(n,s),onLaneError:n=>r.onLaneError(n)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new ue(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;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;r&&this.proceedWebRtcDial(`failover: ${t}`),console.warn(r?"[urun] quic died mid-session on a WT-only leg (no RTCPeerConnection) \u2014 attempting a late WebRTC dial from scratch:":"[urun] quic died mid-session, failing over to webrtc:",t),this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),(async()=>{let n=this.createWebRtc();try{let s=await kt(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Nn,"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 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 Fn=1e4,pe=class{constructor(e,t=Fn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;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:u,...f}=d;n(f)});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 qn="video",fe=class{constructor(e,t=qn){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 $n="video";function lr(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,u=!1,f=()=>{if(c){for(let k of c.getVideoTracks())try{k.stop()}catch{}c=null}u&&(u=!1,t.onOverrideTrack(null))},l=new le(new pe(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new fe(i,t.streamName??$n)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(k,A)=>i.dispatchQuicStreamData(k,A),onQuicLane:()=>i.markStreamDataLaneQuic(),onQuicLaneLost:k=>i.quicStreamDataLaneLost(k),onLaneError:k=>i.raiseQuicStreamDataError(k)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:k=>{d||t.onOverrideAudioTrack(k)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>T(),onMediaTransportLost:k=>{d||(f(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(k),T())},onTransportChange:(k,A)=>{d||(k==="webrtc"&&(f(),T()),t.onTransportChange?.(k,A))}}),h=null,g=()=>{h!==null&&(clearInterval(h),h=null)},S=t.wtRetryBaseMs??2e3,p=t.wtRetryCapMs??3e4,b=null,y=0,T=()=>{if(d||b!==null||l.activeTransport==="webtransport")return;let k=Math.min(S*2**y,p);b=setTimeout(()=>{b=null,y+=1,l.retryWebTransport().then(A=>{if(d){A&&l.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${y})`),y=0,R(A);T()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${y} failed:`,A),T())})},k)},x=()=>{b!==null&&(clearTimeout(b),b=null)},R=async k=>{if(d||k.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;g();let O=!1;h=setInterval(()=>{if(d||l.activeTransport!=="webtransport")return;let N=ur(k);if(!N){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)"),g();return}let D=N.pathLiveness();if(!D.alive){let q=l.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${D.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"),g(),N.fail(`path health: ${D.evidence}`);return}if(!O){if(O=!0,l.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${A}ms \u2014 the QUIC PATH IS HEALTHY (${D.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: ${D.evidence}); webrtc track remains authoritative`)}},A);try{await k.firstMedia}catch(N){g(),console.debug("[urun] webtransport ended before any media flowed:",N);return}if(g(),d||l.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;c=a.captureStream();let W=c.getVideoTracks()[0];W&&(u=!0,t.onOverrideTrack(W))};return(async()=>{let k=await l.connect();if(d){l.disconnect().catch(()=>{});return}await R(k)})().catch(k=>{if(g(),d){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",k);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",k),T();return}o?.proceed(`negotiation unavailable: ${k instanceof Error?k.message:String(k)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",k),T()}),{activeTransport:()=>l.activeTransport,dispose(){d=!0,g(),x(),f(),t.onOverrideAudioTrack?.(null),l.disconnect().catch(()=>{})}}}var Bn=new Set;function Tt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var jn="rpc",Hn="$presence",hr=3e4,pr=3e4,Vn="rpc-resp";function Kn(i){return`${Vn}:${i}`}function St(){return Te()}function Gn(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 zn(i,e,t,r,n,s,o,a,d,c){let u=[],f=null,l=!1,h=null,g=!1,S,p,b=new Promise((m,F)=>{S=m,p=F});b.catch(()=>{});let y=o(),T=null,x=null,R=null,k=null,A=null,O=null,W=!0,N=()=>{R&&(clearTimeout(R),R=null),k&&(k(),k=null)},D=()=>{A&&(clearTimeout(A),A=null),O&&(O(),O=null)},q=!1,H=()=>{q||!g||(q=!0,i.set({rpc:{[e]:null}}))},V=()=>{W=!1,N(),D(),T?.(),T=null,x?.(),x=null,a?.removeEventListener("abort",_),y.dispose(),H()},Q=()=>{if(f){if(u.length>0){let m=f;f=null,m.resolve({value:u.shift(),done:!1})}else if(h!==null){let m=f;f=null,m.reject(h)}else if(l){let m=f;f=null,m.resolve({value:void 0,done:!0})}}},Lt=m=>{l||(u.push(m),Q())},v=m=>{l||(h=m,l=!0,p(m),V(),Q())},w=m=>{l||(l=!0,S(m),V(),Q())},_=()=>{let m=a?.reason;v(m instanceof ye?m:new we(e))},I=m=>{if(!(l||!m||typeof m!="object"))switch(D(),H(),m.t){case"delta":typeof m.delta=="string"&&Lt(m.delta);break;case"response":w(m.body);break;case"error":{let{message:F,code:E}=Gn(m.body);v(new ye(F,{requestId:e,code:m.code??E}));break}}},U=()=>{let m=y.messages()[Symbol.asyncIterator]();T=()=>{m.return?.(void 0)};let F=()=>{W&&m.next().then(E=>{if(W){if(E.done){l||w(void 0);return}I(E.value),F()}},E=>{W&&v(E)})};F()},L=()=>{if(!g){if(g=!0,a){if(a.aborted){v(new we(e));return}a.addEventListener("abort",_,{once:!0})}x=d?.(m=>v(m))??null,U(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:s}}}),c&&c>0&&!i.synced&&(R=setTimeout(()=>{R=null,!l&&!i.synced&&v(new Ge(c,e))},c),k=i.onSynced(()=>N())),O=i.onSynced(()=>{O=null,!(l||q||A)&&(A=setTimeout(()=>{A=null,!(l||q)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(pr/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).`)},pr))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(L(),u.length>0)return Promise.resolve({value:u.shift(),done:!1});if(h!==null){let m=h;return h=null,Promise.reject(m)}return l?Promise.resolve({value:void 0,done:!0}):new Promise((m,F)=>{f={resolve:m,reject:F}})},return(){return l||(l=!0,S(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(m){return l||(l=!0,p(m),V()),Promise.reject(m)}}}},body:b,start:L}}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 Yn(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 _t=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=Yn(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??lt;return rr(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)}},he=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Ht;_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;_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=Bt(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(Hn).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 qt({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,Tt(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 Qe(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 _t(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 Vt(e,this._sessionId,Bn.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Kt(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(jt({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=St(),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(jn),a=Kn(e);return zn(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),s??hr)}requestStream(e,t={}){let r=St();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=St(),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=lr(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}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??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 mr(i){return`urun:session:v2:${i.orgId}:${i.app}:${i.functionName}`}function At(){try{return globalThis.sessionStorage??null}catch{return null}}var Rt=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 Qn(i,e){return i!==void 0&&e!==void 0&&i!==e}function Et(i,e){let t=At(),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=Rt.get(i)??r??null;return!n||Qn(n.actor,e)?null:n}function gr(i,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};Rt.set(i,t);let r=At();if(r)try{r.setItem(i,JSON.stringify(t))}catch{}}function qe(i){Rt.delete(i);let e=At();if(e)try{e.removeItem(i)}catch{}}var vr=new Set(["paused","acquiring","live"]),Xn=new Set(["24h","keep"]);function br(i){if(typeof i!="string"||i.length===0)return null;let e=new Date(i);return Number.isFinite(e.getTime())?e:null}function Jn(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"||!vr.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 ${[...vr].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:br(i.created_at),lastActiveAt:br(i.last_active_at),archived:i.archived===!0,preview:typeof i.preview=="string"&&i.preview.length>0?i.preview:null,recordingsExpired:e,retention:Xn.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 Nt({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(Jn),nextCursor:r}}async end(e){await Ft({...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);gr(i,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var Zn=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function ei(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 ti(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(!(Zn.has(r)||typeof r!="string"))return(n,s)=>{let o=n??{},a=mr({orgId:e.orgId,app:i,functionName:r}),d=!s?.sessionId&&!e.sessionKey&&!!s?.label,c,u=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,f=u(),l=e.jwt,h=e.getAccessToken?async v=>{let w=await e.getAccessToken(v);return w&&(l=w),w}:void 0,g={...e,getAccessToken:h},S=new ve,p=new Ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:f,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),b=new he(f,S,p,Tt(g),ne(g),{activity:s?.activity}),y,T=!1,x=!1,R,k,A=new Promise(v=>{k=v}),O,W=v=>{v.sessionId||R||(R="teardown",O="ticket",_e({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:l,authProvider:e.authProvider}))},N=v=>{R||v.sessionId||(R="abandon",_e({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:l,authProvider:e.authProvider,reason:"client_abandoned"}))},D=v=>{let w=v.sessionId||!c?v:{...v,sessionId:c};y=w,k({status:"ready",handle:w}),(x||R==="teardown")&&W(w)};b.setEndHandler(async()=>{let v=y?{status:"ready",handle:y}:await A;if(v.status==="unavailable")throw new K("[urun] session allocation failed before a releasable request was created",{cause:v.cause});let w=y??v.handle;return qe(a),R==="teardown"?w.sessionId?{status:"paused",sessionId:w.sessionId,reason:"client_ended"}:{status:"canceled",requestId:w.requestId}:(R="end",w.sessionId?Ot({baseUrl:w.baseUrl,sessionId:w.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider}):Xe({baseUrl:w.baseUrl,requestId:w.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider}))}),b.setCancelHandler(async()=>{let v=y?{status:"ready",handle:y}:await A;if(v.status==="unavailable")throw new K("[urun] session allocation failed before a cancellable request was created",{cause:v.cause});let w=y??v.handle;if(w.sessionId)throw new Ve(`[urun] cancel() is for a queued admission request, but this call already has session ${w.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:w.sessionId,code:"cancel_on_live_session"});R="end";try{let _=await Xe({baseUrl:w.baseUrl,requestId:w.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,authProvider:e.authProvider});return qe(a),_}catch(_){throw R==="end"&&(R=void 0),_}});let q=async v=>{let w,_=s?.sessionId??e.sessionKey??c,I,U;if(_===void 0&&!d){let E=Et(a);if(E?.sessionId){if(U=Fe(l),E.actor!==void 0&&U===void 0&&h){let He=await Promise.resolve(h()).catch(()=>{});U=Fe(He??e.jwt)}I=E.actor!==void 0&&U!==void 0&&E.actor!==U?void 0:E.sessionId}}let L=_??I,B=(E,He)=>Wt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:h,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,w=j.sessionId,y&&y.sessionId!==j.sessionId&&D({...y,sessionId:j.sessionId}),T||(e.sessionKey||yr(a,j.sessionId,l),b.setSessionId(j.sessionId)))},onRequest:D}),m;try{m=await B(v,L)}catch(E){if(I===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 ${I} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),Et(a,U)?.sessionId===I&&qe(a),m=await B(u(),void 0)}let F=h?await h()??void 0:e.jwt;if(w&&w!==m.sessionId)throw y&&y.sessionId!==m.sessionId&&D({...y,sessionId:m.sessionId}),new G(`Gateway contract violation: admission minted session ${w} 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 c=m.sessionId,y&&y.sessionId!==m.sessionId&&D({...y,sessionId:m.sessionId}),T||(e.sessionKey||yr(a,m.sessionId,l),b.setSessionId(m.sessionId),b.setArtifactsAuth(ne({...g,baseUrl:m.baseUrl})),p.setEndsAt(m.endsAt),p.seedRegion($t(m.response))),{url:m.wsUrl,sessionId:m.sessionId,jwt:F,iceServers:m.response.ice_servers,endsAt:m.endsAt}},H,V=h?async()=>await h()??H:()=>H,Q=()=>{let v=p.connectedUrl;return v?Re(v):void 0};if(p.setConnectionResolver(async()=>{let v=await q(u());return H=v.jwt,v}),p.on("connected",()=>{p.multiplexer&&S.setTarget(p.multiplexer);let v=p.connectedUrl;v&&b.setDocTransport({wsUrl:v,token:V,resolveServerUrl:Q})}),(async v=>{let w;try{w=await q(v)}catch(_){if(T){k({status:"unavailable",cause:_});return}console.error(`[urun] Failed to create session for ${r}:`,_),y&&N(y);let I=_ instanceof Error?_:new Error(String(_)),U=_ instanceof G?_.httpStatus:void 0,L=_ instanceof G?_.code:void 0,B=_ instanceof G?_.retryAfterSeconds:void 0;p.reportAllocationFailure(I,U,L,B),k({status:"unavailable",cause:_});return}T||(p.setAuth({jwt:w.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:w.url,sessionId:w.sessionId,iceServers:w.iceServers}),ke()&&await Se(),H=w.jwt,b.setDocTransport({wsUrl:w.url,token:V,resolveServerUrl:Q}),await p.connect({app:i,functionName:r,args:o}),b.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(f).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 L=y;L?W(L):x=!0});b.onDisconnect(v);let w,_,I=!1,U=()=>{I||(I=!0,w?.(),_?.())};A.then(L=>{L.status!=="ready"||I||(w=ut(()=>y!==void 0))}),_=b.onPhase(L=>{let B=L?.name;(B==="paused"||B==="error")&&U()}),I&&_(),b.onDisconnect(U)}return b}}})}var wr="https://api.urun.sh",kr="URUN_DEV";function ri(){if(typeof process>"u")return!1;let i=process.env?.[kr];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 ni(i,e={}){if(!i)throw new Y("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=X(e.baseUrl??wr),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??ri())&&(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(l){throw new Y(`[urun] client token mint request failed: ${l instanceof Error?l.message:String(l)}`)}let o={};try{o=await s.json()}catch{}if(!s.ok){let l=typeof o.message=="string"?o.message:`HTTP ${s.status}`;throw new Y(`[urun] client token mint failed: ${l}`,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,u=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 f=Number.isFinite(c)?new Date(c):new Date(Date.now()+(u??60)*1e3);return{token:a,expiresAt:f,orgId:d}}var Sr=3e4,_r="stream:",It=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=`${_r}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${_r}${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 ${Sr}ms`)))},Sr);this._pendingRpc.set(s,{resolve:r,reject:n,timer:o}),this._ws.send(JSON.stringify({rpcId:s,type:e,...t}))})}};function ii(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 Mt(n);return new It(n,s)}var si='video/mp4; codecs="avc1.42E01E"';function oi(i,e){let t=e?.codec??si,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 l;try{l=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 h=i.getReader();function g(){return l.updating?new Promise(p=>{l.addEventListener("updateend",()=>p(),{once:!0})}):Promise.resolve()}async function S(){try{for(;;){let{done:p,value:b}=await h.read();if(p){await g(),n.readyState==="open"&&n.endOfStream();return}await g();try{l.appendBuffer(b)}catch(y){if(y instanceof DOMException&&y.name==="QuotaExceededError"){let T=l.buffered;if(T.length>0){let x=T.start(T.length-1);l.remove(0,x),await g(),l.appendBuffer(b)}else throw y}else throw y}}}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(),u=0,f=c.length;if(f===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(s)},{once:!0});else for(let l of c)l.addEventListener("ended",()=>{u++,u>=f&&URL.revokeObjectURL(s)});return d}function ai(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 di(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 di(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 ci(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 Tr(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function ui(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function li(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function Ct(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,Ct(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(${Tr(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 u=new Error(`${a} \u2014 ${c.kind} capture lost: ${d||o}`);u.cause=o,Ct(c,u)}throw o}let s=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of s){let a=ui(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(${Tr(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw d;Ct(o,d);continue}if(o.track=a,o.stream=li(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}},pi=null;function fi(){return pi??=new je}var Ar="input",hi=30;function mi(i){let e=i.now??Date.now,t=i.field??Ar,r=1e3/Math.max(i.hz??30,.001),n=new Set,s=0,o=0,a=0,d=0,c,u=null,f=!1,l=()=>{if(f)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{}},h=()=>{if(f)return;let g=e();if(c===void 0||g-c>=r){u&&(clearTimeout(u),u=null),l();return}if(u)return;let S=Math.max(r-(g-c),0);u=setTimeout(()=>{u=null,l()},S),u.unref?.()};return{keyDown(g){let S=String(g).toLowerCase();n.has(S)||(n.add(S),h())},keyUp(g){let S=String(g).toLowerCase();n.delete(S)&&h()},setButtons(g){let S=Number.isFinite(g)?Number(g):0;S!==s&&(s=S,h())},movePointer(g,S){let p=Number.isFinite(g)?Number(g):0,b=Number.isFinite(S)?Number(S):0;p===0&&b===0||(o+=p,a+=b,h())},heldKeys(){return[...n]},clear(){f||(n.clear(),s=0,u&&(clearTimeout(u),u=null),l())},dispose(){if(f)return;let g=n.size>0||s!==0;n.clear(),s=0,u&&(clearTimeout(u),u=null),g&&l(),f=!0}}}var gi=1024,vi=.92,bi=262144,yi=256e3,Pt=[.9,.8,.7,.6,.5],Rr=.8,wi=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 ki(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 Ir(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 Er(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 Dt(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 Ir(s,r,n)}async function Si(i,e,t,r){let{width:n,height:s}=e,o=await Dt(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 Dt(i,n,s,t,d),o.size<=256e3))return Er(`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<wi;d++)if(n=Math.max(16,Math.round(n*Rr)),s=Math.max(16,Math.round(s*Rr)),o=await Dt(i,n,s,t,a),o.size<=256e3)return Er(`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 _i(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:s}=e,o=await ki(i);try{let a=Ut(o.width,o.height,t),d=await Si(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 Ti(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 Ai(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Ri(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 u=await Ir(d,s,o);return{bytes:new Uint8Array(await u.arrayBuffer()),type:s,width:a.width,height:a.height,source:"camera"}}var Ei=new Set(["w","a","s","d"]),te=(i,e)=>Math.min(e,Math.max(-e,i));function Ii(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,u=0,f=null,l=new Set;return{pointerDelta(h,g){d=te(d-h*e,o),c=te(c-g*e,o)},keyDown(h){let g=h.toLowerCase();Ei.has(g)&&l.add(g)},keyUp(h){l.delete(h.toLowerCase())},clearKeys(){l.clear()},frameArrived(){let h=1-s;d*=h,c*=h,u*=h},tick(h){if(f===null){f=h;return}let g=Math.max(0,Math.min(100,h-f))/1e3;f=h,l.has("w")&&(u=te(u+t*g,a)),l.has("s")&&(u=te(u-t*g,a)),l.has("a")&&(d=te(d+r*g,o)),l.has("d")&&(d=te(d-r*g,o));let S=Math.exp(-g*1e3/n);d*=S,c*=S,u*=S},transform(){return{translateX:d,translateY:c,scale:Math.exp(u)}},isIdentity(h=5e-4){return Math.abs(d)<h&&Math.abs(c)<h&&Math.abs(u)<h},reset(){d=0,c=0,u=0,l.clear()}}}export{Jr as ACTIVATION_COLD_BOOT_AFTER_MS,Zr as ACTIVATION_DEGRADED_AFTER_MS,rt as ACTIVATION_HINT_PATH,Xr as ACTIVATION_STILL_AFTER_MS,ot as ACTIVITY_DOM_EVENTS,Qt as ACTIVITY_FIELD,pn as ACTIVITY_STAMP_MIN_INTERVAL_MS,re as ActivationMonitor,ti as App,qr as BACKOFF_BASE_MS,Br as BACKOFF_MAX_ATTEMPTS,$r as BACKOFF_MAX_MS,Nr 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,bi as DATA_CHANNEL_MESSAGE_CEILING,hr as DEFAULT_DOC_SYNC_TIMEOUT_MS,wr as DEFAULT_GATEWAY_URL,Cr as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,vi as DEFAULT_REFERENCE_JPEG_QUALITY,gi as DEFAULT_REFERENCE_MAX_SIZE,Wr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Gr as DERIVED_LEG_SEP,P as DGRAM_HEADER_BYTES,er as FOCUS_FIELD,hn as FOREGROUND_COALESCE_MS,de as FrameReassembler,un as GENERATION_TICK_EMIT_INTERVAL_MS,ln as GENERATION_TICK_MAX_EXTRAPOLATION_MS,hi as INPUT_PRESENCE_DEFAULT_HZ,Ar as INPUT_PRESENCE_FIELD,J as InvalidDurationError,nt as LEGACY_ACTIVATION_HINT_PATH,tt as PLATFORM_DOC_NAME,Ue as PermanentLockedError,De as PinRequiresActiveTempError,se as PresenceTracker,Pr as ProduceAckTimeoutError,Ce as RecordingNotFoundError,Z as RecordingsClient,M as RecordingsError,ie as RecordingsUnauthorizedError,we as RequestAbortError,Ye as RequestCancelledError,Ge as RequestDocSyncError,ye as RequestError,Ke as RequestTimeoutError,Pe as RetainNotTempError,Ie as RuntimeArtifactNotFoundError,z as RuntimeArtifactsClient,C as RuntimeArtifactsError,Ee as RuntimeArtifactsUnauthorizedError,Qr as SIGNALING_PROTOCOL_VERSION,Ze as STREAM_END,he as Session,G as SessionAllocationError,me as SessionDirectory,be as SessionDirectoryError,Ve as SessionEndError,K as SessionEndUnavailableError,Ur as SessionFailedError,ze as StreamDirectionConflict,le as TransportNegotiator,Mr as TransportSessionMismatchError,pe as TransportSessionSignaling,kr as URUN_DEV_ENV,Zt as USER_ACTIVITY_FIELD,fn as USER_ACTIVITY_MIN_INTERVAL_MS,Xt as VISIBILITY_FIELD,yi as WIRE_MESSAGE_BUDGET,nr as WT_CONTROL_FRAME_MAX,or as WT_DATA_STREAM_VERSION,fe as WebRtcSession,ue as WebTransportSession,oe as WtControlDecoder,Me as WtDataStreamParser,Gt as activationHintFrom,Ai as cameraCaptureAvailable,Ri as captureStillFromVideo,jr as computeBackoffDelay,gt as consumeWtDataStreams,at as createActivityTracker,Ii as createCameraWarp,ni as createClientToken,ci as createCreditsClient,mi as createInputPresencePublisher,cn as createRecordingsClient,tn as createRuntimeArtifactsClient,ii as createStore,et as decodeStreamEnvelope,Yr as derivedLegName,zr as derivedLegRole,Dr as describeSessionFailure,Fr as describeSessionPhase,Kr as encodeStreamEnvelope,ft as encodeWtControlFrame,Ut as fitWithin,it as isDurationString,Or as isPausedPhase,ai as isPendingRecording,Hr as isRetryableSessionError,xr as isWakingPhase,lt as mediaRecorderChunkSource,_i as normalizeReferenceImage,an as normalizeRetention,ut as observeLeaveConfirm,dt as observePageLifecycle,ct as observePageTeardown,ae as parseDgramHeader,Vr as prewake,Ti as referenceImageErrorMessage,_e as releaseSessionBeacon,ei as sessionDirectory,Lr as sessionFailureFromMediaError,fi as sharedCaptureController,oi as videoStream,st as watchGenerationTick,Qe as whenLive,ht as writeDgramHeader};
|