@urun-sh/core 0.2.40 → 0.2.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.browser.d.mts +5 -1
- package/dist/index.browser.d.ts +5 -1
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +5 -5
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
|
|
2
|
-
import{A as Ge,B as be,C as Ye,D as Je,E as Xe,F as Bt,G as ee,I as te,J as re,L as Qe,N as ne,P as Ze,Q as et,R as tt,S as rt,T as nt,a as ze,b as X,c as N,d as Pt,e as Q,f as me,g as he,h as ge,i as Mt,j as xt,k as Z,l as ve,m as Dt,n as Ot,o as Ut,p as we,q as Lt,r as Ft,s as ye,t as Nt,u as qt,v as Wt,w as jt,x as $t,y as Ht,z as O}from"./chunk-JGXO6MFH.mjs";var Vt=15e3,Kt=45e3,zt=12e4,_e="platform",Se="activation",Te="desired.activation";function st(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 Gt=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],q=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 Gt){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let n={state:t,elapsedMs:r,stream:e.name},o=st(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let i of Array.from(this._handlers))i(n)}};var S=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)}},se=class extends S{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},ie=class extends S{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function W(s){return{baseUrl:s.baseUrl,fallbackUrls:s.fallbackUrls,orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}function Yt(s){return new I(s)}var I=class{_options;constructor(e){this._options=e}async list(e){let r=ot(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new S("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(it)}async getDownloadUrl(e,t){let r=ot(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!Xt(n))throw new S("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:it(r.artifact),downloadUrl:n}}async _request(e,t){let r=Ge(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 S&&Qt(n.status))throw n}throw n??new S("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${O(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 Zt(i.status,a,c)}try{return await i.json()}catch(a){throw new S(`[urun] runtime artifacts: invalid JSON response from ${O(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=O(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 it(s){if(!s||typeof s!="object")throw new S("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=s,t=E(e,"artifact_id")||E(e,"id"),r=E(e,"filename"),n=E(e,"kind"),o=E(e,"status")||"ready",i=Jt(e,"size_bytes"),a=E(e,"sha256");if(!t||!r||!n||i==null||!a)throw new S("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:E(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:E(e,"created_at"),expiresAt:E(e,"expires_at")}}function E(s,e){let t=s[e];return typeof t=="string"&&t.length>0?t:void 0}function Jt(s,e){let t=s[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function Xt(s){try{return new URL(s).protocol==="https:"}catch{return!1}}function Qt(s){return s===401||s===403}function Zt(s,e,t){return s===401?new se(t,e):s===404?new ie(t,e):new S(t,s,e)}function ot(s){if(!s||typeof s!="object"||Array.isArray(s))throw new S("[urun] runtime artifacts: malformed response",0,"bad_response");return s}var A=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)}},j=class extends A{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends A{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ae=class extends A{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)}},ce=class extends A{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},de=class extends A{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},U=class extends A{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 ke(s){return/^(\d+[smhdw])+$/.test(s)}function er(s){if(s==="pin")return{action:"pin"};if(ke(s))return{action:"retain",duration:s};throw new U(`[urun] recordings: "${s}" is not a duration or "pin"`)}function tr(s,e,t){let r=t||e||`HTTP ${s}`;if(s===401)return new j(r,e??"unauthorized");if(s===404)return new oe(r,e??"not_found");if(s===400)return new U(r,e??"bad_request",400);if(s===409)switch(e){case"retain_not_temp":return new ae(r,e);case"pin_requires_active_temp":return new ce(r,e);case"permanent_locked":return new de(r,e)}return new A(r,{status:s,code:e??`http_${s}`})}var L=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!ke(t))throw new U(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new A("[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 tr(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 j("[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 rr(s){return new L(s)}var at="activity",ct="visibility",nr=15e3,Re=["pointerdown","pointermove","keydown","wheel","touchstart"];function Ae(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 h=e();if(!(o!==void 0&&h-o<15e3)){o=h;try{s.awareness.setLocalStateField(at,{at:h})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{s.awareness.setLocalStateField(ct,r.visibilityState)}catch{}},c=()=>i(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let h of Re)t.addEventListener(h,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 h of Re)t.removeEventListener(h,c,{capture:!0});r&&r.removeEventListener("visibilitychange",u),d&&(clearInterval(d),d=null)}}}}var sr=250;function Ee(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 Ce(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)}}var dt="video/mp4";function Ie(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 h=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(dt)?dt:void 0),p=new MediaStream([a]),l=new d(p,h?{mimeType:h}:void 0);r=l;let f=Promise.resolve();l.ondataavailable=w=>{let y=w.data;o||!y||y.size===0||(f=f.then(async()=>{let b=new Uint8Array(await y.arrayBuffer());o||c(b)}))},l.onstop=()=>{f.then(()=>{o||u()})},l.onerror=()=>{f.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 ir(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 ut(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 ir(o)}import{encode as or,decode as ar}from"@msgpack/msgpack";var lt=65536;function Me(s){let e=or(s),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var $=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>lt)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(ar(n))}return t}},H=12,Pe=1;function xe(s){let e=s.getUint8(8);return{groupId:s.getUint32(0,!0),frameSeq:s.getUint32(4,!0),keyframe:(e&Pe)===Pe,fragIndex:s.getUint8(9),fragCount:s.getUint8(10)}}function cr(s){let e=new Uint8Array(H),t=new DataView(e.buffer);return t.setUint32(0,s.groupId,!0),t.setUint32(4,s.frameSeq,!0),t.setUint8(8,s.keyframe?Pe:0),t.setUint8(9,s.fragIndex),t.setUint8(10,s.fragCount),t.setUint8(11,0),e}var dr=100,B=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??dr}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<H)return;let t=xe(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(H),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 ur=/^avc[13]\.[0-9a-fA-F]{6}$/;function lr(s){return ur.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 De(s,e){let t=lr(s);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var pr=250,fr=3,mr=1e4,Oe=2500,V=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 B({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");De(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 $,o=[],i=await this.readControl(r,n,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");De(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<mr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=fr){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 ${Oe}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Oe}ms`))},Oe);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(Me(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(()=>{})},pr)}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 pt=2500,ft=["av01.0.08M.08","avc1.42E01F","avc1.640028"],K=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:ft};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 mt(a.start(),this.opts.quicDeadlineMs??pt,"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:ft}}),!this.offer.webtransport)return null;let n=this.createWebTransportSession();try{await mt(n.start(),this.opts.quicDeadlineMs??pt,"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 V(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 mt(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 hr=1e4,z=class{constructor(e,t=hr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=re();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,...h}=c;n(h)});this.carrier.sendSignal({type:e,requestId:r,...t})})}notify(e,t){this.carrier.sendSignal({type:e,...t})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};var gr="video",G=class{constructor(e,t=gr){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 vr="video";function ht(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 m of c.getVideoTracks())try{m.stop()}catch{}c=null}u&&(u=!1,t.onOverrideTrack(null))},h=new K(new z(s),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new G(s,t.streamName??vr)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(m,g)=>{m==="webrtc"&&(d(),_()),t.onTransportChange?.(m,g)}}),p=null,l=()=>{p!==null&&(clearTimeout(p),p=null)},f=t.wtRetryBaseMs??2e3,w=t.wtRetryCapMs??3e4,y=null,b=0,_=()=>{if(a||y!==null||h.activeTransport==="webtransport")return;let m=Math.min(f*2**b,w);y=setTimeout(()=>{y=null,b+=1,h.retryWebTransport().then(g=>{if(!a){if(g)return console.debug(`[urun] webtransport upgraded in background (retry ${b})`),b=0,k(g);_()}}).catch(g=>{a||(console.debug(`[urun] webtransport background retry ${b} failed:`,g),_())})},m)},T=()=>{y!==null&&(clearTimeout(y),y=null)},k=async m=>{if(a||m.kind!=="webtransport")return;let g=t.firstMediaWarnMs??1e4;if(l(),p=setTimeout(()=>{a||h.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${g}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},g),await m.firstMedia,l(),a||h.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let R=c.getVideoTracks()[0];R&&(u=!0,t.onOverrideTrack(R))};return(async()=>{let m=await h.connect();await k(m)})().catch(m=>{l(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",m),_()}),{activeTransport:()=>h.activeTransport,dispose(){a=!0,l(),T(),d(),h.disconnect().catch(()=>{})}}}var wr=new Set;function Fe(s){if(s.functionsUrl)return{functionsUrl:s.functionsUrl,orgId:s.orgId,apiKey:s.apiKey,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}var yr="rpc",vt=3e4,br="rpc-resp";function _r(s){return`${br}:${s}`}function Ue(){return re()}function Sr(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 Tr(s,e,t,r,n,o,i,a,c,u){let d=[],h=null,p=!1,l=null,f=!1,w,y,b=new Promise((v,C)=>{w=v,y=C});b.catch(()=>{});let _=i(),T=null,k=null,m=null,g=null,R=!0,M=()=>{m&&(clearTimeout(m),m=null),g&&(g(),g=null)},$e=!1,He=()=>{$e||!f||($e=!0,s.set({rpc:{[e]:null}}))},J=()=>{R=!1,M(),T?.(),T=null,k?.(),k=null,a?.removeEventListener("abort",Ve),_.dispose(),He()},fe=()=>{if(h){if(d.length>0){let v=h;h=null,v.resolve({value:d.shift(),done:!1})}else if(l!==null){let v=h;h=null,v.reject(l)}else if(p){let v=h;h=null,v.resolve({value:void 0,done:!0})}}},Et=v=>{p||(d.push(v),fe())},x=v=>{p||(l=v,p=!0,y(v),J(),fe())},Be=v=>{p||(p=!0,w(v),J(),fe())},Ve=()=>{let v=a?.reason;x(v instanceof Q?v:new Z(e))},Ct=v=>{if(!(p||!v||typeof v!="object"))switch(He(),v.t){case"delta":typeof v.delta=="string"&&Et(v.delta);break;case"response":Be(v.body);break;case"error":{let{message:C,code:D}=Sr(v.body);x(new Q(C,{requestId:e,code:v.code??D}));break}}},It=()=>{let v=_.messages()[Symbol.asyncIterator]();T=()=>{v.return?.(void 0)};let C=()=>{R&&v.next().then(D=>{if(R){if(D.done){p||Be(void 0);return}Ct(D.value),C()}},D=>{R&&x(D)})};C()},Ke=()=>{if(!f){if(f=!0,a){if(a.aborted){x(new Z(e));return}a.addEventListener("abort",Ve,{once:!0})}k=c?.(v=>x(v))??null,It(),s.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!s.synced&&(m=setTimeout(()=>{m=null,!p&&!s.synced&&x(new he(u,e))},u),g=s.onSynced(()=>M()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Ke(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(l!==null){let v=l;return l=null,Promise.reject(v)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((v,C)=>{h={resolve:v,reject:C}})},return(){return p||(p=!0,w(void 0),J()),Promise.resolve({value:void 0,done:!0})},throw(v){return p||(p=!0,y(v),J()),Promise.reject(v)}}}},body:b,start:Ke}}function gt(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 kr(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=gt(o);c&&(a.rt=c);let u=gt(i);return u&&(a.br=u),a}var Le=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._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,o={push(a){if(!n)if(r){let c=r;r=null,c({value:a,done:!1})}else t.push(a)},end(){if(n=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{n=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):n?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=kr(t,this._name),n=r?.br;if(n?.by==="runtime")throw new ge(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??Ie;return ut(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)}},Y=class s{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new tt;_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=Qe(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Ee(()=>this.recover()),this._activity=Ae({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new q({onPhase:i=>this.onPhase(i),hint:()=>this.doc(_e).get(Se)??this.doc("control").get(Te),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 Xe({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 X,i=new ne({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,o,i,Fe(t),W({...t,baseUrl:r.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),i.setEndsAt(r.endsAt),ee()&&await te(),a.setDocTransport({wsUrl:r.wsUrl,token:n}),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 ye(this,e)}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new L(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,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 I(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new I(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 Le(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 rt(e,this._sessionId,wr.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=nt(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=Ze(e.wsUrl),r=`${t}\0${e.token??""}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(et({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=Ue(),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 me(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(yr),a=_r(e);return Tr(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??vt)}requestStream(e,t={}){let r=Ue();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Ue(),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=ht(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new N)}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 ve)}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 wt(s){return`urun:logical:v1:${s.orgId}:${s.app}:${s.functionName}`}function Ne(){try{return globalThis.sessionStorage??null}catch{return null}}function yt(s){let e=Ne();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 bt(s,e){let t=Ne();if(t)try{t.setItem(s,JSON.stringify({logicalId:e.logicalId}))}catch{}}function ue(s){let e=Ne();if(e)try{e.removeItem(s)}catch{}}var Rr=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Ar(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(!(Rr.has(r)||typeof r!="string"))return n=>{let o=n??{},i=wt({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 m=>{let g=await e.getAccessToken(m);return g&&(u=g),g}:void 0,h={...e,getAccessToken:d},p=new X,l=new ne({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),f=new Y(c,p,l,Fe(h),W(h)),w,y,b=new Promise(m=>{y=m}),_=m=>{w=m,y({status:"ready",handle:m})};f.setEndHandler(async()=>{let m=w?{status:"ready",handle:w}:await b;if(m.status==="unavailable")throw new N("[urun] session allocation failed before a releasable request was created",{cause:m.cause});let g=m.handle;return ue(i),Ye({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider})});let T=async m=>{let g=await Je({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider,idempotencyKey:m,sessionKey:e.sessionKey??yt(i)?.logicalId,priority:e.priority,onAdmission:M=>l.reportAdmission(M),onRequest:_}),R=d?await d()??void 0:e.jwt;return e.sessionKey||bt(i,{logicalId:g.sessionId}),f.setSessionId(g.sessionId),f.setArtifactsAuth(W({...h,baseUrl:g.baseUrl})),l.setEndsAt(g.endsAt),{url:g.wsUrl,sessionId:g.sessionId,jwt:R,iceServers:g.response.ice_servers,endsAt:g.endsAt}},k;if(l.setConnectionResolver(async()=>{let m=await T(a());return k=m.jwt,m}),l.on("connected",()=>{l.multiplexer&&p.setTarget(l.multiplexer);let m=l.connectedUrl;m&&f.setDocTransport({wsUrl:m,token:k})}),(async()=>{let m;try{m=await T(c)}catch(g){console.error(`[urun] Failed to create session for ${r}:`,g),ue(i);let R=g instanceof Error?g:new Error(String(g)),M=g instanceof we?g.httpStatus:void 0;l.reportAllocationFailure(R,M),y({status:"unavailable",cause:g});return}l.setAuth({jwt:m.jwt,authProvider:e.authProvider,orgId:e.orgId}),l.setConnection({url:m.url,sessionId:m.sessionId,iceServers:m.iceServers}),ee()&&await te(),k=m.jwt,f.setDocTransport({wsUrl:m.url,token:m.jwt}),await l.connect({app:s,functionName:r,args:o}),f.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(m=>{console.error(`[urun] Failed to connect session for ${r}:`,m)}),e.releaseOnLeave!==!1){let m=Ce(()=>{let g=w;g&&(ue(i),be({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))});f.onDisconnect(m)}return f}}})}var _t="https://api.urun.sh",P=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Er(s,e={}){if(!s)throw new P("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=O(e.baseUrl??_t),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);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 P(`[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 P(`[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 P("[urun] client token mint returned no token (control-plane contract violation)",o.status);let h=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:h,orgId:c}}var St=3e4,Tt="stream:",qe=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=`${Tt}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${Tt}${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 ${St}ms`)))},St);this._pendingRpc.set(o,{resolve:r,reject:n,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Cr(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 ze(n);return new qe(n,o)}var Ir='video/mp4; codecs="avc1.42E01E"';function Pr(s,e){let t=e?.codec??Ir,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 f(){return p.updating?new Promise(y=>{p.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:y,value:b}=await l.read();if(y){await f(),n.readyState==="open"&&n.endOfStream();return}await f();try{p.appendBuffer(b)}catch(_){if(_ instanceof DOMException&&_.name==="QuotaExceededError"){let T=p.buffered;if(T.length>0){let k=T.start(T.length-1);p.remove(0,k),await f(),p.appendBuffer(b)}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,h=u.length;if(h===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=h&&URL.revokeObjectURL(o)});return c}function Mr(s){return s.status.startsWith("pending_")}var le=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 kt(s){let e=[];return s.audio&&e.push("audio"),s.video&&e.push("video"),e.join("+")}function xr(s,e){return e==="audio"?s.getAudioTracks():s.getVideoTracks()}function Dr(s,e){let t=s.getTracks();if(t.length===1&&t[0]===e)return s;try{return new MediaStream([e])}catch{return s}}function We(s,e){for(let t of[...s.lostListeners])try{t(e)}catch{}}var pe=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,We(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 le;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(${kt(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,We(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=xr(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(${kt(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;We(i,c);continue}if(i.track=a,i.stream=Dr(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}},Or=null;function Ur(){return Or??=new pe}var Rt="input",Lr=30;function Fr(s){let e=s.now??Date.now,t=s.field??Rt,r=1e3/Math.max(s.hz??30,.001),n=new Set,o=0,i=0,a=0,c=0,u,d=null,h=!1,p=()=>{if(h)return;u=e(),c+=1;let f={keys:[...n],buttons:o,pointer:{x:i,y:a},seq:c,at:u};try{s.awareness.setLocalStateField(t,f)}catch{}},l=()=>{if(h)return;let f=e();if(u===void 0||f-u>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let w=Math.max(r-(f-u),0);d=setTimeout(()=>{d=null,p()},w),d.unref?.()};return{keyDown(f){let w=String(f).toLowerCase();n.has(w)||(n.add(w),l())},keyUp(f){let w=String(f).toLowerCase();n.delete(w)&&l()},setButtons(f){let w=Number.isFinite(f)?Number(f):0;w!==o&&(o=w,l())},movePointer(f,w){let y=Number.isFinite(f)?Number(f):0,b=Number.isFinite(w)?Number(w):0;y===0&&b===0||(i+=y,a+=b,l())},heldKeys(){return[...n]},clear(){h||(n.clear(),o=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(h)return;let f=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),f&&p(),h=!0}}}var Nr=1024,qr=.92;function je(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 Wr(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 At(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}async function jr(s,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,i=await Wr(s);try{let a=je(i.width,i.height,t),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)");r==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(i,0,0,a.width,a.height);let d=await At(c,r,n);return{bytes:new Uint8Array(await d.arrayBuffer()),type:r,width:a.width,height:a.height,source:o}}finally{i.close()}}function $r(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 Hr(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Br(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=je(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 At(c,o,i);return{bytes:new Uint8Array(await d.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var Vr=new Set(["w","a","s","d"]),F=(s,e)=>Math.min(e,Math.max(-e,s));function Kr(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,h=null,p=new Set;return{pointerDelta(l,f){c=F(c-l*e,i),u=F(u-f*e,i)},keyDown(l){let f=l.toLowerCase();Vr.has(f)&&p.add(f)},keyUp(l){p.delete(l.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let l=1-o;c*=l,u*=l,d*=l},tick(l){if(h===null){h=l;return}let f=Math.max(0,Math.min(100,l-h))/1e3;h=l,p.has("w")&&(d=F(d+t*f,a)),p.has("s")&&(d=F(d-t*f,a)),p.has("a")&&(c=F(c+r*f,i)),p.has("d")&&(c=F(c-r*f,i));let w=Math.exp(-f*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{Kt as ACTIVATION_COLD_BOOT_AFTER_MS,zt as ACTIVATION_DEGRADED_AFTER_MS,Se as ACTIVATION_HINT_PATH,Vt as ACTIVATION_STILL_AFTER_MS,Re as ACTIVITY_DOM_EVENTS,at as ACTIVITY_FIELD,nr as ACTIVITY_STAMP_MIN_INTERVAL_MS,q as ActivationMonitor,Ar as App,qt as BACKOFF_BASE_MS,jt as BACKOFF_MAX_ATTEMPTS,Wt as BACKOFF_MAX_MS,pe as CaptureController,le as CaptureUnavailableError,P as ClientTokenError,vt as DEFAULT_DOC_SYNC_TIMEOUT_MS,_t as DEFAULT_GATEWAY_URL,Mt as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,qr as DEFAULT_REFERENCE_JPEG_QUALITY,Nr as DEFAULT_REFERENCE_MAX_SIZE,Ft as DEFAULT_WHEN_LIVE_TIMEOUT_MS,H as DGRAM_HEADER_BYTES,sr as FOREGROUND_COALESCE_MS,B as FrameReassembler,Lr as INPUT_PRESENCE_DEFAULT_HZ,Rt as INPUT_PRESENCE_FIELD,U as InvalidDurationError,Te as LEGACY_ACTIVATION_HINT_PATH,_e as PLATFORM_DOC_NAME,de as PermanentLockedError,ce as PinRequiresActiveTempError,xt as ProduceAckTimeoutError,oe as RecordingNotFoundError,L as RecordingsClient,A as RecordingsError,j as RecordingsUnauthorizedError,Z as RequestAbortError,ve as RequestCancelledError,he as RequestDocSyncError,Q as RequestError,me as RequestTimeoutError,ae as RetainNotTempError,ie as RuntimeArtifactNotFoundError,I as RuntimeArtifactsClient,S as RuntimeArtifactsError,se as RuntimeArtifactsUnauthorizedError,Y as Session,we as SessionAllocationError,Pt as SessionEndError,N as SessionEndUnavailableError,Ot as SessionFailedError,ge as StreamDirectionConflict,K as TransportNegotiator,z as TransportSessionSignaling,ct as VISIBILITY_FIELD,lt as WT_CONTROL_FRAME_MAX,G as WebRtcSession,V as WebTransportSession,$ as WtControlDecoder,st as activationHintFrom,Hr as cameraCaptureAvailable,Br as captureStillFromVideo,$t as computeBackoffDelay,Ae as createActivityTracker,Kr as createCameraWarp,Er as createClientToken,Fr as createInputPresencePublisher,rr as createRecordingsClient,Yt as createRuntimeArtifactsClient,Cr as createStore,Dt as describeSessionFailure,Nt as describeSessionPhase,Me as encodeWtControlFrame,je as fitWithin,ke as isDurationString,Mr as isPendingRecording,Ht as isRetryableSessionError,Lt as isWakingPhase,Ie as mediaRecorderChunkSource,jr as normalizeReferenceImage,er as normalizeRetention,Ee as observePageLifecycle,Ce as observePageTeardown,xe as parseDgramHeader,Bt as prewake,$r as referenceImageErrorMessage,be as releaseSessionBeacon,Ut as sessionFailureFromMediaError,Ur as sharedCaptureController,Pr as videoStream,ye as whenLive,cr as writeDgramHeader};
|
|
2
|
+
import{A as Je,B as be,C as Xe,D as Qe,E as Ze,F as zt,G as ee,I as te,J as re,L as et,N as ne,P as tt,Q as rt,R as nt,S as st,T as it,a as Ye,b as X,c as F,d as Ot,e as Q,f as fe,g as he,h as ge,i as Ut,j as Lt,k as Z,l as ve,m as Nt,n as Ft,o as Wt,p as we,q as qt,r as jt,s as ye,t as $t,u as Bt,v as Ht,w as Vt,x as Kt,y as Gt,z as O}from"./chunk-JGXO6MFH.mjs";var Yt=15e3,Jt=45e3,Xt=12e4,_e="platform",Se="activation",Te="desired.activation";function ot(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 Qt=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],W=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 Qt){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let n={state:t,elapsedMs:r,stream:e.name},o=ot(this._options.hint());o!==void 0&&(n.hint=o),e.lastEvent=n;for(let i of Array.from(this._handlers))i(n)}};var S=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)}},se=class extends S{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},ie=class extends S{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function q(s){return{baseUrl:s.baseUrl,fallbackUrls:s.fallbackUrls,orgId:s.orgId,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}function Zt(s){return new I(s)}var I=class{_options;constructor(e){this._options=e}async list(e){let r=ct(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new S("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(at)}async getDownloadUrl(e,t){let r=ct(await this._request(t,`/${encodeURIComponent(e)}/download`)),n=r.download_url;if(typeof n!="string"||!tr(n))throw new S("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:at(r.artifact),downloadUrl:n}}async _request(e,t){let r=Je(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 S&&rr(n.status))throw n}throw n??new S("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let n=`${O(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 nr(i.status,a,c)}try{return await i.json()}catch(a){throw new S(`[urun] runtime artifacts: invalid JSON response from ${O(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=O(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 at(s){if(!s||typeof s!="object")throw new S("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=s,t=E(e,"artifact_id")||E(e,"id"),r=E(e,"filename"),n=E(e,"kind"),o=E(e,"status")||"ready",i=er(e,"size_bytes"),a=E(e,"sha256");if(!t||!r||!n||i==null||!a)throw new S("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:n,filename:r,contentType:E(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:E(e,"created_at"),expiresAt:E(e,"expires_at")}}function E(s,e){let t=s[e];return typeof t=="string"&&t.length>0?t:void 0}function er(s,e){let t=s[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function tr(s){try{return new URL(s).protocol==="https:"}catch{return!1}}function rr(s){return s===401||s===403}function nr(s,e,t){return s===401?new se(t,e):s===404?new ie(t,e):new S(t,s,e)}function ct(s){if(!s||typeof s!="object"||Array.isArray(s))throw new S("[urun] runtime artifacts: malformed response",0,"bad_response");return s}var R=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)}},j=class extends R{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends R{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ae=class extends R{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)}},ce=class extends R{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},de=class extends R{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},U=class extends R{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 ke(s){return/^(\d+[smhdw])+$/.test(s)}function sr(s){if(s==="pin")return{action:"pin"};if(ke(s))return{action:"retain",duration:s};throw new U(`[urun] recordings: "${s}" is not a duration or "pin"`)}function ir(s,e,t){let r=t||e||`HTTP ${s}`;if(s===401)return new j(r,e??"unauthorized");if(s===404)return new oe(r,e??"not_found");if(s===400)return new U(r,e??"bad_request",400);if(s===409)switch(e){case"retain_not_temp":return new ae(r,e);case"pin_requires_active_temp":return new ce(r,e);case"permanent_locked":return new de(r,e)}return new R(r,{status:s,code:e??`http_${s}`})}var L=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!ke(t))throw new U(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new R("[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 ir(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 j("[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 or(s){return new L(s)}var dt="activity",ut="visibility",ar=15e3,Ae=["pointerdown","pointermove","keydown","wheel","touchstart"];function Re(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 h=e();if(!(o!==void 0&&h-o<15e3)){o=h;try{s.awareness.setLocalStateField(dt,{at:h})}catch{}}},a=()=>{if(!(n||!r||r.visibilityState===void 0))try{s.awareness.setLocalStateField(ut,r.visibilityState)}catch{}},c=()=>i(),u=()=>{a(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&i()};if(t)for(let h of Ae)t.addEventListener(h,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 h of Ae)t.removeEventListener(h,c,{capture:!0});r&&r.removeEventListener("visibilitychange",u),d&&(clearInterval(d),d=null)}}}}var cr=250;function Ee(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 Ce(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)}}var lt="video/mp4";function Ie(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 h=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(lt)?lt:void 0),p=new MediaStream([a]),l=new d(p,h?{mimeType:h}: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 b=new Uint8Array(await y.arrayBuffer());o||c(b)}))},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 dr(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 pt(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 dr(o)}import{encode as ur,decode as lr}from"@msgpack/msgpack";var mt=65536;function Pe(s){let e=ur(s),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var $=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>mt)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let n=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(lr(n))}return t}},B=12,Me=1;function xe(s){let e=s.getUint8(8);return{groupId:s.getUint32(0,!0),frameSeq:s.getUint32(4,!0),keyframe:(e&Me)===Me,fragIndex:s.getUint8(9),fragCount:s.getUint8(10)}}function pr(s){let e=new Uint8Array(B),t=new DataView(e.buffer);return t.setUint32(0,s.groupId,!0),t.setUint32(4,s.frameSeq,!0),t.setUint8(8,s.keyframe?Me:0),t.setUint8(9,s.fragIndex),t.setUint8(10,s.fragCount),t.setUint8(11,0),e}var mr=100,H=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??mr}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(e){if(e.byteLength<B)return;let t=xe(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(B),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 fr=/^avc[13]\.[0-9a-fA-F]{6}$/;function hr(s){return fr.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 De(s,e){let t=hr(s);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var gr=250,vr=3,wr=1e4,Oe=2500,V=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 H({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");De(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 $,o=[],i=await this.readControl(r,n,o);if(i?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");De(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<wr),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=vr){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 ${Oe}ms \u2014 broken WT media leg; failing over to WebRTC LOUDLY`),this.die(`no-first-frame: datagrams flowing but nothing decoded within ${Oe}ms`))},Oe);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(Pe(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(()=>{})},gr)}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 ft=2500,ht=["av01.0.08M.08","avc1.42E01F","avc1.640028"],K=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:ht};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 gt(a.start(),this.opts.quicDeadlineMs??ft,"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:ht}}),!this.offer.webtransport)return null;let n=this.createWebTransportSession();try{await gt(n.start(),this.opts.quicDeadlineMs??ft,"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 V(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 gt(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 yr=1e4,G=class{constructor(e,t=yr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=re();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,...h}=c;n(h)});this.carrier.sendSignal({type:e,requestId:r,...t})})}notify(e,t){this.carrier.sendSignal({type:e,...t})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};var br="video",z=class{constructor(e,t=br){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 _r="video";function vt(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 f of c.getVideoTracks())try{f.stop()}catch{}c=null}u&&(u=!1,t.onOverrideTrack(null))},h=new K(new G(s),e,{canvas:i,createWebRtcSession:t.createWebRtcSession??(()=>new z(s,t.streamName??_r)),createWebTransportSession:t.createWebTransportSession,onTransportChange:(f,g)=>{f==="webrtc"&&(d(),_()),t.onTransportChange?.(f,g)}}),p=null,l=()=>{p!==null&&(clearTimeout(p),p=null)},m=t.wtRetryBaseMs??2e3,w=t.wtRetryCapMs??3e4,y=null,b=0,_=()=>{if(a||y!==null||h.activeTransport==="webtransport")return;let f=Math.min(m*2**b,w);y=setTimeout(()=>{y=null,b+=1,h.retryWebTransport().then(g=>{if(!a){if(g)return console.debug(`[urun] webtransport upgraded in background (retry ${b})`),b=0,k(g);_()}}).catch(g=>{a||(console.debug(`[urun] webtransport background retry ${b} failed:`,g),_())})},f)},T=()=>{y!==null&&(clearTimeout(y),y=null)},k=async f=>{if(a||f.kind!=="webtransport")return;let g=t.firstMediaWarnMs??1e4;if(l(),p=setTimeout(()=>{a||h.activeTransport!=="webtransport"||console.warn(`[urun] webtransport established but no QUIC media after ${g}ms \u2014 no media datagrams reached this client; webrtc track remains authoritative`)},g),await f.firstMedia,l(),a||h.activeTransport!=="webtransport"||typeof i.captureStream!="function")return;c=i.captureStream();let A=c.getVideoTracks()[0];A&&(u=!0,t.onOverrideTrack(A))};return(async()=>{let f=await h.connect();await k(f)})().catch(f=>{l(),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",f),_()}),{activeTransport:()=>h.activeTransport,dispose(){a=!0,l(),T(),d(),h.disconnect().catch(()=>{})}}}var Sr=new Set;function Ne(s){if(s.functionsUrl)return{functionsUrl:s.functionsUrl,orgId:s.orgId,apiKey:s.apiKey,jwt:s.jwt,getAccessToken:s.getAccessToken,authProvider:s.authProvider}}var Tr="rpc",yt=3e4,kr="rpc-resp";function Ar(s){return`${kr}:${s}`}function Ue(){return re()}function Rr(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 Er(s,e,t,r,n,o,i,a,c,u){let d=[],h=null,p=!1,l=null,m=!1,w,y,b=new Promise((v,C)=>{w=v,y=C});b.catch(()=>{});let _=i(),T=null,k=null,f=null,g=null,A=!0,P=()=>{f&&(clearTimeout(f),f=null),g&&(g(),g=null)},He=!1,Ve=()=>{He||!m||(He=!0,s.set({rpc:{[e]:null}}))},J=()=>{A=!1,P(),T?.(),T=null,k?.(),k=null,a?.removeEventListener("abort",Ge),_.dispose(),Ve()},me=()=>{if(h){if(d.length>0){let v=h;h=null,v.resolve({value:d.shift(),done:!1})}else if(l!==null){let v=h;h=null,v.reject(l)}else if(p){let v=h;h=null,v.resolve({value:void 0,done:!0})}}},Pt=v=>{p||(d.push(v),me())},x=v=>{p||(l=v,p=!0,y(v),J(),me())},Ke=v=>{p||(p=!0,w(v),J(),me())},Ge=()=>{let v=a?.reason;x(v instanceof Q?v:new Z(e))},xt=v=>{if(!(p||!v||typeof v!="object"))switch(Ve(),v.t){case"delta":typeof v.delta=="string"&&Pt(v.delta);break;case"response":Ke(v.body);break;case"error":{let{message:C,code:D}=Rr(v.body);x(new Q(C,{requestId:e,code:v.code??D}));break}}},Dt=()=>{let v=_.messages()[Symbol.asyncIterator]();T=()=>{v.return?.(void 0)};let C=()=>{A&&v.next().then(D=>{if(A){if(D.done){p||Ke(void 0);return}xt(D.value),C()}},D=>{A&&x(D)})};C()},ze=()=>{if(!m){if(m=!0,a){if(a.aborted){x(new Z(e));return}a.addEventListener("abort",Ge,{once:!0})}k=c?.(v=>x(v))??null,Dt(),s.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:n,stream:o}}}),u&&u>0&&!s.synced&&(f=setTimeout(()=>{f=null,!p&&!s.synced&&x(new he(u,e))},u),g=s.onSynced(()=>P()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(ze(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(l!==null){let v=l;return l=null,Promise.reject(v)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((v,C)=>{h={resolve:v,reject:C}})},return(){return p||(p=!0,w(void 0),J()),Promise.resolve({value:void 0,done:!0})},throw(v){return p||(p=!0,y(v),J()),Promise.reject(v)}}}},body:b,start:ze}}function wt(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 Cr(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=wt(o);c&&(a.rt=c);let u=wt(i);return u&&(a.br=u),a}var Le=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._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,n=!1,o={push(a){if(!n)if(r){let c=r;r=null,c({value:a,done:!1})}else t.push(a)},end(){if(n=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{n=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):n?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,r=this._handlers.get("track");if(r)for(let n of r)n(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Cr(t,this._name),n=r?.br;if(n?.by==="runtime")throw new ge(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??Ie;return pt(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)}},Y=class s{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new nt;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_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=et(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=Ee(()=>this.recover()),this._activity=Re({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0}),this._activation=new W({onPhase:i=>this.onPhase(i),hint:()=>this.doc(_e).get(Se)??this.doc("control").get(Te),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 Ze({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 X,i=new ne({url:r.wsUrl,orgId:t.orgId,jwt:n,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new s(e,o,i,Ne(t),q({...t,baseUrl:r.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),i.setEndsAt(r.endsAt),ee()&&await te(),a.setDocTransport({wsUrl:r.wsUrl,token:n}),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 ye(this,e)}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new L(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,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 I(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new I(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 Le(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._activity?.touch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new st(e,this._sessionId,Sr.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=it(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=tt(e.wsUrl),r=`${t}\0${e.token??""}\0${this._sessionId}`;r!==this._docEndpointKey&&(this._docEndpointKey=r,this.connectDocs(rt({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=Ue(),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 fe(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(Tr),a=Ar(e);return Er(i,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),n,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),o??yt)}requestStream(e,t={}){let r=Ue();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=Ue(),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=vt(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t)}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.disconnect(),e)),this._endPromise):Promise.reject(new F)}disconnect(){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 ve)}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 bt(s){return`urun:logical:v1:${s.orgId}:${s.app}:${s.functionName}`}function Fe(){try{return globalThis.sessionStorage??null}catch{return null}}function _t(s){let e=Fe();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 St(s,e){let t=Fe();if(t)try{t.setItem(s,JSON.stringify({logicalId:e.logicalId}))}catch{}}function ue(s){let e=Fe();if(e)try{e.removeItem(s)}catch{}}var Ir=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Mr(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(!(Ir.has(r)||typeof r!="string"))return n=>{let o=n??{},i=bt({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 f=>{let g=await e.getAccessToken(f);return g&&(u=g),g}:void 0,h={...e,getAccessToken:d},p=new X,l=new ne({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:c}),m=new Y(c,p,l,Ne(h),q(h)),w,y,b=new Promise(f=>{y=f}),_=f=>{w=f,y({status:"ready",handle:f})};m.setEndHandler(async()=>{let f=w?{status:"ready",handle:w}:await b;if(f.status==="unavailable")throw new F("[urun] session allocation failed before a releasable request was created",{cause:f.cause});let g=f.handle;return ue(i),Xe({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider})});let T=async f=>{let g=await Qe({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:d,authProvider:e.authProvider,idempotencyKey:f,sessionKey:e.sessionKey??_t(i)?.logicalId,priority:e.priority,onAdmission:P=>l.reportAdmission(P),onRequest:_}),A=d?await d()??void 0:e.jwt;return e.sessionKey||St(i,{logicalId:g.sessionId}),m.setSessionId(g.sessionId),m.setArtifactsAuth(q({...h,baseUrl:g.baseUrl})),l.setEndsAt(g.endsAt),{url:g.wsUrl,sessionId:g.sessionId,jwt:A,iceServers:g.response.ice_servers,endsAt:g.endsAt}},k;if(l.setConnectionResolver(async()=>{let f=await T(a());return k=f.jwt,f}),l.on("connected",()=>{l.multiplexer&&p.setTarget(l.multiplexer);let f=l.connectedUrl;f&&m.setDocTransport({wsUrl:f,token:k})}),(async()=>{let f;try{f=await T(c)}catch(g){console.error(`[urun] Failed to create session for ${r}:`,g),ue(i);let A=g instanceof Error?g:new Error(String(g)),P=g instanceof we?g.httpStatus:void 0;l.reportAllocationFailure(A,P),y({status:"unavailable",cause:g});return}l.setAuth({jwt:f.jwt,authProvider:e.authProvider,orgId:e.orgId}),l.setConnection({url:f.url,sessionId:f.sessionId,iceServers:f.iceServers}),ee()&&await te(),k=f.jwt,m.setDocTransport({wsUrl:f.url,token:f.jwt}),await l.connect({app:s,functionName:r,args:o}),m.negotiateMediaTransport({allowWebTransport:e.allowWebTransport})})().catch(f=>{console.error(`[urun] Failed to connect session for ${r}:`,f)}),e.releaseOnLeave!==!1){let f=Ce(()=>{let g=w;g&&(ue(i),be({baseUrl:g.baseUrl,requestId:g.requestId,orgId:e.orgId,jwt:u,authProvider:e.authProvider}))});m.onDisconnect(f)}return m}}})}var Tt="https://api.urun.sh",M=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Pr(s,e={}){if(!s)throw new M("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=O(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);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 M(`[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 M(`[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 M("[urun] client token mint returned no token (control-plane contract violation)",o.status);let h=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:h,orgId:c}}var kt=3e4,At="stream:",We=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=`${At}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${At}${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 ${kt}ms`)))},kt);this._pendingRpc.set(o,{resolve:r,reject:n,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function xr(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 Ye(n);return new We(n,o)}var Dr='video/mp4; codecs="avc1.42E01E"';function Or(s,e){let t=e?.codec??Dr,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:b}=await l.read();if(y){await m(),n.readyState==="open"&&n.endOfStream();return}await m();try{p.appendBuffer(b)}catch(_){if(_ instanceof DOMException&&_.name==="QuotaExceededError"){let T=p.buffered;if(T.length>0){let k=T.start(T.length-1);p.remove(0,k),await m(),p.appendBuffer(b)}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,h=u.length;if(h===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=h&&URL.revokeObjectURL(o)});return c}function Ur(s){return s.status.startsWith("pending_")}var le=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 Rt(s){let e=[];return s.audio&&e.push("audio"),s.video&&e.push("video"),e.join("+")}function Lr(s,e){return e==="audio"?s.getAudioTracks():s.getVideoTracks()}function Nr(s,e){let t=s.getTracks();if(t.length===1&&t[0]===e)return s;try{return new MediaStream([e])}catch{return s}}function qe(s,e){for(let t of[...s.lostListeners])try{t(e)}catch{}}var pe=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,qe(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 le;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(${Rt(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,qe(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=Lr(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(${Rt(r)}) returned no ${i.kind} track`),{name:"NotFoundError"});if(i===e)throw c;qe(i,c);continue}if(i.track=a,i.stream=Nr(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}},Fr=null;function Wr(){return Fr??=new pe}var Et="input",qr=30;function jr(s){let e=s.now??Date.now,t=s.field??Et,r=1e3/Math.max(s.hz??30,.001),n=new Set,o=0,i=0,a=0,c=0,u,d=null,h=!1,p=()=>{if(h)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(h)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,b=Number.isFinite(w)?Number(w):0;y===0&&b===0||(i+=y,a+=b,l())},heldKeys(){return[...n]},clear(){h||(n.clear(),o=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(h)return;let m=n.size>0||o!==0;n.clear(),o=0,d&&(clearTimeout(d),d=null),m&&p(),h=!0}}}var $r=1024,Br=.92,Hr=262144,Vr=256e3,je=[.9,.8,.7,.6,.5],Ct=.8,Kr=8;function Be(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 Gr(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 Mt(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 It(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 $e(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 Mt(o,r,n)}async function zr(s,e,t,r){let{width:n,height:o}=e,i=await $e(s,n,o,t,r);if(i.size<=256e3)return{blob:i,width:n,height:o};if(t==="image/jpeg"){for(let c of je)if(!(c>=r)&&(i=await $e(s,n,o,t,c),i.size<=256e3))return It(`quality ${r} -> ${c}`,i.size),{blob:i,width:n,height:o}}let a=t==="image/jpeg"?je[je.length-1]:r;for(let c=0;c<Kr;c++)if(n=Math.max(16,Math.round(n*Ct)),o=Math.max(16,Math.round(o*Ct)),i=await $e(s,n,o,t,a),i.size<=256e3)return It(`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 Yr(s,e){let{maxSize:t=1024,type:r="image/jpeg",quality:n=.92,source:o}=e,i=await Gr(s);try{let a=Be(i.width,i.height,t),c=await zr(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 Jr(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 Xr(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Qr(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=Be(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 Mt(c,o,i);return{bytes:new Uint8Array(await d.arrayBuffer()),type:o,width:a.width,height:a.height,source:"camera"}}var Zr=new Set(["w","a","s","d"]),N=(s,e)=>Math.min(e,Math.max(-e,s));function en(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,h=null,p=new Set;return{pointerDelta(l,m){c=N(c-l*e,i),u=N(u-m*e,i)},keyDown(l){let m=l.toLowerCase();Zr.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(h===null){h=l;return}let m=Math.max(0,Math.min(100,l-h))/1e3;h=l,p.has("w")&&(d=N(d+t*m,a)),p.has("s")&&(d=N(d-t*m,a)),p.has("a")&&(c=N(c+r*m,i)),p.has("d")&&(c=N(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{Jt as ACTIVATION_COLD_BOOT_AFTER_MS,Xt as ACTIVATION_DEGRADED_AFTER_MS,Se as ACTIVATION_HINT_PATH,Yt as ACTIVATION_STILL_AFTER_MS,Ae as ACTIVITY_DOM_EVENTS,dt as ACTIVITY_FIELD,ar as ACTIVITY_STAMP_MIN_INTERVAL_MS,W as ActivationMonitor,Mr as App,Bt as BACKOFF_BASE_MS,Vt as BACKOFF_MAX_ATTEMPTS,Ht as BACKOFF_MAX_MS,pe as CaptureController,le as CaptureUnavailableError,M as ClientTokenError,Hr as DATA_CHANNEL_MESSAGE_CEILING,yt as DEFAULT_DOC_SYNC_TIMEOUT_MS,Tt as DEFAULT_GATEWAY_URL,Ut as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,Br as DEFAULT_REFERENCE_JPEG_QUALITY,$r as DEFAULT_REFERENCE_MAX_SIZE,jt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,B as DGRAM_HEADER_BYTES,cr as FOREGROUND_COALESCE_MS,H as FrameReassembler,qr as INPUT_PRESENCE_DEFAULT_HZ,Et as INPUT_PRESENCE_FIELD,U as InvalidDurationError,Te as LEGACY_ACTIVATION_HINT_PATH,_e as PLATFORM_DOC_NAME,de as PermanentLockedError,ce as PinRequiresActiveTempError,Lt as ProduceAckTimeoutError,oe as RecordingNotFoundError,L as RecordingsClient,R as RecordingsError,j as RecordingsUnauthorizedError,Z as RequestAbortError,ve as RequestCancelledError,he as RequestDocSyncError,Q as RequestError,fe as RequestTimeoutError,ae as RetainNotTempError,ie as RuntimeArtifactNotFoundError,I as RuntimeArtifactsClient,S as RuntimeArtifactsError,se as RuntimeArtifactsUnauthorizedError,Y as Session,we as SessionAllocationError,Ot as SessionEndError,F as SessionEndUnavailableError,Ft as SessionFailedError,ge as StreamDirectionConflict,K as TransportNegotiator,G as TransportSessionSignaling,ut as VISIBILITY_FIELD,Vr as WIRE_MESSAGE_BUDGET,mt as WT_CONTROL_FRAME_MAX,z as WebRtcSession,V as WebTransportSession,$ as WtControlDecoder,ot as activationHintFrom,Xr as cameraCaptureAvailable,Qr as captureStillFromVideo,Kt as computeBackoffDelay,Re as createActivityTracker,en as createCameraWarp,Pr as createClientToken,jr as createInputPresencePublisher,or as createRecordingsClient,Zt as createRuntimeArtifactsClient,xr as createStore,Nt as describeSessionFailure,$t as describeSessionPhase,Pe as encodeWtControlFrame,Be as fitWithin,ke as isDurationString,Ur as isPendingRecording,Gt as isRetryableSessionError,qt as isWakingPhase,Ie as mediaRecorderChunkSource,Yr as normalizeReferenceImage,sr as normalizeRetention,Ee as observePageLifecycle,Ce as observePageTeardown,xe as parseDgramHeader,zt as prewake,Jr as referenceImageErrorMessage,be as releaseSessionBeacon,Wt as sessionFailureFromMediaError,Wr as sharedCaptureController,Or as videoStream,ye as whenLive,pr as writeDgramHeader};
|