@urun-sh/core 0.2.25 → 0.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{B as ae,D as Ye,E as Xe,F as Je,G as Qe,H as Ze,a as Ge,b as te,c as F,d as O,e as re,f as _e,g as Se,h as ke,i as Rt,j as Et,k as ne,l as Te,m as Ct,n as Pt,o as It,p as T,q as Mt,r as xt,s as Ae,t as Ot,u as se,w as ie,x as oe,z as ze}from"./chunk-3OLMNSI3.mjs";var Dt=15e3,Ut=45e3,Lt=12e4,Re="desired.activation";function et(n){if(typeof n=="string"&&n.length>0)return n;if(n&&typeof n=="object"){let e=n.note;if(typeof e=="string"&&e.length>0)return e}}var qt=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],N=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 s=()=>this._firstMedia(e);r.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",s));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 qt){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 s={state:t,elapsedMs:r,stream:e.name},o=et(this._options.hint());o!==void 0&&(s.hint=o),e.lastEvent=s;for(let i of Array.from(this._handlers))i(s)}};var tt=500,rt=15e3,D=6;function ce(n,e=Math.random){if(!Number.isFinite(n)||n<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${n}`);let t=Math.min(rt,tt*2**n);return Math.round(e()*t)}function de(n){if(n instanceof T){let e=n.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return n instanceof Error?n.name==="TypeError"||n.name==="TimeoutError"||n.name==="AbortError":!1}var Ft="session-api.prod.cloud.urun.sh",Nt=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function S(n){return n.trim().replace(/\/+$/,"")}function ue(n,e){let t=[],r=s=>{if(!s)return;let o=S(s);o&&!t.includes(o)&&t.push(o)};r(n);for(let s of e??[])r(s);for(let s of Zt(n))r(s);return t}async function nt(n){try{let e=await W(n),t=await fetch(`${S(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/release`,{method:"POST",headers:j(n,e)}),r=await le(t);if(!t.ok)throw new O(r.error_message||r.error_code||`[urun] session release failed: HTTP ${t.status}`,{requestId:n.requestId,code:r.error_code,httpStatus:t.status});let s=String(r.status??"");if(s!=="closed"&&s!=="cancelled"&&s!=="canceled")throw new O("[urun] session release returned an unrecognized terminal status",{requestId:n.requestId,code:"invalid_release_response",httpStatus:t.status});return{status:s==="closed"?"ended":"canceled",requestId:n.requestId}}catch(e){throw e instanceof O?e:new O("[urun] session release request failed",{requestId:n.requestId,cause:e})}}function st(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var jt=120,Wt=1e3,$t=20,Bt=5,Ht=500,it=1e4,Kt=3;function Vt(n){if(!n)return null;try{let e=new URL(n),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return S(`${e.origin}${t}`)}catch{return null}}async function ot(n){let e=ue(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s=0;s<D;s++){for(let o of e)try{return await Gt(o,n,{pollAttempts:jt,retryAfterLimitMs:r?Wt:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof C)throw t}if(!de(t))break;s+1<D&&await Ee(ce(s))}throw t??new Error("[urun] session allocation failed")}async function Gt(n,e,t){let r,s,o,i=n,a=0,c=new Set,u=Date.now()+t.pollAttempts*it;for(let d=0;d<t.pollAttempts;d++){s=o??await W(e),o=void 0;let v=Math.max(1,Math.min($t,Math.floor((u-Date.now())/1e3))),l=!!r,w=Date.now(),p=r?await fetch(`${i}/api/session-requests/${encodeURIComponent(r)}?wait_s=${v}`,{headers:j(e,s),signal:Qt((v+Bt)*1e3)}):await fetch(`${i}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...j(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(zt(e))});if(!r&&(p.status===307||p.status===308)){let h=Vt(p.headers.get("location"));if(h&&h!==i&&a<Kt){a+=1,i=h;continue}throw new T(`[urun] session create redirected from ${i} without a usable target`,{httpStatus:p.status})}let f=await le(p);if(f.request_id)try{e.onRequest?.({requestId:f.request_id,baseUrl:i})}catch{}if(p.ok&&(f.status==="allocated"||!f.status&&!!f.session_id)&&!!f.session_id){let h=f.session_id;if(!f.ws_url)throw new C(`[urun] gateway allocated session ${h} without ws_url`);if(!ct(f.ws_url))throw new C(`[urun] gateway allocated session ${h} with non-absolute ws_url`);return{baseUrl:i,sessionId:h,wsUrl:f.ws_url,endsAt:st(f.ends_at),response:f}}if(p.status===202||f.status==="pending"||f.status==="queued"||f.queued){if(r=f.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(Xt(f,r))}catch{}let h=Date.now()-w<Ht;l&&h&&await Ee(Jt(p,f,t.retryAfterLimitMs));continue}if((p.status===401||p.status===403)&&e.getAccessToken){let h=s??"";c.add(h);let b=await W(e,{forceRefresh:!0,reason:"unauthorized"});if(b&&!c.has(b)){o=b,r=void 0;continue}}let m=f.error_message||f.error_code||`HTTP ${p.status}`;throw new T(`[urun] session allocation failed at ${i}: ${m}`,{httpStatus:p.status})}throw new T(`[urun] timed out waiting for session allocation at ${i}`)}function j(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function W(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function zt(n){return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey,...n.sessionKey?{logical_id:n.sessionKey}:{}}}async function at(n){let e=ue(n.baseUrl,n.fallbackUrls),t=null;for(let r=0;r<D;r++){for(let s of e)try{let o={baseUrl:s,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},i=await W(o),a=await fetch(`${S(s)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:j(o,i)});if(!a.ok)throw new T(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${a.status}`,{httpStatus:a.status});let c=await le(a);if(!c.ws_url||!ct(c.ws_url))throw new C(`[urun] viewer-connect returned no usable ws_url for ${n.sessionId}`);return{baseUrl:S(s),sessionId:n.sessionId,wsUrl:c.ws_url,endsAt:st(c.ends_at),response:c}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),t instanceof C)throw t}if(!de(t))break;r+1<D&&await Ee(ce(r))}throw t??new Error("[urun] viewer-connect failed")}async function Yt(n){try{let e=S(n.baseUrl),t=await W(n),r=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...j(n,t),"Content-Type":"application/json"},body:JSON.stringify({app:n.app,function:n.functionName})});if(r.status===404)return{status:"unknown-app"};if(!r.ok)return{status:"unavailable"};let s=await le(r),o={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(o.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(o.warmCapable=s.warm_capable),o}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function le(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function Xt(n,e){let t={status:n.status==="queued"||n.queued?"queued":"pending",requestId:e};typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(t.queue={position:n.queue_position,depth:n.queue_depth});let r=n.runtime_state;return(r==="unavailable"||r==="starting"||r==="busy")&&(t.runtime={state:r},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(t.runtime.reason=n.runtime_reason)),t}function Jt(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),o=t??it;return Number.isFinite(s)&&s>0?Math.min(s*1e3,o):1e3}function Ee(n){return new Promise(e=>setTimeout(e,n))}function Qt(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var C=class extends Error{};function ct(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function Zt(n){try{return new URL(n).hostname!==Ft?[]:Nt}catch{return[]}}var _=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},pe=class extends _{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},fe=class extends _{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function $(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function er(n){return new P(n)}var P=class{_options;constructor(e){this._options=e}async list(e){let r=ut(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new _("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(dt)}async getDownloadUrl(e,t){let r=ut(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!rr(s))throw new _("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:dt(r.artifact),downloadUrl:s}}async _request(e,t){let r=ue(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),s instanceof _&&nr(s.status))throw s}throw s??new _("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${S(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),i=await fetch(s,{method:"GET",headers:this._headers(o)});if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await fetch(s,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:c}=await this._readError(i,e);throw sr(i.status,a,c)}try{return await i.json()}catch(a){throw new _(`[urun] runtime artifacts: invalid JSON response from ${S(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=S(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:i,message:a}=o;return{code:typeof i=="string"&&i.length>0?i:`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 dt(n){if(!n||typeof n!="object")throw new _("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=R(e,"artifact_id")||R(e,"id"),r=R(e,"filename"),s=R(e,"kind"),o=R(e,"status")||"ready",i=tr(e,"size_bytes"),a=R(e,"sha256");if(!t||!r||!s||i==null||!a)throw new _("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:R(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:R(e,"created_at"),expiresAt:R(e,"expires_at")}}function R(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function tr(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function rr(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function nr(n){return n===401||n===403}function sr(n,e,t){return n===401?new pe(t,e):n===404?new fe(t,e):new _(t,n,e)}function ut(n){if(!n||typeof n!="object"||Array.isArray(n))throw new _("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var k=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)}},B=class extends k{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},me=class extends k{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},he=class extends k{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)}},ge=class extends k{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)}},ve=class extends k{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)}},U=class extends k{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 Ce(n){return/^(\d+[smhdw])+$/.test(n)}function ir(n){if(n==="pin")return{action:"pin"};if(Ce(n))return{action:"retain",duration:n};throw new U(`[urun] recordings: "${n}" is not a duration or "pin"`)}function or(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new B(r,e??"unauthorized");if(n===404)return new me(r,e??"not_found");if(n===400)return new U(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new he(r,e);case"pin_requires_active_temp":return new ge(r,e);case"permanent_locked":return new ve(r,e)}return new k(r,{status:n,code:e??`http_${n}`})}var L=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(!Ce(t))throw new U(`[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 k("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),o=await this._resolveToken(),i=await this._fetch(s,e,o,r.body);if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await this._fetch(s,e,o,r.body))}if(!i.ok){let{code:a,message:c}=await this._readError(i);throw or(i.status,a,c)}return this._readJson(i)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){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 i={method:t,headers:o};return s!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(e,i)}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 B("[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:s,message:o}=r;return{code:typeof s=="string"?s:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function ar(n){return new L(n)}var lt="activity",cr=15e3,Pe=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ie(n){let e=n.now??Date.now,t=n.windowTarget!==void 0?n.windowTarget:typeof window<"u"?window:null,r=n.documentTarget!==void 0?n.documentTarget:typeof document<"u"?document:null,s=!1,o,i=()=>{if(s)return;let d=e();if(!(o!==void 0&&d-o<15e3)){o=d;try{n.awareness.setLocalStateField(lt,{at:d})}catch{}}},a=()=>i(),c=()=>{(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let d of Pe)t.addEventListener(d,a,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",c);let u=null;return n.isProducing&&(u=setInterval(()=>{if(!s)try{n.isProducing?.()&&i()}catch{}},15e3),u.unref?.()),i(),{touch:i,dispose(){if(!s){if(s=!0,t)for(let d of Pe)t.removeEventListener(d,a,{capture:!0});r&&r.removeEventListener("visibilitychange",c),u&&(clearInterval(u),u=null)}}}}var dr=250;function Me(n){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,n())};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)}}var pt="video/mp4";function xe(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,o=!1,i=(a,c,u)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)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 v=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(pt)?pt:void 0),l=new MediaStream([a]),w=new d(l,v?{mimeType:v}:void 0);r=w;let p=Promise.resolve();w.ondataavailable=f=>{let y=f.data;o||!y||y.size===0||(p=p.then(async()=>{let m=new Uint8Array(await y.arrayBuffer());o||c(m)}))},w.onstop=()=>{p.then(()=>{o||u()})},w.onerror=()=>{p.then(()=>{o||u()})},w.start(t)};return{start(a,c){if(r||o)return;let u=n.track();if(u){i(u,a,c);return}s=n.onTrack(d=>{!d||r||o||(s?.(),s=null,i(d,a,c))})},stop(){if(o)return;o=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function ur(n){let e=n;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=n.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function ft(n,e){let t=null,r=!1,s=!1,o=new ReadableStream({pull(i){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{i.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{i.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return ur(o)}import{encode as lr,decode as pr}from"@msgpack/msgpack";var mt=65536;function De(n){let e=lr(n),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var H=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>mt)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let s=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(pr(s))}return t}},K=12,Oe=1;function Ue(n){let e=n.getUint8(8);return{groupId:n.getUint32(0,!0),frameSeq:n.getUint32(4,!0),keyframe:(e&Oe)===Oe,fragIndex:n.getUint8(9),fragCount:n.getUint8(10)}}function fr(n){let e=new Uint8Array(K),t=new DataView(e.buffer);return t.setUint32(0,n.groupId,!0),t.setUint32(4,n.frameSeq,!0),t.setUint8(8,n.keyframe?Oe:0),t.setUint8(9,n.fragIndex),t.setUint8(10,n.fragCount),t.setUint8(11,0),e}var mr=100,V=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??mr}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<K)return;let t=Ue(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,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(K),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let s of this.pending.keys())s<t.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}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((i,a)=>i+a.byteLength,0),s=new Uint8Array(r),o=0;for(let i of t.chunks)s.set(i,o),o+=i.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:s})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var hr=250,gr=3,vr=1e4,G=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r;this.firstMedia=new Promise((s,o)=>{this.firstFrameResolve=s,this.firstFrameReject=o}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new V({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};firstFrameResolve=null;firstFrameReject=null;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(a=>({algorithm:"sha-256",value:Uint8Array.from(atob(a),c=>c.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let t=await this.wt.createBidirectionalStream();this.writer=t.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let r=t.readable.getReader(),s=new H,o=[],i=await this.readControl(r,s,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");this.initDecoder(i.codec,i.width,i.height),this.controlLoop(r,s,o).catch(a=>this.die(`control loop: ${a}`)),this.datagramLoop().catch(a=>this.die(`datagram loop: ${a}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(a=>this.die(`connection error: ${a}`))}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}onDead(e){this.deadCb=e}stats(){return this.lastStats}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="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 s({output:i=>{this.canvas.width=i.displayWidth,this.canvas.height=i.displayHeight,o.drawImage(i,0,0),i.close()},error:i=>this.onDecoderError(i)}),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(s=>t-s<vr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=gr){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(s){this.die(`decoder re-init: ${s instanceof Error?s.message:String(s)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}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;let s=performance.now();if(this.lastArrivalTs>0){let o=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;!this.decoder||typeof s!="function"||(this.decoder.decode(new s({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(De(e))}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:o,done:i}=await e.read();if(i)return null;o&&r.push(...t.push(o))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;s.t==="ping"&&this.sendControl({t:"pong",ts:s.ts}).catch(()=>{})}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),o=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:o>0?100*s.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},hr)}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;try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var wr=2500,yr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],z=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&s,webcodecs:r,codecs:yr};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:o});let i=o.webtransport&&!!this.offer.webtransport;if(i){let a=null;try{return a=this.createWebTransportSession(),await br(a.start(),this.opts.quicDeadlineMs??wr,"quic connect deadline"),this.session=a,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){console.warn("[urun] webtransport failed, falling back to webrtc:",c),a?.stop().catch(()=>{}),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}return this.session=await this.startWebRtc(),i||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){await this.session?.stop(),this.session=null}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 G(e,this.sessionId,this.opts.canvas)}async startWebRtc(){let e=this.opts.createWebRtcSession();return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}armFailover(){let e=this.session;e.onDead(t=>{console.warn("[urun] quic died mid-session, failing over to webrtc:",t),e.stop().catch(()=>{}),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(r){this.session=null,console.error("[urun] failover to webrtc also failed:",r)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function br(n,e,t){return new Promise((r,s)=>{let o=setTimeout(()=>s(new Error(t)),e);n.then(i=>{clearTimeout(o),r(i)},i=>{clearTimeout(o),s(i)})})}var _r=1e4,Y=class{constructor(e,t=_r){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=oe();return new Promise((s,o)=>{let i=setTimeout(()=>{a(),o(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(i),a(),c.error){o(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:u,requestId:d,...v}=c;s(v)});this.carrier.sendSignal({type:e,requestId:r,...t})})}notify(e,t){this.carrier.sendSignal({type:e,...t})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};var Sr="video",X=class{constructor(e,t=Sr){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),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 kr="video";function ht(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let i=s.createElement("canvas"),a=!1,c=null,u=!1,d=()=>{if(c){for(let l of c.getVideoTracks())try{l.stop()}catch{}c=null}u&&(u=!1,t.onOverrideTrack(null))},v=new z(new Y(n),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new X(n,t.streamName??kr)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(l,w)=>{l==="webrtc"&&d(),t.onTransportChange?.(l,w)}});return(async()=>{let l=await v.connect();if(a||l.kind!=="webtransport"||(await l.firstMedia,a||v.activeTransport!=="webtransport")||typeof i.captureStream!="function")return;c=i.captureStream();let w=c.getVideoTracks()[0];w&&(u=!0,t.onOverrideTrack(w))})().catch(l=>{console.debug?.("[urun] transport negotiation unavailable, staying on webrtc:",l)}),{activeTransport:()=>v.activeTransport,dispose(){a=!0,d(),v.disconnect().catch(()=>{})}}}var Tr=new Set;function Fe(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var Ar="rpc",vt=3e4,Rr="rpc-resp";function Er(n){return`${Rr}:${n}`}function Le(){return oe()}function Cr(n){if(n&&typeof n=="object"){let e=n.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 n=="string"?n:JSON.stringify(n)}}function Pr(n,e,t,r,s,o,i,a,c,u){let d=[],v=null,l=!1,w=null,p=!1,f,y,m=new Promise((g,E)=>{f=g,y=E});m.catch(()=>{});let h=i(),b=null,A=null,q=null,Q=null,Z=!0,We=()=>{q&&(clearTimeout(q),q=null),Q&&(Q(),Q=null)},$e=!1,Be=()=>{$e||!p||($e=!0,n.set({rpc:{[e]:null}}))},ee=()=>{Z=!1,We(),b?.(),b=null,A?.(),A=null,a?.removeEventListener("abort",Ke),h.dispose(),Be()},be=()=>{if(v){if(d.length>0){let g=v;v=null,g.resolve({value:d.shift(),done:!1})}else if(w!==null){let g=v;v=null,g.reject(w)}else if(l){let g=v;v=null,g.resolve({value:void 0,done:!0})}}},kt=g=>{l||(d.push(g),be())},M=g=>{l||(w=g,l=!0,y(g),ee(),be())},He=g=>{l||(l=!0,f(g),ee(),be())},Ke=()=>{let g=a?.reason;M(g instanceof re?g:new ne(e))},Tt=g=>{if(!(l||!g||typeof g!="object"))switch(Be(),g.t){case"delta":typeof g.delta=="string"&&kt(g.delta);break;case"response":He(g.body);break;case"error":{let{message:E,code:x}=Cr(g.body);M(new re(E,{requestId:e,code:g.code??x}));break}}},At=()=>{let g=h.messages()[Symbol.asyncIterator]();b=()=>{g.return?.(void 0)};let E=()=>{Z&&g.next().then(x=>{if(Z){if(x.done){l||He(void 0);return}Tt(x.value),E()}},x=>{Z&&M(x)})};E()},Ve=()=>{if(!p){if(p=!0,a){if(a.aborted){M(new ne(e));return}a.addEventListener("abort",Ke,{once:!0})}A=c?.(g=>M(g))??null,At(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:o}}}),u&&u>0&&!n.synced&&(q=setTimeout(()=>{q=null,!l&&!n.synced&&M(new Se(u,e))},u),Q=n.onSynced(()=>We()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Ve(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(w!==null){let g=w;return w=null,Promise.reject(g)}return l?Promise.resolve({value:void 0,done:!0}):new Promise((g,E)=>{v={resolve:g,reject:E}})},return(){return l||(l=!0,f(void 0),ee()),Promise.resolve({value:void 0,done:!0})},throw(g){return l||(l=!0,y(g),ee()),Promise.reject(g)}}}},body:m,start:Ve}}function gt(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Ir(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:o,br:i}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=gt(o);c&&(a.rt=c);let u=gt(i);return u&&(a.br=u),a}var qe=class{constructor(e,t,r,s,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_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._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,o={push(a){if(!s)if(r){let c=r;r=null,c({value:a,done:!1})}else t.push(a)},end(){if(s=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{s=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_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 s of r)s(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Ir(t,this._name),s=r?.br;if(s?.by==="runtime")throw new ke(this._name,"runtime","browser");if(s)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let i=r?.kind??e;i&&(o.kind=i),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??xe;return ft(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}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)}},J=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Je;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;constructor(e,t,r,s,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=o,this._streamData=ze(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Me(()=>this.recover()),this._activity=Ie({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new N({onPhase:i=>this.onPhase(i),hint:()=>this.doc("control").get(Re),onData:(i,a)=>this._streamData.onData(i,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 at({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new te,i=new ae({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,o,i,Fe(t),$({...t,baseUrl:r.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),i.setEndsAt(r.endsAt),se()&&await ie(),a.setDocTransport({wsUrl:r.wsUrl,token:s}),await i.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)}whenLive(e){return Ae(this,e)}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 L(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),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 P(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new P(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 qe(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 Qe(e,this._sessionId,Tr.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ze(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=Ye(e.wsUrl),r=`${t}\0${e.token??""}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(Xe({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket})))}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=Le(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>s.abort(new _e(a,r)),a)}let i=this._consumeResponse(r,e,!1,s.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,r,s,o){this._activity?.touch();let i=this.doc(Ar),a=Er(e);return Pr(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??vt)}requestStream(e,t={}){let r=Le();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Le(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.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)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=ht(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new F)}disconnect(){this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._activation.dispose(),this._recoveryHooks.clear();let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new Te)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var Mr=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function xr(n,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(!(Mr.has(r)||typeof r!="string"))return s=>{let o=s??{},i=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=i(),c=new te,u=new ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),d=new J(a,c,u,Fe(e),$(e)),v,l,w=new Promise(m=>{l=m}),p=m=>{v=m,l({status:"ready",handle:m})};d.setEndHandler(async()=>{let m=v?{status:"ready",handle:v}:await w;if(m.status==="unavailable")throw new F("[urun] session allocation failed before a releasable request was created",{cause:m.cause});let h=m.handle;return nt({baseUrl:h.baseUrl,requestId:h.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})});let f=async m=>{let h=await ot({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:m,sessionKey:e.sessionKey,onAdmission:A=>u.reportAdmission(A),onRequest:p}),b=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return d.setSessionId(h.sessionId),d.setArtifactsAuth($({...e,baseUrl:h.baseUrl})),u.setEndsAt(h.endsAt),{url:h.wsUrl,sessionId:h.sessionId,jwt:b,iceServers:h.response.ice_servers,endsAt:h.endsAt}},y;return u.setConnectionResolver(async()=>{let m=await f(i());return y=m.jwt,m}),u.on("connected",()=>{u.multiplexer&&c.setTarget(u.multiplexer);let m=u.connectedUrl;m&&d.setDocTransport({wsUrl:m,token:y})}),(async()=>{let m;try{m=await f(a)}catch(h){console.error(`[urun] Failed to create session for ${r}:`,h);let b=h instanceof Error?h:new Error(String(h)),A=h instanceof T?h.httpStatus:void 0;u.reportAllocationFailure(b,A),l({status:"unavailable",cause:h});return}u.setAuth({jwt:m.jwt,authProvider:e.authProvider,orgId:e.orgId}),u.setConnection({url:m.url,sessionId:m.sessionId,iceServers:m.iceServers}),se()&&await ie(),y=m.jwt,d.setDocTransport({wsUrl:m.url,token:m.jwt}),await u.connect({app:n,functionName:r,args:o}),d.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(m=>{console.error(`[urun] Failed to connect session for ${r}:`,m)}),d}}})}var wt="https://api.urun.sh",I=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Or(n,e={}){if(!n)throw new I("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=S(e.baseUrl??wt),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s)})}catch(l){throw new I(`[urun] client token mint request failed: ${l instanceof Error?l.message:String(l)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let l=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new I(`[urun] client token mint failed: ${l}`,o.status)}let a=typeof i.token=="string"?i.token:"",c=typeof i.org_id=="string"?i.org_id:"",u=typeof i.expires_at=="string"?Date.parse(i.expires_at):Number.NaN,d=typeof i.expires_in=="number"?i.expires_in:void 0;if(!a)throw new I("[urun] client token mint returned no token (control-plane contract violation)",o.status);let v=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:v,orgId:c}}var yt=3e4,bt="stream:",Ne=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let o=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(o.timer),s.error?o.reject(new Error(s.error)):o.resolve(s.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=`${bt}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${bt}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),s(new Error(`RPC request "${e}" timed out after ${yt}ms`)))},yt);this._pendingRpc.set(o,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Dr(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let o=new Ge(s);return new Ne(s,o)}var Ur='video/mp4; codecs="avc1.42E01E"';function Lr(n,e){let t=e?.codec??Ur,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,o=URL.createObjectURL(s);r.src=o,s.addEventListener("sourceopen",()=>{let l;try{l=s.addSourceBuffer(t)}catch(y){throw y instanceof DOMException&&y.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).`):y}let w=n.getReader();function p(){return l.updating?new Promise(y=>{l.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function f(){try{for(;;){let{done:y,value:m}=await w.read();if(y){await p(),s.readyState==="open"&&s.endOfStream();return}await p();try{l.appendBuffer(m)}catch(h){if(h instanceof DOMException&&h.name==="QuotaExceededError"){let b=l.buffered;if(b.length>0){let A=b.start(b.length-1);l.remove(0,A),await p(),l.appendBuffer(m)}else throw h}else throw h}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}f()}),r.play().catch(()=>{});let i=r,a=i.captureStream??i.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),u=c.getTracks(),d=0,v=u.length;if(v===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let l of u)l.addEventListener("ended",()=>{d++,d>=v&&URL.revokeObjectURL(o)});return c}function qr(n){return n.status.startsWith("pending_")}var we=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 _t(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function Fr(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function Nr(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function je(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var ye=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,je(r,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.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 we;return t=>e.getUserMedia(t)}async converge(e){for(let i of this.claims.values())i.track&&(i.track.stop(),i.track=null,i.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},s;try{s=await t(r)}catch(i){let a=`one-capture getUserMedia(${_t(r)}) failed`,c=i instanceof Error?i.message:String(i);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let d=new Error(`${a} \u2014 ${u.kind} capture lost: ${c||i}`);d.cause=i,je(u,d)}throw i}let o=[...this.claims.values()].sort((i,a)=>i===e?1:a===e?-1:0);for(let i of o){let a=Fr(s,i.kind)[0]??null;if(i.released){a?.stop();continue}if(!a){this.claims.delete(i.kind),i.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${_t(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;je(i,c);continue}if(i.track=a,i.stream=Nr(s,a),i!==e)for(let c of[...i.trackListeners])try{c(a,i.stream)}catch{}}}createState(e,t){let r=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(o){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=o,await r.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(e)===s&&r.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(o){return s.trackListeners.add(o),()=>s.trackListeners.delete(o)},onLost(o){return s.lostListeners.add(o),()=>s.lostListeners.delete(o)}}};return s}},jr=null;function Wr(){return jr??=new ye}var St="input",$r=30;function Br(n){let e=n.now??Date.now,t=n.field??St,r=1e3/Math.max(n.hz??30,.001),s=new Set,o=0,i=0,a=0,c=0,u,d=null,v=!1,l=()=>{if(v)return;u=e(),c+=1;let p={keys:[...s],buttons:o,pointer:{x:i,y:a},seq:c,at:u};try{n.awareness.setLocalStateField(t,p)}catch{}},w=()=>{if(v)return;let p=e();if(u===void 0||p-u>=r){d&&(clearTimeout(d),d=null),l();return}if(d)return;let f=Math.max(r-(p-u),0);d=setTimeout(()=>{d=null,l()},f),d.unref?.()};return{keyDown(p){let f=String(p).toLowerCase();s.has(f)||(s.add(f),w())},keyUp(p){let f=String(p).toLowerCase();s.delete(f)&&w()},setButtons(p){let f=Number.isFinite(p)?Number(p):0;f!==o&&(o=f,w())},movePointer(p,f){let y=Number.isFinite(p)?Number(p):0,m=Number.isFinite(f)?Number(f):0;y===0&&m===0||(i+=y,a+=m,w())},heldKeys(){return[...s]},clear(){v||(s.clear(),o=0,d&&(clearTimeout(d),d=null),l())},dispose(){if(v)return;let p=s.size>0||o!==0;s.clear(),o=0,d&&(clearTimeout(d),d=null),p&&l(),v=!0}}}export{Ut as ACTIVATION_COLD_BOOT_AFTER_MS,Lt as ACTIVATION_DEGRADED_AFTER_MS,Re as ACTIVATION_HINT_PATH,Dt as ACTIVATION_STILL_AFTER_MS,Pe as ACTIVITY_DOM_EVENTS,lt as ACTIVITY_FIELD,cr as ACTIVITY_STAMP_MIN_INTERVAL_MS,N as ActivationMonitor,xr as App,tt as BACKOFF_BASE_MS,D as BACKOFF_MAX_ATTEMPTS,rt as BACKOFF_MAX_MS,ye as CaptureController,we as CaptureUnavailableError,I as ClientTokenError,vt as DEFAULT_DOC_SYNC_TIMEOUT_MS,wt as DEFAULT_GATEWAY_URL,Rt as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,xt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,K as DGRAM_HEADER_BYTES,dr as FOREGROUND_COALESCE_MS,V as FrameReassembler,$r as INPUT_PRESENCE_DEFAULT_HZ,St as INPUT_PRESENCE_FIELD,U as InvalidDurationError,ve as PermanentLockedError,ge as PinRequiresActiveTempError,Et as ProduceAckTimeoutError,me as RecordingNotFoundError,L as RecordingsClient,k as RecordingsError,B as RecordingsUnauthorizedError,ne as RequestAbortError,Te as RequestCancelledError,Se as RequestDocSyncError,re as RequestError,_e as RequestTimeoutError,he as RetainNotTempError,fe as RuntimeArtifactNotFoundError,P as RuntimeArtifactsClient,_ as RuntimeArtifactsError,pe as RuntimeArtifactsUnauthorizedError,J as Session,T as SessionAllocationError,O as SessionEndError,F as SessionEndUnavailableError,Pt as SessionFailedError,ke as StreamDirectionConflict,z as TransportNegotiator,Y as TransportSessionSignaling,mt as WT_CONTROL_FRAME_MAX,X as WebRtcSession,G as WebTransportSession,H as WtControlDecoder,et as activationHintFrom,ce as computeBackoffDelay,Ie as createActivityTracker,Or as createClientToken,Br as createInputPresencePublisher,ar as createRecordingsClient,er as createRuntimeArtifactsClient,Dr as createStore,Ct as describeSessionFailure,Ot as describeSessionPhase,De as encodeWtControlFrame,Ce as isDurationString,qr as isPendingRecording,de as isRetryableSessionError,Mt as isWakingPhase,xe as mediaRecorderChunkSource,ir as normalizeRetention,Me as observePageLifecycle,Ue as parseDgramHeader,Yt as prewake,It as sessionFailureFromMediaError,Wr as sharedCaptureController,Lr as videoStream,Ae as whenLive,fr as writeDgramHeader};
1
+ import{B as ae,D as tt,E as rt,F as nt,G as st,H as it,a as Ze,b as te,c as F,d as D,e as re,f as Se,g as ke,h as Te,i as Lt,j as qt,k as ne,l as Ae,m as Ft,n as Nt,o as jt,p as T,q as Wt,r as $t,s as Re,t as Bt,u as se,w as ie,x as oe,z as et}from"./chunk-3OLMNSI3.mjs";var Ht=15e3,Kt=45e3,Vt=12e4,Ee="desired.activation";function ot(n){if(typeof n=="string"&&n.length>0)return n;if(n&&typeof n=="object"){let e=n.note;if(typeof e=="string"&&e.length>0)return e}}var Gt=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],N=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 s=()=>this._firstMedia(e);r.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",s));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 Gt){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 s={state:t,elapsedMs:r,stream:e.name},o=ot(this._options.hint());o!==void 0&&(s.hint=o),e.lastEvent=s;for(let i of Array.from(this._handlers))i(s)}};var at=500,ct=15e3,U=6;function de(n,e=Math.random){if(!Number.isFinite(n)||n<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${n}`);let t=Math.min(ct,at*2**n);return Math.round(e()*t)}function ue(n){if(n instanceof T){let e=n.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return n instanceof Error?n.name==="TypeError"||n.name==="TimeoutError"||n.name==="AbortError":!1}var dt=10,zt=.5,ce=dt;function Ie(){return ce<1?!1:(ce-=1,!0)}function Ce(){ce=Math.min(dt,ce+zt)}var Yt="session-api.prod.cloud.urun.sh",Jt=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function S(n){return n.trim().replace(/\/+$/,"")}function le(n,e){let t=[],r=s=>{if(!s)return;let o=S(s);o&&!t.includes(o)&&t.push(o)};r(n);for(let s of e??[])r(s);for(let s of ur(n))r(s);return t}async function ut(n){try{let e=await W(n),t=await fetch(`${S(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/release`,{method:"POST",headers:j(n,e)}),r=await pe(t);if(!t.ok)throw new D(r.error_message||r.error_code||`[urun] session release failed: HTTP ${t.status}`,{requestId:n.requestId,code:r.error_code,httpStatus:t.status});let s=String(r.status??"");if(s!=="closed"&&s!=="cancelled"&&s!=="canceled")throw new D("[urun] session release returned an unrecognized terminal status",{requestId:n.requestId,code:"invalid_release_response",httpStatus:t.status});return{status:s==="closed"?"ended":"canceled",requestId:n.requestId}}catch(e){throw e instanceof D?e:new D("[urun] session release request failed",{requestId:n.requestId,cause:e})}}function lt(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var Xt=120,Qt=1e3,Zt=20,er=5,tr=500,pt=1e4,rr=3;function nr(n){if(!n)return null;try{let e=new URL(n),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return S(`${e.origin}${t}`)}catch{return null}}async function ft(n){let e=le(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s=0;s<U;s++){for(let o of e)try{let i=await sr(o,n,{pollAttempts:Xt,retryAfterLimitMs:r?Qt:void 0});return Ce(),i}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof C)throw t}if(!ue(t))break;if(s+1<U){if(!Ie())break;await Pe(de(s))}}throw t??new Error("[urun] session allocation failed")}async function sr(n,e,t){let r,s,o,i=n,a=0,c=new Set,l=Date.now()+t.pollAttempts*pt;for(let d=0;d<t.pollAttempts;d++){s=o??await W(e),o=void 0;let h=Math.max(1,Math.min(Zt,Math.floor((l-Date.now())/1e3))),u=!!r,w=Date.now(),f=r?await fetch(`${i}/api/session-requests/${encodeURIComponent(r)}?wait_s=${h}`,{headers:j(e,s),signal:dr((h+er)*1e3)}):await fetch(`${i}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...j(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(ir(e))});if(!r&&(f.status===307||f.status===308)){let p=nr(f.headers.get("location"));if(p&&p!==i&&a<rr){a+=1,i=p;continue}throw new T(`[urun] session create redirected from ${i} without a usable target`,{httpStatus:f.status})}let m=await pe(f);if(m.request_id)try{e.onRequest?.({requestId:m.request_id,baseUrl:i})}catch{}if(f.ok&&(m.status==="allocated"||!m.status&&!!m.session_id)&&!!m.session_id){let p=m.session_id;if(!m.ws_url)throw new C(`[urun] gateway allocated session ${p} without ws_url`);if(!ht(m.ws_url))throw new C(`[urun] gateway allocated session ${p} with non-absolute ws_url`);return{baseUrl:i,sessionId:p,wsUrl:m.ws_url,endsAt:lt(m.ends_at),response:m}}if(f.status===202||m.status==="pending"||m.status==="queued"||m.queued){if(r=m.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(ar(m,r))}catch{}let p=Date.now()-w<tr;u&&p&&await Pe(cr(f,m,t.retryAfterLimitMs));continue}if((f.status===401||f.status===403)&&e.getAccessToken){let p=s??"";c.add(p);let v=await W(e,{forceRefresh:!0,reason:"unauthorized"});if(v&&!c.has(v)){o=v,r=void 0;continue}}let b=m.error_message||m.error_code||`HTTP ${f.status}`;throw new T(`[urun] session allocation failed at ${i}: ${b}`,{httpStatus:f.status})}throw new T(`[urun] timed out waiting for session allocation at ${i}`)}function j(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function W(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function ir(n){return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey,...n.sessionKey?{logical_id:n.sessionKey}:{}}}async function mt(n){let e=le(n.baseUrl,n.fallbackUrls),t=null;for(let r=0;r<U;r++){for(let s of e)try{let o={baseUrl:s,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},i=await W(o),a=await fetch(`${S(s)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:j(o,i)});if(!a.ok)throw new T(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${a.status}`,{httpStatus:a.status});let c=await pe(a);if(!c.ws_url||!ht(c.ws_url))throw new C(`[urun] viewer-connect returned no usable ws_url for ${n.sessionId}`);return Ce(),{baseUrl:S(s),sessionId:n.sessionId,wsUrl:c.ws_url,endsAt:lt(c.ends_at),response:c}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),t instanceof C)throw t}if(!ue(t))break;if(r+1<U){if(!Ie())break;await Pe(de(r))}}throw t??new Error("[urun] viewer-connect failed")}async function or(n){try{let e=S(n.baseUrl),t=await W(n),r=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...j(n,t),"Content-Type":"application/json"},body:JSON.stringify({app:n.app,function:n.functionName})});if(r.status===404)return{status:"unknown-app"};if(!r.ok)return{status:"unavailable"};let s=await pe(r),o={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(o.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(o.warmCapable=s.warm_capable),o}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function pe(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function ar(n,e){let t={status:n.status==="queued"||n.queued?"queued":"pending",requestId:e};typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(t.queue={position:n.queue_position,depth:n.queue_depth});let r=n.runtime_state;return(r==="unavailable"||r==="starting"||r==="busy")&&(t.runtime={state:r},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(t.runtime.reason=n.runtime_reason)),t}function cr(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),o=t??pt;return Number.isFinite(s)&&s>0?Math.min(s*1e3,o):1e3}function Pe(n){return new Promise(e=>setTimeout(e,n))}function dr(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var C=class extends Error{};function ht(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function ur(n){try{return new URL(n).hostname!==Yt?[]:Jt}catch{return[]}}var _=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},fe=class extends _{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},me=class extends _{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function $(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function lr(n){return new P(n)}var P=class{_options;constructor(e){this._options=e}async list(e){let r=vt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new _("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(gt)}async getDownloadUrl(e,t){let r=vt(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!fr(s))throw new _("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:gt(r.artifact),downloadUrl:s}}async _request(e,t){let r=le(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),s instanceof _&&mr(s.status))throw s}throw s??new _("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${S(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),i=await fetch(s,{method:"GET",headers:this._headers(o)});if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await fetch(s,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:c}=await this._readError(i,e);throw hr(i.status,a,c)}try{return await i.json()}catch(a){throw new _(`[urun] runtime artifacts: invalid JSON response from ${S(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=S(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:i,message:a}=o;return{code:typeof i=="string"&&i.length>0?i:`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 gt(n){if(!n||typeof n!="object")throw new _("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=E(e,"artifact_id")||E(e,"id"),r=E(e,"filename"),s=E(e,"kind"),o=E(e,"status")||"ready",i=pr(e,"size_bytes"),a=E(e,"sha256");if(!t||!r||!s||i==null||!a)throw new _("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:E(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:E(e,"created_at"),expiresAt:E(e,"expires_at")}}function E(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function pr(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function fr(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function mr(n){return n===401||n===403}function hr(n,e,t){return n===401?new fe(t,e):n===404?new me(t,e):new _(t,n,e)}function vt(n){if(!n||typeof n!="object"||Array.isArray(n))throw new _("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var k=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)}},B=class extends k{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},he=class extends k{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ge=class extends k{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)}},ve=class extends k{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)}},we=class extends k{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)}},L=class extends k{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 Me(n){return/^(\d+[smhdw])+$/.test(n)}function gr(n){if(n==="pin")return{action:"pin"};if(Me(n))return{action:"retain",duration:n};throw new L(`[urun] recordings: "${n}" is not a duration or "pin"`)}function vr(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new B(r,e??"unauthorized");if(n===404)return new he(r,e??"not_found");if(n===400)return new L(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new ge(r,e);case"pin_requires_active_temp":return new ve(r,e);case"permanent_locked":return new we(r,e)}return new k(r,{status:n,code:e??`http_${n}`})}var q=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(!Me(t))throw new L(`[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 k("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),o=await this._resolveToken(),i=await this._fetch(s,e,o,r.body);if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await this._fetch(s,e,o,r.body))}if(!i.ok){let{code:a,message:c}=await this._readError(i);throw vr(i.status,a,c)}return this._readJson(i)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){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 i={method:t,headers:o};return s!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(e,i)}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 B("[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:s,message:o}=r;return{code:typeof s=="string"?s:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function wr(n){return new q(n)}var wt="activity",yr=15e3,xe=["pointerdown","pointermove","keydown","wheel","touchstart"];function Oe(n){let e=n.now??Date.now,t=n.windowTarget!==void 0?n.windowTarget:typeof window<"u"?window:null,r=n.documentTarget!==void 0?n.documentTarget:typeof document<"u"?document:null,s=!1,o,i=()=>{if(s)return;let d=e();if(!(o!==void 0&&d-o<15e3)){o=d;try{n.awareness.setLocalStateField(wt,{at:d})}catch{}}},a=()=>i(),c=()=>{(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let d of xe)t.addEventListener(d,a,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",c);let l=null;return n.isProducing&&(l=setInterval(()=>{if(!s)try{n.isProducing?.()&&i()}catch{}},15e3),l.unref?.()),i(),{touch:i,dispose(){if(!s){if(s=!0,t)for(let d of xe)t.removeEventListener(d,a,{capture:!0});r&&r.removeEventListener("visibilitychange",c),l&&(clearInterval(l),l=null)}}}}var br=250;function De(n){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,n())};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)}}var yt="video/mp4";function Ue(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,o=!1,i=(a,c,l)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let h=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(yt)?yt:void 0),u=new MediaStream([a]),w=new d(u,h?{mimeType:h}:void 0);r=w;let f=Promise.resolve();w.ondataavailable=m=>{let y=m.data;o||!y||y.size===0||(f=f.then(async()=>{let b=new Uint8Array(await y.arrayBuffer());o||c(b)}))},w.onstop=()=>{f.then(()=>{o||l()})},w.onerror=()=>{f.then(()=>{o||l()})},w.start(t)};return{start(a,c){if(r||o)return;let l=n.track();if(l){i(l,a,c);return}s=n.onTrack(d=>{!d||r||o||(s?.(),s=null,i(d,a,c))})},stop(){if(o)return;o=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function _r(n){let e=n;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=n.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 bt(n,e){let t=null,r=!1,s=!1,o=new ReadableStream({pull(i){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{i.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{i.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return _r(o)}import{encode as Sr,decode as kr}from"@msgpack/msgpack";var _t=65536;function qe(n){let e=Sr(n),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var H=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>_t)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let s=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(kr(s))}return t}},K=12,Le=1;function Fe(n){let e=n.getUint8(8);return{groupId:n.getUint32(0,!0),frameSeq:n.getUint32(4,!0),keyframe:(e&Le)===Le,fragIndex:n.getUint8(9),fragCount:n.getUint8(10)}}function Tr(n){let e=new Uint8Array(K),t=new DataView(e.buffer);return t.setUint32(0,n.groupId,!0),t.setUint32(4,n.frameSeq,!0),t.setUint8(8,n.keyframe?Le:0),t.setUint8(9,n.fragIndex),t.setUint8(10,n.fragCount),t.setUint8(11,0),e}var Ar=100,V=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Ar}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<K)return;let t=Fe(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,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(K),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let s of this.pending.keys())s<t.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}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((i,a)=>i+a.byteLength,0),s=new Uint8Array(r),o=0;for(let i of t.chunks)s.set(i,o),o+=i.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:s})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Rr=250,Er=3,Ir=1e4,Ne=2500,G=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r;this.firstMedia=new Promise((s,o)=>{this.firstFrameResolve=s,this.firstFrameReject=o}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new V({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};firstFrameResolve=null;firstFrameReject=null;firstFrameOutput=!1;firstDecodeTimer=null;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(a=>({algorithm:"sha-256",value:Uint8Array.from(atob(a),c=>c.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let t=await this.wt.createBidirectionalStream();this.writer=t.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let r=t.readable.getReader(),s=new H,o=[],i=await this.readControl(r,s,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");this.initDecoder(i.codec,i.width,i.height),this.controlLoop(r,s,o).catch(a=>this.die(`control loop: ${a}`)),this.datagramLoop().catch(a=>this.die(`datagram loop: ${a}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(a=>this.die(`connection error: ${a}`))}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}onDead(e){this.deadCb=e}stats(){return this.lastStats}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="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 s({output:i=>{this.firstFrameOutput=!0,this.firstDecodeTimer&&(clearTimeout(this.firstDecodeTimer),this.firstDecodeTimer=null),this.canvas.width=i.displayWidth,this.canvas.height=i.displayHeight,o.drawImage(i,0,0),i.close()},error:i=>this.onDecoderError(i)}),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(s=>t-s<Ir),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=Er){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(s){this.die(`decoder re-init: ${s instanceof Error?s.message:String(s)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}armFirstDecodeDeadline(){if(this.firstDecodeTimer||this.firstFrameOutput||this.stopped||this.deadFired)return;let e=setTimeout(()=>{this.firstDecodeTimer=null,!(this.firstFrameOutput||this.stopped||this.deadFired)&&(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${Ne}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Ne}ms`))},Ne);e.unref?.(),this.firstDecodeTimer=e}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;this.armFirstDecodeDeadline();let s=performance.now();if(this.lastArrivalTs>0){let o=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;!this.decoder||typeof s!="function"||(this.decoder.decode(new s({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(qe(e))}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:o,done:i}=await e.read();if(i)return null;o&&r.push(...t.push(o))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;s.t==="ping"&&this.sendControl({t:"pong",ts:s.ts}).catch(()=>{})}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),o=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:o>0?100*s.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Rr)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstDecodeTimer&&clearTimeout(this.firstDecodeTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var Cr=2500,Pr=["av01.0.08M.08","avc1.42E01F","avc1.640028"],z=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&s,webcodecs:r,codecs:Pr};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:o});let i=o.webtransport&&!!this.offer.webtransport;if(i){let a=null;try{return a=this.createWebTransportSession(),await Mr(a.start(),this.opts.quicDeadlineMs??Cr,"quic connect deadline"),this.session=a,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){console.warn("[urun] webtransport failed, falling back to webrtc:",c),a?.stop().catch(()=>{}),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}return this.session=await this.startWebRtc(),i||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){await this.session?.stop(),this.session=null}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 G(e,this.sessionId,this.opts.canvas)}async startWebRtc(){let e=this.opts.createWebRtcSession();return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}armFailover(){let e=this.session;e.onDead(t=>{console.warn("[urun] quic died mid-session, failing over to webrtc:",t),e.stop().catch(()=>{}),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(r){this.session=null,console.error("[urun] failover to webrtc also failed:",r)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function Mr(n,e,t){return new Promise((r,s)=>{let o=setTimeout(()=>s(new Error(t)),e);n.then(i=>{clearTimeout(o),r(i)},i=>{clearTimeout(o),s(i)})})}var xr=1e4,Y=class{constructor(e,t=xr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=oe();return new Promise((s,o)=>{let i=setTimeout(()=>{a(),o(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(i),a(),c.error){o(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:l,requestId:d,...h}=c;s(h)});this.carrier.sendSignal({type:e,requestId:r,...t})})}notify(e,t){this.carrier.sendSignal({type:e,...t})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};var Or="video",J=class{constructor(e,t=Or){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),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 Dr="video";function St(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let i=s.createElement("canvas"),a=!1,c=null,l=!1,d=()=>{if(c){for(let u of c.getVideoTracks())try{u.stop()}catch{}c=null}l&&(l=!1,t.onOverrideTrack(null))},h=new z(new Y(n),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new J(n,t.streamName??Dr)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(u,w)=>{u==="webrtc"&&d(),t.onTransportChange?.(u,w)}});return(async()=>{let u=await h.connect();if(a||u.kind!=="webtransport"||(await u.firstMedia,a||h.activeTransport!=="webtransport")||typeof i.captureStream!="function")return;c=i.captureStream();let w=c.getVideoTracks()[0];w&&(l=!0,t.onOverrideTrack(w))})().catch(u=>{console.debug?.("[urun] transport negotiation unavailable, staying on webrtc:",u)}),{activeTransport:()=>h.activeTransport,dispose(){a=!0,d(),h.disconnect().catch(()=>{})}}}var Ur=new Set;function $e(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var Lr="rpc",Tt=3e4,qr="rpc-resp";function Fr(n){return`${qr}:${n}`}function je(){return oe()}function Nr(n){if(n&&typeof n=="object"){let e=n.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 n=="string"?n:JSON.stringify(n)}}function jr(n,e,t,r,s,o,i,a,c,l){let d=[],h=null,u=!1,w=null,f=!1,m,y,b=new Promise((g,I)=>{m=g,y=I});b.catch(()=>{});let p=i(),v=null,A=null,R=null,Q=null,Z=!0,Ge=()=>{R&&(clearTimeout(R),R=null),Q&&(Q(),Q=null)},ze=!1,Ye=()=>{ze||!f||(ze=!0,n.set({rpc:{[e]:null}}))},ee=()=>{Z=!1,Ge(),v?.(),v=null,A?.(),A=null,a?.removeEventListener("abort",Xe),p.dispose(),Ye()},_e=()=>{if(h){if(d.length>0){let g=h;h=null,g.resolve({value:d.shift(),done:!1})}else if(w!==null){let g=h;h=null,g.reject(w)}else if(u){let g=h;h=null,g.resolve({value:void 0,done:!0})}}},Ot=g=>{u||(d.push(g),_e())},x=g=>{u||(w=g,u=!0,y(g),ee(),_e())},Je=g=>{u||(u=!0,m(g),ee(),_e())},Xe=()=>{let g=a?.reason;x(g instanceof re?g:new ne(e))},Dt=g=>{if(!(u||!g||typeof g!="object"))switch(Ye(),g.t){case"delta":typeof g.delta=="string"&&Ot(g.delta);break;case"response":Je(g.body);break;case"error":{let{message:I,code:O}=Nr(g.body);x(new re(I,{requestId:e,code:g.code??O}));break}}},Ut=()=>{let g=p.messages()[Symbol.asyncIterator]();v=()=>{g.return?.(void 0)};let I=()=>{Z&&g.next().then(O=>{if(Z){if(O.done){u||Je(void 0);return}Dt(O.value),I()}},O=>{Z&&x(O)})};I()},Qe=()=>{if(!f){if(f=!0,a){if(a.aborted){x(new ne(e));return}a.addEventListener("abort",Xe,{once:!0})}A=c?.(g=>x(g))??null,Ut(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:o}}}),l&&l>0&&!n.synced&&(R=setTimeout(()=>{R=null,!u&&!n.synced&&x(new ke(l,e))},l),Q=n.onSynced(()=>Ge()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Qe(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(w!==null){let g=w;return w=null,Promise.reject(g)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((g,I)=>{h={resolve:g,reject:I}})},return(){return u||(u=!0,m(void 0),ee()),Promise.resolve({value:void 0,done:!0})},throw(g){return u||(u=!0,y(g),ee()),Promise.reject(g)}}}},body:b,start:Qe}}function kt(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Wr(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:o,br:i}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=kt(o);c&&(a.rt=c);let l=kt(i);return l&&(a.br=l),a}var We=class{constructor(e,t,r,s,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_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._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,o={push(a){if(!s)if(r){let c=r;r=null,c({value:a,done:!1})}else t.push(a)},end(){if(s=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{s=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_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 s of r)s(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Wr(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Te(this._name,"runtime","browser");if(s)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let i=r?.kind??e;i&&(o.kind=i),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??Ue;return bt(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}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)}},X=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new nt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;constructor(e,t,r,s,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=o,this._streamData=et(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=De(()=>this.recover()),this._activity=Oe({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new N({onPhase:i=>this.onPhase(i),hint:()=>this.doc("control").get(Ee),onData:(i,a)=>this._streamData.onData(i,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 mt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new te,i=new ae({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,o,i,$e(t),$({...t,baseUrl:r.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),i.setEndsAt(r.endsAt),se()&&await ie(),a.setDocTransport({wsUrl:r.wsUrl,token:s}),await i.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)}whenLive(e){return Re(this,e)}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 q(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),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 P(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new P(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 We(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 st(e,this._sessionId,Ur.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=it(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=tt(e.wsUrl),r=`${t}\0${e.token??""}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(rt({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket})))}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=je(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>s.abort(new Se(a,r)),a)}let i=this._consumeResponse(r,e,!1,s.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,r,s,o){this._activity?.touch();let i=this.doc(Lr),a=Fr(e);return jr(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??Tt)}requestStream(e,t={}){let r=je();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=je(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.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)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=St(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new F)}disconnect(){this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._activation.dispose(),this._recoveryHooks.clear();let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new Ae)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};function At(n){return`urun:logical:v1:${n.orgId}:${n.app}:${n.functionName}`}function Be(){try{return globalThis.sessionStorage??null}catch{return null}}function Rt(n){let e=Be();if(!e)return null;try{let t=e.getItem(n);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 Et(n,e){let t=Be();if(t)try{t.setItem(n,JSON.stringify({logicalId:e.logicalId}))}catch{}}function He(n){let e=Be();if(e)try{e.removeItem(n)}catch{}}var $r=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Br(n,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(!($r.has(r)||typeof r!="string"))return s=>{let o=s??{},i=At({orgId:e.orgId,app:n,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),l=new te,d=new ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),h=new X(c,l,d,$e(e),$(e)),u,w,f=new Promise(p=>{w=p}),m=p=>{u=p,w({status:"ready",handle:p})};h.setEndHandler(async()=>{let p=u?{status:"ready",handle:u}:await f;if(p.status==="unavailable")throw new F("[urun] session allocation failed before a releasable request was created",{cause:p.cause});let v=p.handle;return He(i),ut({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})});let y=async p=>{let v=await ft({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:p,sessionKey:e.sessionKey??Rt(i)?.logicalId,onAdmission:R=>d.reportAdmission(R),onRequest:m}),A=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return e.sessionKey||Et(i,{logicalId:v.sessionId}),h.setSessionId(v.sessionId),h.setArtifactsAuth($({...e,baseUrl:v.baseUrl})),d.setEndsAt(v.endsAt),{url:v.wsUrl,sessionId:v.sessionId,jwt:A,iceServers:v.response.ice_servers,endsAt:v.endsAt}},b;return d.setConnectionResolver(async()=>{let p=await y(a());return b=p.jwt,p}),d.on("connected",()=>{d.multiplexer&&l.setTarget(d.multiplexer);let p=d.connectedUrl;p&&h.setDocTransport({wsUrl:p,token:b})}),(async()=>{let p;try{p=await y(c)}catch(v){console.error(`[urun] Failed to create session for ${r}:`,v),He(i);let A=v instanceof Error?v:new Error(String(v)),R=v instanceof T?v.httpStatus:void 0;d.reportAllocationFailure(A,R),w({status:"unavailable",cause:v});return}d.setAuth({jwt:p.jwt,authProvider:e.authProvider,orgId:e.orgId}),d.setConnection({url:p.url,sessionId:p.sessionId,iceServers:p.iceServers}),se()&&await ie(),b=p.jwt,h.setDocTransport({wsUrl:p.url,token:p.jwt}),await d.connect({app:n,functionName:r,args:o}),h.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(p=>{console.error(`[urun] Failed to connect session for ${r}:`,p)}),h}}})}var It="https://api.urun.sh",M=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Hr(n,e={}){if(!n)throw new M("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=S(e.baseUrl??It),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s)})}catch(u){throw new M(`[urun] client token mint request failed: ${u instanceof Error?u.message:String(u)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let u=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new M(`[urun] client token mint failed: ${u}`,o.status)}let a=typeof i.token=="string"?i.token:"",c=typeof i.org_id=="string"?i.org_id:"",l=typeof i.expires_at=="string"?Date.parse(i.expires_at):Number.NaN,d=typeof i.expires_in=="number"?i.expires_in:void 0;if(!a)throw new M("[urun] client token mint returned no token (control-plane contract violation)",o.status);let h=Number.isFinite(l)?new Date(l):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:h,orgId:c}}var Ct=3e4,Pt="stream:",Ke=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let o=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(o.timer),s.error?o.reject(new Error(s.error)):o.resolve(s.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=`${Pt}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${Pt}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),s(new Error(`RPC request "${e}" timed out after ${Ct}ms`)))},Ct);this._pendingRpc.set(o,{resolve:r,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Kr(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let o=new Ze(s);return new Ke(s,o)}var Vr='video/mp4; codecs="avc1.42E01E"';function Gr(n,e){let t=e?.codec??Vr,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,o=URL.createObjectURL(s);r.src=o,s.addEventListener("sourceopen",()=>{let u;try{u=s.addSourceBuffer(t)}catch(y){throw y instanceof DOMException&&y.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).`):y}let w=n.getReader();function f(){return u.updating?new Promise(y=>{u.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function m(){try{for(;;){let{done:y,value:b}=await w.read();if(y){await f(),s.readyState==="open"&&s.endOfStream();return}await f();try{u.appendBuffer(b)}catch(p){if(p instanceof DOMException&&p.name==="QuotaExceededError"){let v=u.buffered;if(v.length>0){let A=v.start(v.length-1);u.remove(0,A),await f(),u.appendBuffer(b)}else throw p}else throw p}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}m()}),r.play().catch(()=>{});let i=r,a=i.captureStream??i.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),l=c.getTracks(),d=0,h=l.length;if(h===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let u of l)u.addEventListener("ended",()=>{d++,d>=h&&URL.revokeObjectURL(o)});return c}function zr(n){return n.status.startsWith("pending_")}var ye=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 Mt(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function Yr(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function Jr(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function Ve(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var be=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,Ve(r,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.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 ye;return t=>e.getUserMedia(t)}async converge(e){for(let i of this.claims.values())i.track&&(i.track.stop(),i.track=null,i.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},s;try{s=await t(r)}catch(i){let a=`one-capture getUserMedia(${Mt(r)}) failed`,c=i instanceof Error?i.message:String(i);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==e){let d=new Error(`${a} \u2014 ${l.kind} capture lost: ${c||i}`);d.cause=i,Ve(l,d)}throw i}let o=[...this.claims.values()].sort((i,a)=>i===e?1:a===e?-1:0);for(let i of o){let a=Yr(s,i.kind)[0]??null;if(i.released){a?.stop();continue}if(!a){this.claims.delete(i.kind),i.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${Mt(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;Ve(i,c);continue}if(i.track=a,i.stream=Jr(s,a),i!==e)for(let c of[...i.trackListeners])try{c(a,i.stream)}catch{}}}createState(e,t){let r=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(o){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=o,await r.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(e)===s&&r.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(o){return s.trackListeners.add(o),()=>s.trackListeners.delete(o)},onLost(o){return s.lostListeners.add(o),()=>s.lostListeners.delete(o)}}};return s}},Xr=null;function Qr(){return Xr??=new be}var xt="input",Zr=30;function en(n){let e=n.now??Date.now,t=n.field??xt,r=1e3/Math.max(n.hz??30,.001),s=new Set,o=0,i=0,a=0,c=0,l,d=null,h=!1,u=()=>{if(h)return;l=e(),c+=1;let f={keys:[...s],buttons:o,pointer:{x:i,y:a},seq:c,at:l};try{n.awareness.setLocalStateField(t,f)}catch{}},w=()=>{if(h)return;let f=e();if(l===void 0||f-l>=r){d&&(clearTimeout(d),d=null),u();return}if(d)return;let m=Math.max(r-(f-l),0);d=setTimeout(()=>{d=null,u()},m),d.unref?.()};return{keyDown(f){let m=String(f).toLowerCase();s.has(m)||(s.add(m),w())},keyUp(f){let m=String(f).toLowerCase();s.delete(m)&&w()},setButtons(f){let m=Number.isFinite(f)?Number(f):0;m!==o&&(o=m,w())},movePointer(f,m){let y=Number.isFinite(f)?Number(f):0,b=Number.isFinite(m)?Number(m):0;y===0&&b===0||(i+=y,a+=b,w())},heldKeys(){return[...s]},clear(){h||(s.clear(),o=0,d&&(clearTimeout(d),d=null),u())},dispose(){if(h)return;let f=s.size>0||o!==0;s.clear(),o=0,d&&(clearTimeout(d),d=null),f&&u(),h=!0}}}export{Kt as ACTIVATION_COLD_BOOT_AFTER_MS,Vt as ACTIVATION_DEGRADED_AFTER_MS,Ee as ACTIVATION_HINT_PATH,Ht as ACTIVATION_STILL_AFTER_MS,xe as ACTIVITY_DOM_EVENTS,wt as ACTIVITY_FIELD,yr as ACTIVITY_STAMP_MIN_INTERVAL_MS,N as ActivationMonitor,Br as App,at as BACKOFF_BASE_MS,U as BACKOFF_MAX_ATTEMPTS,ct as BACKOFF_MAX_MS,be as CaptureController,ye as CaptureUnavailableError,M as ClientTokenError,Tt as DEFAULT_DOC_SYNC_TIMEOUT_MS,It as DEFAULT_GATEWAY_URL,Lt as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,$t as DEFAULT_WHEN_LIVE_TIMEOUT_MS,K as DGRAM_HEADER_BYTES,br as FOREGROUND_COALESCE_MS,V as FrameReassembler,Zr as INPUT_PRESENCE_DEFAULT_HZ,xt as INPUT_PRESENCE_FIELD,L as InvalidDurationError,we as PermanentLockedError,ve as PinRequiresActiveTempError,qt as ProduceAckTimeoutError,he as RecordingNotFoundError,q as RecordingsClient,k as RecordingsError,B as RecordingsUnauthorizedError,ne as RequestAbortError,Ae as RequestCancelledError,ke as RequestDocSyncError,re as RequestError,Se as RequestTimeoutError,ge as RetainNotTempError,me as RuntimeArtifactNotFoundError,P as RuntimeArtifactsClient,_ as RuntimeArtifactsError,fe as RuntimeArtifactsUnauthorizedError,X as Session,T as SessionAllocationError,D as SessionEndError,F as SessionEndUnavailableError,Nt as SessionFailedError,Te as StreamDirectionConflict,z as TransportNegotiator,Y as TransportSessionSignaling,_t as WT_CONTROL_FRAME_MAX,J as WebRtcSession,G as WebTransportSession,H as WtControlDecoder,ot as activationHintFrom,de as computeBackoffDelay,Oe as createActivityTracker,Hr as createClientToken,en as createInputPresencePublisher,wr as createRecordingsClient,lr as createRuntimeArtifactsClient,Kr as createStore,Ft as describeSessionFailure,Bt as describeSessionPhase,qe as encodeWtControlFrame,Me as isDurationString,zr as isPendingRecording,ue as isRetryableSessionError,Wt as isWakingPhase,Ue as mediaRecorderChunkSource,gr as normalizeRetention,De as observePageLifecycle,Fe as parseDgramHeader,or as prewake,jt as sessionFailureFromMediaError,Qr as sharedCaptureController,Gr as videoStream,Re as whenLive,Tr as writeDgramHeader};
package/dist/index.d.mts CHANGED
@@ -861,6 +861,9 @@ declare class WebTransportSession implements MediaSession {
861
861
  private firstFrameResolve;
862
862
  private firstFrameReject;
863
863
 
864
+ private firstFrameOutput;
865
+ private firstDecodeTimer;
866
+
864
867
  readonly firstMedia: Promise<void>;
865
868
  constructor(offer: NonNullable<TransportOfferResponse['webtransport']>, sessionId: string, canvas: HTMLCanvasElement);
866
869
 
@@ -875,6 +878,8 @@ declare class WebTransportSession implements MediaSession {
875
878
  private initDecoder;
876
879
 
877
880
  private onDecoderError;
881
+
882
+ private armFirstDecodeDeadline;
878
883
  private datagramLoop;
879
884
  private decodeFrame;
880
885
  private sendControl;
package/dist/index.d.ts CHANGED
@@ -861,6 +861,9 @@ declare class WebTransportSession implements MediaSession {
861
861
  private firstFrameResolve;
862
862
  private firstFrameReject;
863
863
 
864
+ private firstFrameOutput;
865
+ private firstDecodeTimer;
866
+
864
867
  readonly firstMedia: Promise<void>;
865
868
  constructor(offer: NonNullable<TransportOfferResponse['webtransport']>, sessionId: string, canvas: HTMLCanvasElement);
866
869
 
@@ -875,6 +878,8 @@ declare class WebTransportSession implements MediaSession {
875
878
  private initDecoder;
876
879
 
877
880
  private onDecoderError;
881
+
882
+ private armFirstDecodeDeadline;
878
883
  private datagramLoop;
879
884
  private decodeFrame;
880
885
  private sendControl;