@urun-sh/core 0.2.56 → 0.2.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +66 -1
- package/dist/{chunk-ROHOB3GT.mjs → chunk-GR7O2DMI.mjs} +5 -5
- package/dist/{chunk-5MCYL2CA.mjs → chunk-TZ4YVHOL.mjs} +2 -2
- package/dist/index.browser.d.mts +86 -3
- package/dist/index.browser.d.ts +86 -3
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +86 -3
- package/dist/index.d.ts +86 -3
- package/dist/index.js +5 -5
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.d.mts +1 -1
- package/dist/internal.browser.d.ts +1 -1
- package/dist/internal.browser.js +2 -2
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +5 -5
- package/dist/internal.mjs +1 -1
- package/dist/{stream-data-Cb0t-gV0.d.mts → stream-data-Cgh02-qs.d.mts} +87 -3
- package/dist/{stream-data-Cb0t-gV0.d.ts → stream-data-Cgh02-qs.d.ts} +87 -3
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
|
|
2
|
-
import{A as N,B as Xe,C as Se,D as Qe,E as Ze,F as et,G as Xt,H as ne,K as se,L as ie,N as tt,P as Qt,Q as Zt,R as er,S as oe,U as rt,V as nt,W as st,X as it,Y as ot,a as Je,b as ee,c as B,d as Lt,e as te,f as ge,g as ve,h as we,i as Nt,j as Ft,k as re,l as ye,m as Wt,n as qt,o as jt,p as Bt,q as be,r as $t,s as Ht,t as _e,u as Vt,v as Kt,w as Gt,x as zt,y as Yt,z as Jt}from"./chunk-ROHOB3GT.mjs";var tr=15e3,rr=45e3,nr=12e4,ke="platform",Te="activation",Re="desired.activation";function at(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 sr=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],$=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 sr){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=at(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 ir(s){return new D(s)}var D=class{_options;constructor(e){this._options=e}async list(e){let r=dt(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new k("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(ct)}async getDownloadUrl(e,t){let r=dt(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!ar(n))throw new k("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:ct(r.artifact),downloadUrl:n}}async _request(e,t){let r=Xe(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&&cr(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 dr(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 ct(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=or(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 or(s,e){let t=s[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function ar(s){try{return new URL(s).protocol==="https:"}catch{return!1}}function cr(s){return s===401||s===403}function dr(s,e,t){return s===401?new ae(t,e):s===404?new ce(t,e):new k(t,s,e)}function dt(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)}},F=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 ur(s){if(s==="pin")return{action:"pin"};if(Ae(s))return{action:"retain",duration:s};throw new F(`[urun] recordings: "${s}" is not a duration or "pin"`)}function lr(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 F(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 W=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 F(`[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 lr(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 pr(s){return new W(s)}var ut="activity",lt="visibility",mr=15e3,Ee=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ce(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(ut,{at:f})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{s.awareness.setLocalStateField(lt,r.visibilityState)}catch{}},c=()=>i(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let f of Ee)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 Ee)t.removeEventListener(f,c,{capture:!0});r&&r.removeEventListener("visibilitychange",u),d&&(clearInterval(d),d=null)}}}}var fr=250;function Ie(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 Pe(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 pt="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(pt)?pt: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 y=w.data;o||!y||y.size===0||(m=m.then(async()=>{let _=new Uint8Array(await y.arrayBuffer());o||c(_)}))},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 hr(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 mt(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 hr(o)}import{encode as gr,decode as vr}from"@msgpack/msgpack";var ft=65536;function Oe(s){let e=gr(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>ft)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(vr(n))}return t}},G=12,De=1;function Ue(s){let e=s.getUint8(8);return{groupId:s.getUint32(0,!0),frameSeq:s.getUint32(4,!0),keyframe:(e&De)===De,fragIndex:s.getUint8(9),fragCount:s.getUint8(10)}}function wr(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?De:0),t.setUint8(9,s.fragIndex),t.setUint8(10,s.fragCount),t.setUint8(11,0),e}var yr=100,z=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??yr}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 br=/^avc[13]\.[0-9a-fA-F]{6}$/;function _r(s){return br.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 Le(s,e){let t=_r(s);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var Sr=250,kr=3,Tr=1e4,Ne=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};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");Le(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");Le(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}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<Tr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=kr){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 ${Ne}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Ne}ms`))},Ne);e.unref?.(),this.firstDecodeTimer=e}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;this.armFirstDecodeDeadline();let 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(Oe(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(()=>{})},Sr)}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 ht=2500,gt=["av01.0.08M.08","avc1.42E01F","avc1.640028"],J=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",n=this.opts.allowWebTransport??!0,o={webtransport:t&&r&&n,webcodecs:r,codecs:gt};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 vt(a.start(),this.opts.quicDeadlineMs??ht,"quic connect deadline"),this.session=a,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){console.warn("[urun] webtransport failed, falling back to webrtc:",c),a?.stop().catch(()=>{}),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}return this.session=await this.startWebRtc(),i||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){await this.session?.stop(),this.session=null}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;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:gt}}),!this.offer.webtransport)return null;let n=this.createWebTransportSession();try{await vt(n.start(),this.opts.quicDeadlineMs??ht,"quic connect deadline")}catch(o){throw n.stop().catch(()=>{}),o}return this.session!==r?(n.stop().catch(()=>{}),null):(this.session=n,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),n)}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),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 vt(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 Rr=1e4,X=class{constructor(e,t=Rr){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 Ar="video",Q=class{constructor(e,t=Ar){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 Er="video";function wt(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 b of c.getVideoTracks())try{b.stop()}catch{}c=null}u&&(u=!1,t.onOverrideTrack(null))},f=new J(new X(s),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new Q(s,t.streamName??Er)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(b,h)=>{b==="webrtc"&&(d(),S()),t.onTransportChange?.(b,h)}}),p=null,l=()=>{p!==null&&(clearTimeout(p),p=null)},m=t.wtRetryBaseMs??2e3,w=t.wtRetryCapMs??3e4,y=null,_=0,S=()=>{if(a||y!==null||f.activeTransport==="webtransport")return;let b=Math.min(m*2**_,w);y=setTimeout(()=>{y=null,_+=1,f.retryWebTransport().then(h=>{if(!a){if(h)return console.debug(`[urun] webtransport upgraded in background (retry ${_})`),_=0,T(h);S()}}).catch(h=>{a||(console.debug(`[urun] webtransport background retry ${_} failed:`,h),S())})},b)},R=()=>{y!==null&&(clearTimeout(y),y=null)},T=async b=>{if(a||b.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 b.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 b=await f.connect();await T(b)})().catch(b=>{l(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",b),S()}),{activeTransport:()=>f.activeTransport,dispose(){a=!0,l(),R(),d(),f.disconnect().catch(()=>{})}}}var Cr=new Set;function qe(s){if(s.functionsUrl)return{functionsUrl:s.functionsUrl,orgId:s.orgId,apiKey:s.apiKey,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}var Ir="rpc",bt=3e4,Pr="rpc-resp";function Mr(s){return`${Pr}:${s}`}function Fe(){return ie()}function xr(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 Dr(s,e,t,r,n,o,i,a,c,u){let d=[],f=null,p=!1,l=null,m=!1,w,y,_=new Promise((g,M)=>{w=g,y=M});_.catch(()=>{});let S=i(),R=null,T=null,b=null,h=null,v=!0,I=()=>{b&&(clearTimeout(b),b=null),h&&(h(),h=null)},E=!1,j=()=>{E||!m||(E=!0,s.set({rpc:{[e]:null}}))},A=()=>{v=!1,I(),R?.(),R=null,T?.(),T=null,a?.removeEventListener("abort",ze),S.dispose(),j()},x=()=>{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})}}},Dt=g=>{p||(d.push(g),x())},U=g=>{p||(l=g,p=!0,y(g),A(),x())},Ge=g=>{p||(p=!0,w(g),A(),x())},ze=()=>{let g=a?.reason;U(g instanceof te?g:new re(e))},Ot=g=>{if(!(p||!g||typeof g!="object"))switch(j(),g.t){case"delta":typeof g.delta=="string"&&Dt(g.delta);break;case"response":Ge(g.body);break;case"error":{let{message:M,code:L}=xr(g.body);U(new te(M,{requestId:e,code:g.code??L}));break}}},Ut=()=>{let g=S.messages()[Symbol.asyncIterator]();R=()=>{g.return?.(void 0)};let M=()=>{v&&g.next().then(L=>{if(v){if(L.done){p||Ge(void 0);return}Ot(L.value),M()}},L=>{v&&U(L)})};M()},Ye=()=>{if(!m){if(m=!0,a){if(a.aborted){U(new re(e));return}a.addEventListener("abort",ze,{once:!0})}T=c?.(g=>U(g))??null,Ut(),s.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!s.synced&&(b=setTimeout(()=>{b=null,!p&&!s.synced&&U(new ve(u,e))},u),h=s.onSynced(()=>I()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Ye(),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),A()),Promise.resolve({value:void 0,done:!0})},throw(g){return p||(p=!0,y(g),A()),Promise.reject(g)}}}},body:_,start:Ye}}function yt(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 Or(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=yt(o);c&&(a.rt=c);let u=yt(i);return u&&(a.br=u),a}var We=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=Or(t,this._name),n=r?.br;if(n?.by==="runtime")throw new we(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 mt(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 st;_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=tt(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Ie(()=>this.recover()),this._activity=Ce({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new $({onPhase:i=>this.onPhase(i),hint:()=>this.doc(ke).get(Te)??this.doc("control").get(Re),onData:(i,a)=>this._streamData.onData(i,a)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await et({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,qe(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)}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 W(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 D(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new D(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new We(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new it(e,this._sessionId,Cr.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=ot(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=rt(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(nt({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=Fe(),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 ge(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(Ir),a=Mr(e);return Dr(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??bt)}requestStream(e,t={}){let r=Fe();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Fe(),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=wt(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new B)}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 _t(s){return`urun:logical:v1:${s.orgId}:${s.app}:${s.functionName}`}function je(){try{return globalThis.sessionStorage??null}catch{return null}}function St(s){let e=je();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 kt(s,e){let t=je();if(t)try{t.setItem(s,JSON.stringify({logicalId:e.logicalId}))}catch{}}function me(s){let e=je();if(e)try{e.removeItem(s)}catch{}}var Ur=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Lr(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(!(Ur.has(r)||typeof r!="string"))return n=>{let o=n??{},i=_t({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,diagnosticSink:e.diagnosticSink}),m=new Z(c,p,l,qe(f),H(f)),w,y,_=new Promise(h=>{y=h}),S=h=>{w=h,y({status:"ready",handle:h})};m.setEndHandler(async()=>{let h=w?{status:"ready",handle:w}:await _;if(h.status==="unavailable")throw new B("[urun] session allocation failed before a releasable request was created",{cause:h.cause});let v=h.handle;return me(i),Qe({baseUrl:v.baseUrl,requestId:v.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider})});let R=async h=>{let v=await Ze({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??St(i)?.logicalId,priority:e.priority,onAdmission:E=>l.reportAdmission(E),onRequest:S}),I=d?await d()??void 0:e.jwt;return e.sessionKey||kt(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,b=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:b})}),(async()=>{let h;try{h=await R(c)}catch(v){console.error(`[urun] Failed to create session for ${r}:`,v),me(i);let I=v instanceof Error?v:new Error(String(v)),E=v instanceof be?v.httpStatus:void 0;l.reportAllocationFailure(I,E),y({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:b}),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=Pe(()=>{if(l.leaveLeg()||l.connectedUrl!==null)return;let A=w;A&&(me(i),Se({baseUrl:A.baseUrl,requestId:A.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))});m.onDisconnect(h);let v,I,E=!1,j=()=>{E||(E=!0,v?.(),I?.())};_.then(A=>{A.status!=="ready"||E||(v=Me(()=>w!==void 0))}),I=m.onPhase(A=>{let x=A?.name;(x==="ended"||x==="expired"||x==="error")&&j()}),E&&I(),m.onDisconnect(j)}return m}}})}var Tt="https://api.urun.sh",Rt="URUN_DEV";function Nr(){if(typeof process>"u")return!1;let s=process.env?.[Rt];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 Fr(s,e={}){if(!s)throw new O("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=N(e.baseUrl??Tt),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??Nr())&&(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 At=3e4,Et="stream:",Be=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=`${Et}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Et}${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 ${At}ms`)))},At);this._pendingRpc.set(o,{resolve:r,reject:n,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Wr(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 Je(n);return new Be(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(y){throw y instanceof DOMException&&y.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):y}let l=s.getReader();function m(){return p.updating?new Promise(y=>{p.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:y,value:_}=await l.read();if(y){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{p.appendBuffer(_)}catch(S){if(S instanceof DOMException&&S.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(_)}else throw S}else throw S}}}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 Br(s){return s.status.startsWith("pending_")}var fe=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 Ct(s){let e=[];return s.audio&&e.push("audio"),s.video&&e.push("video"),e.join("+")}function $r(s,e){return e==="audio"?s.getAudioTracks():s.getVideoTracks()}function Hr(s,e){let t=s.getTracks();if(t.length===1&&t[0]===e)return s;try{return new MediaStream([e])}catch{return s}}function $e(s,e){for(let t of[...s.lostListeners])try{t(e)}catch{}}var he=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,$e(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 fe;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(${Ct(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,$e(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=$r(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(${Ct(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;$e(i,c);continue}if(i.track=a,i.stream=Hr(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}},Vr=null;function Kr(){return Vr??=new he}var It="input",Gr=30;function zr(s){let e=s.now??Date.now,t=s.field??It,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 y=Number.isFinite(m)?Number(m):0,_=Number.isFinite(w)?Number(w):0;y===0&&_===0||(i+=y,a+=_,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 Yr=1024,Jr=.92,Xr=262144,Qr=256e3,He=[.9,.8,.7,.6,.5],Pt=.8,Zr=8;function Ke(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 en(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 xt(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 Mt(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 Ve(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 xt(o,r,n)}async function tn(s,e,t,r){let{width:n,height:o}=e,i=await Ve(s,n,o,t,r);if(i.size<=256e3)return{blob:i,width:n,height:o};if(t==="image/jpeg"){for(let c of He)if(!(c>=r)&&(i=await Ve(s,n,o,t,c),i.size<=256e3))return Mt(`quality ${r} -> ${c}`,i.size),{blob:i,width:n,height:o}}let a=t==="image/jpeg"?He[He.length-1]:r;for(let c=0;c<Zr;c++)if(n=Math.max(16,Math.round(n*Pt)),o=Math.max(16,Math.round(o*Pt)),i=await Ve(s,n,o,t,a),i.size<=256e3)return Mt(`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 rn(s,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,i=await en(s);try{let a=Ke(i.width,i.height,t),c=await tn(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 nn(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 sn(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function on(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=Ke(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 xt(c,o,i);return{bytes:new Uint8Array(await d.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var an=new Set(["w","a","s","d"]),q=(s,e)=>Math.min(e,Math.max(-e,s));function cn(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();an.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{rr as ACTIVATION_COLD_BOOT_AFTER_MS,nr as ACTIVATION_DEGRADED_AFTER_MS,Te as ACTIVATION_HINT_PATH,tr as ACTIVATION_STILL_AFTER_MS,Ee as ACTIVITY_DOM_EVENTS,ut as ACTIVITY_FIELD,mr as ACTIVITY_STAMP_MIN_INTERVAL_MS,$ as ActivationMonitor,Lr as App,Kt as BACKOFF_BASE_MS,zt as BACKOFF_MAX_ATTEMPTS,Gt as BACKOFF_MAX_MS,he as CaptureController,fe as CaptureUnavailableError,O as ClientTokenError,Xr as DATA_CHANNEL_MESSAGE_CEILING,bt as DEFAULT_DOC_SYNC_TIMEOUT_MS,Tt as DEFAULT_GATEWAY_URL,Nt as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Jr as DEFAULT_REFERENCE_JPEG_QUALITY,Yr as DEFAULT_REFERENCE_MAX_SIZE,Ht as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Qt as DERIVED_LEG_SEP,G as DGRAM_HEADER_BYTES,fr as FOREGROUND_COALESCE_MS,z as FrameReassembler,Gr as INPUT_PRESENCE_DEFAULT_HZ,It as INPUT_PRESENCE_FIELD,F as InvalidDurationError,Re as LEGACY_ACTIVATION_HINT_PATH,ke as PLATFORM_DOC_NAME,pe as PermanentLockedError,le as PinRequiresActiveTempError,Ft as ProduceAckTimeoutError,de as RecordingNotFoundError,W as RecordingsClient,C as RecordingsError,V as RecordingsUnauthorizedError,re as RequestAbortError,ye as RequestCancelledError,ve as RequestDocSyncError,te as RequestError,ge as RequestTimeoutError,ue as RetainNotTempError,ce as RuntimeArtifactNotFoundError,D as RuntimeArtifactsClient,k as RuntimeArtifactsError,ae as RuntimeArtifactsUnauthorizedError,Z as Session,be as SessionAllocationError,Lt as SessionEndError,B as SessionEndUnavailableError,qt as SessionFailedError,we as StreamDirectionConflict,J as TransportNegotiator,Bt as TransportSessionMismatchError,X as TransportSessionSignaling,Rt as URUN_DEV_ENV,lt as VISIBILITY_FIELD,Qr as WIRE_MESSAGE_BUDGET,ft as WT_CONTROL_FRAME_MAX,Q as WebRtcSession,Y as WebTransportSession,K as WtControlDecoder,at as activationHintFrom,sn as cameraCaptureAvailable,on as captureStillFromVideo,Yt as computeBackoffDelay,Ce as createActivityTracker,cn as createCameraWarp,Fr as createClientToken,zr as createInputPresencePublisher,pr as createRecordingsClient,ir as createRuntimeArtifactsClient,Wr as createStore,er as derivedLegName,Zt as derivedLegRole,Wt as describeSessionFailure,Vt as describeSessionPhase,Oe as encodeWtControlFrame,Ke as fitWithin,Ae as isDurationString,Br as isPendingRecording,Jt as isRetryableSessionError,$t as isWakingPhase,xe as mediaRecorderChunkSource,rn as normalizeReferenceImage,ur as normalizeRetention,Me as observeLeaveConfirm,Ie as observePageLifecycle,Pe as observePageTeardown,Ue as parseDgramHeader,Xt as prewake,nn as referenceImageErrorMessage,Se as releaseSessionBeacon,jt as sessionFailureFromMediaError,Kr as sharedCaptureController,jr as videoStream,_e as whenLive,wr as writeDgramHeader};
|
|
2
|
+
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-GR7O2DMI.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,4 +1,4 @@
|
|
|
1
|
-
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, n as DOC_SYNC_WIRE_CONTRACT_VERSION, o as DeferredChannelMultiplexer, p as DeferredDocConnector, r as DocConnection, s as DocConnectionState, t as DocConnector, u as DocTokenSupplier, L as LoopbackStreamData,
|
|
1
|
+
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, n as DOC_SYNC_WIRE_CONTRACT_VERSION, o as DeferredChannelMultiplexer, p as DeferredDocConnector, r as DocConnection, s as DocConnectionState, t as DocConnector, u as DocTokenSupplier, L as LoopbackStreamData, $ as SessionDocumentImpl, a5 as SessionStartOptions, ae as StreamDataTransport, af as TransportSession, ag as TransportSessionOptions, aj as allocateSession, ak as createPresence, al as createWebsocketDocConnector, am as deriveYjsServerUrl, at as streamDataLabel, au as transportStreamData } from './stream-data-Cgh02-qs.mjs';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, n as DOC_SYNC_WIRE_CONTRACT_VERSION, o as DeferredChannelMultiplexer, p as DeferredDocConnector, r as DocConnection, s as DocConnectionState, t as DocConnector, u as DocTokenSupplier, L as LoopbackStreamData,
|
|
1
|
+
export { a as AccessTokenOptions, d as AllocateSessionOptions, e as AllocatedSession, j as ChannelMessage, k as ChannelMultiplexer, l as ChannelName, n as DOC_SYNC_WIRE_CONTRACT_VERSION, o as DeferredChannelMultiplexer, p as DeferredDocConnector, r as DocConnection, s as DocConnectionState, t as DocConnector, u as DocTokenSupplier, L as LoopbackStreamData, $ as SessionDocumentImpl, a5 as SessionStartOptions, ae as StreamDataTransport, af as TransportSession, ag as TransportSessionOptions, aj as allocateSession, ak as createPresence, al as createWebsocketDocConnector, am as deriveYjsServerUrl, at as streamDataLabel, au as transportStreamData } from './stream-data-Cgh02-qs.js';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|