@urun-sh/core 0.3.6 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.browser.d.mts +16 -3
- package/dist/index.browser.d.ts +16 -3
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +16 -3
- package/dist/index.d.ts +16 -3
- 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.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/{stream-data-DSwDgcFU.d.mts → stream-data-W9S0z8Wv.d.mts} +22 -1
- package/dist/{stream-data-DSwDgcFU.d.ts → stream-data-W9S0z8Wv.d.ts} +22 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
|
|
2
|
-
import{$ as Mt,A as Cr,B as Ir,C as H,D as Ct,E as we,F as It,G as Dt,H as Pt,I as Dr,J as ye,M as ke,N as Se,O as Ge,P as Pr,Q as Ke,S as Ut,U as Ur,V as Mr,W as Lr,X as xr,Y as _e,_ as Te,a as Et,aa as Lt,b as he,ba as xt,c as ee,ca as Ot,d as hr,e as ge,f as qe,g as $e,h as Be,i as gr,j as vr,k as ve,l as je,m as br,n as wr,o as yr,p as kr,q as be,r as Rt,s as Sr,t as Ve,u as _r,v as He,w as Tr,x as Ar,y as Er,z as Rr}from"./chunk-FSUNC7FS.mjs";var Or=15e3,Wr=45e3,Nr=12e4,ze="platform",Ye="activation",Qe="desired.activation";function Wt(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 Fr=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],te=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==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=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 Fr){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},o=Wt(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let s of Array.from(this._handlers))s(n)}};var E=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)}},Ae=class extends E{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ee=class extends E{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function re(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function qr(i){return new $(i)}var $=class{_options;constructor(e){this._options=e}async list(e){let r=Ft(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new E("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Nt)}async getDownloadUrl(e,t){let r=Ft(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!Br(n))throw new E("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Nt(r.artifact),downloadUrl:n}}async _request(e,t){let r=Ct(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(s){if(n=s instanceof Error?s:new Error(String(s)),n instanceof E&&jr(n.status))throw n}throw n??new E("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${H(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),s=await fetch(n,{method:"GET",headers:this._headers(o)});if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await fetch(n,{method:"GET",headers:this._headers(o)}))}if(!s.ok){let{code:a,message:d}=await this._readError(s,e);throw Vr(s.status,a,d)}try{return await s.json()}catch(a){throw new E(`[urun] runtime artifacts: invalid JSON response from ${H(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=H(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:s,message:a}=o;return{code:typeof s=="string"&&s.length>0?s:`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 Nt(i){if(!i||typeof i!="object")throw new E("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=O(e,"artifact_id")||O(e,"id"),r=O(e,"filename"),n=O(e,"kind"),o=O(e,"status")||"ready",s=$r(e,"size_bytes"),a=O(e,"sha256");if(!t||!r||!n||s==null||!a)throw new E("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:O(e,"content_type")||"application/octet-stream",sizeBytes:s,sha256:a,status:o,createdAt:O(e,"created_at"),expiresAt:O(e,"expires_at")}}function O(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function $r(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function Br(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function jr(i){return i===401||i===403}function Vr(i,e,t){return i===401?new Ae(t,e):i===404?new Ee(t,e):new E(t,i,e)}function Ft(i){if(!i||typeof i!="object"||Array.isArray(i))throw new E("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var U=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)}},ne=class extends U{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Re=class extends U{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Ce=class extends U{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)}},Ie=class extends U{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)}},De=class extends U{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)}},G=class extends U{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 Xe(i){return/^(\d+[smhdw])+$/.test(i)}function Hr(i){if(i==="pin")return{action:"pin"};if(Xe(i))return{action:"retain",duration:i};throw new G(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Gr(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new ne(r,e??"unauthorized");if(i===404)return new Re(r,e??"not_found");if(i===400)return new G(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Ce(r,e);case"pin_requires_active_temp":return new Ie(r,e);case"permanent_locked":return new De(r,e)}return new U(r,{status:i,code:e??`http_${i}`})}var K=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(!Xe(t))throw new G(`[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 U("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),o=await this._resolveToken(),s=await this._fetch(n,e,o,r.body);if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await this._fetch(n,e,o,r.body))}if(!s.ok){let{code:a,message:d}=await this._readError(s);throw Gr(s.status,a,d)}return this._readJson(s)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,s])=>`${encodeURIComponent(o)}=${encodeURIComponent(s)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let s={method:t,headers:o};return n!==void 0&&(o["Content-Type"]="application/json",s.body=JSON.stringify(n)),fetch(e,s)}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 ne("[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:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Kr(i){return new K(i)}var zr=1e3,Yr=12e3;function Je(i,e,t={}){let r=null,n=0,o=0,s=null,a=-1,d=()=>{let h=i.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let y=i.get("desired.billing.epoch"),_=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof y=="number"&&Number.isFinite(y)?y:0,updatedAtMs:typeof _=="number"&&Number.isFinite(_)?_:null}},u=()=>{if(r===null)return null;let h=Math.min(Math.max(0,Date.now()-n),o);return r+h/1e3},c=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let y=i.get("desired.billing.creditsPerSecond");return typeof y=="number"&&Number.isFinite(y)&&y>0?y:null},l=()=>{let h=u();if(h===null)return;let y=Math.floor(h);if(y<=a)return;a=y;let _={seconds:y},T=c();T!==null&&(_.estimatedCredits=y*T),e(_)},p=h=>{n=Date.now();let y=h===null?0:Math.max(0,n-h);o=Math.max(0,12e3-y)},f=()=>{let h=d();if(h!==null){if(s!==null&&h.epoch!==s){s=h.epoch,r=h.seconds,a=-1,p(h.updatedAtMs),l();return}r!==null&&h.seconds<=r||(s=h.epoch,r=h.seconds,p(h.updatedAtMs),l())}};f();let m=i.on("change",f),v=setInterval(l,1e3);return v.unref?.(),()=>{clearInterval(v),m()}}var qt="activity",$t="visibility",Qr=15e3,Ze=["pointerdown","pointermove","keydown","wheel","touchstart"];function et(i){let e=i.now??Date.now,t=i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,r=i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,n=!1,o,s=()=>{if(n)return;let l=e();if(!(o!==void 0&&l-o<15e3)){o=l;try{i.awareness.setLocalStateField(qt,{at:l})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{i.awareness.setLocalStateField($t,r.visibilityState)}catch{}},d=()=>s(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&s()};if(t)for(let l of Ze)t.addEventListener(l,d,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",u);let c=null;return i.isProducing&&(c=setInterval(()=>{if(!n)try{i.isProducing?.()&&s()}catch{}},15e3),c.unref?.()),s(),a(),{touch:s,dispose(){if(!n){if(n=!0,t)for(let l of Ze)t.removeEventListener(l,d,{capture:!0});r&&r.removeEventListener("visibilitychange",u),c&&(clearInterval(c),c=null)}}}}var jt="user_activity",Vt="focus",Xr=3e4;function Bt(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var ie=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(Bt(e.state));let t=e.on("stateChange",n=>{this._setState(Bt(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(Vt,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(jt,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 Jr=250;function tt(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 rt(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 nt(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 Ht="video/mp4";function it(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,o=!1,s=(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(Ht)?Ht:void 0),p=new MediaStream([a]),f=new c(p,l?{mimeType:l}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=v=>{let h=v.data;o||!h||h.size===0||(m=m.then(async()=>{let y=new Uint8Array(await h.arrayBuffer());o||d(y)}))},f.onstop=()=>{m.then(()=>{o||u()})},f.onerror=()=>{m.then(()=>{o||u()})},f.start(t)};return{start(a,d){if(r||o)return;let u=i.track();if(u){s(u,a,d);return}n=i.onTrack(c=>{!c||r||o||(n?.(),n=null,s(c,a,d))})},stop(){if(o)return;o=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Zr(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 Gt(i,e){let t=null,r=!1,n=!1,o=new ReadableStream({pull(s){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{s.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{s.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Zr(o)}import{encode as en,decode as tn}from"@msgpack/msgpack";var Kt=65536;function ot(i){let e=en(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var se=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>Kt)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(tn(n))}return t}},R=12,st=1,rn=0,Pe=1,zt=2;function oe(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&st)===st,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function at(i){let e=new Uint8Array(R),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?st:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??rn),e}var nn=100,Yt=100,ae=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??nn}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<R)return;let t=oe(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(R),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-Yt?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Yt}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((s,a)=>s+a.byteLength,0),n=new Uint8Array(r),o=0;for(let s of t.chunks)n.set(s,o),o+=s.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 sn=/^avc[13]\.[0-9a-fA-F]{6}$/;function on(i){return sn.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 dt(i,e){let t=on(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var Qt=1,Ue=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!==Qt)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=Ke(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===Ge&&(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 ct(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&an(r,e).catch(o=>{e.onLaneError(o instanceof Error?o:new Error(String(o)))})}}async function an(i,e){let t=i.getReader(),r=new Ue;try{for(;;){let{value:n,done:o}=await t.read();if(o)break;if(!(!n||n.byteLength===0))for(let{name:s,payload:a}of r.push(n))e.onData(s,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var ut=40,pt=48e3,dn=64,cn=100,lt=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<R)return;let t=oe(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-cn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let 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>dn;){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(R),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),o=new Uint8Array(n),s=0;for(let a of r.chunks)o.set(a,s),s+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:o})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},un=3,ln=1e4,Me=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??ut;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${ut}ms`),r=ut),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 lt(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/pt)),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,o=Math.max(1,e.numberOfChannels),s=t.createBuffer(o,n,e.sampleRate);for(let c=0;c<o;c++){let l=new Float32Array(n);e.copyTo(l,{planeIndex:c,format:"f32-planar"}),s.copyToChannel(l,c)}let a=n/e.sampleRate;e.close();let d=t.createBufferSource();d.buffer=s,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<ln),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=un){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 de=1200,pn=3,fn=1e4;function mn(i){return Math.round(i*(pt/1e6))%2**32>>>0}function ft(i,e,t,r,n){let o=r-R;if(o<=0)return null;let s=Math.max(1,Math.ceil(t.byteLength/o));if(s>255)return null;let a=[];for(let d=0;d<s;d++){let u=t.subarray(d*o,Math.min((d+1)*o,t.byteLength)),c=at({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:d,fragCount:s,lane:n?.lane??Pe}),l=new Uint8Array(R+u.byteLength);l.set(c,0),l.set(u,R),a.push(l)}return a}var Le=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;generation=0;cancelCapture=null;nodeBridge=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}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}let n;if(hn(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 o=++this.generation,s=new r({track:n}).readable.getReader(),a=!1;this.cancelCapture=()=>{a=!0,s.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&o===this.generation;){let{value:d,done:u}=await s.read();if(u)break;if(d){if(a||this.stopped||o!==this.generation){d.close();break}this.encodeAudioData(d)}}})().catch(d=>{!a&&!this.stopped&&o===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.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=ft(this.frameSeq,mn(e.timestamp),t,this.sink.maxDatagramSize()||de);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<fn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=pn){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 hn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var gn=9e4,vn="avc1.42E01F",bn=60,wn=3,yn=1e4;function kn(i){return Math.round(i*(gn/1e6))%2**32>>>0}var xe=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,o=new r({track:e}).readable.getReader(),s=!1;this.cancelCapture=()=>{s=!0,o.cancel().catch(()=>{})},(async()=>{for(;!s&&!this.stopped&&n===this.generation;){let{value:a,done:d}=await o.read();if(d)break;if(a){if(s||this.stopped||n!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!s&&!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 o=globalThis.VideoEncoder;if(typeof o!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new o({output:s=>this.sendFrame(s),error:s=>this.onEncoderError(s)})),this.encoderDims=t,this.encoder.configure({codec:vn,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(s){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${s instanceof Error?s.message:String(s)}`);return}}let n=this.keyframeWanted||this.framesSinceKeyframe>=bn;this.keyframeWanted=!1,this.framesSinceKeyframe=n?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:n})}catch(o){this.onEncoderError(o instanceof Error?o:new Error(String(o)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=ft(this.frameSeq,kn(e.timestamp),t,this.sink.maxDatagramSize()||de,{lane:zt,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<yn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=wn){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 Sn(i){return i.byteLength>=2&&i[0]===1&&i[1]===3}var Oe=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 o=this.streams.get(e);if(!o){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),o={writer:a},this.streams.set(e,o)}let s=new Uint8Array(4+t.byteLength);new DataView(s.buffer).setUint32(0,t.byteLength,!0),s.set(t,4),await o.writer.write(s),Sn(t)&&(this.streams.delete(e),await o.writer.close().catch(()=>{}))}catch(o){throw this.die(o instanceof Error?o.message:String(o)),o}});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 Xt=250,_n=3,Tn=1e4,mt=2500,An=25,En=2e3,ce=class{constructor(e,t,r,n,o,s,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=n;this.audioUplink=o;this.videoUplink=s;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;reassembler=new ae({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&&dt(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 o=n.readable.getReader(),s=new se,a=[],d=await this.readControl(o,s,a);if(d?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");if(r&&(dt(d.codec,"hello-ack"),this.initDecoder(d.codec,d.width,d.height)),this.offer.audio&&this.audioLane){let c=new Me(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??de}};if(this.offer.audioUp===!0&&this.audioUplink)try{let c=new Le(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 xe(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 Oe({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(o,s,a).catch(c=>this.die(`control loop: ${c}`)),this.datagramLoop().catch(c=>this.die(`datagram loop: ${c}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(c=>this.die(`connection error: ${c}`))}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,ct(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 o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new n({output:s=>{this.frameOutputEver=!0,this.frameOutputsInWindow++,this.canvas.width=s.displayWidth,this.canvas.height=s.displayHeight,o.drawImage(s,0,0),s.close()},error:s=>this.onDecoderError(s)}),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<Tn),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=_n){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+=Xt;else return this.decodeStalledMs=0,!1;return this.decodeStalledMs<mt?!1:(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${mt}ms \u2014 broken WT media leg; failing over LOUDLY`),this.die(`decode-stall: datagrams flowing but nothing decoded within ${mt}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<En),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<An)&&(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>=R&&t[11]===Pe){this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;this.videoArrivedEver=!0,this.videoArrivalsInWindow++;let n=performance.now();if(this.lastArrivalTs>0){let o=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-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){await this.writer.write(ot(e))}async readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;let{value:o,done:s}=await e.read();if(s)return null;o&&r.push(...t.push(o))}}async controlLoop(e,t,r){for(;!this.stopped;){let n=await this.readControl(e,t,r);if(!n)break;n.t==="ping"&&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(),o=this.videoArrivalsInWindow,s=this.frameOutputsInWindow;if(this.videoArrivalsInWindow=0,this.frameOutputsInWindow=0,this.evaluateDecodeLiveness(o,s))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(()=>{})},Xt)}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 Jt=2500,Zt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Rn=1e4,ue=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;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&n,webcodecs:r,codecs:Zt,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:o});let s=o.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,d=s&&!!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.opts.webRtcDial?.proceed(s?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),s){let u=null;try{return u=this.createWebTransportSession(),await ht(u.start(),this.opts.quicDeadlineMs??Jt,"quic connect deadline"),this.engageQuicDataLane(u,o.wtData===!0),this.session=u,d&&(this.wtOnlyLeg=!0,this.opts.webRtcDial?.skip("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.opts.webRtcDial?.proceed(`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=s?"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(),s||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.quicDataLane=!1;let e=this.session;this.session=null,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,o=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",s=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:Zt,wtData:n,wtAudio:o,wtAudioUp:s,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;let u=this.createWebTransportSession();try{await ht(u.start(),this.opts.quicDeadlineMs??Jt,"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.wtOnlyLeg=!0,this.opts.webRtcDial?.skip("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,o)=>r.onData(n,o),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 ce(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())}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.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(`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 o=await ht(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Rn,"webrtc failover produced no media transport");if(this.session!==e){o.stop().catch(()=>{});return}this.session=o,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(o){if(n.stop().catch(()=>{}),this.session!==e)return;this.session=null;let s=o instanceof Error?o.message:String(o),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 (${s}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${s}). 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 ht(i,e,t){return new Promise((r,n)=>{let o=setTimeout(()=>n(new Error(t)),e);i.then(s=>{clearTimeout(o),r(s)},s=>{clearTimeout(o),n(s)})})}var Cn=1e4,le=class{constructor(e,t=Cn){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=Se();return new Promise((n,o)=>{let s=setTimeout(()=>{a(),o(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(s),a(),d.error){o(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(s),a(),o(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 In="video",pe=class{constructor(e,t=In){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))}};var Dn="video";function er(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 s=i.holdWebRtcDial?.(),a=n.createElement("canvas"),d=!1,u=null,c=!1,l=()=>{if(u){for(let k of u.getVideoTracks())try{k.stop()}catch{}u=null}c&&(c=!1,t.onOverrideTrack(null))},p=new ue(new le(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new pe(i,t.streamName??Dn)),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:s,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>T(),onMediaTransportLost:k=>{d||(l(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(k),T())},onTransportChange:(k,A)=>{d||(k==="webrtc"&&(l(),T()),t.onTransportChange?.(k,A))}}),f=null,m=()=>{f!==null&&(clearTimeout(f),f=null)},v=t.wtRetryBaseMs??2e3,h=t.wtRetryCapMs??3e4,y=null,_=0,T=()=>{if(d||y!==null||p.activeTransport==="webtransport")return;let k=Math.min(v*2**_,h);y=setTimeout(()=>{y=null,_+=1,p.retryWebTransport().then(A=>{if(d){A&&p.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${_})`),_=0,I(A);T()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${_} failed:`,A),T())})},k)},M=()=>{y!==null&&(clearTimeout(y),y=null)},I=async k=>{if(d||k.kind!=="webtransport")return;let A=t.firstMediaWarnMs??1e4;m(),f=setTimeout(()=>{if(!(d||p.activeTransport!=="webtransport")){if(t.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED: webtransport established but delivered no media for ${A}ms \u2014 no QUIC media datagrams reached this client and WebRTC fallback is disabled by policy; tearing the dead leg down and retrying WT`),k.stop().catch(()=>{}),T();return}console.warn(`[urun] webtransport established but no QUIC media after ${A}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)}},A);try{await k.firstMedia}catch(D){m(),console.debug("[urun] webtransport ended before any media flowed:",D);return}if(m(),d||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;u=a.captureStream();let C=u.getVideoTracks()[0];C&&(c=!0,t.onOverrideTrack(C))};return(async()=>{let k=await p.connect();if(d){p.disconnect().catch(()=>{});return}await I(k)})().catch(k=>{if(m(),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}s?.proceed(`negotiation unavailable: ${k instanceof Error?k.message:String(k)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",k),T()}),{activeTransport:()=>p.activeTransport,dispose(){d=!0,m(),M(),l(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var Pn=new Set;function bt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var Un="rpc",nr=3e4,tr=3e4,Mn="rpc-resp";function Ln(i){return`${Mn}:${i}`}function gt(){return Se()}function xn(i){if(i&&typeof i=="object"){let e=i.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof i=="string"?i:JSON.stringify(i)}}function On(i,e,t,r,n,o,s,a,d,u){let c=[],l=null,p=!1,f=null,m=!1,v,h,y=new Promise((w,N)=>{v=w,h=N});y.catch(()=>{});let _=s(),T=null,M=null,I=null,k=null,A=null,C=null,D=!0,X=()=>{I&&(clearTimeout(I),I=null),k&&(k(),k=null)},J=()=>{A&&(clearTimeout(A),A=null),C&&(C(),C=null)},x=!1,Z=()=>{x||!m||(x=!0,i.set({rpc:{[e]:null}}))},F=()=>{D=!1,X(),J(),T?.(),T=null,M?.(),M=null,a?.removeEventListener("abort",P),_.dispose(),Z()},q=()=>{if(l){if(c.length>0){let w=l;l=null,w.resolve({value:c.shift(),done:!1})}else if(f!==null){let w=l;l=null,w.reject(f)}else if(p){let w=l;l=null,w.resolve({value:void 0,done:!0})}}},g=w=>{p||(c.push(w),q())},b=w=>{p||(f=w,p=!0,h(w),F(),q())},S=w=>{p||(p=!0,v(w),F(),q())},P=()=>{let w=a?.reason;b(w instanceof ge?w:new ve(e))},W=w=>{if(!(p||!w||typeof w!="object"))switch(J(),Z(),w.t){case"delta":typeof w.delta=="string"&&g(w.delta);break;case"response":S(w.body);break;case"error":{let{message:N,code:V}=xn(w.body);b(new ge(N,{requestId:e,code:w.code??V}));break}}},L=()=>{let w=_.messages()[Symbol.asyncIterator]();T=()=>{w.return?.(void 0)};let N=()=>{D&&w.next().then(V=>{if(D){if(V.done){p||S(void 0);return}W(V.value),N()}},V=>{D&&b(V)})};N()},j=()=>{if(!m){if(m=!0,a){if(a.aborted){b(new ve(e));return}a.addEventListener("abort",P,{once:!0})}M=d?.(w=>b(w))??null,L(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!i.synced&&(I=setTimeout(()=>{I=null,!p&&!i.synced&&b(new $e(u,e))},u),k=i.onSynced(()=>X())),C=i.onSynced(()=>{C=null,!(p||x||A)&&(A=setTimeout(()=>{A=null,!(p||x)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(tr/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).`)},tr))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(j(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(f!==null){let w=f;return f=null,Promise.reject(w)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((w,N)=>{l={resolve:w,reject:N}})},return(){return p||(p=!0,v(void 0),F()),Promise.resolve({value:void 0,done:!0})},throw(w){return p||(p=!0,h(w),F()),Promise.reject(w)}}}},body:y,start:j}}function rr(i){if(i&&typeof i=="object"){let{epoch:e,by:t}=i,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Wn(i,e){let r=i.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:o,br:s}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let d=rr(o);d&&(a.rt=d);let u=rr(s);return u&&(a.br=u),a}var vt=class{constructor(e,t,r,n,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let s=this._transport.getTrackByName(this._name)??null;s!==this._track&&this._setTrack(s)})}_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,o=null,s={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(s);let a=()=>{n=!0,e._messageConsumers.delete(s)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||n)&&(o=e._streamConsumeUnavailableError(d),a(),r)){let u=r;r=null,u.reject(o)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):o?Promise.reject(o):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=Wn(t,this._name),n=r?.br;if(n?.by==="runtime")throw new Be(this._name,"runtime","browser");if(n)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let s=r?.kind??e;s&&(o.kind=s),t.set({streams:{[this._name]:o}})}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??it;return Gt(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},fe=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Lt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_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,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=o,this._streamData=Ut(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=tt(()=>this.recover()),this._activity=et({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._presenceTracker=new ie({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this._activation=new te({onPhase:s=>this.onPhase(s),hint:()=>this.doc(ze).get(Ye)??this.doc("control").get(Qe),onData:(s,a)=>this._streamData.onData(s,a)})}_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 Pt({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,o=new he,s=new _e({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new i(e,o,s,bt(t),re({...t,baseUrl:r.baseUrl}));s.on("connected",()=>{s.multiplexer&&o.setTarget(s.multiplexer)}),s.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),s.setEndsAt(r.endsAt),ye()&&await ke();let d=t.getAccessToken,u=d?async()=>await d()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:u}),await s.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}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 He(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=Je(this.doc("control"),r=>{for(let n of Array.from(this._generationTickHandlers))try{n(r)}catch(o){console.warn("[urun] generationTick handler failed:",o)}})),()=>{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 K(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 $(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new $(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}stream(e){let t=this._streams.get(e);return t||(t=new vt(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new xt(e,this._sessionId,Pn.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ot(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=Te(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(Mt({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=gt(),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 o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;o=setTimeout(()=>n.abort(new qe(d,r)),d)}let s=this._consumeResponse(r,e,!1,n.signal);s.start();let a=this._presenceTracker?.workBegin();return s.body.finally(()=>{o&&clearTimeout(o),a?.()})}_consumeResponse(e,t,r,n,o){this._activity?.touch(),this._presenceTracker?.consumerRead();let s=this.doc(Un),a=Ln(e);return On(s,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),o??nr)}requestStream(e,t={}){let r=gt();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=gt(),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=er(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.disconnect(),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new ee)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}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 t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new je)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function ir(i){return`urun:logical:v1:${i.orgId}:${i.app}:${i.functionName}`}function wt(){try{return globalThis.sessionStorage??null}catch{return null}}function yt(i){let e=wt();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let r=JSON.parse(t);return typeof r?.logicalId!="string"||r.logicalId.length===0?null:{logicalId:r.logicalId}}catch{return null}}function sr(i,e){let t=wt();if(t)try{t.setItem(i,JSON.stringify({logicalId:e.logicalId}))}catch{}}function z(i){let e=wt();if(e)try{e.removeItem(i)}catch{}}var Nn=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Fn(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(!(Nn.has(r)||typeof r!="string"))return n=>{let o=n??{},s=ir({orgId:e.orgId,app:i,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,d=a(),u=e.jwt,c=e.getAccessToken?async g=>{let b=await e.getAccessToken(g);return b&&(u=b),b}:void 0,l={...e,getAccessToken:c},p=new he,f=new _e({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:d,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),m=new fe(d,p,f,bt(l),re(l)),v,h=!1,y=!1,_,T,M=new Promise(g=>{T=g}),I=g=>{_||(_="teardown",we({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},k=g=>{_||(_="abandon",we({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider,reason:"client_abandoned"}))},A=g=>{v=g,T({status:"ready",handle:g}),y&&I(g)};m.setEndHandler(async()=>{let g=v?{status:"ready",handle:v}:await M;if(g.status==="unavailable")throw new ee("[urun] session allocation failed before a releasable request was created",{cause:g.cause});let b=v??g.handle;return z(s),_==="teardown"?{status:"ended",requestId:b.requestId}:(_="end",It({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:c,authProvider:e.authProvider}))});let C=!1,D=!1,X=!1,J=async g=>{let b=e.sessionKey?void 0:yt(s)?.logicalId;C=!e.sessionKey&&b!==void 0;let S=await Dt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:c,authProvider:e.authProvider,idempotencyKey:g,sessionKey:e.sessionKey??b,priority:e.priority,onAdmission:W=>f.reportAdmission(W),onRequest:A}),P=c?await c()??void 0:e.jwt;return h||(e.sessionKey||sr(s,{logicalId:S.sessionId}),m.setSessionId(S.sessionId),m.setArtifactsAuth(re({...l,baseUrl:S.baseUrl})),f.setEndsAt(S.endsAt)),{url:S.wsUrl,sessionId:S.sessionId,jwt:P,iceServers:S.response.ice_servers,endsAt:S.endsAt}},x,Z=c?async()=>await c()??x:()=>x,F=()=>{let g=f.connectedUrl;return g?Te(g):void 0};f.setConnectionResolver(async()=>{let g=await J(a());return x=g.jwt,g}),f.on("phase",g=>{if(!Ve(g)||f.intentionalDisconnect||e.sessionKey)return;let b=yt(s)?.logicalId;b&&g.sessionId&&b!==g.sessionId||z(s)}),f.on("connected",()=>{f.multiplexer&&p.setTarget(f.multiplexer);let g=f.connectedUrl;g&&m.setDocTransport({wsUrl:g,token:Z,resolveServerUrl:F})});let q=async g=>{let b;try{b=await J(g)}catch(S){if(h){T({status:"unavailable",cause:S});return}if(console.error(`[urun] Failed to create session for ${r}:`,S),z(s),!D&&C&&Rt(S))return D=!0,console.warn(`[urun] the resumed session for ${r} was already closed server-side (terminal create echo) \u2014 discarding the stored resumption id and creating a fresh session`),q(a());v&&k(v);let P=S instanceof Error?S:new Error(String(S)),W=S instanceof be?S.httpStatus:void 0,L=S instanceof be?S.code:void 0;f.reportAllocationFailure(P,W,L),T({status:"unavailable",cause:S});return}h||(f.setAuth({jwt:b.jwt,authProvider:e.authProvider,orgId:e.orgId}),f.setConnection({url:b.url,sessionId:b.sessionId,iceServers:b.iceServers}),ye()&&await ke(),x=b.jwt,m.setDocTransport({wsUrl:b.url,token:Z,resolveServerUrl:F}),await f.connect({app:i,functionName:r,args:o}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))};if(m.onPhase(g=>{let b=g?.name;if(b==="live"){X=!0;return}b!=="ended"&&b!=="expired"&&b!=="error"||f.intentionalDisconnect||b==="error"&&g?.error?.kind!=="runtime-failed"||(e.sessionKey||z(s),!X&&C&&!D&&(D=!0,console.warn(`[urun] resumed session ${m.id} for ${r} is closed server-side (${b}) \u2014 discarding the stored resumption id and creating a fresh session`),q(a()).catch(S=>{console.error(`[urun] fresh-session fall-through failed for ${r}:`,S)})))}),q(d).catch(g=>{console.error(`[urun] Failed to connect session for ${r}:`,g)}),e.releaseOnLeave!==!1){let g=rt(()=>{if(h=!0,e.sessionKey||z(s),f.leaveLeg())return;if(f.connectedUrl!==null){f.disconnect();return}f.disconnect();let L=v;L?I(L):y=!0});m.onDisconnect(g);let b,S,P=!1,W=()=>{P||(P=!0,b?.(),S?.())};M.then(L=>{L.status!=="ready"||P||(b=nt(()=>v!==void 0))}),S=m.onPhase(L=>{let j=L?.name;(j==="ended"||j==="expired"||j==="error")&&W()}),P&&S(),m.onDisconnect(W)}return m}}})}var or="https://api.urun.sh",ar="URUN_DEV";function qn(){if(typeof process>"u")return!1;let i=process.env?.[ar];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var B=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function $n(i,e={}){if(!i)throw new B("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=H(e.baseUrl??or),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??qn())&&(n.dev=!0);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(n)})}catch(p){throw new B(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let s={};try{s=await o.json()}catch{}if(!o.ok){let p=typeof s.message=="string"?s.message:`HTTP ${o.status}`;throw new B(`[urun] client token mint failed: ${p}`,o.status)}let a=typeof s.token=="string"?s.token:"",d=typeof s.org_id=="string"?s.org_id:"",u=typeof s.expires_at=="string"?Date.parse(s.expires_at):Number.NaN,c=typeof s.expires_in=="number"?s.expires_in:void 0;if(!a)throw new B("[urun] client token mint returned no token (control-plane contract violation)",o.status);let l=Number.isFinite(u)?new Date(u):new Date(Date.now()+(c??60)*1e3);return{token:a,expiresAt:l,orgId:d}}var dr=3e4,cr="stream:",kt=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 o=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(o.timer),n.error?o.reject(new Error(n.error)):o.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=`${cr}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${cr}${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 o=String(++this._rpcId),s=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),n(new Error(`RPC request "${e}" timed out after ${dr}ms`)))},dr);this._pendingRpc.set(o,{resolve:r,reject:n,timer:s}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Bn(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 o=new Et(n);return new kt(n,o)}var jn='video/mp4; codecs="avc1.42E01E"';function Vn(i,e){let t=e?.codec??jn,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);r.src=o,n.addEventListener("sourceopen",()=>{let p;try{p=n.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):h}let f=i.getReader();function m(){return p.updating?new Promise(h=>{p.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function v(){try{for(;;){let{done:h,value:y}=await f.read();if(h){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{p.appendBuffer(y)}catch(_){if(_ instanceof DOMException&&_.name==="QuotaExceededError"){let T=p.buffered;if(T.length>0){let M=T.start(T.length-1);p.remove(0,M),await m(),p.appendBuffer(y)}else throw _}else throw _}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}v()}),r.play().catch(()=>{});let s=r,a=s.captureStream??s.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(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{c++,c>=l&&URL.revokeObjectURL(o)});return d}function Hn(i){return i.status.startsWith("pending_")}var Y=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)}},me=class extends Y{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Gn(i,e,t){let r=t||e||`HTTP ${i}`;return i===401?new me(r,e??"unauthorized"):new Y(r,{status:i,code:e??`http_${i}`})}var We=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 Y("[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),o=await this._resolveToken(),s=await this._fetch(n,e,o);if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await this._fetch(n,e,o))}if(!s.ok){let{code:a,message:d}=await this._readError(s);throw Gn(s.status,a,d)}return this._readJson(s)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,s])=>`${encodeURIComponent(o)}=${encodeURIComponent(s)}`).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 me("[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:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Kn(i){return new We(i)}var Ne=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 ur(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function zn(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Yn(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function St(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var Fe=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,St(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 Ne;return t=>e.getUserMedia(t)}async converge(e){for(let s of this.claims.values())s.track&&(s.track.stop(),s.track=null,s.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(s){let a=`one-capture getUserMedia(${ur(r)}) failed`,d=s instanceof Error?s.message:String(s);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||s}`);c.cause=s,St(u,c)}throw s}let o=[...this.claims.values()].sort((s,a)=>s===e?1:a===e?-1:0);for(let s of o){let a=zn(n,s.kind)[0]??null;if(s.released){a?.stop();continue}if(!a){this.claims.delete(s.kind),s.released=!0;let d=Object.assign(new Error(`one-capture getUserMedia(${ur(r)}) returned no ${s.kind} track`),{name:"NotFoundError"});if(s===e)throw d;St(s,d);continue}if(s.track=a,s.stream=Yn(n,a),s!==e)for(let d of[...s.trackListeners])try{d(a,s.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(o){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=o,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(o){return n.trackListeners.add(o),()=>n.trackListeners.delete(o)},onLost(o){return n.lostListeners.add(o),()=>n.lostListeners.delete(o)}}};return n}},Qn=null;function Xn(){return Qn??=new Fe}var lr="input",Jn=30;function Zn(i){let e=i.now??Date.now,t=i.field??lr,r=1e3/Math.max(i.hz??30,.001),n=new Set,o=0,s=0,a=0,d=0,u,c=null,l=!1,p=()=>{if(l)return;u=e(),d+=1;let m={keys:[...n],buttons:o,pointer:{x:s,y:a},seq:d,at:u};try{i.awareness.setLocalStateField(t,m)}catch{}},f=()=>{if(l)return;let m=e();if(u===void 0||m-u>=r){c&&(clearTimeout(c),c=null),p();return}if(c)return;let v=Math.max(r-(m-u),0);c=setTimeout(()=>{c=null,p()},v),c.unref?.()};return{keyDown(m){let v=String(m).toLowerCase();n.has(v)||(n.add(v),f())},keyUp(m){let v=String(m).toLowerCase();n.delete(v)&&f()},setButtons(m){let v=Number.isFinite(m)?Number(m):0;v!==o&&(o=v,f())},movePointer(m,v){let h=Number.isFinite(m)?Number(m):0,y=Number.isFinite(v)?Number(v):0;h===0&&y===0||(s+=h,a+=y,f())},heldKeys(){return[...n]},clear(){l||(n.clear(),o=0,c&&(clearTimeout(c),c=null),p())},dispose(){if(l)return;let m=n.size>0||o!==0;n.clear(),o=0,c&&(clearTimeout(c),c=null),m&&p(),l=!0}}}var ei=1024,ti=.92,ri=262144,ni=256e3,_t=[.9,.8,.7,.6,.5],pr=.8,ii=8;function At(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 si(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 mr(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 fr(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 Tt(i,e,t,r,n){let o=document.createElement("canvas");o.width=e,o.height=t;let s=o.getContext("2d");if(!s)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(s.fillStyle="#fff",s.fillRect(0,0,e,t)),s.drawImage(i,0,0,e,t),await mr(o,r,n)}async function oi(i,e,t,r){let{width:n,height:o}=e,s=await Tt(i,n,o,t,r);if(s.size<=256e3)return{blob:s,width:n,height:o};if(t==="image/jpeg"){for(let d of _t)if(!(d>=r)&&(s=await Tt(i,n,o,t,d),s.size<=256e3))return fr(`quality ${r} -> ${d}`,s.size),{blob:s,width:n,height:o}}let a=t==="image/jpeg"?_t[_t.length-1]:r;for(let d=0;d<ii;d++)if(n=Math.max(16,Math.round(n*pr)),o=Math.max(16,Math.round(o*pr)),s=await Tt(i,n,o,t,a),s.size<=256e3)return fr(`downscaled to ${n}x${o} @ q${a}`,s.size),{blob:s,width:n,height:o};throw new Error(`this image cannot be sent: even at ${n}x${o} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function ai(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,s=await si(i);try{let a=At(s.width,s.height,t),d=await oi(s,a,r,n);return{bytes:new Uint8Array(await d.blob.arrayBuffer()),type:r,width:d.width,height:d.height,source:o}}finally{s.close()}}function di(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 ci(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function ui(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:o="image/jpeg",quality:s=.92}=e??{},a=At(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)");o==="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 mr(d,o,s);return{bytes:new Uint8Array(await c.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var li=new Set(["w","a","s","d"]),Q=(i,e)=>Math.min(e,Math.max(-e,i));function pi(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:o=.06,maxPan:s=.12,maxLogZoom:a=.22}=i,d=0,u=0,c=0,l=null,p=new Set;return{pointerDelta(f,m){d=Q(d-f*e,s),u=Q(u-m*e,s)},keyDown(f){let m=f.toLowerCase();li.has(m)&&p.add(m)},keyUp(f){p.delete(f.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let f=1-o;d*=f,u*=f,c*=f},tick(f){if(l===null){l=f;return}let m=Math.max(0,Math.min(100,f-l))/1e3;l=f,p.has("w")&&(c=Q(c+t*m,a)),p.has("s")&&(c=Q(c-t*m,a)),p.has("a")&&(d=Q(d+r*m,s)),p.has("d")&&(d=Q(d-r*m,s));let v=Math.exp(-m*1e3/n);d*=v,u*=v,c*=v},transform(){return{translateX:d,translateY:u,scale:Math.exp(c)}},isIdentity(f=5e-4){return Math.abs(d)<f&&Math.abs(u)<f&&Math.abs(c)<f},reset(){d=0,u=0,c=0,p.clear()}}}export{Wr as ACTIVATION_COLD_BOOT_AFTER_MS,Nr as ACTIVATION_DEGRADED_AFTER_MS,Ye as ACTIVATION_HINT_PATH,Or as ACTIVATION_STILL_AFTER_MS,Ze as ACTIVITY_DOM_EVENTS,qt as ACTIVITY_FIELD,Qr as ACTIVITY_STAMP_MIN_INTERVAL_MS,te as ActivationMonitor,Fn as App,Ar as BACKOFF_BASE_MS,Rr as BACKOFF_MAX_ATTEMPTS,Er as BACKOFF_MAX_MS,Fe as CaptureController,Ne as CaptureUnavailableError,B as ClientTokenError,We as CreditsClient,Y as CreditsError,me as CreditsUnauthorizedError,ri as DATA_CHANNEL_MESSAGE_CEILING,nr as DEFAULT_DOC_SYNC_TIMEOUT_MS,or as DEFAULT_GATEWAY_URL,gr as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,ti as DEFAULT_REFERENCE_JPEG_QUALITY,ei as DEFAULT_REFERENCE_MAX_SIZE,_r as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Ur as DERIVED_LEG_SEP,R as DGRAM_HEADER_BYTES,Vt as FOCUS_FIELD,Jr as FOREGROUND_COALESCE_MS,ae as FrameReassembler,zr as GENERATION_TICK_EMIT_INTERVAL_MS,Yr as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Jn as INPUT_PRESENCE_DEFAULT_HZ,lr as INPUT_PRESENCE_FIELD,G as InvalidDurationError,Qe as LEGACY_ACTIVATION_HINT_PATH,ze as PLATFORM_DOC_NAME,De as PermanentLockedError,Ie as PinRequiresActiveTempError,ie as PresenceTracker,vr as ProduceAckTimeoutError,Re as RecordingNotFoundError,K as RecordingsClient,U as RecordingsError,ne as RecordingsUnauthorizedError,ve as RequestAbortError,je as RequestCancelledError,$e as RequestDocSyncError,ge as RequestError,qe as RequestTimeoutError,Ce as RetainNotTempError,Ee as RuntimeArtifactNotFoundError,$ as RuntimeArtifactsClient,E as RuntimeArtifactsError,Ae as RuntimeArtifactsUnauthorizedError,xr as SIGNALING_PROTOCOL_VERSION,Ge as STREAM_END,fe as Session,be as SessionAllocationError,hr as SessionEndError,ee as SessionEndUnavailableError,wr as SessionFailedError,Be as StreamDirectionConflict,ue as TransportNegotiator,kr as TransportSessionMismatchError,le as TransportSessionSignaling,ar as URUN_DEV_ENV,jt as USER_ACTIVITY_FIELD,Xr as USER_ACTIVITY_MIN_INTERVAL_MS,$t as VISIBILITY_FIELD,ni as WIRE_MESSAGE_BUDGET,Kt as WT_CONTROL_FRAME_MAX,Qt as WT_DATA_STREAM_VERSION,pe as WebRtcSession,ce as WebTransportSession,se as WtControlDecoder,Ue as WtDataStreamParser,Wt as activationHintFrom,ci as cameraCaptureAvailable,ui as captureStillFromVideo,Cr as computeBackoffDelay,ct as consumeWtDataStreams,et as createActivityTracker,pi as createCameraWarp,$n as createClientToken,Kn as createCreditsClient,Zn as createInputPresencePublisher,Kr as createRecordingsClient,qr as createRuntimeArtifactsClient,Bn as createStore,Ke as decodeStreamEnvelope,Lr as derivedLegName,Mr as derivedLegRole,br as describeSessionFailure,Tr as describeSessionPhase,Pr as encodeStreamEnvelope,ot as encodeWtControlFrame,At as fitWithin,Xe as isDurationString,Hn as isPendingRecording,Ir as isRetryableSessionError,Ve as isServerTerminalPhase,Sr as isWakingPhase,it as mediaRecorderChunkSource,ai as normalizeReferenceImage,Hr as normalizeRetention,nt as observeLeaveConfirm,tt as observePageLifecycle,rt as observePageTeardown,oe as parseDgramHeader,Dr as prewake,di as referenceImageErrorMessage,we as releaseSessionBeacon,yr as sessionFailureFromMediaError,Xn as sharedCaptureController,Vn as videoStream,Je as watchGenerationTick,He as whenLive,at as writeDgramHeader};
|
|
2
|
+
import{$ as Mt,A as Ir,B as Dr,C as K,D as It,E as we,F as Dt,G as Pt,H as Ut,I as Pr,J as ye,M as ke,N as Se,O as Ge,P as Ur,Q as Ke,S as Lt,U as Lr,V as Mr,W as xr,X as Wr,Y as _e,_ as Te,a as Rt,aa as xt,b as he,ba as Wt,c as ee,ca as Ot,d as gr,e as ge,f as qe,g as $e,h as Be,i as vr,j as br,k as ve,l as je,m as wr,n as yr,o as kr,p as Sr,q as be,r as Ct,s as _r,t as Ve,u as Tr,v as He,w as Ar,x as Er,y as Rr,z as Cr}from"./chunk-FSUNC7FS.mjs";var Or=15e3,Nr=45e3,Fr=12e4,ze="platform",Ye="activation",Qe="desired.activation";function Nt(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}],te=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==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=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},o=Nt(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let s of Array.from(this._handlers))s(n)}};var E=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)}},Ae=class extends E{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ee=class extends E{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function re(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function $r(i){return new j(i)}var j=class{_options;constructor(e){this._options=e}async list(e){let r=qt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new E("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Ft)}async getDownloadUrl(e,t){let r=qt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!jr(n))throw new E("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Ft(r.artifact),downloadUrl:n}}async _request(e,t){let r=It(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(s){if(n=s instanceof Error?s:new Error(String(s)),n instanceof E&&Vr(n.status))throw n}throw n??new E("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${K(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),s=await fetch(n,{method:"GET",headers:this._headers(o)});if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await fetch(n,{method:"GET",headers:this._headers(o)}))}if(!s.ok){let{code:a,message:d}=await this._readError(s,e);throw Hr(s.status,a,d)}try{return await s.json()}catch(a){throw new E(`[urun] runtime artifacts: invalid JSON response from ${K(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=K(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:s,message:a}=o;return{code:typeof s=="string"&&s.length>0?s:`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 Ft(i){if(!i||typeof i!="object")throw new E("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=N(e,"artifact_id")||N(e,"id"),r=N(e,"filename"),n=N(e,"kind"),o=N(e,"status")||"ready",s=Br(e,"size_bytes"),a=N(e,"sha256");if(!t||!r||!n||s==null||!a)throw new E("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:N(e,"content_type")||"application/octet-stream",sizeBytes:s,sha256:a,status:o,createdAt:N(e,"created_at"),expiresAt:N(e,"expires_at")}}function N(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function Br(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function jr(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function Vr(i){return i===401||i===403}function Hr(i,e,t){return i===401?new Ae(t,e):i===404?new Ee(t,e):new E(t,i,e)}function qt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new E("[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)}},ne=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)}},Re=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)}},Ce=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)}},Ie=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)}},De=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)}},z=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 Xe(i){return/^(\d+[smhdw])+$/.test(i)}function Gr(i){if(i==="pin")return{action:"pin"};if(Xe(i))return{action:"retain",duration:i};throw new z(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Kr(i,e,t){let r=t||e||`HTTP ${i}`;if(i===401)return new ne(r,e??"unauthorized");if(i===404)return new Re(r,e??"not_found");if(i===400)return new z(r,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Ce(r,e);case"pin_requires_active_temp":return new Ie(r,e);case"permanent_locked":return new De(r,e)}return new x(r,{status:i,code:e??`http_${i}`})}var Y=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(!Xe(t))throw new z(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new 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),o=await this._resolveToken(),s=await this._fetch(n,e,o,r.body);if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await this._fetch(n,e,o,r.body))}if(!s.ok){let{code:a,message:d}=await this._readError(s);throw Kr(s.status,a,d)}return this._readJson(s)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,s])=>`${encodeURIComponent(o)}=${encodeURIComponent(s)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let s={method:t,headers:o};return n!==void 0&&(o["Content-Type"]="application/json",s.body=JSON.stringify(n)),fetch(e,s)}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 ne("[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:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function zr(i){return new Y(i)}var Yr=1e3,Qr=12e3;function Je(i,e,t={}){let r=null,n=0,o=0,s=null,a=-1,d=()=>{let h=i.get("desired.billing.generationSeconds");if(typeof h!="number"||!Number.isFinite(h)||h<=0)return null;let y=i.get("desired.billing.epoch"),_=i.get("desired.billing.updatedAtMs");return{seconds:h,epoch:typeof y=="number"&&Number.isFinite(y)?y:0,updatedAtMs:typeof _=="number"&&Number.isFinite(_)?_:null}},u=()=>{if(r===null)return null;let h=Math.min(Math.max(0,Date.now()-n),o);return r+h/1e3},c=()=>{let h=t.creditsPerSecond;if(typeof h=="number"&&Number.isFinite(h)&&h>0)return h;let y=i.get("desired.billing.creditsPerSecond");return typeof y=="number"&&Number.isFinite(y)&&y>0?y:null},l=()=>{let h=u();if(h===null)return;let y=Math.floor(h);if(y<=a)return;a=y;let _={seconds:y},T=c();T!==null&&(_.estimatedCredits=y*T),e(_)},p=h=>{n=Date.now();let y=h===null?0:Math.max(0,n-h);o=Math.max(0,12e3-y)},f=()=>{let h=d();if(h!==null){if(s!==null&&h.epoch!==s){s=h.epoch,r=h.seconds,a=-1,p(h.updatedAtMs),l();return}r!==null&&h.seconds<=r||(s=h.epoch,r=h.seconds,p(h.updatedAtMs),l())}};f();let m=i.on("change",f),v=setInterval(l,1e3);return v.unref?.(),()=>{clearInterval(v),m()}}var $t="activity",Bt="visibility",Xr=15e3,Ze=["pointerdown","pointermove","keydown","wheel","touchstart"];function et(i){let e=i.now??Date.now,t=i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,r=i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,n=!1,o,s=()=>{if(n)return;let l=e();if(!(o!==void 0&&l-o<15e3)){o=l;try{i.awareness.setLocalStateField($t,{at:l})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{i.awareness.setLocalStateField(Bt,r.visibilityState)}catch{}},d=()=>s(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&s()};if(t)for(let l of Ze)t.addEventListener(l,d,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",u);let c=null;return i.isProducing&&(c=setInterval(()=>{if(!n)try{i.isProducing?.()&&s()}catch{}},15e3),c.unref?.()),s(),a(),{touch:s,dispose(){if(!n){if(n=!0,t)for(let l of Ze)t.removeEventListener(l,d,{capture:!0});r&&r.removeEventListener("visibilitychange",u),c&&(clearInterval(c),c=null)}}}}var Vt="user_activity",Ht="focus",Jr=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 ie=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(Ht,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(Vt,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 Zr=250;function tt(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 rt(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 nt(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 Gt="video/mp4";function it(i,e={}){let t=e.timesliceMs??1e3,r=null,n=null,o=!1,s=(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(Gt)?Gt:void 0),p=new MediaStream([a]),f=new c(p,l?{mimeType:l}:void 0);r=f;let m=Promise.resolve();f.ondataavailable=v=>{let h=v.data;o||!h||h.size===0||(m=m.then(async()=>{let y=new Uint8Array(await h.arrayBuffer());o||d(y)}))},f.onstop=()=>{m.then(()=>{o||u()})},f.onerror=()=>{m.then(()=>{o||u()})},f.start(t)};return{start(a,d){if(r||o)return;let u=i.track();if(u){s(u,a,d);return}n=i.onTrack(c=>{!c||r||o||(n?.(),n=null,s(c,a,d))})},stop(){if(o)return;o=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function en(i){let e=i;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=i.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Kt(i,e){let t=null,r=!1,n=!1,o=new ReadableStream({pull(s){r||(r=!0,t=i(e),t.start(a=>{if(!n)try{s.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{s.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return en(o)}import{encode as tn,decode as rn}from"@msgpack/msgpack";var zt=65536;function ot(i){let e=tn(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var se=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>zt)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(rn(n))}return t}},R=12,st=1,nn=0,Pe=1,Yt=2;function oe(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&st)===st,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function at(i){let e=new Uint8Array(R),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?st:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??nn),e}var sn=100,Qt=100,ae=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??sn}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<R)return;let t=oe(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(R),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-Qt?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Qt}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((s,a)=>s+a.byteLength,0),n=new Uint8Array(r),o=0;for(let s of t.chunks)n.set(s,o),o+=s.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 on=/^avc[13]\.[0-9a-fA-F]{6}$/;function an(i){return on.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 dt(i,e){let t=an(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var Xt=1,Ue=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!==Xt)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=Ke(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===Ge&&(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 ct(i,e){let t=i.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&dn(r,e).catch(o=>{e.onLaneError(o instanceof Error?o:new Error(String(o)))})}}async function dn(i,e){let t=i.getReader(),r=new Ue;try{for(;;){let{value:n,done:o}=await t.read();if(o)break;if(!(!n||n.byteLength===0))for(let{name:s,payload:a}of r.push(n))e.onData(s,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var ut=40,pt=48e3,cn=64,un=100,lt=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<R)return;let t=oe(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-un)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>cn;){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(R),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),o=new Uint8Array(n),s=0;for(let a of r.chunks)o.set(a,s),s+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:o})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},ln=3,pn=1e4,Le=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??ut;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${ut}ms`),r=ut),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 lt(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/pt)),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,o=Math.max(1,e.numberOfChannels),s=t.createBuffer(o,n,e.sampleRate);for(let c=0;c<o;c++){let l=new Float32Array(n);e.copyTo(l,{planeIndex:c,format:"f32-planar"}),s.copyToChannel(l,c)}let a=n/e.sampleRate;e.close();let d=t.createBufferSource();d.buffer=s,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<pn),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=ln){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 de=1200,fn=3,mn=1e4;function hn(i){return Math.round(i*(pt/1e6))%2**32>>>0}function ft(i,e,t,r,n){let o=r-R;if(o<=0)return null;let s=Math.max(1,Math.ceil(t.byteLength/o));if(s>255)return null;let a=[];for(let d=0;d<s;d++){let u=t.subarray(d*o,Math.min((d+1)*o,t.byteLength)),c=at({groupId:e>>>0,frameSeq:i>>>0,keyframe:n?.keyframe??!0,fragIndex:d,fragCount:s,lane:n?.lane??Pe}),l=new Uint8Array(R+u.byteLength);l.set(c,0),l.set(u,R),a.push(l)}return a}var Me=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;generation=0;cancelCapture=null;nodeBridge=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}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}let n;if(gn(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 o=++this.generation,s=new r({track:n}).readable.getReader(),a=!1;this.cancelCapture=()=>{a=!0,s.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&o===this.generation;){let{value:d,done:u}=await s.read();if(u)break;if(d){if(a||this.stopped||o!==this.generation){d.close();break}this.encodeAudioData(d)}}})().catch(d=>{!a&&!this.stopped&&o===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.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=ft(this.frameSeq,hn(e.timestamp),t,this.sink.maxDatagramSize()||de);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<mn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=fn){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 gn(i){let e=i;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var vn=9e4,bn="avc1.42E01F",wn=60,yn=3,kn=1e4;function Sn(i){return Math.round(i*(vn/1e6))%2**32>>>0}var xe=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,o=new r({track:e}).readable.getReader(),s=!1;this.cancelCapture=()=>{s=!0,o.cancel().catch(()=>{})},(async()=>{for(;!s&&!this.stopped&&n===this.generation;){let{value:a,done:d}=await o.read();if(d)break;if(a){if(s||this.stopped||n!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!s&&!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 o=globalThis.VideoEncoder;if(typeof o!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new o({output:s=>this.sendFrame(s),error:s=>this.onEncoderError(s)})),this.encoderDims=t,this.encoder.configure({codec:bn,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(s){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${s instanceof Error?s.message:String(s)}`);return}}let n=this.keyframeWanted||this.framesSinceKeyframe>=wn;this.keyframeWanted=!1,this.framesSinceKeyframe=n?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:n})}catch(o){this.onEncoderError(o instanceof Error?o:new Error(String(o)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=ft(this.frameSeq,Sn(e.timestamp),t,this.sink.maxDatagramSize()||de,{lane:Yt,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<kn),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=yn){this.die(`video encoder: ${e.message}`);return}console.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",e.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(e){this.stopped||(console.warn(`[urun] WT video uplink lane dead (${e}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function _n(i){return i.byteLength>=2&&i[0]===1&&i[1]===3}var We=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 o=this.streams.get(e);if(!o){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),o={writer:a},this.streams.set(e,o)}let s=new Uint8Array(4+t.byteLength);new DataView(s.buffer).setUint32(0,t.byteLength,!0),s.set(t,4),await o.writer.write(s),_n(t)&&(this.streams.delete(e),await o.writer.close().catch(()=>{}))}catch(o){throw this.die(o instanceof Error?o.message:String(o)),o}});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 mt=250,Tn=3,An=1e4,ht=2500,En=25,Rn=2e3,ce=class{constructor(e,t,r,n,o,s,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=n;this.audioUplink=o;this.videoUplink=s;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 ae({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&&dt(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 o=n.readable.getReader(),s=new se,a=[],d=await this.readControl(o,s,a);if(d?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");if(r&&(dt(d.codec,"hello-ack"),this.initDecoder(d.codec,d.width,d.height)),this.offer.audio&&this.audioLane){let c=new Le(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??de}};if(this.offer.audioUp===!0&&this.audioUplink)try{let c=new Me(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 xe(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 We({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(o,s,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 ${mt}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,ct(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 o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new n({output:s=>{this.frameOutputEver=!0,this.frameOutputsInWindow++,this.canvas.width=s.displayWidth,this.canvas.height=s.displayHeight,o.drawImage(s,0,0),s.close()},error:s=>this.onDecoderError(s)}),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<An),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=Tn){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+=mt;else return this.decodeStalledMs=0,!1;return this.decodeStalledMs<ht?!1:(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${ht}ms \u2014 broken WT media leg; failing over LOUDLY`),this.die(`decode-stall: datagrams flowing but nothing decoded within ${ht}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<Rn),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<En)&&(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>=R&&t[11]===Pe){this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;this.videoArrivedEver=!0,this.videoArrivalsInWindow++;let n=performance.now();if(this.lastArrivalTs>0){let o=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-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(ot(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:o,done:s}=await e.read();if(s)return null;o&&r.push(...t.push(o))}}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(),o=this.videoArrivalsInWindow,s=this.frameOutputsInWindow;if(this.videoArrivalsInWindow=0,this.frameOutputsInWindow=0,this.evaluateDecodeLiveness(o,s))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(()=>{})},mt)}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 Jt=2500,Zt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Cn=1e4,ue=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,o={webtransport:t&&r&&n,webcodecs:r,codecs:Zt,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:o});let s=o.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,d=s&&!!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(s?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),s){let u=null;try{return u=this.createWebTransportSession(),await gt(u.start(),this.opts.quicDeadlineMs??Jt,"quic connect deadline"),this.engageQuicDataLane(u,o.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=s?"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(),s||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,o=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",s=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:Zt,wtData:n,wtAudio:o,wtAudioUp:s,wtVideoUp:a,wtDataUp:d}}),!this.offer.webtransport)return null;let u=this.createWebTransportSession();try{await gt(u.start(),this.opts.quicDeadlineMs??Jt,"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,o)=>r.onData(n,o),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 ce(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 o=await gt(this.startWebRtcOn(n),this.opts.webRtcFailoverDeadlineMs??Cn,"webrtc failover produced no media transport");if(this.session!==e){o.stop().catch(()=>{});return}this.session=o,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(o){if(n.stop().catch(()=>{}),this.session!==e)return;this.session=null;let s=o instanceof Error?o.message:String(o),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 (${s}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${s}). 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 gt(i,e,t){return new Promise((r,n)=>{let o=setTimeout(()=>n(new Error(t)),e);i.then(s=>{clearTimeout(o),r(s)},s=>{clearTimeout(o),n(s)})})}var In=1e4,le=class{constructor(e,t=In){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=Se();return new Promise((n,o)=>{let s=setTimeout(()=>{a(),o(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(s),a(),d.error){o(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(s),a(),o(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 Dn="video",pe=class{constructor(e,t=Dn){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 er(i){let e=i;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Pn="video";function tr(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 s=i.holdWebRtcDial?.(),a=n.createElement("canvas"),d=!1,u=null,c=!1,l=()=>{if(u){for(let k of u.getVideoTracks())try{k.stop()}catch{}u=null}c&&(c=!1,t.onOverrideTrack(null))},p=new ue(new le(i),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new pe(i,t.streamName??Pn)),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:s,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>T(),onMediaTransportLost:k=>{d||(l(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(k),T())},onTransportChange:(k,A)=>{d||(k==="webrtc"&&(l(),T()),t.onTransportChange?.(k,A))}}),f=null,m=()=>{f!==null&&(clearInterval(f),f=null)},v=t.wtRetryBaseMs??2e3,h=t.wtRetryCapMs??3e4,y=null,_=0,T=()=>{if(d||y!==null||p.activeTransport==="webtransport")return;let k=Math.min(v*2**_,h);y=setTimeout(()=>{y=null,_+=1,p.retryWebTransport().then(A=>{if(d){A&&p.disconnect().catch(()=>{});return}if(A)return console.debug(`[urun] webtransport upgraded in background (retry ${_})`),_=0,D(A);T()}).catch(A=>{d||(console.debug(`[urun] webtransport background retry ${_} failed:`,A),T())})},k)},W=()=>{y!==null&&(clearTimeout(y),y=null)},D=async k=>{if(d||k.kind!=="webtransport")return;let A=t.pathHealthProbeMs??1e4;m();let C=!1;f=setInterval(()=>{if(d||p.activeTransport!=="webtransport")return;let P=er(k);if(!P){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)"),m();return}let U=P.pathLiveness();if(!U.alive){let L=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${U.evidence}`+(L?" \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"),m(),P.fail(`path health: ${U.evidence}`);return}if(!C){if(C=!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 k.firstMedia}catch(P){m(),console.debug("[urun] webtransport ended before any media flowed:",P);return}if(m(),d||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;u=a.captureStream();let I=u.getVideoTracks()[0];I&&(c=!0,t.onOverrideTrack(I))};return(async()=>{let k=await p.connect();if(d){p.disconnect().catch(()=>{});return}await D(k)})().catch(k=>{if(m(),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}s?.proceed(`negotiation unavailable: ${k instanceof Error?k.message:String(k)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",k),T()}),{activeTransport:()=>p.activeTransport,dispose(){d=!0,m(),W(),l(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var Un=new Set;function wt(i){if(i.functionsUrl)return{functionsUrl:i.functionsUrl,orgId:i.orgId,apiKey:i.apiKey,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}var Ln="rpc",ir=3e4,rr=3e4,Mn="rpc-resp";function xn(i){return`${Mn}:${i}`}function vt(){return Se()}function Wn(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 On(i,e,t,r,n,o,s,a,d,u){let c=[],l=null,p=!1,f=null,m=!1,v,h,y=new Promise((w,q)=>{v=w,h=q});y.catch(()=>{});let _=s(),T=null,W=null,D=null,k=null,A=null,C=null,I=!0,P=()=>{D&&(clearTimeout(D),D=null),k&&(k(),k=null)},U=()=>{A&&(clearTimeout(A),A=null),C&&(C(),C=null)},L=!1,Z=()=>{L||!m||(L=!0,i.set({rpc:{[e]:null}}))},$=()=>{I=!1,P(),U(),T?.(),T=null,W?.(),W=null,a?.removeEventListener("abort",M),_.dispose(),Z()},B=()=>{if(l){if(c.length>0){let w=l;l=null,w.resolve({value:c.shift(),done:!1})}else if(f!==null){let w=l;l=null,w.reject(f)}else if(p){let w=l;l=null,w.resolve({value:void 0,done:!0})}}},g=w=>{p||(c.push(w),B())},b=w=>{p||(f=w,p=!0,h(w),$(),B())},S=w=>{p||(p=!0,v(w),$(),B())},M=()=>{let w=a?.reason;b(w instanceof ge?w:new ve(e))},F=w=>{if(!(p||!w||typeof w!="object"))switch(U(),Z(),w.t){case"delta":typeof w.delta=="string"&&g(w.delta);break;case"response":S(w.body);break;case"error":{let{message:q,code:G}=Wn(w.body);b(new ge(q,{requestId:e,code:w.code??G}));break}}},O=()=>{let w=_.messages()[Symbol.asyncIterator]();T=()=>{w.return?.(void 0)};let q=()=>{I&&w.next().then(G=>{if(I){if(G.done){p||S(void 0);return}F(G.value),q()}},G=>{I&&b(G)})};q()},H=()=>{if(!m){if(m=!0,a){if(a.aborted){b(new ve(e));return}a.addEventListener("abort",M,{once:!0})}W=d?.(w=>b(w))??null,O(),i.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!i.synced&&(D=setTimeout(()=>{D=null,!p&&!i.synced&&b(new $e(u,e))},u),k=i.onSynced(()=>P())),C=i.onSynced(()=>{C=null,!(p||L||A)&&(A=setTimeout(()=>{A=null,!(p||L)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(rr/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).`)},rr))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(H(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(f!==null){let w=f;return f=null,Promise.reject(w)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((w,q)=>{l={resolve:w,reject:q}})},return(){return p||(p=!0,v(void 0),$()),Promise.resolve({value:void 0,done:!0})},throw(w){return p||(p=!0,h(w),$()),Promise.reject(w)}}}},body:y,start:H}}function nr(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 Nn(i,e){let r=i.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:o,br:s}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let d=nr(o);d&&(a.rt=d);let u=nr(s);return u&&(a.br=u),a}var bt=class{constructor(e,t,r,n,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let s=this._transport.getTrackByName(this._name)??null;s!==this._track&&this._setTrack(s)})}_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,o=null,s={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(s);let a=()=>{n=!0,e._messageConsumers.delete(s)};return e._transport.mediaAvailability().then(d=>{if(!(d===null||n)&&(o=e._streamConsumeUnavailableError(d),a(),r)){let u=r;r=null,u.reject(o)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):o?Promise.reject(o):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=Nn(t,this._name),n=r?.br;if(n?.by==="runtime")throw new Be(this._name,"runtime","browser");if(n)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let s=r?.kind??e;s&&(o.kind=s),t.set({streams:{[this._name]:o}})}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??it;return Kt(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},fe=class i{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new xt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_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,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=o,this._streamData=Lt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=tt(()=>this.recover()),this._activity=et({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._presenceTracker=new ie({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this._activation=new te({onPhase:s=>this.onPhase(s),hint:()=>this.doc(ze).get(Ye)??this.doc("control").get(Qe),onData:(s,a)=>this._streamData.onData(s,a)})}_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 Ut({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,o=new he,s=new _e({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new i(e,o,s,wt(t),re({...t,baseUrl:r.baseUrl}));s.on("connected",()=>{s.multiplexer&&o.setTarget(s.multiplexer)}),s.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),s.setEndsAt(r.endsAt),ye()&&await ke();let d=t.getAccessToken,u=d?async()=>await d()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:u}),await s.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}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 He(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=Je(this.doc("control"),r=>{for(let n of Array.from(this._generationTickHandlers))try{n(r)}catch(o){console.warn("[urun] generationTick handler failed:",o)}})),()=>{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 Y(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 j(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new j(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}stream(e){let t=this._streams.get(e);return t||(t=new bt(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),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 Wt(e,this._sessionId,Un.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ot(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=Te(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(Mt({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=vt(),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 o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let d=t.timeout;o=setTimeout(()=>n.abort(new qe(d,r)),d)}let s=this._consumeResponse(r,e,!1,n.signal);s.start();let a=this._presenceTracker?.workBegin();return s.body.finally(()=>{o&&clearTimeout(o),a?.()})}_consumeResponse(e,t,r,n,o){this._activity?.touch(),this._presenceTracker?.consumerRead();let s=this.doc(Ln),a=xn(e);return On(s,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,d=>(this._activeRequests.add(d),()=>this._activeRequests.delete(d)),o??ir)}requestStream(e,t={}){let r=vt();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=vt(),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=tr(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.disconnect(),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new ee)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}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 t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new je)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function sr(i){return`urun:logical:v1:${i.orgId}:${i.app}:${i.functionName}`}function yt(){try{return globalThis.sessionStorage??null}catch{return null}}function kt(i){let e=yt();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let r=JSON.parse(t);return typeof r?.logicalId!="string"||r.logicalId.length===0?null:{logicalId:r.logicalId}}catch{return null}}function or(i,e){let t=yt();if(t)try{t.setItem(i,JSON.stringify({logicalId:e.logicalId}))}catch{}}function Q(i){let e=yt();if(e)try{e.removeItem(i)}catch{}}var Fn=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function qn(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(!(Fn.has(r)||typeof r!="string"))return n=>{let o=n??{},s=sr({orgId:e.orgId,app:i,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,d=a(),u=e.jwt,c=e.getAccessToken?async g=>{let b=await e.getAccessToken(g);return b&&(u=b),b}:void 0,l={...e,getAccessToken:c},p=new he,f=new _e({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:d,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),m=new fe(d,p,f,wt(l),re(l)),v,h=!1,y=!1,_,T,W=new Promise(g=>{T=g}),D=g=>{_||(_="teardown",we({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))},k=g=>{_||(_="abandon",we({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider,reason:"client_abandoned"}))},A=g=>{v=g,T({status:"ready",handle:g}),y&&D(g)};m.setEndHandler(async()=>{let g=v?{status:"ready",handle:v}:await W;if(g.status==="unavailable")throw new ee("[urun] session allocation failed before a releasable request was created",{cause:g.cause});let b=v??g.handle;return Q(s),_==="teardown"?{status:"ended",requestId:b.requestId}:(_="end",Dt({baseUrl:b.baseUrl,requestId:b.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:c,authProvider:e.authProvider}))});let C=!1,I=!1,P=!1,U=async g=>{let b=e.sessionKey?void 0:kt(s)?.logicalId;C=!e.sessionKey&&b!==void 0;let S=await Pt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:i,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:c,authProvider:e.authProvider,idempotencyKey:g,sessionKey:e.sessionKey??b,priority:e.priority,onAdmission:F=>f.reportAdmission(F),onRequest:A}),M=c?await c()??void 0:e.jwt;return h||(e.sessionKey||or(s,{logicalId:S.sessionId}),m.setSessionId(S.sessionId),m.setArtifactsAuth(re({...l,baseUrl:S.baseUrl})),f.setEndsAt(S.endsAt)),{url:S.wsUrl,sessionId:S.sessionId,jwt:M,iceServers:S.response.ice_servers,endsAt:S.endsAt}},L,Z=c?async()=>await c()??L:()=>L,$=()=>{let g=f.connectedUrl;return g?Te(g):void 0};f.setConnectionResolver(async()=>{let g=await U(a());return L=g.jwt,g}),f.on("phase",g=>{if(!Ve(g)||f.intentionalDisconnect||e.sessionKey)return;let b=kt(s)?.logicalId;b&&g.sessionId&&b!==g.sessionId||Q(s)}),f.on("connected",()=>{f.multiplexer&&p.setTarget(f.multiplexer);let g=f.connectedUrl;g&&m.setDocTransport({wsUrl:g,token:Z,resolveServerUrl:$})});let B=async g=>{let b;try{b=await U(g)}catch(S){if(h){T({status:"unavailable",cause:S});return}if(console.error(`[urun] Failed to create session for ${r}:`,S),Q(s),!I&&C&&Ct(S))return I=!0,console.warn(`[urun] the resumed session for ${r} was already closed server-side (terminal create echo) \u2014 discarding the stored resumption id and creating a fresh session`),B(a());v&&k(v);let M=S instanceof Error?S:new Error(String(S)),F=S instanceof be?S.httpStatus:void 0,O=S instanceof be?S.code:void 0;f.reportAllocationFailure(M,F,O),T({status:"unavailable",cause:S});return}h||(f.setAuth({jwt:b.jwt,authProvider:e.authProvider,orgId:e.orgId}),f.setConnection({url:b.url,sessionId:b.sessionId,iceServers:b.iceServers}),ye()&&await ke(),L=b.jwt,m.setDocTransport({wsUrl:b.url,token:Z,resolveServerUrl:$}),await f.connect({app:i,functionName:r,args:o}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))};if(m.onPhase(g=>{let b=g?.name;if(b==="live"){P=!0;return}b!=="ended"&&b!=="expired"&&b!=="error"||f.intentionalDisconnect||b==="error"&&g?.error?.kind!=="runtime-failed"||(e.sessionKey||Q(s),!P&&C&&!I&&(I=!0,console.warn(`[urun] resumed session ${m.id} for ${r} is closed server-side (${b}) \u2014 discarding the stored resumption id and creating a fresh session`),B(a()).catch(S=>{console.error(`[urun] fresh-session fall-through failed for ${r}:`,S)})))}),B(d).catch(g=>{console.error(`[urun] Failed to connect session for ${r}:`,g)}),e.releaseOnLeave!==!1){let g=rt(()=>{if(h=!0,e.sessionKey||Q(s),f.leaveLeg())return;if(f.connectedUrl!==null){f.disconnect();return}f.disconnect();let O=v;O?D(O):y=!0});m.onDisconnect(g);let b,S,M=!1,F=()=>{M||(M=!0,b?.(),S?.())};W.then(O=>{O.status!=="ready"||M||(b=nt(()=>v!==void 0))}),S=m.onPhase(O=>{let H=O?.name;(H==="ended"||H==="expired"||H==="error")&&F()}),M&&S(),m.onDisconnect(F)}return m}}})}var ar="https://api.urun.sh",dr="URUN_DEV";function $n(){if(typeof process>"u")return!1;let i=process.env?.[dr];if(typeof i!="string")return!1;let e=i.trim().toLowerCase();return e==="1"||e==="true"}var V=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Bn(i,e={}){if(!i)throw new V("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=K(e.baseUrl??ar),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??$n())&&(n.dev=!0);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(n)})}catch(p){throw new V(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let s={};try{s=await o.json()}catch{}if(!o.ok){let p=typeof s.message=="string"?s.message:`HTTP ${o.status}`;throw new V(`[urun] client token mint failed: ${p}`,o.status)}let a=typeof s.token=="string"?s.token:"",d=typeof s.org_id=="string"?s.org_id:"",u=typeof s.expires_at=="string"?Date.parse(s.expires_at):Number.NaN,c=typeof s.expires_in=="number"?s.expires_in:void 0;if(!a)throw new V("[urun] client token mint returned no token (control-plane contract violation)",o.status);let l=Number.isFinite(u)?new Date(u):new Date(Date.now()+(c??60)*1e3);return{token:a,expiresAt:l,orgId:d}}var cr=3e4,ur="stream:",St=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 o=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(o.timer),n.error?o.reject(new Error(n.error)):o.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=`${ur}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${ur}${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 o=String(++this._rpcId),s=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),n(new Error(`RPC request "${e}" timed out after ${cr}ms`)))},cr);this._pendingRpc.set(o,{resolve:r,reject:n,timer:s}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function jn(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 o=new Rt(n);return new St(n,o)}var Vn='video/mp4; codecs="avc1.42E01E"';function Hn(i,e){let t=e?.codec??Vn,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);r.src=o,n.addEventListener("sourceopen",()=>{let p;try{p=n.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):h}let f=i.getReader();function m(){return p.updating?new Promise(h=>{p.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function v(){try{for(;;){let{done:h,value:y}=await f.read();if(h){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{p.appendBuffer(y)}catch(_){if(_ instanceof DOMException&&_.name==="QuotaExceededError"){let T=p.buffered;if(T.length>0){let W=T.start(T.length-1);p.remove(0,W),await m(),p.appendBuffer(y)}else throw _}else throw _}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}v()}),r.play().catch(()=>{});let s=r,a=s.captureStream??s.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(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{c++,c>=l&&URL.revokeObjectURL(o)});return d}function Gn(i){return i.status.startsWith("pending_")}var X=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)}},me=class extends X{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function Kn(i,e,t){let r=t||e||`HTTP ${i}`;return i===401?new me(r,e??"unauthorized"):new X(r,{status:i,code:e??`http_${i}`})}var Oe=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 X("[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),o=await this._resolveToken(),s=await this._fetch(n,e,o);if(s.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,s=await this._fetch(n,e,o))}if(!s.ok){let{code:a,message:d}=await this._readError(s);throw Kn(s.status,a,d)}return this._readJson(s)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,s])=>`${encodeURIComponent(o)}=${encodeURIComponent(s)}`).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 me("[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:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function zn(i){return new Oe(i)}var Ne=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 lr(i){let e=[];return i.audio&&e.push("audio"),i.video&&e.push("video"),e.join("+")}function Yn(i,e){return e==="audio"?i.getAudioTracks():i.getVideoTracks()}function Qn(i,e){let t=i.getTracks();if(t.length===1&&t[0]===e)return i;try{return new MediaStream([e])}catch{return i}}function _t(i,e){for(let t of[...i.lostListeners])try{t(e)}catch{}}var Fe=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,_t(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 Ne;return t=>e.getUserMedia(t)}async converge(e){for(let s of this.claims.values())s.track&&(s.track.stop(),s.track=null,s.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(s){let a=`one-capture getUserMedia(${lr(r)}) failed`,d=s instanceof Error?s.message:String(s);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||s}`);c.cause=s,_t(u,c)}throw s}let o=[...this.claims.values()].sort((s,a)=>s===e?1:a===e?-1:0);for(let s of o){let a=Yn(n,s.kind)[0]??null;if(s.released){a?.stop();continue}if(!a){this.claims.delete(s.kind),s.released=!0;let d=Object.assign(new Error(`one-capture getUserMedia(${lr(r)}) returned no ${s.kind} track`),{name:"NotFoundError"});if(s===e)throw d;_t(s,d);continue}if(s.track=a,s.stream=Qn(n,a),s!==e)for(let d of[...s.trackListeners])try{d(a,s.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(o){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=o,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(o){return n.trackListeners.add(o),()=>n.trackListeners.delete(o)},onLost(o){return n.lostListeners.add(o),()=>n.lostListeners.delete(o)}}};return n}},Xn=null;function Jn(){return Xn??=new Fe}var pr="input",Zn=30;function ei(i){let e=i.now??Date.now,t=i.field??pr,r=1e3/Math.max(i.hz??30,.001),n=new Set,o=0,s=0,a=0,d=0,u,c=null,l=!1,p=()=>{if(l)return;u=e(),d+=1;let m={keys:[...n],buttons:o,pointer:{x:s,y:a},seq:d,at:u};try{i.awareness.setLocalStateField(t,m)}catch{}},f=()=>{if(l)return;let m=e();if(u===void 0||m-u>=r){c&&(clearTimeout(c),c=null),p();return}if(c)return;let v=Math.max(r-(m-u),0);c=setTimeout(()=>{c=null,p()},v),c.unref?.()};return{keyDown(m){let v=String(m).toLowerCase();n.has(v)||(n.add(v),f())},keyUp(m){let v=String(m).toLowerCase();n.delete(v)&&f()},setButtons(m){let v=Number.isFinite(m)?Number(m):0;v!==o&&(o=v,f())},movePointer(m,v){let h=Number.isFinite(m)?Number(m):0,y=Number.isFinite(v)?Number(v):0;h===0&&y===0||(s+=h,a+=y,f())},heldKeys(){return[...n]},clear(){l||(n.clear(),o=0,c&&(clearTimeout(c),c=null),p())},dispose(){if(l)return;let m=n.size>0||o!==0;n.clear(),o=0,c&&(clearTimeout(c),c=null),m&&p(),l=!0}}}var ti=1024,ri=.92,ni=262144,ii=256e3,Tt=[.9,.8,.7,.6,.5],fr=.8,si=8;function Et(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 oi(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 hr(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 mr(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 At(i,e,t,r,n){let o=document.createElement("canvas");o.width=e,o.height=t;let s=o.getContext("2d");if(!s)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(s.fillStyle="#fff",s.fillRect(0,0,e,t)),s.drawImage(i,0,0,e,t),await hr(o,r,n)}async function ai(i,e,t,r){let{width:n,height:o}=e,s=await At(i,n,o,t,r);if(s.size<=256e3)return{blob:s,width:n,height:o};if(t==="image/jpeg"){for(let d of Tt)if(!(d>=r)&&(s=await At(i,n,o,t,d),s.size<=256e3))return mr(`quality ${r} -> ${d}`,s.size),{blob:s,width:n,height:o}}let a=t==="image/jpeg"?Tt[Tt.length-1]:r;for(let d=0;d<si;d++)if(n=Math.max(16,Math.round(n*fr)),o=Math.max(16,Math.round(o*fr)),s=await At(i,n,o,t,a),s.size<=256e3)return mr(`downscaled to ${n}x${o} @ q${a}`,s.size),{blob:s,width:n,height:o};throw new Error(`this image cannot be sent: even at ${n}x${o} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function di(i,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,s=await oi(i);try{let a=Et(s.width,s.height,t),d=await ai(s,a,r,n);return{bytes:new Uint8Array(await d.blob.arrayBuffer()),type:r,width:d.width,height:d.height,source:o}}finally{s.close()}}function ci(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 ui(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function li(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:o="image/jpeg",quality:s=.92}=e??{},a=Et(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)");o==="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 hr(d,o,s);return{bytes:new Uint8Array(await c.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var pi=new Set(["w","a","s","d"]),J=(i,e)=>Math.min(e,Math.max(-e,i));function fi(i={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:o=.06,maxPan:s=.12,maxLogZoom:a=.22}=i,d=0,u=0,c=0,l=null,p=new Set;return{pointerDelta(f,m){d=J(d-f*e,s),u=J(u-m*e,s)},keyDown(f){let m=f.toLowerCase();pi.has(m)&&p.add(m)},keyUp(f){p.delete(f.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let f=1-o;d*=f,u*=f,c*=f},tick(f){if(l===null){l=f;return}let m=Math.max(0,Math.min(100,f-l))/1e3;l=f,p.has("w")&&(c=J(c+t*m,a)),p.has("s")&&(c=J(c-t*m,a)),p.has("a")&&(d=J(d+r*m,s)),p.has("d")&&(d=J(d-r*m,s));let v=Math.exp(-m*1e3/n);d*=v,u*=v,c*=v},transform(){return{translateX:d,translateY:u,scale:Math.exp(c)}},isIdentity(f=5e-4){return Math.abs(d)<f&&Math.abs(u)<f&&Math.abs(c)<f},reset(){d=0,u=0,c=0,p.clear()}}}export{Nr as ACTIVATION_COLD_BOOT_AFTER_MS,Fr as ACTIVATION_DEGRADED_AFTER_MS,Ye as ACTIVATION_HINT_PATH,Or as ACTIVATION_STILL_AFTER_MS,Ze as ACTIVITY_DOM_EVENTS,$t as ACTIVITY_FIELD,Xr as ACTIVITY_STAMP_MIN_INTERVAL_MS,te as ActivationMonitor,qn as App,Er as BACKOFF_BASE_MS,Cr as BACKOFF_MAX_ATTEMPTS,Rr as BACKOFF_MAX_MS,Fe as CaptureController,Ne as CaptureUnavailableError,V as ClientTokenError,Oe as CreditsClient,X as CreditsError,me as CreditsUnauthorizedError,ni as DATA_CHANNEL_MESSAGE_CEILING,ir as DEFAULT_DOC_SYNC_TIMEOUT_MS,ar as DEFAULT_GATEWAY_URL,vr as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,ri as DEFAULT_REFERENCE_JPEG_QUALITY,ti as DEFAULT_REFERENCE_MAX_SIZE,Tr as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Lr as DERIVED_LEG_SEP,R as DGRAM_HEADER_BYTES,Ht as FOCUS_FIELD,Zr as FOREGROUND_COALESCE_MS,ae as FrameReassembler,Yr as GENERATION_TICK_EMIT_INTERVAL_MS,Qr as GENERATION_TICK_MAX_EXTRAPOLATION_MS,Zn as INPUT_PRESENCE_DEFAULT_HZ,pr as INPUT_PRESENCE_FIELD,z as InvalidDurationError,Qe as LEGACY_ACTIVATION_HINT_PATH,ze as PLATFORM_DOC_NAME,De as PermanentLockedError,Ie as PinRequiresActiveTempError,ie as PresenceTracker,br as ProduceAckTimeoutError,Re as RecordingNotFoundError,Y as RecordingsClient,x as RecordingsError,ne as RecordingsUnauthorizedError,ve as RequestAbortError,je as RequestCancelledError,$e as RequestDocSyncError,ge as RequestError,qe as RequestTimeoutError,Ce as RetainNotTempError,Ee as RuntimeArtifactNotFoundError,j as RuntimeArtifactsClient,E as RuntimeArtifactsError,Ae as RuntimeArtifactsUnauthorizedError,Wr as SIGNALING_PROTOCOL_VERSION,Ge as STREAM_END,fe as Session,be as SessionAllocationError,gr as SessionEndError,ee as SessionEndUnavailableError,yr as SessionFailedError,Be as StreamDirectionConflict,ue as TransportNegotiator,Sr as TransportSessionMismatchError,le as TransportSessionSignaling,dr as URUN_DEV_ENV,Vt as USER_ACTIVITY_FIELD,Jr as USER_ACTIVITY_MIN_INTERVAL_MS,Bt as VISIBILITY_FIELD,ii as WIRE_MESSAGE_BUDGET,zt as WT_CONTROL_FRAME_MAX,Xt as WT_DATA_STREAM_VERSION,pe as WebRtcSession,ce as WebTransportSession,se as WtControlDecoder,Ue as WtDataStreamParser,Nt as activationHintFrom,ui as cameraCaptureAvailable,li as captureStillFromVideo,Ir as computeBackoffDelay,ct as consumeWtDataStreams,et as createActivityTracker,fi as createCameraWarp,Bn as createClientToken,zn as createCreditsClient,ei as createInputPresencePublisher,zr as createRecordingsClient,$r as createRuntimeArtifactsClient,jn as createStore,Ke as decodeStreamEnvelope,xr as derivedLegName,Mr as derivedLegRole,wr as describeSessionFailure,Ar as describeSessionPhase,Ur as encodeStreamEnvelope,ot as encodeWtControlFrame,Et as fitWithin,Xe as isDurationString,Gn as isPendingRecording,Dr as isRetryableSessionError,Ve as isServerTerminalPhase,_r as isWakingPhase,it as mediaRecorderChunkSource,di as normalizeReferenceImage,Gr as normalizeRetention,nt as observeLeaveConfirm,tt as observePageLifecycle,rt as observePageTeardown,oe as parseDgramHeader,Pr as prewake,ci as referenceImageErrorMessage,we as releaseSessionBeacon,kr as sessionFailureFromMediaError,Jn as sharedCaptureController,Hn as videoStream,Je as watchGenerationTick,He as whenLive,at as writeDgramHeader};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, o as DOC_SYNC_WIRE_CONTRACT_VERSION, p as DeferredChannelMultiplexer, q as DeferredDocConnector, t as DocConnection, u as DocConnectionState, v as DocConnector, w as DocServerUrlResolver, x as DocTokenSupplier, L as LoopbackStreamData,
|
|
1
|
+
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, o as DOC_SYNC_WIRE_CONTRACT_VERSION, p as DeferredChannelMultiplexer, q as DeferredDocConnector, t as DocConnection, u as DocConnectionState, v as DocConnector, w as DocServerUrlResolver, x as DocTokenSupplier, L as LoopbackStreamData, ad as SessionDocumentImpl, aj as SessionStartOptions, au as StreamDataTransport, az as TransportSession, aA as TransportSessionOptions, aQ as allocateSession, aS as createPresence, aT as createWebsocketDocConnector, aV as deriveYjsServerUrl, b3 as streamDataLabel, b4 as transportStreamData } from './stream-data-W9S0z8Wv.mjs';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, o as DOC_SYNC_WIRE_CONTRACT_VERSION, p as DeferredChannelMultiplexer, q as DeferredDocConnector, t as DocConnection, u as DocConnectionState, v as DocConnector, w as DocServerUrlResolver, x as DocTokenSupplier, L as LoopbackStreamData,
|
|
1
|
+
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, o as DOC_SYNC_WIRE_CONTRACT_VERSION, p as DeferredChannelMultiplexer, q as DeferredDocConnector, t as DocConnection, u as DocConnectionState, v as DocConnector, w as DocServerUrlResolver, x as DocTokenSupplier, L as LoopbackStreamData, ad as SessionDocumentImpl, aj as SessionStartOptions, au as StreamDataTransport, az as TransportSession, aA as TransportSessionOptions, aQ as allocateSession, aS as createPresence, aT as createWebsocketDocConnector, aV as deriveYjsServerUrl, b3 as streamDataLabel, b4 as transportStreamData } from './stream-data-W9S0z8Wv.js';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|
package/dist/internal.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, o as DOC_SYNC_WIRE_CONTRACT_VERSION, p as DeferredChannelMultiplexer, q as DeferredDocConnector, t as DocConnection, u as DocConnectionState, v as DocConnector, w as DocServerUrlResolver, x as DocTokenSupplier, L as LoopbackStreamData,
|
|
1
|
+
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, o as DOC_SYNC_WIRE_CONTRACT_VERSION, p as DeferredChannelMultiplexer, q as DeferredDocConnector, t as DocConnection, u as DocConnectionState, v as DocConnector, w as DocServerUrlResolver, x as DocTokenSupplier, L as LoopbackStreamData, ad as SessionDocumentImpl, aj as SessionStartOptions, au as StreamDataTransport, az as TransportSession, aA as TransportSessionOptions, aQ as allocateSession, aS as createPresence, aT as createWebsocketDocConnector, aV as deriveYjsServerUrl, b3 as streamDataLabel, b4 as transportStreamData } from './stream-data-W9S0z8Wv.mjs';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|
package/dist/internal.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, o as DOC_SYNC_WIRE_CONTRACT_VERSION, p as DeferredChannelMultiplexer, q as DeferredDocConnector, t as DocConnection, u as DocConnectionState, v as DocConnector, w as DocServerUrlResolver, x as DocTokenSupplier, L as LoopbackStreamData,
|
|
1
|
+
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, o as DOC_SYNC_WIRE_CONTRACT_VERSION, p as DeferredChannelMultiplexer, q as DeferredDocConnector, t as DocConnection, u as DocConnectionState, v as DocConnector, w as DocServerUrlResolver, x as DocTokenSupplier, L as LoopbackStreamData, ad as SessionDocumentImpl, aj as SessionStartOptions, au as StreamDataTransport, az as TransportSession, aA as TransportSessionOptions, aQ as allocateSession, aS as createPresence, aT as createWebsocketDocConnector, aV as deriveYjsServerUrl, b3 as streamDataLabel, b4 as transportStreamData } from './stream-data-W9S0z8Wv.js';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|