@urun-sh/core 0.2.11 → 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/dist/{chunk-4CEMGU66.mjs → chunk-ESLF63FX.mjs} +1 -1
- package/dist/{chunk-BSQZXFHN.mjs → chunk-SHMKV7WG.mjs} +1 -1
- package/dist/index.browser.d.mts +90 -4
- package/dist/index.browser.d.ts +90 -4
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +90 -4
- package/dist/index.d.ts +90 -4
- package/dist/index.js +5 -5
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.d.mts +1 -1
- package/dist/internal.browser.d.ts +1 -1
- package/dist/internal.browser.js +2 -2
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +1 -1
- package/dist/internal.mjs +1 -1
- package/dist/{stream-data-DWu57atL.d.mts → stream-data-GIyoXg7t.d.mts} +9 -9
- package/dist/{stream-data-DWu57atL.d.ts → stream-data-GIyoXg7t.d.ts} +9 -9
- 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 xe,B as Ie,C as Ee,D as Oe,a as Ae,b as N,c as B,d as ie,e as oe,f as ae,g as G,h as ce,i as Xe,j as Ye,k as Qe,l as T,m as Ze,n as et,o as ue,p as tt,q as K,s as z,t as Te,v as Pe,x as W,z as Ce}from"./chunk-BSQZXFHN.mjs";var rt="session-api.prod.cloud.urun.sh",nt=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function b(n){return n.trim().replace(/\/+$/,"")}function J(n,e){let t=[],r=s=>{if(!s)return;let i=b(s);i&&!t.includes(i)&&t.push(i)};r(n);for(let s of e??[])r(s);for(let s of yt(n))r(s);return t}function Me(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var st=120,it=1e3,ot=20,at=5,ct=500,Ue=1e4,ut=3;function dt(n){if(!n)return null;try{let e=new URL(n),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return b(`${e.origin}${t}`)}catch{return null}}async function De(n){let e=J(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s of e)try{return await lt(s,n,{pollAttempts:st,retryAfterLimitMs:r?it:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof P)throw t}throw t??new Error("[urun] session allocation failed")}async function lt(n,e,t){let r,s,i,o=n,a=0,l=new Set,d=Date.now()+t.pollAttempts*Ue;for(let g=0;g<t.pollAttempts;g++){s=i??await V(e),i=void 0;let h=Math.max(1,Math.min(ot,Math.floor((d-Date.now())/1e3))),c=!!r,p=Date.now(),f=r?await fetch(`${o}/api/session-requests/${encodeURIComponent(r)}?wait_s=${h}`,{headers:H(e,s),signal:wt((h+at)*1e3)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...H(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(pt(e))});if(!r&&(f.status===307||f.status===308)){let w=dt(f.headers.get("location"));if(w&&w!==o&&a<ut){a+=1,o=w;continue}throw new T(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:f.status})}let m=await de(f);if(f.ok&&(m.status==="allocated"||!m.status&&!!m.session_id)&&!!m.session_id){let w=m.session_id;if(!m.ws_url)throw new P(`[urun] gateway allocated session ${w} without ws_url`);if(!qe(m.ws_url))throw new P(`[urun] gateway allocated session ${w} with non-absolute ws_url`);return{baseUrl:o,sessionId:w,wsUrl:m.ws_url,endsAt:Me(m.ends_at),response:m}}if(f.status===202||m.status==="pending"||m.status==="queued"||m.queued){if(r=m.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(ft(m,r))}catch{}let w=Date.now()-p<ct;c&&w&&await ht(gt(f,m,t.retryAfterLimitMs));continue}if((f.status===401||f.status===403)&&e.getAccessToken){let w=s??"";l.add(w);let v=await V(e,{forceRefresh:!0,reason:"unauthorized"});if(v&&!l.has(v)){i=v,r=void 0;continue}}let k=m.error_message||m.error_code||`HTTP ${f.status}`;throw new T(`[urun] session allocation failed at ${o}: ${k}`,{httpStatus:f.status})}throw new T(`[urun] timed out waiting for session allocation at ${o}`)}function H(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function V(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function pt(n){return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey}}async function Le(n){let e=J(n.baseUrl,n.fallbackUrls),t=null;for(let r of e)try{let s={baseUrl:r,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},i=await V(s),o=await fetch(`${b(r)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:H(s,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${o.status}`);let a=await de(o);if(!a.ws_url||!qe(a.ws_url))throw new P(`[urun] viewer-connect returned no usable ws_url for ${n.sessionId}`);return{baseUrl:b(r),sessionId:n.sessionId,wsUrl:a.ws_url,endsAt:Me(a.ends_at),response:a}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof P)throw t}throw t??new Error("[urun] viewer-connect failed")}async function mt(n){try{let e=b(n.baseUrl),t=await V(n),r=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...H(n,t),"Content-Type":"application/json"},body:JSON.stringify({app:n.app,function:n.functionName})});if(r.status===404)return{status:"unknown-app"};if(!r.ok)return{status:"unavailable"};let s=await de(r),i={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(i.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(i.warmCapable=s.warm_capable),i}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function de(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function ft(n,e){let t={status:n.status==="queued"||n.queued?"queued":"pending",requestId:e};typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(t.queue={position:n.queue_position,depth:n.queue_depth});let r=n.runtime_state;return(r==="unavailable"||r==="starting"||r==="busy")&&(t.runtime={state:r},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(t.runtime.reason=n.runtime_reason)),t}function gt(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),i=t??Ue;return Number.isFinite(s)&&s>0?Math.min(s*1e3,i):1e3}function ht(n){return new Promise(e=>setTimeout(e,n))}function wt(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var P=class extends Error{};function qe(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function yt(n){try{return new URL(n).hostname!==rt?[]:nt}catch{return[]}}var _=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},X=class extends _{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Y=class extends _{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function D(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function _t(n){return new C(n)}var C=class{_options;constructor(e){this._options=e}async list(e){let r=$e(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new _("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(je)}async getDownloadUrl(e,t){let r=$e(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!St(s))throw new _("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:je(r.artifact),downloadUrl:s}}async _request(e,t){let r=J(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of r)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof _&&kt(s.status))throw s}throw s??new _("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${b(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:l}=await this._readError(o,e);throw bt(o.status,a,l)}try{return await o.json()}catch(a){throw new _(`[urun] runtime artifacts: invalid JSON response from ${b(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=b(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`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 je(n){if(!n||typeof n!="object")throw new _("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=R(e,"artifact_id")||R(e,"id"),r=R(e,"filename"),s=R(e,"kind"),i=R(e,"status")||"ready",o=vt(e,"size_bytes"),a=R(e,"sha256");if(!t||!r||!s||o==null||!a)throw new _("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:R(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:R(e,"created_at"),expiresAt:R(e,"expires_at")}}function R(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function vt(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function St(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function kt(n){return n===401||n===403}function bt(n,e,t){return n===401?new X(t,e):n===404?new Y(t,e):new _(t,n,e)}function $e(n){if(!n||typeof n!="object"||Array.isArray(n))throw new _("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var S=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)}},L=class extends S{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Q=class extends S{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Z=class extends S{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)}},ee=class extends S{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)}},te=class extends S{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)}},E=class extends S{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 le(n){return/^(\d+[smhdw])+$/.test(n)}function Rt(n){if(n==="pin")return{action:"pin"};if(le(n))return{action:"retain",duration:n};throw new E(`[urun] recordings: "${n}" is not a duration or "pin"`)}function At(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new L(r,e??"unauthorized");if(n===404)return new Q(r,e??"not_found");if(n===400)return new E(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new Z(r,e);case"pin_requires_active_temp":return new ee(r,e);case"permanent_locked":return new te(r,e)}return new S(r,{status:n,code:e??`http_${n}`})}var O=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(!le(t))throw new E(`[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 S("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,r.body))}if(!o.ok){let{code:a,message:l}=await this._readError(o);throw At(o.status,a,l)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let i={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}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 L("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Tt(n){return new O(n)}var Pt=250;function pe(n){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let r=Date.now();r-e<250||(e=r,n())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}var Fe="video/mp4";function me(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,i=!1,o=(a,l,d)=>{let g=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!g)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 g.isTypeSupported=="function"&&g.isTypeSupported(Fe)?Fe:void 0),c=new MediaStream([a]),p=new g(c,h?{mimeType:h}:void 0);r=p;let f=Promise.resolve();p.ondataavailable=m=>{let y=m.data;i||!y||y.size===0||(f=f.then(async()=>{let k=new Uint8Array(await y.arrayBuffer());i||l(k)}))},p.onstop=()=>{f.then(()=>{i||d()})},p.onerror=()=>{f.then(()=>{i||d()})},p.start(t)};return{start(a,l){if(r||i)return;let d=n.track();if(d){o(d,a,l);return}s=n.onTrack(g=>{!g||r||i||(s?.(),s=null,o(g,a,l))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Ct(n){let e=n;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=n.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Ne(n,e){let t=null,r=!1,s=!1,i=new ReadableStream({pull(o){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Ct(i)}var xt=new Set;function he(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var It="rpc",Ge=3e4,Et="rpc-resp";function Ot(n){return`${Et}:${n}`}function fe(){return Te()}function Mt(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function Ut(n,e,t,r,s,i,o,a,l,d){let g=[],h=null,c=!1,p=null,f=!1,m,y,k=new Promise((u,A)=>{m=u,y=A});k.catch(()=>{});let w=o(),v=null,M=null,U=null,j=null,$=!0,_e=()=>{U&&(clearTimeout(U),U=null),j&&(j(),j=null)},ve=!1,Se=()=>{ve||!f||(ve=!0,n.set({rpc:{[e]:null}}))},F=()=>{$=!1,_e(),v?.(),v=null,M?.(),M=null,a?.removeEventListener("abort",be),w.dispose(),Se()},se=()=>{if(h){if(g.length>0){let u=h;h=null,u.resolve({value:g.shift(),done:!1})}else if(p!==null){let u=h;h=null,u.reject(p)}else if(c){let u=h;h=null,u.resolve({value:void 0,done:!0})}}},He=u=>{c||(g.push(u),se())},x=u=>{c||(p=u,c=!0,y(u),F(),se())},ke=u=>{c||(c=!0,m(u),F(),se())},be=()=>{let u=a?.reason;x(u instanceof B?u:new G(e))},Ve=u=>{if(!(c||!u||typeof u!="object"))switch(Se(),u.t){case"delta":typeof u.delta=="string"&&He(u.delta);break;case"response":ke(u.body);break;case"error":{let{message:A,code:I}=Mt(u.body);x(new B(A,{requestId:e,code:u.code??I}));break}}},Je=()=>{let u=w.messages()[Symbol.asyncIterator]();v=()=>{u.return?.(void 0)};let A=()=>{$&&u.next().then(I=>{if($){if(I.done){c||ke(void 0);return}Ve(I.value),A()}},I=>{$&&x(I)})};A()},Re=()=>{if(!f){if(f=!0,a){if(a.aborted){x(new G(e));return}a.addEventListener("abort",be,{once:!0})}M=l?.(u=>x(u))??null,Je(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),d&&d>0&&!n.synced&&(U=setTimeout(()=>{U=null,!c&&!n.synced&&x(new oe(d,e))},d),j=n.onSynced(()=>_e()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Re(),g.length>0)return Promise.resolve({value:g.shift(),done:!1});if(p!==null){let u=p;return p=null,Promise.reject(u)}return c?Promise.resolve({value:void 0,done:!0}):new Promise((u,A)=>{h={resolve:u,reject:A}})},return(){return c||(c=!0,m(void 0),F()),Promise.resolve({value:void 0,done:!0})},throw(u){return c||(c=!0,y(u),F()),Promise.reject(u)}}}},body:k,start:Re}}function Be(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Dt(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let l=Be(i);l&&(a.rt=l);let d=Be(o);return d&&(a.br=d),a}var ge=class{constructor(e,t,r,s){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;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;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,i={push(a){if(!s)if(r){let l=r;r=null,l({value:a,done:!1})}else t.push(a)},end(){if(s=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{s=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return o(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._transport.subscribeStream(this._name),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._track}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Dt(t,this._name),s=r?.br;if(s?.by==="runtime")throw new ae(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}async attach(e){this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(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??me;return Ne(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._subscribed&&this._transport.unsubscribeStream(this._name),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},q=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Ie;_streamData;_presence=null;_activeRequests=new Set;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_lifecycleUnsub=null;constructor(e,t,r,s,i){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=Pe(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=pe(()=>this.recover())}_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 Le({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new N,o=new W({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,he(t),D({...t,baseUrl:r.baseUrl}));return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),K()&&await z(),a.setDocTransport({wsUrl:r.wsUrl,token:s}),await o.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)}whenLive(e){return ue(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 O(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new C(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new C(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)}stream(e){let t=this._streams.get(e);return t||(t=new ge(e,this._transport,this._streamData,()=>this.doc("control")),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Ee(e,this._sessionId,xt.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Oe(this.doc("control").awareness)),this._presence}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs(xe({serverUrl:Ce(e.wsUrl),sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket}))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=fe(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;i=setTimeout(()=>s.abort(new ie(a,r)),a)}let o=this._consumeResponse(r,e,!1,s.signal);return o.start(),o.body.finally(()=>{i&&clearTimeout(i)})}_consumeResponse(e,t,r,s,i){let o=this.doc(It),a=Ot(e);return Ut(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,l=>(this._activeRequests.add(l),()=>this._activeRequests.delete(l)),i??Ge)}requestStream(e,t={}){let r=fe();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=fe(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}disconnect(){this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._recoveryHooks.clear();let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new ce)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var Lt=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function qt(n,e){return new Proxy({},{get(t,r){if(!(Lt.has(r)||typeof r!="string"))return s=>{let i=s??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),l=new N,d=new W({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),g=new q(a,l,d,he(e),D(e)),h=async c=>{let p=await De({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:c,onAdmission:m=>d.reportAdmission(m)}),f=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return g.setSessionId(p.sessionId),g.setArtifactsAuth(D({...e,baseUrl:p.baseUrl})),d.setEndsAt(p.endsAt),{url:p.wsUrl,sessionId:p.sessionId,jwt:f,iceServers:p.response.ice_servers,endsAt:p.endsAt}};return d.setConnectionResolver(()=>h(o())),d.on("connected",()=>{d.multiplexer&&l.setTarget(d.multiplexer)}),(async()=>{let c;try{c=await h(a)}catch(p){console.error(`[urun] Failed to create session for ${r}:`,p);let f=p instanceof Error?p:new Error(String(p)),m=p instanceof T?p.httpStatus:void 0;d.reportAllocationFailure(f,m);return}d.setAuth({jwt:c.jwt,authProvider:e.authProvider,orgId:e.orgId}),d.setConnection({url:c.url,sessionId:c.sessionId,iceServers:c.iceServers}),K()&&await z(),g.setDocTransport({wsUrl:c.url,token:c.jwt}),await d.connect({app:n,functionName:r,args:i})})().catch(c=>{console.error(`[urun] Failed to connect session for ${r}:`,c)}),g}}})}var Ke=3e4,ze="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 s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${ze}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${ze}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${Ke}ms`)))},Ke);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function jt(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let i=new Ae(s);return new we(s,i)}var $t='video/mp4; codecs="avc1.42E01E"';function Ft(n,e){let t=e?.codec??$t,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);r.src=i,s.addEventListener("sourceopen",()=>{let c;try{c=s.addSourceBuffer(t)}catch(y){throw y instanceof DOMException&&y.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):y}let p=n.getReader();function f(){return c.updating?new Promise(y=>{c.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function m(){try{for(;;){let{done:y,value:k}=await p.read();if(y){await f(),s.readyState==="open"&&s.endOfStream();return}await f();try{c.appendBuffer(k)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let v=c.buffered;if(v.length>0){let M=v.start(v.length-1);c.remove(0,M),await f(),c.appendBuffer(k)}else throw w}else throw w}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}m()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let l=a.call(r),d=l.getTracks(),g=0,h=d.length;if(h===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let c of d)c.addEventListener("ended",()=>{g++,g>=h&&URL.revokeObjectURL(i)});return l}function Nt(n){return n.status.startsWith("pending_")}var re=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 We(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function Bt(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function Gt(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function ye(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var ne=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,ye(r,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new re;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(r)}catch(o){let a=`one-capture getUserMedia(${We(r)}) failed`,l=o instanceof Error?o.message:String(o);for(let d of[...this.claims.values()])if(this.claims.delete(d.kind),d.released=!0,d!==e){let g=new Error(`${a} \u2014 ${d.kind} capture lost: ${l||o}`);g.cause=o,ye(d,g)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=Bt(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let l=Object.assign(new Error(`one-capture getUserMedia(${We(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw l;ye(o,l);continue}if(o.track=a,o.stream=Gt(s,a),o!==e)for(let l of[...o.trackListeners])try{l(a,o.stream)}catch{}}}createState(e,t){let r=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await r.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(e)===s&&r.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},Kt=null;function zt(){return Kt??=new ne}export{qt as App,ne as CaptureController,re as CaptureUnavailableError,Ge as DEFAULT_DOC_SYNC_TIMEOUT_MS,et as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Pt as FOREGROUND_COALESCE_MS,E as InvalidDurationError,te as PermanentLockedError,ee as PinRequiresActiveTempError,Q as RecordingNotFoundError,O as RecordingsClient,S as RecordingsError,L as RecordingsUnauthorizedError,G as RequestAbortError,ce as RequestCancelledError,oe as RequestDocSyncError,B as RequestError,ie as RequestTimeoutError,Z as RetainNotTempError,Y as RuntimeArtifactNotFoundError,C as RuntimeArtifactsClient,_ as RuntimeArtifactsError,X as RuntimeArtifactsUnauthorizedError,q as Session,T as SessionAllocationError,Ye as SessionFailedError,ae as StreamDirectionConflict,Tt as createRecordingsClient,_t as createRuntimeArtifactsClient,jt as createStore,Xe as describeSessionFailure,tt as describeSessionPhase,le as isDurationString,Nt as isPendingRecording,Ze as isWakingPhase,me as mediaRecorderChunkSource,Rt as normalizeRetention,pe as observePageLifecycle,mt as prewake,Qe as sessionFailureFromMediaError,zt as sharedCaptureController,Ft as videoStream,ue as whenLive};
|
|
2
|
+
import{A as Ee,B as Me,C as Oe,D as Ue,a as Pe,b as F,c as B,d as ie,e as oe,f as ae,g as G,h as ce,i as et,j as tt,k as rt,l as T,m as nt,n as st,o as ue,p as it,q as K,s as z,t as Ce,v as Ie,x as V,z as xe}from"./chunk-SHMKV7WG.mjs";var ot="session-api.prod.cloud.urun.sh",at=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function b(r){return r.trim().replace(/\/+$/,"")}function Y(r,e){let t=[],n=s=>{if(!s)return;let i=b(s);i&&!t.includes(i)&&t.push(i)};n(r);for(let s of e??[])n(s);for(let s of kt(r))n(s);return t}function Le(r){if(typeof r!="string"||r.length===0)return null;let e=new Date(r);return Number.isFinite(e.getTime())?e:null}var ct=120,ut=1e3,dt=20,lt=5,pt=500,De=1e4,mt=3;function ft(r){if(!r)return null;try{let e=new URL(r),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return b(`${e.origin}${t}`)}catch{return null}}async function qe(r){let e=Y(r.baseUrl,r.fallbackUrls),t=null,n=e.length>1;for(let s of e)try{return await gt(s,r,{pollAttempts:ct,retryAfterLimitMs:n?ut:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof P)throw t}throw t??new Error("[urun] session allocation failed")}async function gt(r,e,t){let n,s,i,o=r,a=0,m=new Set,u=Date.now()+t.pollAttempts*De;for(let c=0;c<t.pollAttempts;c++){s=i??await W(e),i=void 0;let h=Math.max(1,Math.min(dt,Math.floor((u-Date.now())/1e3))),l=!!n,g=Date.now(),d=n?await fetch(`${o}/api/session-requests/${encodeURIComponent(n)}?wait_s=${h}`,{headers:H(e,s),signal:St((h+lt)*1e3)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...H(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(ht(e))});if(!n&&(d.status===307||d.status===308)){let y=ft(d.headers.get("location"));if(y&&y!==o&&a<mt){a+=1,o=y;continue}throw new T(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:d.status})}let p=await de(d);if(d.ok&&(p.status==="allocated"||!p.status&&!!p.session_id)&&!!p.session_id){let y=p.session_id;if(!p.ws_url)throw new P(`[urun] gateway allocated session ${y} without ws_url`);if(!Ne(p.ws_url))throw new P(`[urun] gateway allocated session ${y} with non-absolute ws_url`);return{baseUrl:o,sessionId:y,wsUrl:p.ws_url,endsAt:Le(p.ends_at),response:p}}if(d.status===202||p.status==="pending"||p.status==="queued"||p.queued){if(n=p.request_id||n,!n)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(yt(p,n))}catch{}let y=Date.now()-g<pt;l&&y&&await _t(vt(d,p,t.retryAfterLimitMs));continue}if((d.status===401||d.status===403)&&e.getAccessToken){let y=s??"";m.add(y);let S=await W(e,{forceRefresh:!0,reason:"unauthorized"});if(S&&!m.has(S)){i=S,n=void 0;continue}}let _=p.error_message||p.error_code||`HTTP ${d.status}`;throw new T(`[urun] session allocation failed at ${o}: ${_}`,{httpStatus:d.status})}throw new T(`[urun] timed out waiting for session allocation at ${o}`)}function H(r,e){let t={"X-Tenant-Id":r.orgId,"X-Auth-Provider":r.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function W(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function ht(r){return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey}}async function je(r){let e=Y(r.baseUrl,r.fallbackUrls),t=null;for(let n of e)try{let s={baseUrl:n,app:"",functionName:"",orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider,idempotencyKey:""},i=await W(s),o=await fetch(`${b(n)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,{headers:H(s,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${r.sessionId} failed: HTTP ${o.status}`);let a=await de(o);if(!a.ws_url||!Ne(a.ws_url))throw new P(`[urun] viewer-connect returned no usable ws_url for ${r.sessionId}`);return{baseUrl:b(n),sessionId:r.sessionId,wsUrl:a.ws_url,endsAt:Le(a.ends_at),response:a}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof P)throw t}throw t??new Error("[urun] viewer-connect failed")}async function wt(r){try{let e=b(r.baseUrl),t=await W(r),n=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...H(r,t),"Content-Type":"application/json"},body:JSON.stringify({app:r.app,function:r.functionName})});if(n.status===404)return{status:"unknown-app"};if(!n.ok)return{status:"unavailable"};let s=await de(n),i={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(i.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(i.warmCapable=s.warm_capable),i}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function de(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function yt(r,e){let t={status:r.status==="queued"||r.queued?"queued":"pending",requestId:e};typeof r.queue_position=="number"&&typeof r.queue_depth=="number"&&(t.queue={position:r.queue_position,depth:r.queue_depth});let n=r.runtime_state;return(n==="unavailable"||n==="starting"||n==="busy")&&(t.runtime={state:n},typeof r.runtime_reason=="string"&&r.runtime_reason.length>0&&(t.runtime.reason=r.runtime_reason)),t}function vt(r,e,t){let n=Number(r.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??n),i=t??De;return Number.isFinite(s)&&s>0?Math.min(s*1e3,i):1e3}function _t(r){return new Promise(e=>setTimeout(e,r))}function St(r){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(r):void 0}var P=class extends Error{};function Ne(r){try{let e=new URL(r);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function kt(r){try{return new URL(r).hostname!==ot?[]:at}catch{return[]}}var v=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},J=class extends v{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},X=class extends v{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function L(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function bt(r){return new C(r)}var C=class{_options;constructor(e){this._options=e}async list(e){let n=Fe(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new v("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map($e)}async getDownloadUrl(e,t){let n=Fe(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=n.download_url;if(typeof s!="string"||!Rt(s))throw new v("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:$e(n.artifact),downloadUrl:s}}async _request(e,t){let n=Y(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of n)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof v&&Tt(s.status))throw s}throw s??new v("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let s=`${b(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:m}=await this._readError(o,e);throw Pt(o.status,a,m)}try{return await o.json()}catch(a){throw new v(`[urun] runtime artifacts: invalid JSON response from ${b(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 n=b(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${n}: ${a}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function $e(r){if(!r||typeof r!="object")throw new v("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=A(e,"artifact_id")||A(e,"id"),n=A(e,"filename"),s=A(e,"kind"),i=A(e,"status")||"ready",o=At(e,"size_bytes"),a=A(e,"sha256");if(!t||!n||!s||o==null||!a)throw new v("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:n,contentType:A(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:A(e,"created_at"),expiresAt:A(e,"expires_at")}}function A(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function At(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function Rt(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function Tt(r){return r===401||r===403}function Pt(r,e,t){return r===401?new J(t,e):r===404?new X(t,e):new v(t,r,e)}function Fe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new v("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var k=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},D=class extends k{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Z=class extends k{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Q=class extends k{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},ee=class extends k{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},te=class extends k{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},E=class extends k{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function le(r){return/^(\d+[smhdw])+$/.test(r)}function Ct(r){if(r==="pin")return{action:"pin"};if(le(r))return{action:"retain",duration:r};throw new E(`[urun] recordings: "${r}" is not a duration or "pin"`)}function It(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new D(n,e??"unauthorized");if(r===404)return new Z(n,e??"not_found");if(r===400)return new E(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new Q(n,e);case"pin_requires_active_temp":return new ee(n,e);case"permanent_locked":return new te(n,e)}return new k(n,{status:r,code:e??`http_${r}`})}var M=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!le(t))throw new E(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new k("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let s=this._buildUrl(t,n.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,n.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,n.body))}if(!o.ok){let{code:a,message:m}=await this._readError(o);throw It(o.status,a,m)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(n+=`?${s}`),n}_fetch(e,t,n,s){let i={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}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 D("[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 n=(await e.json()).error;if(n&&typeof n=="object"){let{code:s,message:i}=n;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function xt(r){return new M(r)}var Be="activity",Et=15e3,pe=["pointerdown","pointermove","keydown","wheel","touchstart"];function me(r){let e=r.now??Date.now,t=r.windowTarget!==void 0?r.windowTarget:typeof window<"u"?window:null,n=r.documentTarget!==void 0?r.documentTarget:typeof document<"u"?document:null,s=!1,i,o=()=>{if(s)return;let c=e();if(!(i!==void 0&&c-i<15e3)){i=c;try{r.awareness.setLocalStateField(Be,{at:c})}catch{}}},a=()=>o(),m=()=>{(!n||n.visibilityState===void 0||n.visibilityState==="visible")&&o()};if(t)for(let c of pe)t.addEventListener(c,a,{passive:!0,capture:!0});n&&n.addEventListener("visibilitychange",m);let u=null;return r.isProducing&&(u=setInterval(()=>{if(!s)try{r.isProducing?.()&&o()}catch{}},15e3),u.unref?.()),o(),{touch:o,dispose(){if(!s){if(s=!0,t)for(let c of pe)t.removeEventListener(c,a,{capture:!0});n&&n.removeEventListener("visibilitychange",m),u&&(clearInterval(u),u=null)}}}}var Mt=250;function fe(r){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 n=Date.now();n-e<250||(e=n,r())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}var Ge="video/mp4";function ge(r,e={}){let t=e.timesliceMs??1e3,n=null,s=null,i=!1,o=(a,m,u)=>{let c=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!c)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let h=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(Ge)?Ge:void 0),l=new MediaStream([a]),g=new c(l,h?{mimeType:h}:void 0);n=g;let d=Promise.resolve();g.ondataavailable=p=>{let w=p.data;i||!w||w.size===0||(d=d.then(async()=>{let _=new Uint8Array(await w.arrayBuffer());i||m(_)}))},g.onstop=()=>{d.then(()=>{i||u()})},g.onerror=()=>{d.then(()=>{i||u()})},g.start(t)};return{start(a,m){if(n||i)return;let u=r.track();if(u){o(u,a,m);return}s=r.onTrack(c=>{!c||n||i||(s?.(),s=null,o(c,a,m))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Ot(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.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 Ke(r,e){let t=null,n=!1,s=!1,i=new ReadableStream({pull(o){n||(n=!0,t=r(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Ot(i)}var Ut=new Set;function ye(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var Lt="rpc",Ve=3e4,Dt="rpc-resp";function qt(r){return`${Dt}:${r}`}function he(){return Ce()}function jt(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function Nt(r,e,t,n,s,i,o,a,m,u){let c=[],h=null,l=!1,g=null,d=!1,p,w,_=new Promise((f,R)=>{p=f,w=R});_.catch(()=>{});let y=o(),S=null,O=null,U=null,j=null,N=!0,Se=()=>{U&&(clearTimeout(U),U=null),j&&(j(),j=null)},ke=!1,be=()=>{ke||!d||(ke=!0,r.set({rpc:{[e]:null}}))},$=()=>{N=!1,Se(),S?.(),S=null,O?.(),O=null,a?.removeEventListener("abort",Re),y.dispose(),be()},se=()=>{if(h){if(c.length>0){let f=h;h=null,f.resolve({value:c.shift(),done:!1})}else if(g!==null){let f=h;h=null,f.reject(g)}else if(l){let f=h;h=null,f.resolve({value:void 0,done:!0})}}},Xe=f=>{l||(c.push(f),se())},I=f=>{l||(g=f,l=!0,w(f),$(),se())},Ae=f=>{l||(l=!0,p(f),$(),se())},Re=()=>{let f=a?.reason;I(f instanceof B?f:new G(e))},Ze=f=>{if(!(l||!f||typeof f!="object"))switch(be(),f.t){case"delta":typeof f.delta=="string"&&Xe(f.delta);break;case"response":Ae(f.body);break;case"error":{let{message:R,code:x}=jt(f.body);I(new B(R,{requestId:e,code:f.code??x}));break}}},Qe=()=>{let f=y.messages()[Symbol.asyncIterator]();S=()=>{f.return?.(void 0)};let R=()=>{N&&f.next().then(x=>{if(N){if(x.done){l||Ae(void 0);return}Ze(x.value),R()}},x=>{N&&I(x)})};R()},Te=()=>{if(!d){if(d=!0,a){if(a.aborted){I(new G(e));return}a.addEventListener("abort",Re,{once:!0})}O=m?.(f=>I(f))??null,Qe(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:s,stream:i}}}),u&&u>0&&!r.synced&&(U=setTimeout(()=>{U=null,!l&&!r.synced&&I(new oe(u,e))},u),j=r.onSynced(()=>Se()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Te(),c.length>0)return Promise.resolve({value:c.shift(),done:!1});if(g!==null){let f=g;return g=null,Promise.reject(f)}return l?Promise.resolve({value:void 0,done:!0}):new Promise((f,R)=>{h={resolve:f,reject:R}})},return(){return l||(l=!0,p(void 0),$()),Promise.resolve({value:void 0,done:!0})},throw(f){return l||(l=!0,w(f),$()),Promise.reject(f)}}}},body:_,start:Te}}function ze(r){if(r&&typeof r=="object"){let{epoch:e,by:t}=r,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function $t(r,e){let n=r.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:s,rt:i,br:o}=n,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let m=ze(i);m&&(a.rt=m);let u=ze(o);return u&&(a.br=u),a}var we=class{constructor(e,t,n,s,i){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=s;this._onActivity=i;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=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],n=null,s=!1,i={push(a){if(!s)if(n){let m=n;n=null,m({value:a,done:!1})}else t.push(a)},end(){if(s=!0,n){let a=n;n=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{s=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{n=a})},return(){return o(),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._track}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=$t(t,this._name),s=n?.br;if(s?.by==="runtime")throw new ae(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};n?.rt&&(i.rt=n.rt);let o=n?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}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??ge;return Ke(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.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){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let t=this._handlers.get("track");if(t)for(let n of t)n(e)}},q=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Me;_streamData;_presence=null;_activity=null;_activeRequests=new Set;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_lifecycleUnsub=null;constructor(e,t,n,s,i){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=Ie(n),this._wireControlDocIncarnation(),this._lifecycleUnsub=fe(()=>this.recover()),this._activity=me({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0})}_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 n=await je({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new F,o=new V({url:n.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,i,o,ye(t),L({...t,baseUrl:n.baseUrl}));return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),o.setEndsAt(n.endsAt),K()&&await z(),a.setDocTransport({wsUrl:n.wsUrl,token:s}),await o.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)}whenLive(e){return ue(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 M(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,s)=>t.retain(n,s),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new C(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new C(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 n of this._docs.values())n.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new we(e,this._transport,this._streamData,()=>this.doc("control"),()=>this._activity?.touch()),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new Oe(e,this._sessionId,Ut.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ue(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs(Ee({serverUrl:xe(e.wsUrl),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 n=he(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;i=setTimeout(()=>s.abort(new ie(a,n)),a)}let o=this._consumeResponse(n,e,!1,s.signal);return o.start(),o.body.finally(()=>{i&&clearTimeout(i)})}_consumeResponse(e,t,n,s,i){this._activity?.touch();let o=this.doc(Lt),a=qt(e);return Nt(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),s,m=>(this._activeRequests.add(m),()=>this._activeRequests.delete(m)),i??Ve)}requestStream(e,t={}){let n=he();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=he(),s=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}disconnect(){this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._activity?.dispose(),this._activity=null,this._recoveryHooks.clear();let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new ce)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var Ft=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Bt(r,e){return new Proxy({},{get(t,n){if(!(Ft.has(n)||typeof n!="string"))return s=>{let i=s??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),m=new F,u=new V({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),c=new q(a,m,u,ye(e),L(e)),h=async l=>{let g=await qe({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:l,onAdmission:p=>u.reportAdmission(p)}),d=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return c.setSessionId(g.sessionId),c.setArtifactsAuth(L({...e,baseUrl:g.baseUrl})),u.setEndsAt(g.endsAt),{url:g.wsUrl,sessionId:g.sessionId,jwt:d,iceServers:g.response.ice_servers,endsAt:g.endsAt}};return u.setConnectionResolver(()=>h(o())),u.on("connected",()=>{u.multiplexer&&m.setTarget(u.multiplexer)}),(async()=>{let l;try{l=await h(a)}catch(g){console.error(`[urun] Failed to create session for ${n}:`,g);let d=g instanceof Error?g:new Error(String(g)),p=g instanceof T?g.httpStatus:void 0;u.reportAllocationFailure(d,p);return}u.setAuth({jwt:l.jwt,authProvider:e.authProvider,orgId:e.orgId}),u.setConnection({url:l.url,sessionId:l.sessionId,iceServers:l.iceServers}),K()&&await z(),c.setDocTransport({wsUrl:l.url,token:l.jwt}),await u.connect({app:r,functionName:n,args:i})})().catch(l=>{console.error(`[urun] Failed to connect session for ${n}:`,l)}),c}}})}var He=3e4,We="stream:",ve=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",n=>{let s;try{s=JSON.parse(typeof n.data=="string"?n.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let n=`${We}${e}`;return this._multiplexer.on(n,s=>{t(s)})}emit(e,t){let n=`${We}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(n,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((n,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${He}ms`)))},He);this._pendingRpc.set(i,{resolve:n,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function Gt(r){let n=`${r.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(r.orgId)}`,s=new WebSocket(n);(r.jwt||r.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:r.orgId,jwt:r.jwt,authProvider:r.authProvider,apiKey:r.apiKey}))});let i=new Pe(s);return new ve(s,i)}var Kt='video/mp4; codecs="avc1.42E01E"';function zt(r,e){let t=e?.codec??Kt,n=document.createElement("video");n.muted=!0,n.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);n.src=i,s.addEventListener("sourceopen",()=>{let l;try{l=s.addSourceBuffer(t)}catch(w){throw w instanceof DOMException&&w.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).`):w}let g=r.getReader();function d(){return l.updating?new Promise(w=>{l.addEventListener("updateend",()=>w(),{once:!0})}):Promise.resolve()}async function p(){try{for(;;){let{done:w,value:_}=await g.read();if(w){await d(),s.readyState==="open"&&s.endOfStream();return}await d();try{l.appendBuffer(_)}catch(y){if(y instanceof DOMException&&y.name==="QuotaExceededError"){let S=l.buffered;if(S.length>0){let O=S.start(S.length-1);l.remove(0,O),await d(),l.appendBuffer(_)}else throw y}else throw y}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}p()}),n.play().catch(()=>{});let o=n,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let m=a.call(n),u=m.getTracks(),c=0,h=u.length;if(h===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let l of u)l.addEventListener("ended",()=>{c++,c>=h&&URL.revokeObjectURL(i)});return m}function Vt(r){return r.status.startsWith("pending_")}var re=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 Ye(r){let e=[];return r.audio&&e.push("audio"),r.video&&e.push("video"),e.join("+")}function Ht(r,e){return e==="audio"?r.getAudioTracks():r.getVideoTracks()}function Wt(r,e){let t=r.getTracks();if(t.length===1&&t[0]===e)return r;try{return new MediaStream([e])}catch{return r}}function _e(r,e){for(let t of[...r.lostListeners])try{t(e)}catch{}}var ne=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let n=this.claims.get(e);n&&(this.claims.delete(e),n.released=!0,n.track=null,n.stream=null,_e(n,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new re;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),n={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(n)}catch(o){let a=`one-capture getUserMedia(${Ye(n)}) failed`,m=o instanceof Error?o.message:String(o);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let c=new Error(`${a} \u2014 ${u.kind} capture lost: ${m||o}`);c.cause=o,_e(u,c)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=Ht(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let m=Object.assign(new Error(`one-capture getUserMedia(${Ye(n)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw m;_e(o,m);continue}if(o.track=a,o.stream=Wt(s,a),o!==e)for(let m of[...o.trackListeners])try{m(a,o.stream)}catch{}}}createState(e,t){let n=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return n.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await n.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,n.claims.get(e)===s&&n.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},Yt=null;function Jt(){return Yt??=new ne}var Je="input",Xt=30;function Zt(r){let e=r.now??Date.now,t=r.field??Je,n=1e3/Math.max(r.hz??30,.001),s=new Set,i=0,o=0,a=0,m=0,u,c=null,h=!1,l=()=>{if(h)return;u=e(),m+=1;let d={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:m,at:u};try{r.awareness.setLocalStateField(t,d)}catch{}},g=()=>{if(h)return;let d=e();if(u===void 0||d-u>=n){c&&(clearTimeout(c),c=null),l();return}if(c)return;let p=Math.max(n-(d-u),0);c=setTimeout(()=>{c=null,l()},p),c.unref?.()};return{keyDown(d){let p=String(d).toLowerCase();s.has(p)||(s.add(p),g())},keyUp(d){let p=String(d).toLowerCase();s.delete(p)&&g()},setButtons(d){let p=Number.isFinite(d)?Number(d):0;p!==i&&(i=p,g())},movePointer(d,p){let w=Number.isFinite(d)?Number(d):0,_=Number.isFinite(p)?Number(p):0;w===0&&_===0||(o+=w,a+=_,g())},heldKeys(){return[...s]},clear(){h||(s.clear(),i=0,c&&(clearTimeout(c),c=null),l())},dispose(){if(h)return;let d=s.size>0||i!==0;s.clear(),i=0,c&&(clearTimeout(c),c=null),d&&l(),h=!0}}}export{pe as ACTIVITY_DOM_EVENTS,Be as ACTIVITY_FIELD,Et as ACTIVITY_STAMP_MIN_INTERVAL_MS,Bt as App,ne as CaptureController,re as CaptureUnavailableError,Ve as DEFAULT_DOC_SYNC_TIMEOUT_MS,st as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Mt as FOREGROUND_COALESCE_MS,Xt as INPUT_PRESENCE_DEFAULT_HZ,Je as INPUT_PRESENCE_FIELD,E as InvalidDurationError,te as PermanentLockedError,ee as PinRequiresActiveTempError,Z as RecordingNotFoundError,M as RecordingsClient,k as RecordingsError,D as RecordingsUnauthorizedError,G as RequestAbortError,ce as RequestCancelledError,oe as RequestDocSyncError,B as RequestError,ie as RequestTimeoutError,Q as RetainNotTempError,X as RuntimeArtifactNotFoundError,C as RuntimeArtifactsClient,v as RuntimeArtifactsError,J as RuntimeArtifactsUnauthorizedError,q as Session,T as SessionAllocationError,tt as SessionFailedError,ae as StreamDirectionConflict,me as createActivityTracker,Zt as createInputPresencePublisher,xt as createRecordingsClient,bt as createRuntimeArtifactsClient,Gt as createStore,et as describeSessionFailure,it as describeSessionPhase,le as isDurationString,Vt as isPendingRecording,nt as isWakingPhase,ge as mediaRecorderChunkSource,Ct as normalizeRetention,fe as observePageLifecycle,wt as prewake,rt as sessionFailureFromMediaError,Jt as sharedCaptureController,zt as videoStream,ue as whenLive};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DOC_SYNC_WIRE_CONTRACT_VERSION, h as DeferredChannelMultiplexer, i as DeferredDocConnector, j as DocConnection, k as DocConnector, n as LoopbackStreamData, I as SessionDocumentImpl, Q as SessionStartOptions, Z as StreamDataTransport, _ as TransportSession, $ as TransportSessionOptions, a1 as createPresence, a2 as createWebsocketDocConnector, a3 as deriveYjsServerUrl, a6 as streamDataLabel, a7 as transportStreamData } from './stream-data-
|
|
1
|
+
export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DOC_SYNC_WIRE_CONTRACT_VERSION, h as DeferredChannelMultiplexer, i as DeferredDocConnector, j as DocConnection, k as DocConnector, n as LoopbackStreamData, I as SessionDocumentImpl, Q as SessionStartOptions, Z as StreamDataTransport, _ as TransportSession, $ as TransportSessionOptions, a1 as createPresence, a2 as createWebsocketDocConnector, a3 as deriveYjsServerUrl, a6 as streamDataLabel, a7 as transportStreamData } from './stream-data-GIyoXg7t.mjs';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DOC_SYNC_WIRE_CONTRACT_VERSION, h as DeferredChannelMultiplexer, i as DeferredDocConnector, j as DocConnection, k as DocConnector, n as LoopbackStreamData, I as SessionDocumentImpl, Q as SessionStartOptions, Z as StreamDataTransport, _ as TransportSession, $ as TransportSessionOptions, a1 as createPresence, a2 as createWebsocketDocConnector, a3 as deriveYjsServerUrl, a6 as streamDataLabel, a7 as transportStreamData } from './stream-data-
|
|
1
|
+
export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DOC_SYNC_WIRE_CONTRACT_VERSION, h as DeferredChannelMultiplexer, i as DeferredDocConnector, j as DocConnection, k as DocConnector, n as LoopbackStreamData, I as SessionDocumentImpl, Q as SessionStartOptions, Z as StreamDataTransport, _ as TransportSession, $ as TransportSessionOptions, a1 as createPresence, a2 as createWebsocketDocConnector, a3 as deriveYjsServerUrl, a6 as streamDataLabel, a7 as transportStreamData } from './stream-data-GIyoXg7t.js';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|