@urun-sh/core 0.2.57 → 0.2.59

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{A as N,B as Ze,C as ke,D as et,E as tt,F as rt,G as rr,H as ne,K as se,L as ie,M as nt,N as st,P as it,R as nr,S as sr,T as ir,U as oe,W as ot,X as at,Y as ct,Z as dt,_ as ut,a as Xe,b as ee,c as $,d as jt,e as te,f as ve,g as we,h as be,i as $t,j as Bt,k as re,l as ye,m as Ht,n as Vt,o as Kt,p as Gt,q as Se,r as zt,s as Yt,t as _e,u as Qt,v as Jt,w as Xt,x as Zt,y as er,z as tr}from"./chunk-TZ4YVHOL.mjs";var or=15e3,ar=45e3,cr=12e4,Te="platform",Re="activation",Ee="desired.activation";function lt(s){if(typeof s=="string"&&s.length>0)return s;if(s&&typeof s=="object"){let e=s.note;if(typeof e=="string"&&e.length>0)return e}}var dr=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],B=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of dr){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let n={state:t,elapsedMs:r,stream:e.name},o=lt(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let i of Array.from(this._handlers))i(n)}};var k=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",n){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,n!==void 0&&(this.cause=n),Object.setPrototypeOf(this,new.target.prototype)}},ae=class extends k{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},ce=class extends k{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function H(s){return{baseUrl:s.baseUrl,fallbackUrls:s.fallbackUrls,orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}function ur(s){return new x(s)}var x=class{_options;constructor(e){this._options=e}async list(e){let r=mt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new k("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(pt)}async getDownloadUrl(e,t){let r=mt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!pr(n))throw new k("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:pt(r.artifact),downloadUrl:n}}async _request(e,t){let r=Ze(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(i){if(n=i instanceof Error?i:new Error(String(i)),n instanceof k&&mr(n.status))throw n}throw n??new k("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${N(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),i=await fetch(n,{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(n,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:c}=await this._readError(i,e);throw fr(i.status,a,c)}try{return await i.json()}catch(a){throw new k(`[urun] runtime artifacts: invalid JSON response from ${N(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=N(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 pt(s){if(!s||typeof s!="object")throw new k("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=s,t=P(e,"artifact_id")||P(e,"id"),r=P(e,"filename"),n=P(e,"kind"),o=P(e,"status")||"ready",i=lr(e,"size_bytes"),a=P(e,"sha256");if(!t||!r||!n||i==null||!a)throw new k("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:P(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:P(e,"created_at"),expiresAt:P(e,"expires_at")}}function P(s,e){let t=s[e];return typeof t=="string"&&t.length>0?t:void 0}function lr(s,e){let t=s[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function pr(s){try{return new URL(s).protocol==="https:"}catch{return!1}}function mr(s){return s===401||s===403}function fr(s,e,t){return s===401?new ae(t,e):s===404?new ce(t,e):new k(t,s,e)}function mt(s){if(!s||typeof s!="object"||Array.isArray(s))throw new k("[urun] runtime artifacts: malformed response",0,"bad_response");return s}var C=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)}},V=class extends C{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},de=class extends C{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ue=class extends C{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)}},le=class extends C{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)}},pe=class extends C{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)}},W=class extends C{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 Ae(s){return/^(\d+[smhdw])+$/.test(s)}function hr(s){if(s==="pin")return{action:"pin"};if(Ae(s))return{action:"retain",duration:s};throw new W(`[urun] recordings: "${s}" is not a duration or "pin"`)}function gr(s,e,t){let r=t||e||`HTTP ${s}`;if(s===401)return new V(r,e??"unauthorized");if(s===404)return new de(r,e??"not_found");if(s===400)return new W(r,e??"bad_request",400);if(s===409)switch(e){case"retain_not_temp":return new ue(r,e);case"pin_requires_active_temp":return new le(r,e);case"permanent_locked":return new pe(r,e)}return new C(r,{status:s,code:e??`http_${s}`})}var F=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(!Ae(t))throw new W(`[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 C("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),o=await this._resolveToken(),i=await this._fetch(n,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(n,e,o,r.body))}if(!i.ok){let{code:a,message:c}=await this._readError(i);throw gr(i.status,a,c)}return this._readJson(i)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let i={method:t,headers:o};return n!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(n)),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 V("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function vr(s){return new F(s)}var ft="activity",ht="visibility",wr=15e3,Ce=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ie(s){let e=s.now??Date.now,t=s.windowTarget!==void 0?s.windowTarget:typeof window<"u"?window:null,r=s.documentTarget!==void 0?s.documentTarget:typeof document<"u"?document:null,n=!1,o,i=()=>{if(n)return;let f=e();if(!(o!==void 0&&f-o<15e3)){o=f;try{s.awareness.setLocalStateField(ft,{at:f})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{s.awareness.setLocalStateField(ht,r.visibilityState)}catch{}},c=()=>i(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let f of Ce)t.addEventListener(f,c,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",u);let d=null;return s.isProducing&&(d=setInterval(()=>{if(!n)try{s.isProducing?.()&&i()}catch{}},15e3),d.unref?.()),i(),a(),{touch:i,dispose(){if(!n){if(n=!0,t)for(let f of Ce)t.removeEventListener(f,c,{capture:!0});r&&r.removeEventListener("visibilitychange",u),d&&(clearInterval(d),d=null)}}}}var br=250;function Pe(s){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,s())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function De(s){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,s())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function Me(s){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{s()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var gt="video/mp4";function xe(s,e={}){let t=e.timesliceMs??1e3,r=null,n=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 f=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(gt)?gt:void 0),p=new MediaStream([a]),l=new d(p,f?{mimeType:f}:void 0);r=l;let m=Promise.resolve();l.ondataavailable=w=>{let b=w.data;o||!b||b.size===0||(m=m.then(async()=>{let S=new Uint8Array(await b.arrayBuffer());o||c(S)}))},l.onstop=()=>{m.then(()=>{o||u()})},l.onerror=()=>{m.then(()=>{o||u()})},l.start(t)};return{start(a,c){if(r||o)return;let u=s.track();if(u){i(u,a,c);return}n=s.onTrack(d=>{!d||r||o||(n?.(),n=null,i(d,a,c))})},stop(){if(o)return;o=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function yr(s){let e=s;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=s.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 vt(s,e){let t=null,r=!1,n=!1,o=new ReadableStream({pull(i){r||(r=!0,t=s(e),t.start(a=>{if(!n)try{i.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{i.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return yr(o)}import{encode as Sr,decode as _r}from"@msgpack/msgpack";var wt=65536;function Le(s){let e=Sr(s),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var K=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>wt)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(_r(n))}return t}},G=12,Oe=1;function Ue(s){let e=s.getUint8(8);return{groupId:s.getUint32(0,!0),frameSeq:s.getUint32(4,!0),keyframe:(e&Oe)===Oe,fragIndex:s.getUint8(9),fragCount:s.getUint8(10)}}function kr(s){let e=new Uint8Array(G),t=new DataView(e.buffer);return t.setUint32(0,s.groupId,!0),t.setUint32(4,s.frameSeq,!0),t.setUint8(8,s.keyframe?Oe:0),t.setUint8(9,s.fragIndex),t.setUint8(10,s.fragCount),t.setUint8(11,0),e}var Tr=100,z=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Tr}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<G)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(G),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}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),n=new Uint8Array(r),o=0;for(let i of t.chunks)n.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:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Rr=/^avc[13]\.[0-9a-fA-F]{6}$/;function Er(s){return Rr.test(s)?null:`codec ${JSON.stringify(s)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function Ne(s,e){let t=Er(s);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var bt=1,me=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==bt)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let n=this.buf[1];if(n===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+n)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+n)),this.buf=this.buf.subarray(2+n)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let n=st(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===nt&&(this.ended=!0),t.push({name:this.name,payload:n})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function We(s,e){let t=s.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&Ar(r,e).catch(o=>{e.onLaneError(o instanceof Error?o:new Error(String(o)))})}}async function Ar(s,e){let t=s.getReader(),r=new me;try{for(;;){let{value:n,done:o}=await t.read();if(o)break;if(!(!n||n.byteLength===0))for(let{name:i,payload:a}of r.push(n))e.onData(i,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var Cr=250,Ir=3,Pr=1e4,Fe=2500,Y=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r;this.firstMedia=new Promise((n,o)=>{this.firstFrameResolve=n,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 z({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;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");Ne(this.offer.codec,"transport.offer"),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(),n=new K,o=[],i=await this.readControl(r,n,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");Ne(i.codec,"hello-ack"),this.initDecoder(i.codec,i.width,i.height),this.controlLoop(r,n,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}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");this.dataLaneSink=e,We(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,r){let n=globalThis.VideoDecoder;if(typeof n!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new n({output: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(n=>t-n<Pr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=Ir){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(n){this.die(`decoder re-init: ${n instanceof Error?n.message:String(n)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}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 ${Fe}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Fe}ms`))},Fe);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 n=performance.now();if(this.lastArrivalTs>0){let o=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;!this.decoder||typeof n!="function"||(this.decoder.decode(new n({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}async sendControl(e){await this.writer.write(Le(e))}async readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;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 n=await this.readControl(e,t,r);if(!n)break;n.t==="ping"&&this.sendControl({t:"pong",ts:n.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 n=this.reassembler.drainWindow(),o=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:o>0?100*n.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Cr)}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 yt=2500,St=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Q=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&n,webcodecs:r,codecs:St,wtData:t&&r&&n&&this.opts.dataLane!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:o});let i=o.webtransport&&!!this.offer.webtransport;if(o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),i){let a=null;try{return a=this.createWebTransportSession(),await _t(a.start(),this.opts.quicDeadlineMs??yt,"quic connect deadline"),this.engageQuicDataLane(a,o.wtData===!0),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(){this.quicDataLane=!1,await this.session?.stop(),this.session=null}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,n=this.opts.dataLane!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:St,wtData:n}}),!this.offer.webtransport)return null;let o=this.createWebTransportSession();try{await _t(o.start(),this.opts.quicDeadlineMs??yt,"quic connect deadline")}catch(i){throw o.stop().catch(()=>{}),i}if(this.session!==r)return o.stop().catch(()=>{}),null;try{this.engageQuicDataLane(o,n)}catch(i){throw o.stop().catch(()=>{}),i}return this.session=o,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),o}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(n,o)=>r.onData(n,o),onLaneError:n=>r.onLaneError(n)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new Y(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),this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(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 _t(s,e,t){return new Promise((r,n)=>{let o=setTimeout(()=>n(new Error(t)),e);s.then(i=>{clearTimeout(o),r(i)},i=>{clearTimeout(o),n(i)})})}var Dr=1e4,J=class{constructor(e,t=Dr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=ie();return new Promise((n,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,...f}=c;n(f)});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 Mr="video",X=class{constructor(e,t=Mr){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,n)=>{this.firstMediaResolve=r,this.firstMediaReject=n}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};var xr="video";function kt(s,e,t){let r=globalThis,n=r.document;if(!(typeof n?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let i=n.createElement("canvas"),a=!1,c=null,u=!1,d=()=>{if(c){for(let y of c.getVideoTracks())try{y.stop()}catch{}c=null}u&&(u=!1,t.onOverrideTrack(null))},f=new Q(new J(s),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new X(s,t.streamName??xr)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(y,h)=>s.dispatchQuicStreamData(y,h),onQuicLane:()=>s.markStreamDataLaneQuic(),onQuicLaneLost:y=>s.quicStreamDataLaneLost(y),onLaneError:y=>s.raiseQuicStreamDataError(y)},onTransportChange:(y,h)=>{y==="webrtc"&&(d(),_()),t.onTransportChange?.(y,h)}}),p=null,l=()=>{p!==null&&(clearTimeout(p),p=null)},m=t.wtRetryBaseMs??2e3,w=t.wtRetryCapMs??3e4,b=null,S=0,_=()=>{if(a||b!==null||f.activeTransport==="webtransport")return;let y=Math.min(m*2**S,w);b=setTimeout(()=>{b=null,S+=1,f.retryWebTransport().then(h=>{if(!a){if(h)return console.debug(`[urun] webtransport upgraded in background (retry ${S})`),S=0,T(h);_()}}).catch(h=>{a||(console.debug(`[urun] webtransport background retry ${S} failed:`,h),_())})},y)},R=()=>{b!==null&&(clearTimeout(b),b=null)},T=async y=>{if(a||y.kind!=="webtransport")return;let h=t.firstMediaWarnMs??1e4;if(l(),p=setTimeout(()=>{a||f.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${h}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},h),await y.firstMedia,l(),a||f.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let v=c.getVideoTracks()[0];v&&(u=!0,t.onOverrideTrack(v))};return(async()=>{let y=await f.connect();await T(y)})().catch(y=>{l(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",y),_()}),{activeTransport:()=>f.activeTransport,dispose(){a=!0,l(),R(),d(),f.disconnect().catch(()=>{})}}}var Or=new Set;function $e(s){if(s.functionsUrl)return{functionsUrl:s.functionsUrl,orgId:s.orgId,apiKey:s.apiKey,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}var Lr="rpc",Rt=3e4,Ur="rpc-resp";function Nr(s){return`${Ur}:${s}`}function qe(){return ie()}function Wr(s){if(s&&typeof s=="object"){let e=s.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 s=="string"?s:JSON.stringify(s)}}function Fr(s,e,t,r,n,o,i,a,c,u){let d=[],f=null,p=!1,l=null,m=!1,w,b,S=new Promise((g,D)=>{w=g,b=D});S.catch(()=>{});let _=i(),R=null,T=null,y=null,h=null,v=!0,I=()=>{y&&(clearTimeout(y),y=null),h&&(h(),h=null)},A=!1,j=()=>{A||!m||(A=!0,s.set({rpc:{[e]:null}}))},E=()=>{v=!1,I(),R?.(),R=null,T?.(),T=null,a?.removeEventListener("abort",Qe),_.dispose(),j()},M=()=>{if(f){if(d.length>0){let g=f;f=null,g.resolve({value:d.shift(),done:!1})}else if(l!==null){let g=f;f=null,g.reject(l)}else if(p){let g=f;f=null,g.resolve({value:void 0,done:!0})}}},Wt=g=>{p||(d.push(g),M())},L=g=>{p||(l=g,p=!0,b(g),E(),M())},Ye=g=>{p||(p=!0,w(g),E(),M())},Qe=()=>{let g=a?.reason;L(g instanceof te?g:new re(e))},Ft=g=>{if(!(p||!g||typeof g!="object"))switch(j(),g.t){case"delta":typeof g.delta=="string"&&Wt(g.delta);break;case"response":Ye(g.body);break;case"error":{let{message:D,code:U}=Wr(g.body);L(new te(D,{requestId:e,code:g.code??U}));break}}},qt=()=>{let g=_.messages()[Symbol.asyncIterator]();R=()=>{g.return?.(void 0)};let D=()=>{v&&g.next().then(U=>{if(v){if(U.done){p||Ye(void 0);return}Ft(U.value),D()}},U=>{v&&L(U)})};D()},Je=()=>{if(!m){if(m=!0,a){if(a.aborted){L(new re(e));return}a.addEventListener("abort",Qe,{once:!0})}T=c?.(g=>L(g))??null,qt(),s.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!s.synced&&(y=setTimeout(()=>{y=null,!p&&!s.synced&&L(new we(u,e))},u),h=s.onSynced(()=>I()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Je(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(l!==null){let g=l;return l=null,Promise.reject(g)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((g,D)=>{f={resolve:g,reject:D}})},return(){return p||(p=!0,w(void 0),E()),Promise.resolve({value:void 0,done:!0})},throw(g){return p||(p=!0,b(g),E()),Promise.reject(g)}}}},body:S,start:Je}}function Tt(s){if(s&&typeof s=="object"){let{epoch:e,by:t}=s,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function qr(s,e){let r=s.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:o,br:i}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let c=Tt(o);c&&(a.rt=c);let u=Tt(i);return u&&(a.br=u),a}var je=class{constructor(e,t,r,n,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let 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._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,o=null,i={push(c){if(!n)if(r){let u=r;r=null,u.resolve({value:c,done:!1})}else t.push(c)},end(){if(n=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(i);let a=()=>{n=!0,e._messageConsumers.delete(i)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||n)&&(o=e._streamConsumeUnavailableError(c),a(),r)){let u=r;r=null,u.reject(o)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):o?Promise.reject(o):n?Promise.resolve({value:void 0,done:!0}):new Promise((c,u)=>{r={resolve:c,reject:u}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=qr(t,this._name),n=r?.br;if(n?.by==="runtime")throw new be(this._name,"runtime","browser");if(n)return;let o={br:{epoch:1}};r?.rt&&(o.rt=r.rt);let 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 vt(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},Z=class s{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new ct;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;constructor(e,t,r,n,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=o,this._streamData=it(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Pe(()=>this.recover()),this._activity=Ie({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new B({onPhase:i=>this.onPhase(i),hint:()=>this.doc(Te).get(Re)??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 rt({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new ee,i=new oe({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,o,i,$e(t),H({...t,baseUrl:r.baseUrl}));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),ne()&&await se();let c=t.getAccessToken,u=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:u}),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)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return _e(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 F(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,n)=>t.retain(r,n),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new x(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new x(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 je(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 dt(e,this._sessionId,Or.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=ut(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=ot(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${t}\0${r}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(at({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=qe(),n=new AbortController;t.signal&&(t.signal.aborted?n.abort(t.signal.reason):t.signal.addEventListener("abort",()=>n.abort(t.signal.reason),{once:!0}));let o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>n.abort(new ve(a,r)),a)}let i=this._consumeResponse(r,e,!1,n.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,r,n,o){this._activity?.touch();let i=this.doc(Lr),a=Nr(e);return Fr(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??Rt)}requestStream(e,t={}){let r=qe();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=qe(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=kt(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),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new $)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._activation.dispose(),this._recoveryHooks.clear();let t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new ye)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function Et(s){return`urun:logical:v1:${s.orgId}:${s.app}:${s.functionName}`}function Be(){try{return globalThis.sessionStorage??null}catch{return null}}function At(s){let e=Be();if(!e)return null;try{let t=e.getItem(s);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 Ct(s,e){let t=Be();if(t)try{t.setItem(s,JSON.stringify({logicalId:e.logicalId}))}catch{}}function fe(s){let e=Be();if(e)try{e.removeItem(s)}catch{}}var jr=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function $r(s,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(!(jr.has(r)||typeof r!="string"))return n=>{let o=n??{},i=Et({orgId:e.orgId,app:s,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),u=e.jwt,d=e.getAccessToken?async h=>{let v=await e.getAccessToken(h);return v&&(u=v),v}:void 0,f={...e,getAccessToken:d},p=new ee,l=new oe({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),m=new Z(c,p,l,$e(f),H(f)),w,b,S=new Promise(h=>{b=h}),_=h=>{w=h,b({status:"ready",handle:h})};m.setEndHandler(async()=>{let h=w?{status:"ready",handle:w}:await S;if(h.status==="unavailable")throw new $("[urun] session allocation failed before a releasable request was created",{cause:h.cause});let v=h.handle;return fe(i),et({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider})});let R=async h=>{let v=await tt({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider,idempotencyKey:h,sessionKey:e.sessionKey??At(i)?.logicalId,priority:e.priority,onAdmission:A=>l.reportAdmission(A),onRequest:_}),I=d?await d()??void 0:e.jwt;return e.sessionKey||Ct(i,{logicalId:v.sessionId}),m.setSessionId(v.sessionId),m.setArtifactsAuth(H({...f,baseUrl:v.baseUrl})),l.setEndsAt(v.endsAt),{url:v.wsUrl,sessionId:v.sessionId,jwt:I,iceServers:v.response.ice_servers,endsAt:v.endsAt}},T,y=d?async()=>await d()??T:()=>T;if(l.setConnectionResolver(async()=>{let h=await R(a());return T=h.jwt,h}),l.on("connected",()=>{l.multiplexer&&p.setTarget(l.multiplexer);let h=l.connectedUrl;h&&m.setDocTransport({wsUrl:h,token:y})}),(async()=>{let h;try{h=await R(c)}catch(v){console.error(`[urun] Failed to create session for ${r}:`,v),fe(i);let I=v instanceof Error?v:new Error(String(v)),A=v instanceof Se?v.httpStatus:void 0;l.reportAllocationFailure(I,A),b({status:"unavailable",cause:v});return}l.setAuth({jwt:h.jwt,authProvider:e.authProvider,orgId:e.orgId}),l.setConnection({url:h.url,sessionId:h.sessionId,iceServers:h.iceServers}),ne()&&await se(),T=h.jwt,m.setDocTransport({wsUrl:h.url,token:y}),await l.connect({app:s,functionName:r,args:o}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(h=>{console.error(`[urun] Failed to connect session for ${r}:`,h)}),e.releaseOnLeave!==!1){let h=De(()=>{if(l.leaveLeg()||l.connectedUrl!==null)return;let E=w;E&&(fe(i),ke({baseUrl:E.baseUrl,requestId:E.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))});m.onDisconnect(h);let v,I,A=!1,j=()=>{A||(A=!0,v?.(),I?.())};S.then(E=>{E.status!=="ready"||A||(v=Me(()=>w!==void 0))}),I=m.onPhase(E=>{let M=E?.name;(M==="ended"||M==="expired"||M==="error")&&j()}),A&&I(),m.onDisconnect(j)}return m}}})}var It="https://api.urun.sh",Pt="URUN_DEV";function Br(){if(typeof process>"u")return!1;let s=process.env?.[Pt];if(typeof s!="string")return!1;let e=s.trim().toLowerCase();return e==="1"||e==="true"}var O=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Hr(s,e={}){if(!s)throw new O("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=N(e.baseUrl??It),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),(e.dev??Br())&&(n.dev=!0);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(n)})}catch(p){throw new O(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let p=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new O(`[urun] client token mint failed: ${p}`,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 O("[urun] client token mint returned no token (control-plane contract violation)",o.status);let f=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:f,orgId:c}}var Dt=3e4,Mt="stream:",He=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let o=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(o.timer),n.error?o.reject(new Error(n.error)):o.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${Mt}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Mt}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),n(new Error(`RPC request "${e}" timed out after ${Dt}ms`)))},Dt);this._pendingRpc.set(o,{resolve:r,reject:n,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Vr(s){let r=`${s.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(s.orgId)}`,n=new WebSocket(r);(s.jwt||s.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:s.orgId,jwt:s.jwt,authProvider:s.authProvider,apiKey:s.apiKey}))});let o=new Xe(n);return new He(n,o)}var Kr='video/mp4; codecs="avc1.42E01E"';function Gr(s,e){let t=e?.codec??Kr,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);r.src=o,n.addEventListener("sourceopen",()=>{let p;try{p=n.addSourceBuffer(t)}catch(b){throw b instanceof DOMException&&b.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).`):b}let l=s.getReader();function m(){return p.updating?new Promise(b=>{p.addEventListener("updateend",()=>b(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:b,value:S}=await l.read();if(b){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{p.appendBuffer(S)}catch(_){if(_ instanceof DOMException&&_.name==="QuotaExceededError"){let R=p.buffered;if(R.length>0){let T=R.start(R.length-1);p.remove(0,T),await m(),p.appendBuffer(S)}else throw _}else throw _}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}w()}),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,f=u.length;if(f===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=f&&URL.revokeObjectURL(o)});return c}function zr(s){return s.status.startsWith("pending_")}var he=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function xt(s){let e=[];return s.audio&&e.push("audio"),s.video&&e.push("video"),e.join("+")}function Yr(s,e){return e==="audio"?s.getAudioTracks():s.getVideoTracks()}function Qr(s,e){let t=s.getTracks();if(t.length===1&&t[0]===e)return s;try{return new MediaStream([e])}catch{return s}}function Ve(s,e){for(let t of[...s.lostListeners])try{t(e)}catch{}}var ge=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 n=this.createState(e,t);return this.claims.set(e,n),await this.converge(n),n.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new he;return t=>e.getUserMedia(t)}async converge(e){for(let 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},n;try{n=await t(r)}catch(i){let a=`one-capture getUserMedia(${xt(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,Ve(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=Yr(n,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(${xt(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;Ve(i,c);continue}if(i.track=a,i.stream=Qr(n,a),i!==e)for(let c of[...i.trackListeners])try{c(a,i.stream)}catch{}}}createState(e,t){let r=this,n={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return n.track},get stream(){return n.stream},update(o){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=o,await r.converge(n),!n.track)throw new Error(`${e} capture update yielded no track`);return n.track})},release(){n.released||(n.released=!0,r.claims.get(e)===n&&r.claims.delete(e),n.track?.stop(),n.track=null,n.stream=null)},onTrack(o){return n.trackListeners.add(o),()=>n.trackListeners.delete(o)},onLost(o){return n.lostListeners.add(o),()=>n.lostListeners.delete(o)}}};return n}},Jr=null;function Xr(){return Jr??=new ge}var Ot="input",Zr=30;function en(s){let e=s.now??Date.now,t=s.field??Ot,r=1e3/Math.max(s.hz??30,.001),n=new Set,o=0,i=0,a=0,c=0,u,d=null,f=!1,p=()=>{if(f)return;u=e(),c+=1;let m={keys:[...n],buttons:o,pointer:{x:i,y:a},seq:c,at:u};try{s.awareness.setLocalStateField(t,m)}catch{}},l=()=>{if(f)return;let m=e();if(u===void 0||m-u>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let w=Math.max(r-(m-u),0);d=setTimeout(()=>{d=null,p()},w),d.unref?.()};return{keyDown(m){let w=String(m).toLowerCase();n.has(w)||(n.add(w),l())},keyUp(m){let w=String(m).toLowerCase();n.delete(w)&&l()},setButtons(m){let w=Number.isFinite(m)?Number(m):0;w!==o&&(o=w,l())},movePointer(m,w){let b=Number.isFinite(m)?Number(m):0,S=Number.isFinite(w)?Number(w):0;b===0&&S===0||(i+=b,a+=S,l())},heldKeys(){return[...n]},clear(){f||(n.clear(),o=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(f)return;let m=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),m&&p(),f=!0}}}var tn=1024,rn=.92,nn=262144,sn=256e3,Ke=[.9,.8,.7,.6,.5],Lt=.8,on=8;function ze(s,e,t){if(!(s>0)||!(e>0))throw new Error(`reference image has no pixels (${s}x${e})`);let r=Math.min(1,t/Math.max(s,e));return{width:Math.max(1,Math.round(s*r)),height:Math.max(1,Math.round(e*r))}}async function an(s){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(s,{imageOrientation:"from-image"})}async function Nt(s,e,t){let r=await new Promise(n=>{s.toBlob(n,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function Ut(s,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${s} -> ${e} bytes`)}async function Ge(s,e,t,r,n){let o=document.createElement("canvas");o.width=e,o.height=t;let i=o.getContext("2d");if(!i)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(i.fillStyle="#fff",i.fillRect(0,0,e,t)),i.drawImage(s,0,0,e,t),await Nt(o,r,n)}async function cn(s,e,t,r){let{width:n,height:o}=e,i=await Ge(s,n,o,t,r);if(i.size<=256e3)return{blob:i,width:n,height:o};if(t==="image/jpeg"){for(let c of Ke)if(!(c>=r)&&(i=await Ge(s,n,o,t,c),i.size<=256e3))return Ut(`quality ${r} -> ${c}`,i.size),{blob:i,width:n,height:o}}let a=t==="image/jpeg"?Ke[Ke.length-1]:r;for(let c=0;c<on;c++)if(n=Math.max(16,Math.round(n*Lt)),o=Math.max(16,Math.round(o*Lt)),i=await Ge(s,n,o,t,a),i.size<=256e3)return Ut(`downscaled to ${n}x${o} @ q${a}`,i.size),{blob:i,width:n,height:o};throw new Error(`this image cannot be sent: even at ${n}x${o} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function dn(s,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,i=await an(s);try{let a=ze(i.width,i.height,t),c=await cn(i,a,r,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:o}}finally{i.close()}}function un(s){let e=s instanceof Error?s.name:"",t=s instanceof Error?s.message:String(s);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function ln(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function pn(s,e){let t=s.videoWidth,r=s.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:o="image/jpeg",quality:i=.92}=e??{},a=ze(t,r,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let u=c.getContext("2d");if(!u)throw new Error("could not prepare the reference image (no 2d canvas context)");o==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(s,0,0,a.width,a.height);let d=await Nt(c,o,i);return{bytes:new Uint8Array(await d.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var mn=new Set(["w","a","s","d"]),q=(s,e)=>Math.min(e,Math.max(-e,s));function fn(s={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:o=.06,maxPan:i=.12,maxLogZoom:a=.22}=s,c=0,u=0,d=0,f=null,p=new Set;return{pointerDelta(l,m){c=q(c-l*e,i),u=q(u-m*e,i)},keyDown(l){let m=l.toLowerCase();mn.has(m)&&p.add(m)},keyUp(l){p.delete(l.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let l=1-o;c*=l,u*=l,d*=l},tick(l){if(f===null){f=l;return}let m=Math.max(0,Math.min(100,l-f))/1e3;f=l,p.has("w")&&(d=q(d+t*m,a)),p.has("s")&&(d=q(d-t*m,a)),p.has("a")&&(c=q(c+r*m,i)),p.has("d")&&(c=q(c-r*m,i));let w=Math.exp(-m*1e3/n);c*=w,u*=w,d*=w},transform(){return{translateX:c,translateY:u,scale:Math.exp(d)}},isIdentity(l=5e-4){return Math.abs(c)<l&&Math.abs(u)<l&&Math.abs(d)<l},reset(){c=0,u=0,d=0,p.clear()}}}export{ar as ACTIVATION_COLD_BOOT_AFTER_MS,cr as ACTIVATION_DEGRADED_AFTER_MS,Re as ACTIVATION_HINT_PATH,or as ACTIVATION_STILL_AFTER_MS,Ce as ACTIVITY_DOM_EVENTS,ft as ACTIVITY_FIELD,wr as ACTIVITY_STAMP_MIN_INTERVAL_MS,B as ActivationMonitor,$r as App,Jt as BACKOFF_BASE_MS,Zt as BACKOFF_MAX_ATTEMPTS,Xt as BACKOFF_MAX_MS,ge as CaptureController,he as CaptureUnavailableError,O as ClientTokenError,nn as DATA_CHANNEL_MESSAGE_CEILING,Rt as DEFAULT_DOC_SYNC_TIMEOUT_MS,It as DEFAULT_GATEWAY_URL,$t as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,rn as DEFAULT_REFERENCE_JPEG_QUALITY,tn as DEFAULT_REFERENCE_MAX_SIZE,Yt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,nr as DERIVED_LEG_SEP,G as DGRAM_HEADER_BYTES,br as FOREGROUND_COALESCE_MS,z as FrameReassembler,Zr as INPUT_PRESENCE_DEFAULT_HZ,Ot as INPUT_PRESENCE_FIELD,W as InvalidDurationError,Ee as LEGACY_ACTIVATION_HINT_PATH,Te as PLATFORM_DOC_NAME,pe as PermanentLockedError,le as PinRequiresActiveTempError,Bt as ProduceAckTimeoutError,de as RecordingNotFoundError,F as RecordingsClient,C as RecordingsError,V as RecordingsUnauthorizedError,re as RequestAbortError,ye as RequestCancelledError,we as RequestDocSyncError,te as RequestError,ve as RequestTimeoutError,ue as RetainNotTempError,ce as RuntimeArtifactNotFoundError,x as RuntimeArtifactsClient,k as RuntimeArtifactsError,ae as RuntimeArtifactsUnauthorizedError,Z as Session,Se as SessionAllocationError,jt as SessionEndError,$ as SessionEndUnavailableError,Vt as SessionFailedError,be as StreamDirectionConflict,Q as TransportNegotiator,Gt as TransportSessionMismatchError,J as TransportSessionSignaling,Pt as URUN_DEV_ENV,ht as VISIBILITY_FIELD,sn as WIRE_MESSAGE_BUDGET,wt as WT_CONTROL_FRAME_MAX,bt as WT_DATA_STREAM_VERSION,X as WebRtcSession,Y as WebTransportSession,K as WtControlDecoder,me as WtDataStreamParser,lt as activationHintFrom,ln as cameraCaptureAvailable,pn as captureStillFromVideo,er as computeBackoffDelay,We as consumeWtDataStreams,Ie as createActivityTracker,fn as createCameraWarp,Hr as createClientToken,en as createInputPresencePublisher,vr as createRecordingsClient,ur as createRuntimeArtifactsClient,Vr as createStore,ir as derivedLegName,sr as derivedLegRole,Ht as describeSessionFailure,Qt as describeSessionPhase,Le as encodeWtControlFrame,ze as fitWithin,Ae as isDurationString,zr as isPendingRecording,tr as isRetryableSessionError,zt as isWakingPhase,xe as mediaRecorderChunkSource,dn as normalizeReferenceImage,hr as normalizeRetention,Me as observeLeaveConfirm,Pe as observePageLifecycle,De as observePageTeardown,Ue as parseDgramHeader,rr as prewake,un as referenceImageErrorMessage,ke as releaseSessionBeacon,Kt as sessionFailureFromMediaError,Xr as sharedCaptureController,Gr as videoStream,_e as whenLive,kr as writeDgramHeader};
1
+ import{A as N,B as rt,C as Re,D as nt,E as st,F as it,G as or,H as se,K as ie,L as oe,M as ot,N as at,P as ct,R as ar,S as cr,T as dr,U as ae,W as dt,X as ut,Y as lt,Z as pt,_ as mt,a as tt,b as te,c as $,d as Vt,e as re,f as be,g as ye,h as Se,i as Kt,j as Gt,k as ne,l as _e,m as zt,n as Yt,o as Qt,p as Jt,q as ke,r as Xt,s as Zt,t as Te,u as er,v as tr,w as rr,x as nr,y as sr,z as ir}from"./chunk-5TD2DIRY.mjs";var ur=15e3,lr=45e3,pr=12e4,Ee="platform",Ae="activation",Ce="desired.activation";function ft(s){if(typeof s=="string"&&s.length>0)return s;if(s&&typeof s=="object"){let e=s.note;if(typeof e=="string"&&e.length>0)return e}}var mr=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],B=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="ended"||t?.name==="expired")&&this.dispose()}),this._stopped&&(this._offPhase(),this._offPhase=null)}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;watch(e,t){if(this._stopped||this._watches.has(e))return;let r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let n=()=>this._firstMedia(e);r.addEventListener("unmute",n,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",n));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of mr){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let n={state:t,elapsedMs:r,stream:e.name},o=ft(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let i of Array.from(this._handlers))i(n)}};var k=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",n){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,n!==void 0&&(this.cause=n),Object.setPrototypeOf(this,new.target.prototype)}},ce=class extends k{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},de=class extends k{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function H(s){return{baseUrl:s.baseUrl,fallbackUrls:s.fallbackUrls,orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}function fr(s){return new x(s)}var x=class{_options;constructor(e){this._options=e}async list(e){let r=gt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new k("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(ht)}async getDownloadUrl(e,t){let r=gt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!gr(n))throw new k("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:ht(r.artifact),downloadUrl:n}}async _request(e,t){let r=rt(this._options.baseUrl,this._options.fallbackUrls),n=null;for(let o of r)try{return await this._requestFromBase(o,e,t)}catch(i){if(n=i instanceof Error?i:new Error(String(i)),n instanceof k&&vr(n.status))throw n}throw n??new k("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${N(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,o=await this._resolveToken(),i=await fetch(n,{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(n,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:c}=await this._readError(i,e);throw wr(i.status,a,c)}try{return await i.json()}catch(a){throw new k(`[urun] runtime artifacts: invalid JSON response from ${N(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=N(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 ht(s){if(!s||typeof s!="object")throw new k("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=s,t=P(e,"artifact_id")||P(e,"id"),r=P(e,"filename"),n=P(e,"kind"),o=P(e,"status")||"ready",i=hr(e,"size_bytes"),a=P(e,"sha256");if(!t||!r||!n||i==null||!a)throw new k("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:P(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:P(e,"created_at"),expiresAt:P(e,"expires_at")}}function P(s,e){let t=s[e];return typeof t=="string"&&t.length>0?t:void 0}function hr(s,e){let t=s[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function gr(s){try{return new URL(s).protocol==="https:"}catch{return!1}}function vr(s){return s===401||s===403}function wr(s,e,t){return s===401?new ce(t,e):s===404?new de(t,e):new k(t,s,e)}function gt(s){if(!s||typeof s!="object"||Array.isArray(s))throw new k("[urun] runtime artifacts: malformed response",0,"bad_response");return s}var C=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)}},V=class extends C{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},ue=class extends C{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},le=class extends C{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},pe=class extends C{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)}},me=class extends C{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)}},W=class extends C{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 Ie(s){return/^(\d+[smhdw])+$/.test(s)}function br(s){if(s==="pin")return{action:"pin"};if(Ie(s))return{action:"retain",duration:s};throw new W(`[urun] recordings: "${s}" is not a duration or "pin"`)}function yr(s,e,t){let r=t||e||`HTTP ${s}`;if(s===401)return new V(r,e??"unauthorized");if(s===404)return new ue(r,e??"not_found");if(s===400)return new W(r,e??"bad_request",400);if(s===409)switch(e){case"retain_not_temp":return new le(r,e);case"pin_requires_active_temp":return new pe(r,e);case"permanent_locked":return new me(r,e)}return new C(r,{status:s,code:e??`http_${s}`})}var F=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(!Ie(t))throw new W(`[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 C("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let n=this._buildUrl(t,r.params),o=await this._resolveToken(),i=await this._fetch(n,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(n,e,o,r.body))}if(!i.ok){let{code:a,message:c}=await this._readError(i);throw yr(i.status,a,c)}return this._readJson(i)}_buildUrl(e,t){let r=`${this._base}${e}`,n=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return n&&(r+=`?${n}`),r}_fetch(e,t,r,n){let o={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let i={method:t,headers:o};return n!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(n)),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 V("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:n,message:o}=r;return{code:typeof n=="string"?n:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Sr(s){return new F(s)}var vt="activity",wt="visibility",_r=15e3,Pe=["pointerdown","pointermove","keydown","wheel","touchstart"];function De(s){let e=s.now??Date.now,t=s.windowTarget!==void 0?s.windowTarget:typeof window<"u"?window:null,r=s.documentTarget!==void 0?s.documentTarget:typeof document<"u"?document:null,n=!1,o,i=()=>{if(n)return;let f=e();if(!(o!==void 0&&f-o<15e3)){o=f;try{s.awareness.setLocalStateField(vt,{at:f})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{s.awareness.setLocalStateField(wt,r.visibilityState)}catch{}},c=()=>i(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let f of Pe)t.addEventListener(f,c,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",u);let d=null;return s.isProducing&&(d=setInterval(()=>{if(!n)try{s.isProducing?.()&&i()}catch{}},15e3),d.unref?.()),i(),a(),{touch:i,dispose(){if(!n){if(n=!0,t)for(let f of Pe)t.removeEventListener(f,c,{capture:!0});r&&r.removeEventListener("visibilitychange",u),d&&(clearInterval(d),d=null)}}}}var kr=250;function Me(s){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,s())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function xe(s){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,s())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function Oe(s){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{s()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var bt="video/mp4";function Le(s,e={}){let t=e.timesliceMs??1e3,r=null,n=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 f=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(bt)?bt:void 0),p=new MediaStream([a]),l=new d(p,f?{mimeType:f}:void 0);r=l;let m=Promise.resolve();l.ondataavailable=w=>{let b=w.data;o||!b||b.size===0||(m=m.then(async()=>{let S=new Uint8Array(await b.arrayBuffer());o||c(S)}))},l.onstop=()=>{m.then(()=>{o||u()})},l.onerror=()=>{m.then(()=>{o||u()})},l.start(t)};return{start(a,c){if(r||o)return;let u=s.track();if(u){i(u,a,c);return}n=s.onTrack(d=>{!d||r||o||(n?.(),n=null,i(d,a,c))})},stop(){if(o)return;o=!0,n?.(),n=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Tr(s){let e=s;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=s.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 yt(s,e){let t=null,r=!1,n=!1,o=new ReadableStream({pull(i){r||(r=!0,t=s(e),t.start(a=>{if(!n)try{i.enqueue(a)}catch{}},()=>{if(!n){n=!0;try{i.close()}catch{}}}))},cancel(){n=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Tr(o)}import{encode as Rr,decode as Er}from"@msgpack/msgpack";var St=65536;function Ne(s){let e=Rr(s),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var K=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>St)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(Er(n))}return t}},G=12,Ue=1;function We(s){let e=s.getUint8(8);return{groupId:s.getUint32(0,!0),frameSeq:s.getUint32(4,!0),keyframe:(e&Ue)===Ue,fragIndex:s.getUint8(9),fragCount:s.getUint8(10)}}function Ar(s){let e=new Uint8Array(G),t=new DataView(e.buffer);return t.setUint32(0,s.groupId,!0),t.setUint32(4,s.frameSeq,!0),t.setUint8(8,s.keyframe?Ue:0),t.setUint8(9,s.fragIndex),t.setUint8(10,s.fragCount),t.setUint8(11,0),e}var Cr=100,z=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??Cr}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<G)return;let t=We(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(G),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let n of this.pending.keys())n<t.frameSeq-1&&(this.pending.delete(n),this.framesAbandoned++)}}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),n=new Uint8Array(r),o=0;for(let i of t.chunks)n.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:n})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Ir=/^avc[13]\.[0-9a-fA-F]{6}$/;function Pr(s){return Ir.test(s)?null:`codec ${JSON.stringify(s)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function Fe(s,e){let t=Pr(s);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var _t=1,fe=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==_t)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let n=this.buf[1];if(n===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+n)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+n)),this.buf=this.buf.subarray(2+n)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let n=at(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),n===ot&&(this.ended=!0),t.push({name:this.name,payload:n})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function qe(s,e){let t=s.getReader();for(;;){let{value:r,done:n}=await t.read();if(n)return;r&&Dr(r,e).catch(o=>{e.onLaneError(o instanceof Error?o:new Error(String(o)))})}}async function Dr(s,e){let t=s.getReader(),r=new fe;try{for(;;){let{value:n,done:o}=await t.read();if(o)break;if(!(!n||n.byteLength===0))for(let{name:i,payload:a}of r.push(n))e.onData(i,a)}r.finish()}catch(n){try{await t.cancel?.(n)}catch{}throw n}}var Mr=250,xr=3,Or=1e4,je=2500,Y=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r;this.firstMedia=new Promise((n,o)=>{this.firstFrameResolve=n,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 z({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;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");Fe(this.offer.codec,"transport.offer"),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(),n=new K,o=[],i=await this.readControl(r,n,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");Fe(i.codec,"hello-ack"),this.initDecoder(i.codec,i.width,i.height),this.controlLoop(r,n,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}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");this.dataLaneSink=e,qe(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,r){let n=globalThis.VideoDecoder;if(typeof n!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let o=this.canvas.getContext("2d");if(!o)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r},this.decoder=new n({output: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(n=>t-n<Or),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=xr){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let r=this.decoderConfig;if(!r){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(r.codec,r.width,r.height)}catch(n){this.die(`decoder re-init: ${n instanceof Error?n.message:String(n)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}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 ${je}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${je}ms`))},je);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 n=performance.now();if(this.lastArrivalTs>0){let o=n-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(o-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=n,this.reassembler.push(t)}}decodeFrame(e,t,r){let n=globalThis.EncodedVideoChunk;!this.decoder||typeof n!="function"||(this.decoder.decode(new n({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}async sendControl(e){await this.writer.write(Ne(e))}async readControl(e,t,r=[]){for(;;){let n=r.shift();if(n)return n;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 n=await this.readControl(e,t,r);if(!n)break;n.t==="ping"&&this.sendControl({t:"pong",ts:n.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 n=this.reassembler.drainWindow(),o=n.delivered+n.abandoned;this.lastStats={recvBps:r>0?n.bytes*8/r:0,lossPct:o>0?100*n.abandoned/o:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Mr)}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 kt=2500,Tt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Q=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&n,webcodecs:r,codecs:Tt,wtData:t&&r&&n&&this.opts.dataLane!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:o});let i=o.webtransport&&!!this.offer.webtransport;if(o.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),i){let a=null;try{return a=this.createWebTransportSession(),await Rt(a.start(),this.opts.quicDeadlineMs??kt,"quic connect deadline"),this.engageQuicDataLane(a,o.wtData===!0),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(){this.quicDataLane=!1,await this.session?.stop(),this.session=null}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,n=this.opts.dataLane!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:Tt,wtData:n}}),!this.offer.webtransport)return null;let o=this.createWebTransportSession();try{await Rt(o.start(),this.opts.quicDeadlineMs??kt,"quic connect deadline")}catch(i){throw o.stop().catch(()=>{}),i}if(this.session!==r)return o.stop().catch(()=>{}),null;try{this.engageQuicDataLane(o,n)}catch(i){throw o.stop().catch(()=>{}),i}return this.session=o,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),o}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(n,o)=>r.onData(n,o),onLaneError:n=>r.onLaneError(n)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new Y(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),this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(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 Rt(s,e,t){return new Promise((r,n)=>{let o=setTimeout(()=>n(new Error(t)),e);s.then(i=>{clearTimeout(o),r(i)},i=>{clearTimeout(o),n(i)})})}var Lr=1e4,J=class{constructor(e,t=Lr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=oe();return new Promise((n,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,...f}=c;n(f)});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 Ur="video",X=class{constructor(e,t=Ur){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,n)=>{this.firstMediaResolve=r,this.firstMediaReject=n}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};var Nr="video";function Et(s,e,t){let r=globalThis,n=r.document;if(!(typeof n?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let i=n.createElement("canvas"),a=!1,c=null,u=!1,d=()=>{if(c){for(let y of c.getVideoTracks())try{y.stop()}catch{}c=null}u&&(u=!1,t.onOverrideTrack(null))},f=new Q(new J(s),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new X(s,t.streamName??Nr)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(y,h)=>s.dispatchQuicStreamData(y,h),onQuicLane:()=>s.markStreamDataLaneQuic(),onQuicLaneLost:y=>s.quicStreamDataLaneLost(y),onLaneError:y=>s.raiseQuicStreamDataError(y)},onTransportChange:(y,h)=>{y==="webrtc"&&(d(),_()),t.onTransportChange?.(y,h)}}),p=null,l=()=>{p!==null&&(clearTimeout(p),p=null)},m=t.wtRetryBaseMs??2e3,w=t.wtRetryCapMs??3e4,b=null,S=0,_=()=>{if(a||b!==null||f.activeTransport==="webtransport")return;let y=Math.min(m*2**S,w);b=setTimeout(()=>{b=null,S+=1,f.retryWebTransport().then(h=>{if(!a){if(h)return console.debug(`[urun] webtransport upgraded in background (retry ${S})`),S=0,T(h);_()}}).catch(h=>{a||(console.debug(`[urun] webtransport background retry ${S} failed:`,h),_())})},y)},A=()=>{b!==null&&(clearTimeout(b),b=null)},T=async y=>{if(a||y.kind!=="webtransport")return;let h=t.firstMediaWarnMs??1e4;if(l(),p=setTimeout(()=>{a||f.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${h}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},h),await y.firstMedia,l(),a||f.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let v=c.getVideoTracks()[0];v&&(u=!0,t.onOverrideTrack(v))};return(async()=>{let y=await f.connect();await T(y)})().catch(y=>{l(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",y),_()}),{activeTransport:()=>f.activeTransport,dispose(){a=!0,l(),A(),d(),f.disconnect().catch(()=>{})}}}var Wr=new Set;function He(s){if(s.functionsUrl)return{functionsUrl:s.functionsUrl,orgId:s.orgId,apiKey:s.apiKey,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}var Fr="rpc",It=3e4,At=3e4,qr="rpc-resp";function jr(s){return`${qr}:${s}`}function $e(){return oe()}function $r(s){if(s&&typeof s=="object"){let e=s.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 s=="string"?s:JSON.stringify(s)}}function Br(s,e,t,r,n,o,i,a,c,u){let d=[],f=null,p=!1,l=null,m=!1,w,b,S=new Promise((g,M)=>{w=g,b=M});S.catch(()=>{});let _=i(),A=null,T=null,y=null,h=null,v=null,R=null,E=!0,j=()=>{y&&(clearTimeout(y),y=null),h&&(h(),h=null)},I=()=>{v&&(clearTimeout(v),v=null),R&&(R(),R=null)},D=!1,Je=()=>{D||!m||(D=!0,s.set({rpc:{[e]:null}}))},ee=()=>{E=!1,j(),I(),A?.(),A=null,T?.(),T=null,a?.removeEventListener("abort",Ze),_.dispose(),Je()},we=()=>{if(f){if(d.length>0){let g=f;f=null,g.resolve({value:d.shift(),done:!1})}else if(l!==null){let g=f;f=null,g.reject(l)}else if(p){let g=f;f=null,g.resolve({value:void 0,done:!0})}}},$t=g=>{p||(d.push(g),we())},L=g=>{p||(l=g,p=!0,b(g),ee(),we())},Xe=g=>{p||(p=!0,w(g),ee(),we())},Ze=()=>{let g=a?.reason;L(g instanceof re?g:new ne(e))},Bt=g=>{if(!(p||!g||typeof g!="object"))switch(I(),Je(),g.t){case"delta":typeof g.delta=="string"&&$t(g.delta);break;case"response":Xe(g.body);break;case"error":{let{message:M,code:U}=$r(g.body);L(new re(M,{requestId:e,code:g.code??U}));break}}},Ht=()=>{let g=_.messages()[Symbol.asyncIterator]();A=()=>{g.return?.(void 0)};let M=()=>{E&&g.next().then(U=>{if(E){if(U.done){p||Xe(void 0);return}Bt(U.value),M()}},U=>{E&&L(U)})};M()},et=()=>{if(!m){if(m=!0,a){if(a.aborted){L(new ne(e));return}a.addEventListener("abort",Ze,{once:!0})}T=c?.(g=>L(g))??null,Ht(),s.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!s.synced&&(y=setTimeout(()=>{y=null,!p&&!s.synced&&L(new ye(u,e))},u),h=s.onSynced(()=>j())),R=s.onSynced(()=>{R=null,!(p||D||v)&&(v=setTimeout(()=>{v=null,!(p||D)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(At/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},At))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(et(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(l!==null){let g=l;return l=null,Promise.reject(g)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((g,M)=>{f={resolve:g,reject:M}})},return(){return p||(p=!0,w(void 0),ee()),Promise.resolve({value:void 0,done:!0})},throw(g){return p||(p=!0,b(g),ee()),Promise.reject(g)}}}},body:S,start:et}}function Ct(s){if(s&&typeof s=="object"){let{epoch:e,by:t}=s,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Hr(s,e){let r=s.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:n,rt:o,br:i}=r,a={};(n==="audio"||n==="video"||n==="data")&&(a.kind=n);let c=Ct(o);c&&(a.rt=c);let u=Ct(i);return u&&(a.br=u),a}var Be=class{constructor(e,t,r,n,o){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=n;this._onActivity=o;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let 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._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,o=null,i={push(c){if(!n)if(r){let u=r;r=null,u.resolve({value:c,done:!1})}else t.push(c)},end(){if(n=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(i);let a=()=>{n=!0,e._messageConsumers.delete(i)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||n)&&(o=e._streamConsumeUnavailableError(c),a(),r)){let u=r;r=null,u.reject(o)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):o?Promise.reject(o):n?Promise.resolve({value:void 0,done:!0}):new Promise((c,u)=>{r={resolve:c,reject:u}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Hr(t,this._name),n=r?.br;if(n?.by==="runtime")throw new Se(this._name,"runtime","browser");if(n)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??Le;return yt(t,{track:()=>this.track,onTrack:n=>this.on("track",n)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},Z=class s{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new lt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;constructor(e,t,r,n,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=n,this._artifactsAuth=o,this._streamData=ct(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Me(()=>this.recover()),this._activity=De({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new B({onPhase:i=>this.onPhase(i),hint:()=>this.doc(Ee).get(Ae)??this.doc("control").get(Ce),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 it({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),n=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new te,i=new ae({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,o,i,He(t),H({...t,baseUrl:r.baseUrl}));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();let c=t.getAccessToken,u=c?async()=>await c()??n:n;return a.setDocTransport({wsUrl:r.wsUrl,token:u}),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)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return Te(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 F(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,n)=>t.retain(r,n),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new x(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new x(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 Be(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 pt(e,this._sessionId,Wr.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=mt(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=dt(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",n=`${t}\0${r}\0${this._sessionId}`;n!==this._docEndpointKey&&(this._docEndpointKey=n,this.connectDocs(ut({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=$e(),n=new AbortController;t.signal&&(t.signal.aborted?n.abort(t.signal.reason):t.signal.addEventListener("abort",()=>n.abort(t.signal.reason),{once:!0}));let o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>n.abort(new be(a,r)),a)}let i=this._consumeResponse(r,e,!1,n.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,r,n,o){this._activity?.touch();let i=this.doc(Fr),a=jr(e);return Br(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??It)}requestStream(e,t={}){let r=$e();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=$e(),n=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return n.start(),n.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Et(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),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new $)}disconnect(){let e=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let r of e)try{r()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._activation.dispose(),this._recoveryHooks.clear();let t=Array.from(this._activeRequests);this._activeRequests.clear();for(let r of t)try{r(new _e)}catch{}for(let r of this._docs.values())r.dispose();this._docs.clear();for(let r of this._streams.values())r.dispose();this._streams.clear(),this._transport.disconnect()}};function Pt(s){return`urun:logical:v1:${s.orgId}:${s.app}:${s.functionName}`}function Ve(){try{return globalThis.sessionStorage??null}catch{return null}}function Dt(s){let e=Ve();if(!e)return null;try{let t=e.getItem(s);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 Mt(s,e){let t=Ve();if(t)try{t.setItem(s,JSON.stringify({logicalId:e.logicalId}))}catch{}}function he(s){let e=Ve();if(e)try{e.removeItem(s)}catch{}}var Vr=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Kr(s,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(!(Vr.has(r)||typeof r!="string"))return n=>{let o=n??{},i=Pt({orgId:e.orgId,app:s,functionName:r}),a=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,c=a(),u=e.jwt,d=e.getAccessToken?async h=>{let v=await e.getAccessToken(h);return v&&(u=v),v}:void 0,f={...e,getAccessToken:d},p=new te,l=new ae({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),m=new Z(c,p,l,He(f),H(f)),w,b,S=new Promise(h=>{b=h}),_=h=>{w=h,b({status:"ready",handle:h})};m.setEndHandler(async()=>{let h=w?{status:"ready",handle:w}:await S;if(h.status==="unavailable")throw new $("[urun] session allocation failed before a releasable request was created",{cause:h.cause});let v=h.handle;return he(i),nt({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider})});let A=async h=>{let v=await st({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider,idempotencyKey:h,sessionKey:e.sessionKey??Dt(i)?.logicalId,priority:e.priority,onAdmission:E=>l.reportAdmission(E),onRequest:_}),R=d?await d()??void 0:e.jwt;return e.sessionKey||Mt(i,{logicalId:v.sessionId}),m.setSessionId(v.sessionId),m.setArtifactsAuth(H({...f,baseUrl:v.baseUrl})),l.setEndsAt(v.endsAt),{url:v.wsUrl,sessionId:v.sessionId,jwt:R,iceServers:v.response.ice_servers,endsAt:v.endsAt}},T,y=d?async()=>await d()??T:()=>T;if(l.setConnectionResolver(async()=>{let h=await A(a());return T=h.jwt,h}),l.on("connected",()=>{l.multiplexer&&p.setTarget(l.multiplexer);let h=l.connectedUrl;h&&m.setDocTransport({wsUrl:h,token:y})}),(async()=>{let h;try{h=await A(c)}catch(v){console.error(`[urun] Failed to create session for ${r}:`,v),he(i);let R=v instanceof Error?v:new Error(String(v)),E=v instanceof ke?v.httpStatus:void 0;l.reportAllocationFailure(R,E),b({status:"unavailable",cause:v});return}l.setAuth({jwt:h.jwt,authProvider:e.authProvider,orgId:e.orgId}),l.setConnection({url:h.url,sessionId:h.sessionId,iceServers:h.iceServers}),se()&&await ie(),T=h.jwt,m.setDocTransport({wsUrl:h.url,token:y}),await l.connect({app:s,functionName:r,args:o}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(h=>{console.error(`[urun] Failed to connect session for ${r}:`,h)}),e.releaseOnLeave!==!1){let h=xe(()=>{if(l.leaveLeg()||l.connectedUrl!==null)return;let I=w;I&&(he(i),Re({baseUrl:I.baseUrl,requestId:I.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))});m.onDisconnect(h);let v,R,E=!1,j=()=>{E||(E=!0,v?.(),R?.())};S.then(I=>{I.status!=="ready"||E||(v=Oe(()=>w!==void 0))}),R=m.onPhase(I=>{let D=I?.name;(D==="ended"||D==="expired"||D==="error")&&j()}),E&&R(),m.onDisconnect(j)}return m}}})}var xt="https://api.urun.sh",Ot="URUN_DEV";function Gr(){if(typeof process>"u")return!1;let s=process.env?.[Ot];if(typeof s!="string")return!1;let e=s.trim().toLowerCase();return e==="1"||e==="true"}var O=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function zr(s,e={}){if(!s)throw new O("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=N(e.baseUrl??xt),n={};e.expiresIn!==void 0&&(n.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(n.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(n.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(n.max_session_s=e.maxSessionS),e.subject!==void 0&&(n.subject=e.subject),e.metadata!==void 0&&(n.metadata=e.metadata),(e.dev??Gr())&&(n.dev=!0);let o;try{o=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(n)})}catch(p){throw new O(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let i={};try{i=await o.json()}catch{}if(!o.ok){let p=typeof i.message=="string"?i.message:`HTTP ${o.status}`;throw new O(`[urun] client token mint failed: ${p}`,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 O("[urun] client token mint returned no token (control-plane contract violation)",o.status);let f=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:f,orgId:c}}var Lt=3e4,Ut="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 n;try{n=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let o=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(o.timer),n.error?o.reject(new Error(n.error)):o.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${Ut}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Ut}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),n(new Error(`RPC request "${e}" timed out after ${Lt}ms`)))},Lt);this._pendingRpc.set(o,{resolve:r,reject:n,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Yr(s){let r=`${s.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(s.orgId)}`,n=new WebSocket(r);(s.jwt||s.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:s.orgId,jwt:s.jwt,authProvider:s.authProvider,apiKey:s.apiKey}))});let o=new tt(n);return new Ke(n,o)}var Qr='video/mp4; codecs="avc1.42E01E"';function Jr(s,e){let t=e?.codec??Qr,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);r.src=o,n.addEventListener("sourceopen",()=>{let p;try{p=n.addSourceBuffer(t)}catch(b){throw b instanceof DOMException&&b.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).`):b}let l=s.getReader();function m(){return p.updating?new Promise(b=>{p.addEventListener("updateend",()=>b(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:b,value:S}=await l.read();if(b){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{p.appendBuffer(S)}catch(_){if(_ instanceof DOMException&&_.name==="QuotaExceededError"){let A=p.buffered;if(A.length>0){let T=A.start(A.length-1);p.remove(0,T),await m(),p.appendBuffer(S)}else throw _}else throw _}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}w()}),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,f=u.length;if(f===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=f&&URL.revokeObjectURL(o)});return c}function Xr(s){return s.status.startsWith("pending_")}var ge=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 Nt(s){let e=[];return s.audio&&e.push("audio"),s.video&&e.push("video"),e.join("+")}function Zr(s,e){return e==="audio"?s.getAudioTracks():s.getVideoTracks()}function en(s,e){let t=s.getTracks();if(t.length===1&&t[0]===e)return s;try{return new MediaStream([e])}catch{return s}}function Ge(s,e){for(let t of[...s.lostListeners])try{t(e)}catch{}}var ve=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,Ge(r,new Error(`${e} capture claim superseded by a newer claim`)));let n=this.createState(e,t);return this.claims.set(e,n),await this.converge(n),n.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new ge;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},n;try{n=await t(r)}catch(i){let a=`one-capture getUserMedia(${Nt(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,Ge(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=Zr(n,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(${Nt(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;Ge(i,c);continue}if(i.track=a,i.stream=en(n,a),i!==e)for(let c of[...i.trackListeners])try{c(a,i.stream)}catch{}}}createState(e,t){let r=this,n={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return n.track},get stream(){return n.stream},update(o){return r.enqueue(async()=>{if(n.released)throw new Error(`${e} capture claim already released`);if(n.constraints=o,await r.converge(n),!n.track)throw new Error(`${e} capture update yielded no track`);return n.track})},release(){n.released||(n.released=!0,r.claims.get(e)===n&&r.claims.delete(e),n.track?.stop(),n.track=null,n.stream=null)},onTrack(o){return n.trackListeners.add(o),()=>n.trackListeners.delete(o)},onLost(o){return n.lostListeners.add(o),()=>n.lostListeners.delete(o)}}};return n}},tn=null;function rn(){return tn??=new ve}var Wt="input",nn=30;function sn(s){let e=s.now??Date.now,t=s.field??Wt,r=1e3/Math.max(s.hz??30,.001),n=new Set,o=0,i=0,a=0,c=0,u,d=null,f=!1,p=()=>{if(f)return;u=e(),c+=1;let m={keys:[...n],buttons:o,pointer:{x:i,y:a},seq:c,at:u};try{s.awareness.setLocalStateField(t,m)}catch{}},l=()=>{if(f)return;let m=e();if(u===void 0||m-u>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let w=Math.max(r-(m-u),0);d=setTimeout(()=>{d=null,p()},w),d.unref?.()};return{keyDown(m){let w=String(m).toLowerCase();n.has(w)||(n.add(w),l())},keyUp(m){let w=String(m).toLowerCase();n.delete(w)&&l()},setButtons(m){let w=Number.isFinite(m)?Number(m):0;w!==o&&(o=w,l())},movePointer(m,w){let b=Number.isFinite(m)?Number(m):0,S=Number.isFinite(w)?Number(w):0;b===0&&S===0||(i+=b,a+=S,l())},heldKeys(){return[...n]},clear(){f||(n.clear(),o=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(f)return;let m=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),m&&p(),f=!0}}}var on=1024,an=.92,cn=262144,dn=256e3,ze=[.9,.8,.7,.6,.5],Ft=.8,un=8;function Qe(s,e,t){if(!(s>0)||!(e>0))throw new Error(`reference image has no pixels (${s}x${e})`);let r=Math.min(1,t/Math.max(s,e));return{width:Math.max(1,Math.round(s*r)),height:Math.max(1,Math.round(e*r))}}async function ln(s){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(s,{imageOrientation:"from-image"})}async function jt(s,e,t){let r=await new Promise(n=>{s.toBlob(n,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function qt(s,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${s} -> ${e} bytes`)}async function Ye(s,e,t,r,n){let o=document.createElement("canvas");o.width=e,o.height=t;let i=o.getContext("2d");if(!i)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(i.fillStyle="#fff",i.fillRect(0,0,e,t)),i.drawImage(s,0,0,e,t),await jt(o,r,n)}async function pn(s,e,t,r){let{width:n,height:o}=e,i=await Ye(s,n,o,t,r);if(i.size<=256e3)return{blob:i,width:n,height:o};if(t==="image/jpeg"){for(let c of ze)if(!(c>=r)&&(i=await Ye(s,n,o,t,c),i.size<=256e3))return qt(`quality ${r} -> ${c}`,i.size),{blob:i,width:n,height:o}}let a=t==="image/jpeg"?ze[ze.length-1]:r;for(let c=0;c<un;c++)if(n=Math.max(16,Math.round(n*Ft)),o=Math.max(16,Math.round(o*Ft)),i=await Ye(s,n,o,t,a),i.size<=256e3)return qt(`downscaled to ${n}x${o} @ q${a}`,i.size),{blob:i,width:n,height:o};throw new Error(`this image cannot be sent: even at ${n}x${o} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function mn(s,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,i=await ln(s);try{let a=Qe(i.width,i.height,t),c=await pn(i,a,r,n);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:o}}finally{i.close()}}function fn(s){let e=s instanceof Error?s.name:"",t=s instanceof Error?s.message:String(s);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function hn(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function gn(s,e){let t=s.videoWidth,r=s.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:n=1024,type:o="image/jpeg",quality:i=.92}=e??{},a=Qe(t,r,n),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let u=c.getContext("2d");if(!u)throw new Error("could not prepare the reference image (no 2d canvas context)");o==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(s,0,0,a.width,a.height);let d=await jt(c,o,i);return{bytes:new Uint8Array(await d.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var vn=new Set(["w","a","s","d"]),q=(s,e)=>Math.min(e,Math.max(-e,s));function wn(s={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:n=900,frameRelax:o=.06,maxPan:i=.12,maxLogZoom:a=.22}=s,c=0,u=0,d=0,f=null,p=new Set;return{pointerDelta(l,m){c=q(c-l*e,i),u=q(u-m*e,i)},keyDown(l){let m=l.toLowerCase();vn.has(m)&&p.add(m)},keyUp(l){p.delete(l.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let l=1-o;c*=l,u*=l,d*=l},tick(l){if(f===null){f=l;return}let m=Math.max(0,Math.min(100,l-f))/1e3;f=l,p.has("w")&&(d=q(d+t*m,a)),p.has("s")&&(d=q(d-t*m,a)),p.has("a")&&(c=q(c+r*m,i)),p.has("d")&&(c=q(c-r*m,i));let w=Math.exp(-m*1e3/n);c*=w,u*=w,d*=w},transform(){return{translateX:c,translateY:u,scale:Math.exp(d)}},isIdentity(l=5e-4){return Math.abs(c)<l&&Math.abs(u)<l&&Math.abs(d)<l},reset(){c=0,u=0,d=0,p.clear()}}}export{lr as ACTIVATION_COLD_BOOT_AFTER_MS,pr as ACTIVATION_DEGRADED_AFTER_MS,Ae as ACTIVATION_HINT_PATH,ur as ACTIVATION_STILL_AFTER_MS,Pe as ACTIVITY_DOM_EVENTS,vt as ACTIVITY_FIELD,_r as ACTIVITY_STAMP_MIN_INTERVAL_MS,B as ActivationMonitor,Kr as App,tr as BACKOFF_BASE_MS,nr as BACKOFF_MAX_ATTEMPTS,rr as BACKOFF_MAX_MS,ve as CaptureController,ge as CaptureUnavailableError,O as ClientTokenError,cn as DATA_CHANNEL_MESSAGE_CEILING,It as DEFAULT_DOC_SYNC_TIMEOUT_MS,xt as DEFAULT_GATEWAY_URL,Kt as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,an as DEFAULT_REFERENCE_JPEG_QUALITY,on as DEFAULT_REFERENCE_MAX_SIZE,Zt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,ar as DERIVED_LEG_SEP,G as DGRAM_HEADER_BYTES,kr as FOREGROUND_COALESCE_MS,z as FrameReassembler,nn as INPUT_PRESENCE_DEFAULT_HZ,Wt as INPUT_PRESENCE_FIELD,W as InvalidDurationError,Ce as LEGACY_ACTIVATION_HINT_PATH,Ee as PLATFORM_DOC_NAME,me as PermanentLockedError,pe as PinRequiresActiveTempError,Gt as ProduceAckTimeoutError,ue as RecordingNotFoundError,F as RecordingsClient,C as RecordingsError,V as RecordingsUnauthorizedError,ne as RequestAbortError,_e as RequestCancelledError,ye as RequestDocSyncError,re as RequestError,be as RequestTimeoutError,le as RetainNotTempError,de as RuntimeArtifactNotFoundError,x as RuntimeArtifactsClient,k as RuntimeArtifactsError,ce as RuntimeArtifactsUnauthorizedError,Z as Session,ke as SessionAllocationError,Vt as SessionEndError,$ as SessionEndUnavailableError,Yt as SessionFailedError,Se as StreamDirectionConflict,Q as TransportNegotiator,Jt as TransportSessionMismatchError,J as TransportSessionSignaling,Ot as URUN_DEV_ENV,wt as VISIBILITY_FIELD,dn as WIRE_MESSAGE_BUDGET,St as WT_CONTROL_FRAME_MAX,_t as WT_DATA_STREAM_VERSION,X as WebRtcSession,Y as WebTransportSession,K as WtControlDecoder,fe as WtDataStreamParser,ft as activationHintFrom,hn as cameraCaptureAvailable,gn as captureStillFromVideo,sr as computeBackoffDelay,qe as consumeWtDataStreams,De as createActivityTracker,wn as createCameraWarp,zr as createClientToken,sn as createInputPresencePublisher,Sr as createRecordingsClient,fr as createRuntimeArtifactsClient,Yr as createStore,dr as derivedLegName,cr as derivedLegRole,zt as describeSessionFailure,er as describeSessionPhase,Ne as encodeWtControlFrame,Qe as fitWithin,Ie as isDurationString,Xr as isPendingRecording,ir as isRetryableSessionError,Xt as isWakingPhase,Le as mediaRecorderChunkSource,mn as normalizeReferenceImage,br as normalizeRetention,Oe as observeLeaveConfirm,Me as observePageLifecycle,xe as observePageTeardown,We as parseDgramHeader,or as prewake,fn as referenceImageErrorMessage,Re as releaseSessionBeacon,Qt as sessionFailureFromMediaError,rn as sharedCaptureController,Jr as videoStream,Te as whenLive,Ar as writeDgramHeader};
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { g as AppOptions, f as App$1, a2 as SessionPhase, a8 as SessionStatus, a4 as SessionPhaseName, A as AccessTokenOptions, Q as RuntimeArtifact, S as RuntimeArtifactDownload, R as Recording, Y as Session$1, C as ChannelEndpoint, af as TransportSession, h as AttachOptions, Z as SessionDiagnostic, b as ActivationEvent, a7 as SessionStatsSample, J as RecordingsAccessor, T as RuntimeArtifactsAccessor, a0 as SessionEndResult, a9 as SessionStream$1, ae as StreamDataTransport, $ as SessionDocumentImpl, ad as StreamChunkOptions, m as ChunkReadable, P as Presence, t as DocConnector, u as DocTokenSupplier, N as RequestOptions, O as RequestStreamOptions, ac as StoreOptions, ab as Store, k as ChannelMultiplexer, a1 as SessionFailureKind, ah as TransportState } from './stream-data-Cgh02-qs.mjs';
2
- export { c as ActivationState, i as AudioPlayoutOptions, D as DERIVED_LEG_SEP, q as DerivedLegRole, s as DocConnectionState, I as InboundStatsSample, M as MediaChunkBinding, v as MediaChunkSource, w as MediaChunkSourceFactory, x as MediaRecorderChunkSourceOptions, y as PresenceState, z as PrewakeOptions, B as PrewakeResult, E as PrewakeStatus, F as RecordingBucket, G as RecordingLifecycle, H as RecordingStatus, K as ReleaseSessionBeaconOptions, U as RuntimeAvailability, V as RuntimeWakeDetail, W as RuntimeWakeGolden, X as RuntimeWakeReasonCode, _ as SessionDocument, a3 as SessionPhaseError, a6 as SessionStatsOptions, aa as SessionText, ai as VideoPlayoutOptions, an as derivedLegName, ao as derivedLegRole, ap as isPendingRecording, aq as mediaRecorderChunkSource, ar as prewake, as as releaseSessionBeacon } from './stream-data-Cgh02-qs.mjs';
1
+ import { g as AppOptions, f as App$1, a2 as SessionPhase, a8 as SessionStatus, a4 as SessionPhaseName, A as AccessTokenOptions, Q as RuntimeArtifact, S as RuntimeArtifactDownload, R as Recording, Y as Session$1, C as ChannelEndpoint, af as TransportSession, h as AttachOptions, Z as SessionDiagnostic, b as ActivationEvent, a7 as SessionStatsSample, J as RecordingsAccessor, T as RuntimeArtifactsAccessor, a0 as SessionEndResult, a9 as SessionStream$1, ae as StreamDataTransport, $ as SessionDocumentImpl, ad as StreamChunkOptions, m as ChunkReadable, P as Presence, t as DocConnector, u as DocTokenSupplier, N as RequestOptions, O as RequestStreamOptions, ac as StoreOptions, ab as Store, k as ChannelMultiplexer, a1 as SessionFailureKind, ah as TransportState } from './stream-data-B5wxsIPL.mjs';
2
+ export { c as ActivationState, i as AudioPlayoutOptions, D as DERIVED_LEG_SEP, q as DerivedLegRole, s as DocConnectionState, I as InboundStatsSample, M as MediaChunkBinding, v as MediaChunkSource, w as MediaChunkSourceFactory, x as MediaRecorderChunkSourceOptions, y as PresenceState, z as PrewakeOptions, B as PrewakeResult, E as PrewakeStatus, F as RecordingBucket, G as RecordingLifecycle, H as RecordingStatus, K as ReleaseSessionBeaconOptions, U as RuntimeAvailability, V as RuntimeWakeDetail, W as RuntimeWakeGolden, X as RuntimeWakeReasonCode, _ as SessionDocument, a3 as SessionPhaseError, a6 as SessionStatsOptions, aa as SessionText, ai as VideoPlayoutOptions, an as derivedLegName, ao as derivedLegRole, ap as isPendingRecording, aq as mediaRecorderChunkSource, ar as prewake, as as releaseSessionBeacon } from './stream-data-B5wxsIPL.mjs';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { g as AppOptions, f as App$1, a2 as SessionPhase, a8 as SessionStatus, a4 as SessionPhaseName, A as AccessTokenOptions, Q as RuntimeArtifact, S as RuntimeArtifactDownload, R as Recording, Y as Session$1, C as ChannelEndpoint, af as TransportSession, h as AttachOptions, Z as SessionDiagnostic, b as ActivationEvent, a7 as SessionStatsSample, J as RecordingsAccessor, T as RuntimeArtifactsAccessor, a0 as SessionEndResult, a9 as SessionStream$1, ae as StreamDataTransport, $ as SessionDocumentImpl, ad as StreamChunkOptions, m as ChunkReadable, P as Presence, t as DocConnector, u as DocTokenSupplier, N as RequestOptions, O as RequestStreamOptions, ac as StoreOptions, ab as Store, k as ChannelMultiplexer, a1 as SessionFailureKind, ah as TransportState } from './stream-data-Cgh02-qs.js';
2
- export { c as ActivationState, i as AudioPlayoutOptions, D as DERIVED_LEG_SEP, q as DerivedLegRole, s as DocConnectionState, I as InboundStatsSample, M as MediaChunkBinding, v as MediaChunkSource, w as MediaChunkSourceFactory, x as MediaRecorderChunkSourceOptions, y as PresenceState, z as PrewakeOptions, B as PrewakeResult, E as PrewakeStatus, F as RecordingBucket, G as RecordingLifecycle, H as RecordingStatus, K as ReleaseSessionBeaconOptions, U as RuntimeAvailability, V as RuntimeWakeDetail, W as RuntimeWakeGolden, X as RuntimeWakeReasonCode, _ as SessionDocument, a3 as SessionPhaseError, a6 as SessionStatsOptions, aa as SessionText, ai as VideoPlayoutOptions, an as derivedLegName, ao as derivedLegRole, ap as isPendingRecording, aq as mediaRecorderChunkSource, ar as prewake, as as releaseSessionBeacon } from './stream-data-Cgh02-qs.js';
1
+ import { g as AppOptions, f as App$1, a2 as SessionPhase, a8 as SessionStatus, a4 as SessionPhaseName, A as AccessTokenOptions, Q as RuntimeArtifact, S as RuntimeArtifactDownload, R as Recording, Y as Session$1, C as ChannelEndpoint, af as TransportSession, h as AttachOptions, Z as SessionDiagnostic, b as ActivationEvent, a7 as SessionStatsSample, J as RecordingsAccessor, T as RuntimeArtifactsAccessor, a0 as SessionEndResult, a9 as SessionStream$1, ae as StreamDataTransport, $ as SessionDocumentImpl, ad as StreamChunkOptions, m as ChunkReadable, P as Presence, t as DocConnector, u as DocTokenSupplier, N as RequestOptions, O as RequestStreamOptions, ac as StoreOptions, ab as Store, k as ChannelMultiplexer, a1 as SessionFailureKind, ah as TransportState } from './stream-data-B5wxsIPL.js';
2
+ export { c as ActivationState, i as AudioPlayoutOptions, D as DERIVED_LEG_SEP, q as DerivedLegRole, s as DocConnectionState, I as InboundStatsSample, M as MediaChunkBinding, v as MediaChunkSource, w as MediaChunkSourceFactory, x as MediaRecorderChunkSourceOptions, y as PresenceState, z as PrewakeOptions, B as PrewakeResult, E as PrewakeStatus, F as RecordingBucket, G as RecordingLifecycle, H as RecordingStatus, K as ReleaseSessionBeaconOptions, U as RuntimeAvailability, V as RuntimeWakeDetail, W as RuntimeWakeGolden, X as RuntimeWakeReasonCode, _ as SessionDocument, a3 as SessionPhaseError, a6 as SessionStatsOptions, aa as SessionText, ai as VideoPlayoutOptions, an as derivedLegName, ao as derivedLegRole, ap as isPendingRecording, aq as mediaRecorderChunkSource, ar as prewake, as as releaseSessionBeacon } from './stream-data-B5wxsIPL.js';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5