@urun-sh/core 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{a as be,b as H,c as J,e as X,f as ve,h as ke,j as Y,k as Re,l as Ae,m as Pe,n as Te,o as Ie}from"./chunk-47GHXEPH.mjs";var _=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},j=class extends _{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},L=class extends _{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},F=class extends Error{stream;owner;attempted;constructor(e,t,n){super(`[urun] stream "${e}" is already produced by the ${t}; this (${n}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=n,Object.setPrototypeOf(this,new.target.prototype)}},U=class extends _{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},N=class extends _{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};function xe(r,e){let t=e.error?.reason,n=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(r){case"create-failed":return{message:`[urun] session create failed${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""}${t?`: ${t}`:""}`,hint:e.error?.httpStatus===401||e.error?.httpStatus===403?"The backend rejected this client \u2014 sign in again or check the auth token / org access.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."};case"never-live":{let s=n!==void 0?` after ${n}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`;return e.error?.code==="expired"?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${s} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?{message:`[urun] session ${e.sessionId} was created but never went live${s}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${s} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${t?`: ${t}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${t?`: ${t}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"ended":return{message:`[urun] session ended before going live${e.sessionId?` (id ${e.sessionId})`:""}`,hint:"The session was closed (server-side, or superseded by another connection). Start a new session."}}}var b=class extends Error{kind;status;hint;constructor(e,t,n){let{message:s,hint:i}=xe(e,t);super(s),this.name="SessionFailedError",this.kind=e,this.status=t,this.hint=i,n?.cause!==void 0&&(this.cause=n.cause),Object.setPrototypeOf(this,new.target.prototype)}};function Ge(r,e){if(r instanceof b)return r;let t=r instanceof Error?r:new Error(String(r)),n={phase:e?.phase??"idle",transportState:e?.transportState??"disconnected",...e,error:{reason:t.message,code:t.name,kind:"media-permission"}};return new b("media-permission",n,{cause:r})}var v=class extends Error{httpStatus;constructor(e,t){super(e),this.name="SessionAllocationError",this.httpStatus=t?.httpStatus,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}};var Ce=45e3;function oe(r,e={}){let{timeout:t=Ce,signal:n}=e;return new Promise((s,i)=>{if(n?.aborted){i(n.reason instanceof Error?n.reason:new Error("whenLive aborted"));return}if(r.phase?.name==="live"){s();return}if(r.phase?.name==="error"||r.phase?.name==="ended"){let c=r.phase,h=r.status??{phase:c.name,transportState:"disconnected",sessionId:c.sessionId,requestId:c.requestId,queue:c.queue,error:c.error};i(new b(c.name==="ended"?"ended":c.error?.kind??"transport-failed",h));return}let o,a,f=!1,m=c=>{f||(f=!0,a!==void 0&&clearTimeout(a),n?.removeEventListener("abort",p),o?.(),c?i(c):s())},p=()=>{m(n?.reason instanceof Error?n.reason:new Error("whenLive aborted"))};n?.addEventListener("abort",p,{once:!0});let d=()=>{let c=r.phase;return r.status??{phase:c?.name??"idle",transportState:"disconnected",sessionId:c?.sessionId,requestId:c?.requestId,queue:c?.queue,error:c?.error}},u=c=>m(new b(c,d()));t>0&&(a=setTimeout(()=>{let c=d();c.elapsedMs===void 0&&(c.elapsedMs=t),m(new b("never-live",c))},t)),o=r.onPhase(c=>{c?.name==="live"?m():c?.name==="error"?u(c.error?.kind??"transport-failed"):c?.name==="ended"&&u("ended")}),f&&o()})}function Ve(r){switch(r.name){case"idle":return"Initializing\u2026";case"unavailable":return r.runtime?.reason?`Runtime unavailable \u2014 ${r.runtime.reason}`:"Runtime unavailable";case"queued":return r.queue?`Waiting in queue (position ${r.queue.position} of ${r.queue.depth})\u2026`:r.runtime?.state==="busy"?"All runtimes are busy \u2014 waiting for capacity\u2026":"Waiting for capacity\u2026";case"provisioning":return r.runtime?.state==="starting"?"Starting model\u2026":"Provisioning\u2026";case"connecting":return"Connecting\u2026";case"live":return"Live";case"error":return r.error?.reason?`Session failed \u2014 ${r.error.reason}`:"Session failed";case"ended":return"Session ended"}}var He="session-api.prod.cloud.urun.sh",Je=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function A(r){return r.trim().replace(/\/+$/,"")}function Q(r,e){let t=[],n=s=>{if(!s)return;let i=A(s);i&&!t.includes(i)&&t.push(i)};n(r);for(let s of e??[])n(s);for(let s of it(r))n(s);return t}var Xe=120,Ye=1e3,Qe=3;function Ze(r){if(!r)return null;try{let e=new URL(r),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return A(`${e.origin}${t}`)}catch{return null}}async function Oe(r){let e=Q(r.baseUrl,r.fallbackUrls),t=null,n=e.length>1;for(let s of e)try{return await et(s,r,{pollAttempts:Xe,retryAfterLimitMs:n?Ye:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof x)throw t}throw t??new Error("[urun] session allocation failed")}async function et(r,e,t){let n,s,i,o=r,a=0,f=new Set;for(let m=0;m<t.pollAttempts;m++){s=i??await ce(e),i=void 0;let p=n?await fetch(`${o}/api/session-requests/${encodeURIComponent(n)}`,{headers:ae(e,s)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...ae(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(tt(e))});if(!n&&(p.status===307||p.status===308)){let h=Ze(p.headers.get("location"));if(h&&h!==o&&a<Qe){a+=1,o=h;continue}throw new v(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:p.status})}let d=await Ue(p);if(p.ok&&(d.status==="allocated"||!d.status&&!!d.session_id)&&!!d.session_id){let h=d.session_id;if(!d.ws_url)throw new x(`[urun] gateway allocated session ${h} without ws_url`);if(!qe(d.ws_url))throw new x(`[urun] gateway allocated session ${h} with non-absolute ws_url`);return{baseUrl:o,sessionId:h,wsUrl:d.ws_url,response:d}}if(p.status===202||d.status==="pending"||d.status==="queued"||d.queued){if(n=d.request_id||n,!n)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(rt(d,n))}catch{}await st(nt(p,d,t.retryAfterLimitMs));continue}if((p.status===401||p.status===403)&&e.getAccessToken){let h=s??"";f.add(h);let w=await ce(e,{forceRefresh:!0,reason:"unauthorized"});if(w&&!f.has(w)){i=w,n=void 0;continue}}let c=d.error_message||d.error_code||`HTTP ${p.status}`;throw new v(`[urun] session allocation failed at ${o}: ${c}`,{httpStatus:p.status})}throw new v(`[urun] timed out waiting for session allocation at ${o}`)}function ae(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 ce(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function tt(r){return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey}}async function Ee(r){let e=Q(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 ce(s),o=await fetch(`${A(n)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,{headers:ae(s,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${r.sessionId} failed: HTTP ${o.status}`);let a=await Ue(o);if(!a.ws_url||!qe(a.ws_url))throw new x(`[urun] viewer-connect returned no usable ws_url for ${r.sessionId}`);return{baseUrl:A(n),sessionId:r.sessionId,wsUrl:a.ws_url,response:a}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof x)throw t}throw t??new Error("[urun] viewer-connect failed")}async function Ue(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function rt(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 nt(r,e,t){let n=Number(r.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??n),i=t??1e4;return Number.isFinite(s)&&s>0?Math.min(s*1e3,i):1e3}function st(r){return new Promise(e=>setTimeout(e,r))}var x=class extends Error{};function qe(r){try{let e=new URL(r);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function it(r){try{return new URL(r).hostname!==He?[]:Je}catch{return[]}}var y=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)}},Z=class extends y{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},ee=class extends y{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function B(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function ot(r){return new C(r)}var C=class{_options;constructor(e){this._options=e}async list(e){let n=$e(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new y("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(Me)}async getDownloadUrl(e,t){let n=$e(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=n.download_url;if(typeof s!="string"||!ct(s))throw new y("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Me(n.artifact),downloadUrl:s}}async _request(e,t){let n=Q(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 y&&ut(s.status))throw s}throw s??new y("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let s=`${A(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:f}=await this._readError(o,e);throw dt(o.status,a,f)}try{return await o.json()}catch(a){throw new y(`[urun] runtime artifacts: invalid JSON response from ${A(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=A(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 Me(r){if(!r||typeof r!="object")throw new y("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=k(e,"artifact_id")||k(e,"id"),n=k(e,"filename"),s=k(e,"kind"),i=k(e,"status")||"ready",o=at(e,"size_bytes"),a=k(e,"sha256");if(!t||!n||!s||o==null||!a)throw new y("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:n,contentType:k(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:k(e,"created_at"),expiresAt:k(e,"expires_at")}}function k(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 ct(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function ut(r){return r===401||r===403}function dt(r,e,t){return r===401?new Z(t,e):r===404?new ee(t,e):new y(t,r,e)}function $e(r){if(!r||typeof r!="object"||Array.isArray(r))throw new y("[urun] runtime artifacts: malformed response",0,"bad_response");return r}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)}},z=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)}},te=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)}},re=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)}},ne=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)}},se=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)}},q=class extends S{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 ue(r){return/^(\d+[smhdw])+$/.test(r)}function lt(r){if(r==="pin")return{action:"pin"};if(ue(r))return{action:"retain",duration:r};throw new q(`[urun] recordings: "${r}" is not a duration or "pin"`)}function pt(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new z(n,e??"unauthorized");if(r===404)return new te(n,e??"not_found");if(r===400)return new q(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new re(n,e);case"pin_requires_active_temp":return new ne(n,e);case"permanent_locked":return new se(n,e)}return new S(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(!ue(t))throw new q(`[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,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:f}=await this._readError(o);throw pt(o.status,a,f)}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 z("[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 mt(r){return new M(r)}var De="video/mp4";function de(r,e={}){let t=e.timesliceMs??1e3,n=null,s=null,i=!1,o=(a,f,m)=>{let p=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!p)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 d=e.mimeType??(typeof p.isTypeSupported=="function"&&p.isTypeSupported(De)?De:void 0),u=new MediaStream([a]),c=new p(u,d?{mimeType:d}:void 0);n=c;let h=Promise.resolve();c.ondataavailable=w=>{let g=w.data;i||!g||g.size===0||(h=h.then(async()=>{let P=new Uint8Array(await g.arrayBuffer());i||f(P)}))},c.onstop=()=>{h.then(()=>{i||m()})},c.onerror=()=>{h.then(()=>{i||m()})},c.start(t)};return{start(a,f){if(n||i)return;let m=r.track();if(m){o(m,a,f);return}s=r.onTrack(p=>{!p||n||i||(s?.(),s=null,o(p,a,f))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function ft(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 je(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 ft(i)}var ht=new Set;function me(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var gt="rpc",Fe=3e4,wt="rpc-resp";function yt(r){return`${wt}:${r}`}function le(){return ve()}function St(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 _t(r,e,t,n,s,i,o,a,f,m){let p=[],d=null,u=!1,c=null,h=!1,w,g,P=new Promise((l,R)=>{w=l,g=R});P.catch(()=>{});let T=o(),I=null,$=null,D=null,W=null,G=!0,he=()=>{D&&(clearTimeout(D),D=null),W&&(W(),W=null)},ge=!1,we=()=>{ge||!h||(ge=!0,r.set({rpc:{[e]:null}}))},V=()=>{G=!1,he(),I?.(),I=null,$?.(),$=null,a?.removeEventListener("abort",Se),T.dispose(),we()},ie=()=>{if(d){if(p.length>0){let l=d;d=null,l.resolve({value:p.shift(),done:!1})}else if(c!==null){let l=d;d=null,l.reject(c)}else if(u){let l=d;d=null,l.resolve({value:void 0,done:!0})}}},ze=l=>{u||(p.push(l),ie())},O=l=>{u||(c=l,u=!0,g(l),V(),ie())},ye=l=>{u||(u=!0,w(l),V(),ie())},Se=()=>{let l=a?.reason;O(l instanceof _?l:new U(e))},Ke=l=>{if(!(u||!l||typeof l!="object"))switch(we(),l.t){case"delta":typeof l.delta=="string"&&ze(l.delta);break;case"response":ye(l.body);break;case"error":{let{message:R,code:E}=St(l.body);O(new _(R,{requestId:e,code:l.code??E}));break}}},We=()=>{let l=T.messages()[Symbol.asyncIterator]();I=()=>{l.return?.(void 0)};let R=()=>{G&&l.next().then(E=>{if(G){if(E.done){u||ye(void 0);return}Ke(E.value),R()}},E=>{G&&O(E)})};R()},_e=()=>{if(!h){if(h=!0,a){if(a.aborted){O(new U(e));return}a.addEventListener("abort",Se,{once:!0})}$=f?.(l=>O(l))??null,We(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:s,stream:i}}}),m&&m>0&&!r.synced&&(D=setTimeout(()=>{D=null,!u&&!r.synced&&O(new L(m,e))},m),W=r.onSynced(()=>he()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(_e(),p.length>0)return Promise.resolve({value:p.shift(),done:!1});if(c!==null){let l=c;return c=null,Promise.reject(l)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((l,R)=>{d={resolve:l,reject:R}})},return(){return u||(u=!0,w(void 0),V()),Promise.resolve({value:void 0,done:!0})},throw(l){return u||(u=!0,g(l),V()),Promise.reject(l)}}}},body:P,start:_e}}function Le(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 bt(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 f=Le(i);f&&(a.rt=f);let m=Le(o);return m&&(a.br=m),a}var pe=class{constructor(e,t,n,s){this._name=e;this._transport=t;this._streamData=n;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],n=null,s=!1,i={push(a){if(!s)if(n){let f=n;n=null,f({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._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(),n=bt(t,this._name),s=n?.br;if(s?.by==="runtime")throw new F(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._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??de;return je(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._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 n of t)n(e)}},K=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Pe;_streamData;_presence=null;_activeRequests=new Set;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;constructor(e,t,n,s,i){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=ke(n),this._wireControlDocIncarnation()}_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 Ee({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 H,o=new Y({url:n.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,i,o,me(t),B({...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}),J()&&await X(),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 status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}whenLive(e){return oe(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 pe(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 Te(e,this._sessionId,ht.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ie(this.doc("control").awareness)),this._presence}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs(Ae({serverUrl:Re(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=le(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;i=setTimeout(()=>s.abort(new j(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){let o=this.doc(gt),a=yt(e);return _t(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),s,f=>(this._activeRequests.add(f),()=>this._activeRequests.delete(f)),i??Fe)}requestStream(e,t={}){let n=le();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=le(),s=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new N)}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 vt=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function kt(r,e){return new Proxy({},{get(t,n){if(!(vt.has(n)||typeof n!="string"))return s=>{let i=s??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),f=new H,m=new Y({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),p=new K(a,f,m,me(e),B(e)),d=async u=>{let c=await Oe({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:u,onAdmission:w=>m.reportAdmission(w)}),h=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return p.setSessionId(c.sessionId),p.setArtifactsAuth(B({...e,baseUrl:c.baseUrl})),{url:c.wsUrl,sessionId:c.sessionId,jwt:h,iceServers:c.response.ice_servers}};return m.setConnectionResolver(()=>d(o())),m.on("connected",()=>{m.multiplexer&&f.setTarget(m.multiplexer)}),(async()=>{let u;try{u=await d(a)}catch(c){console.error(`[urun] Failed to create session for ${n}:`,c);let h=c instanceof Error?c:new Error(String(c)),w=c instanceof v?c.httpStatus:void 0;m.reportAllocationFailure(h,w);return}m.setAuth({jwt:u.jwt,authProvider:e.authProvider,orgId:e.orgId}),m.setConnection({url:u.url,sessionId:u.sessionId,iceServers:u.iceServers}),J()&&await X(),p.setDocTransport({wsUrl:u.url,token:u.jwt}),await m.connect({app:r,functionName:n,args:i})})().catch(u=>{console.error(`[urun] Failed to connect session for ${n}:`,u)}),p}}})}var Ne=3e4,Be="stream:",fe=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=`${Be}${e}`;return this._multiplexer.on(n,s=>{t(s)})}emit(e,t){let n=`${Be}${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 ${Ne}ms`)))},Ne);this._pendingRpc.set(i,{resolve:n,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function Rt(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 be(s);return new fe(s,i)}var At='video/mp4; codecs="avc1.42E01E"';function Pt(r,e){let t=e?.codec??At,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 u;try{u=s.addSourceBuffer(t)}catch(g){throw g instanceof DOMException&&g.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).`):g}let c=r.getReader();function h(){return u.updating?new Promise(g=>{u.addEventListener("updateend",()=>g(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:g,value:P}=await c.read();if(g){await h(),s.readyState==="open"&&s.endOfStream();return}await h();try{u.appendBuffer(P)}catch(T){if(T instanceof DOMException&&T.name==="QuotaExceededError"){let I=u.buffered;if(I.length>0){let $=I.start(I.length-1);u.remove(0,$),await h(),u.appendBuffer(P)}else throw T}else throw T}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}w()}),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 f=a.call(n),m=f.getTracks(),p=0,d=m.length;if(d===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let u of m)u.addEventListener("ended",()=>{p++,p>=d&&URL.revokeObjectURL(i)});return f}function Tt(r){return r.status.startsWith("pending_")}export{kt as App,Fe as DEFAULT_DOC_SYNC_TIMEOUT_MS,Ce as DEFAULT_WHEN_LIVE_TIMEOUT_MS,q as InvalidDurationError,se as PermanentLockedError,ne as PinRequiresActiveTempError,te as RecordingNotFoundError,M as RecordingsClient,S as RecordingsError,z as RecordingsUnauthorizedError,U as RequestAbortError,N as RequestCancelledError,L as RequestDocSyncError,_ as RequestError,j as RequestTimeoutError,re as RetainNotTempError,ee as RuntimeArtifactNotFoundError,C as RuntimeArtifactsClient,y as RuntimeArtifactsError,Z as RuntimeArtifactsUnauthorizedError,K as Session,v as SessionAllocationError,b as SessionFailedError,F as StreamDirectionConflict,mt as createRecordingsClient,ot as createRuntimeArtifactsClient,Rt as createStore,xe as describeSessionFailure,Ve as describeSessionPhase,ue as isDurationString,Tt as isPendingRecording,de as mediaRecorderChunkSource,lt as normalizeRetention,Ge as sessionFailureFromMediaError,Pt as videoStream,oe as whenLive};
1
+ import{A as Ae,B as Te,C as Pe,D as Ie,a as Se,b as B,c as N,d as te,e as re,f as ne,g as z,h as se,i as Ke,j as Ge,k as We,l as T,m as He,n as Ve,o as ie,p as Je,q as K,s as G,t as be,v as ke,x as W,z as Re}from"./chunk-MDOFFR4J.mjs";var Xe="session-api.prod.cloud.urun.sh",Ye=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function b(n){return n.trim().replace(/\/+$/,"")}function H(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 at(n))r(s);return t}var Qe=120,Ze=1e3,et=3;function tt(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 Ce(n){let e=H(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s of e)try{return await rt(s,n,{pollAttempts:Qe,retryAfterLimitMs:r?Ze: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 rt(n,e,t){let r,s,i,o=n,a=0,f=new Set;for(let p=0;p<t.pollAttempts;p++){s=i??await ae(e),i=void 0;let l=r?await fetch(`${o}/api/session-requests/${encodeURIComponent(r)}`,{headers:oe(e,s)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...oe(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(nt(e))});if(!r&&(l.status===307||l.status===308)){let g=tt(l.headers.get("location"));if(g&&g!==o&&a<et){a+=1,o=g;continue}throw new T(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:l.status})}let d=await Ee(l);if(l.ok&&(d.status==="allocated"||!d.status&&!!d.session_id)&&!!d.session_id){let g=d.session_id;if(!d.ws_url)throw new P(`[urun] gateway allocated session ${g} without ws_url`);if(!Oe(d.ws_url))throw new P(`[urun] gateway allocated session ${g} with non-absolute ws_url`);return{baseUrl:o,sessionId:g,wsUrl:d.ws_url,response:d}}if(l.status===202||d.status==="pending"||d.status==="queued"||d.queued){if(r=d.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(st(d,r))}catch{}await ot(it(l,d,t.retryAfterLimitMs));continue}if((l.status===401||l.status===403)&&e.getAccessToken){let g=s??"";f.add(g);let w=await ae(e,{forceRefresh:!0,reason:"unauthorized"});if(w&&!f.has(w)){i=w,r=void 0;continue}}let m=d.error_message||d.error_code||`HTTP ${l.status}`;throw new T(`[urun] session allocation failed at ${o}: ${m}`,{httpStatus:l.status})}throw new T(`[urun] timed out waiting for session allocation at ${o}`)}function oe(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 ae(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function nt(n){return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey}}async function xe(n){let e=H(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 ae(s),o=await fetch(`${b(r)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:oe(s,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${o.status}`);let a=await Ee(o);if(!a.ws_url||!Oe(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,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 Ee(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function st(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 it(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),i=t??1e4;return Number.isFinite(s)&&s>0?Math.min(s*1e3,i):1e3}function ot(n){return new Promise(e=>setTimeout(e,n))}var P=class extends Error{};function Oe(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function at(n){try{return new URL(n).hostname!==Xe?[]:Ye}catch{return[]}}var y=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)}},V=class extends y{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},J=class extends y{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(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function ct(n){return new I(n)}var I=class{_options;constructor(e){this._options=e}async list(e){let r=Me(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new y("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Ue)}async getDownloadUrl(e,t){let r=Me(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!dt(s))throw new y("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Ue(r.artifact),downloadUrl:s}}async _request(e,t){let r=H(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 y&&lt(s.status))throw s}throw s??new y("[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:f}=await this._readError(o,e);throw pt(o.status,a,f)}try{return await o.json()}catch(a){throw new y(`[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 Ue(n){if(!n||typeof n!="object")throw new y("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=v(e,"artifact_id")||v(e,"id"),r=v(e,"filename"),s=v(e,"kind"),i=v(e,"status")||"ready",o=ut(e,"size_bytes"),a=v(e,"sha256");if(!t||!r||!s||o==null||!a)throw new y("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:v(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:v(e,"created_at"),expiresAt:v(e,"expires_at")}}function v(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function ut(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function dt(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function lt(n){return n===401||n===403}function pt(n,e,t){return n===401?new V(t,e):n===404?new J(t,e):new y(t,n,e)}function Me(n){if(!n||typeof n!="object"||Array.isArray(n))throw new y("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var _=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 _{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},X=class extends _{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Y=class extends _{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)}},Q=class extends _{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)}},Z=class extends _{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 _{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function ce(n){return/^(\d+[smhdw])+$/.test(n)}function mt(n){if(n==="pin")return{action:"pin"};if(ce(n))return{action:"retain",duration:n};throw new E(`[urun] recordings: "${n}" is not a duration or "pin"`)}function ft(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new D(r,e??"unauthorized");if(n===404)return new X(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 Y(r,e);case"pin_requires_active_temp":return new Q(r,e);case"permanent_locked":return new Z(r,e)}return new _(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(!ce(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 _("[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:f}=await this._readError(o);throw ft(o.status,a,f)}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 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 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 gt(n){return new O(n)}var ht=250;function ue(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 qe="video/mp4";function de(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,i=!1,o=(a,f,p)=>{let l=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!l)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 d=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(qe)?qe:void 0),c=new MediaStream([a]),m=new l(c,d?{mimeType:d}:void 0);r=m;let g=Promise.resolve();m.ondataavailable=w=>{let h=w.data;i||!h||h.size===0||(g=g.then(async()=>{let k=new Uint8Array(await h.arrayBuffer());i||f(k)}))},m.onstop=()=>{g.then(()=>{i||p()})},m.onerror=()=>{g.then(()=>{i||p()})},m.start(t)};return{start(a,f){if(r||i)return;let p=n.track();if(p){o(p,a,f);return}s=n.onTrack(l=>{!l||r||i||(s?.(),s=null,o(l,a,f))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function wt(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 De(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 wt(i)}var yt=new Set;function me(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var _t="rpc",je=3e4,vt="rpc-resp";function St(n){return`${vt}:${n}`}function le(){return be()}function bt(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 kt(n,e,t,r,s,i,o,a,f,p){let l=[],d=null,c=!1,m=null,g=!1,w,h,k=new Promise((u,S)=>{w=u,h=S});k.catch(()=>{});let R=o(),A=null,U=null,M=null,j=null,$=!0,ge=()=>{M&&(clearTimeout(M),M=null),j&&(j(),j=null)},he=!1,we=()=>{he||!g||(he=!0,n.set({rpc:{[e]:null}}))},F=()=>{$=!1,ge(),A?.(),A=null,U?.(),U=null,a?.removeEventListener("abort",_e),R.dispose(),we()},ee=()=>{if(d){if(l.length>0){let u=d;d=null,u.resolve({value:l.shift(),done:!1})}else if(m!==null){let u=d;d=null,u.reject(m)}else if(c){let u=d;d=null,u.resolve({value:void 0,done:!0})}}},Be=u=>{c||(l.push(u),ee())},C=u=>{c||(m=u,c=!0,h(u),F(),ee())},ye=u=>{c||(c=!0,w(u),F(),ee())},_e=()=>{let u=a?.reason;C(u instanceof N?u:new z(e))},Ne=u=>{if(!(c||!u||typeof u!="object"))switch(we(),u.t){case"delta":typeof u.delta=="string"&&Be(u.delta);break;case"response":ye(u.body);break;case"error":{let{message:S,code:x}=bt(u.body);C(new N(S,{requestId:e,code:u.code??x}));break}}},ze=()=>{let u=R.messages()[Symbol.asyncIterator]();A=()=>{u.return?.(void 0)};let S=()=>{$&&u.next().then(x=>{if($){if(x.done){c||ye(void 0);return}Ne(x.value),S()}},x=>{$&&C(x)})};S()},ve=()=>{if(!g){if(g=!0,a){if(a.aborted){C(new z(e));return}a.addEventListener("abort",_e,{once:!0})}U=f?.(u=>C(u))??null,ze(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),p&&p>0&&!n.synced&&(M=setTimeout(()=>{M=null,!c&&!n.synced&&C(new re(p,e))},p),j=n.onSynced(()=>ge()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(ve(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(m!==null){let u=m;return m=null,Promise.reject(u)}return c?Promise.resolve({value:void 0,done:!0}):new Promise((u,S)=>{d={resolve:u,reject:S}})},return(){return c||(c=!0,w(void 0),F()),Promise.resolve({value:void 0,done:!0})},throw(u){return c||(c=!0,h(u),F()),Promise.reject(u)}}}},body:k,start:ve}}function Le(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 Rt(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 f=Le(i);f&&(a.rt=f);let p=Le(o);return p&&(a.br=p),a}var pe=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 f=r;r=null,f({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=Rt(t,this._name),s=r?.br;if(s?.by==="runtime")throw new ne(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??de;return De(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)}},L=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Te;_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=ke(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=ue(()=>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 xe({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 B,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,me(t),q({...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}),K()&&await G(),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 status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}whenLive(e){return ie(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 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)}stream(e){let t=this._streams.get(e);return t||(t=new pe(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 Pe(e,this._sessionId,yt.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ie(this.doc("control").awareness)),this._presence}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs(Ae({serverUrl:Re(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=le(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;i=setTimeout(()=>s.abort(new te(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(_t),a=St(e);return kt(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,f=>(this._activeRequests.add(f),()=>this._activeRequests.delete(f)),i??je)}requestStream(e,t={}){let r=le();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=le(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}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 se)}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 At=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Tt(n,e){return new Proxy({},{get(t,r){if(!(At.has(r)||typeof r!="string"))return s=>{let i=s??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),f=new B,p=new W({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),l=new L(a,f,p,me(e),q(e)),d=async c=>{let m=await Ce({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:w=>p.reportAdmission(w)}),g=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return l.setSessionId(m.sessionId),l.setArtifactsAuth(q({...e,baseUrl:m.baseUrl})),{url:m.wsUrl,sessionId:m.sessionId,jwt:g,iceServers:m.response.ice_servers}};return p.setConnectionResolver(()=>d(o())),p.on("connected",()=>{p.multiplexer&&f.setTarget(p.multiplexer)}),(async()=>{let c;try{c=await d(a)}catch(m){console.error(`[urun] Failed to create session for ${r}:`,m);let g=m instanceof Error?m:new Error(String(m)),w=m instanceof T?m.httpStatus:void 0;p.reportAllocationFailure(g,w);return}p.setAuth({jwt:c.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:c.url,sessionId:c.sessionId,iceServers:c.iceServers}),K()&&await G(),l.setDocTransport({wsUrl:c.url,token:c.jwt}),await p.connect({app:n,functionName:r,args:i})})().catch(c=>{console.error(`[urun] Failed to connect session for ${r}:`,c)}),l}}})}var $e=3e4,Fe="stream:",fe=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=`${Fe}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${Fe}${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 ${$e}ms`)))},$e);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function Pt(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 Se(s);return new fe(s,i)}var It='video/mp4; codecs="avc1.42E01E"';function Ct(n,e){let t=e?.codec??It,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(h){throw h instanceof DOMException&&h.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).`):h}let m=n.getReader();function g(){return c.updating?new Promise(h=>{c.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:h,value:k}=await m.read();if(h){await g(),s.readyState==="open"&&s.endOfStream();return}await g();try{c.appendBuffer(k)}catch(R){if(R instanceof DOMException&&R.name==="QuotaExceededError"){let A=c.buffered;if(A.length>0){let U=A.start(A.length-1);c.remove(0,U),await g(),c.appendBuffer(k)}else throw R}else throw R}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}w()}),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 f=a.call(r),p=f.getTracks(),l=0,d=p.length;if(d===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let c of p)c.addEventListener("ended",()=>{l++,l>=d&&URL.revokeObjectURL(i)});return f}function xt(n){return n.status.startsWith("pending_")}export{Tt as App,je as DEFAULT_DOC_SYNC_TIMEOUT_MS,Ve as DEFAULT_WHEN_LIVE_TIMEOUT_MS,ht as FOREGROUND_COALESCE_MS,E as InvalidDurationError,Z as PermanentLockedError,Q as PinRequiresActiveTempError,X as RecordingNotFoundError,O as RecordingsClient,_ as RecordingsError,D as RecordingsUnauthorizedError,z as RequestAbortError,se as RequestCancelledError,re as RequestDocSyncError,N as RequestError,te as RequestTimeoutError,Y as RetainNotTempError,J as RuntimeArtifactNotFoundError,I as RuntimeArtifactsClient,y as RuntimeArtifactsError,V as RuntimeArtifactsUnauthorizedError,L as Session,T as SessionAllocationError,Ge as SessionFailedError,ne as StreamDirectionConflict,gt as createRecordingsClient,ct as createRuntimeArtifactsClient,Pt as createStore,Ke as describeSessionFailure,Je as describeSessionPhase,ce as isDurationString,xt as isPendingRecording,He as isWakingPhase,de as mediaRecorderChunkSource,mt as normalizeRetention,ue as observePageLifecycle,We as sessionFailureFromMediaError,Ct as videoStream,ie as whenLive};
package/dist/index.d.mts CHANGED
@@ -1,10 +1,12 @@
1
- import { b as AppOptions, a as App$1, J as SessionPhase, Q as SessionStatus, A as AccessTokenOptions, x as RuntimeArtifact, y as RuntimeArtifactDownload, R as Recording, F as Session$1, C as ChannelEndpoint, Z as TransportSession, c as AttachOptions, u as RecordingsAccessor, z as RuntimeArtifactsAccessor, T as SessionStream$1, Y as StreamDataTransport, H as SessionDocumentImpl, X as StreamChunkOptions, g as ChunkReadable, P as Presence, j as DocConnector, v as RequestOptions, w as RequestStreamOptions, W as StoreOptions, V as Store, e as ChannelMultiplexer, I as SessionFailureKind } from './stream-data-B16nTnox.mjs';
2
- export { L as Layer, k as LayoutConfig, l as LayoutContext, M as MediaChunkBinding, n as MediaChunkSource, o as MediaChunkSourceFactory, p as MediaRecorderChunkSourceOptions, q as PresenceState, r as RecordingBucket, s as RecordingLifecycle, t as RecordingStatus, B as RuntimeAvailability, S as SceneContext, E as SceneGraph, G as SessionDocument, K as SessionPhaseError, N as SessionPhaseName, U as SessionText, $ as TransportState, a3 as isPendingRecording, a4 as mediaRecorderChunkSource } from './stream-data-B16nTnox.mjs';
1
+ import { b as AppOptions, a as App$1, K as SessionPhase, T as SessionStatus, O as SessionPhaseName, A as AccessTokenOptions, y as RuntimeArtifact, z as RuntimeArtifactDownload, R as Recording, G as Session$1, C as ChannelEndpoint, _ as TransportSession, c as AttachOptions, v as RecordingsAccessor, B as RuntimeArtifactsAccessor, U as SessionStream$1, Z as StreamDataTransport, I as SessionDocumentImpl, Y as StreamChunkOptions, g as ChunkReadable, P as Presence, k as DocConnector, w as RequestOptions, x as RequestStreamOptions, X as StoreOptions, W as Store, e as ChannelMultiplexer, J as SessionFailureKind } from './stream-data-BS3Z4V1D.mjs';
2
+ export { L as Layer, l as LayoutConfig, m as LayoutContext, M as MediaChunkBinding, o as MediaChunkSource, p as MediaChunkSourceFactory, q as MediaRecorderChunkSourceOptions, r as PresenceState, s as RecordingBucket, t as RecordingLifecycle, u as RecordingStatus, E as RuntimeAvailability, S as SceneContext, F as SceneGraph, H as SessionDocument, N as SessionPhaseError, V as SessionText, a0 as TransportState, a4 as isPendingRecording, a5 as mediaRecorderChunkSource } from './stream-data-BS3Z4V1D.mjs';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5
 
6
6
  declare function App(appId: string, options: AppOptions): App$1;
7
7
 
8
+ declare function isWakingPhase(phase: SessionPhase | SessionPhaseName | null | undefined): boolean;
9
+
8
10
  interface PhaseObservable {
9
11
 
10
12
  readonly phase: SessionPhase;
@@ -227,6 +229,10 @@ declare class Session implements Session$1 {
227
229
  private _recordingsAccessor;
228
230
 
229
231
  private _artifactsAccessor;
232
+
233
+ private _recoveryHooks;
234
+
235
+ private _lifecycleUnsub;
230
236
  constructor(sessionId: string, multiplexer: ChannelEndpoint, transport: TransportSession, recordingsAuth?: RecordingsClientOptions, artifactsAuth?: RuntimeArtifactsClientOptions);
231
237
  private _wireControlDocIncarnation;
232
238
 
@@ -273,9 +279,17 @@ declare class Session implements Session$1 {
273
279
  requestStream(payload: unknown, options?: RequestStreamOptions): AsyncIterable<string>;
274
280
 
275
281
  complete(payload: unknown, options?: RequestStreamOptions): Promise<unknown>;
282
+
283
+ recover(): void;
284
+
285
+ onRecovery(hook: () => void): () => void;
276
286
  disconnect(): void;
277
287
  }
278
288
 
289
+ declare const FOREGROUND_COALESCE_MS = 250;
290
+
291
+ declare function observePageLifecycle(onForeground: () => void): () => void;
292
+
279
293
  declare function createStore(options: StoreOptions): Store & {
280
294
  _getInternals(): {
281
295
  multiplexer: ChannelMultiplexer;
@@ -359,4 +373,4 @@ declare class SessionAllocationError extends Error {
359
373
  });
360
374
  }
361
375
 
362
- export { App, App$1 as AppInterface, AppOptions, AttachOptions, ChunkReadable, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_WHEN_LIVE_TIMEOUT_MS, InvalidDurationError, PermanentLockedError, type PhaseObservable, PinRequiresActiveTempError, Presence, Recording, RecordingNotFoundError, RecordingsAccessor, RecordingsClient, type RecordingsClientOptions, RecordingsError, RecordingsUnauthorizedError, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionFailedError, SessionFailureKind, Session$1 as SessionInterface, SessionPhase, SessionStatus, SessionStream$1 as SessionStream, Store, StoreOptions, StreamChunkOptions, StreamDirectionConflict, type VideoStreamOptions, type WhenLiveOptions, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, isDurationString, normalizeRetention, sessionFailureFromMediaError, videoStream, whenLive };
376
+ export { App, App$1 as AppInterface, AppOptions, AttachOptions, ChunkReadable, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_WHEN_LIVE_TIMEOUT_MS, FOREGROUND_COALESCE_MS, InvalidDurationError, PermanentLockedError, type PhaseObservable, PinRequiresActiveTempError, Presence, Recording, RecordingNotFoundError, RecordingsAccessor, RecordingsClient, type RecordingsClientOptions, RecordingsError, RecordingsUnauthorizedError, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionFailedError, SessionFailureKind, Session$1 as SessionInterface, SessionPhase, SessionPhaseName, SessionStatus, SessionStream$1 as SessionStream, Store, StoreOptions, StreamChunkOptions, StreamDirectionConflict, type VideoStreamOptions, type WhenLiveOptions, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, isDurationString, isWakingPhase, normalizeRetention, observePageLifecycle, sessionFailureFromMediaError, videoStream, whenLive };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
- import { b as AppOptions, a as App$1, J as SessionPhase, Q as SessionStatus, A as AccessTokenOptions, x as RuntimeArtifact, y as RuntimeArtifactDownload, R as Recording, F as Session$1, C as ChannelEndpoint, Z as TransportSession, c as AttachOptions, u as RecordingsAccessor, z as RuntimeArtifactsAccessor, T as SessionStream$1, Y as StreamDataTransport, H as SessionDocumentImpl, X as StreamChunkOptions, g as ChunkReadable, P as Presence, j as DocConnector, v as RequestOptions, w as RequestStreamOptions, W as StoreOptions, V as Store, e as ChannelMultiplexer, I as SessionFailureKind } from './stream-data-B16nTnox.js';
2
- export { L as Layer, k as LayoutConfig, l as LayoutContext, M as MediaChunkBinding, n as MediaChunkSource, o as MediaChunkSourceFactory, p as MediaRecorderChunkSourceOptions, q as PresenceState, r as RecordingBucket, s as RecordingLifecycle, t as RecordingStatus, B as RuntimeAvailability, S as SceneContext, E as SceneGraph, G as SessionDocument, K as SessionPhaseError, N as SessionPhaseName, U as SessionText, $ as TransportState, a3 as isPendingRecording, a4 as mediaRecorderChunkSource } from './stream-data-B16nTnox.js';
1
+ import { b as AppOptions, a as App$1, K as SessionPhase, T as SessionStatus, O as SessionPhaseName, A as AccessTokenOptions, y as RuntimeArtifact, z as RuntimeArtifactDownload, R as Recording, G as Session$1, C as ChannelEndpoint, _ as TransportSession, c as AttachOptions, v as RecordingsAccessor, B as RuntimeArtifactsAccessor, U as SessionStream$1, Z as StreamDataTransport, I as SessionDocumentImpl, Y as StreamChunkOptions, g as ChunkReadable, P as Presence, k as DocConnector, w as RequestOptions, x as RequestStreamOptions, X as StoreOptions, W as Store, e as ChannelMultiplexer, J as SessionFailureKind } from './stream-data-BS3Z4V1D.js';
2
+ export { L as Layer, l as LayoutConfig, m as LayoutContext, M as MediaChunkBinding, o as MediaChunkSource, p as MediaChunkSourceFactory, q as MediaRecorderChunkSourceOptions, r as PresenceState, s as RecordingBucket, t as RecordingLifecycle, u as RecordingStatus, E as RuntimeAvailability, S as SceneContext, F as SceneGraph, H as SessionDocument, N as SessionPhaseError, V as SessionText, a0 as TransportState, a4 as isPendingRecording, a5 as mediaRecorderChunkSource } from './stream-data-BS3Z4V1D.js';
3
3
  import 'yjs';
4
4
  import 'y-protocols/awareness';
5
5
 
6
6
  declare function App(appId: string, options: AppOptions): App$1;
7
7
 
8
+ declare function isWakingPhase(phase: SessionPhase | SessionPhaseName | null | undefined): boolean;
9
+
8
10
  interface PhaseObservable {
9
11
 
10
12
  readonly phase: SessionPhase;
@@ -227,6 +229,10 @@ declare class Session implements Session$1 {
227
229
  private _recordingsAccessor;
228
230
 
229
231
  private _artifactsAccessor;
232
+
233
+ private _recoveryHooks;
234
+
235
+ private _lifecycleUnsub;
230
236
  constructor(sessionId: string, multiplexer: ChannelEndpoint, transport: TransportSession, recordingsAuth?: RecordingsClientOptions, artifactsAuth?: RuntimeArtifactsClientOptions);
231
237
  private _wireControlDocIncarnation;
232
238
 
@@ -273,9 +279,17 @@ declare class Session implements Session$1 {
273
279
  requestStream(payload: unknown, options?: RequestStreamOptions): AsyncIterable<string>;
274
280
 
275
281
  complete(payload: unknown, options?: RequestStreamOptions): Promise<unknown>;
282
+
283
+ recover(): void;
284
+
285
+ onRecovery(hook: () => void): () => void;
276
286
  disconnect(): void;
277
287
  }
278
288
 
289
+ declare const FOREGROUND_COALESCE_MS = 250;
290
+
291
+ declare function observePageLifecycle(onForeground: () => void): () => void;
292
+
279
293
  declare function createStore(options: StoreOptions): Store & {
280
294
  _getInternals(): {
281
295
  multiplexer: ChannelMultiplexer;
@@ -359,4 +373,4 @@ declare class SessionAllocationError extends Error {
359
373
  });
360
374
  }
361
375
 
362
- export { App, App$1 as AppInterface, AppOptions, AttachOptions, ChunkReadable, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_WHEN_LIVE_TIMEOUT_MS, InvalidDurationError, PermanentLockedError, type PhaseObservable, PinRequiresActiveTempError, Presence, Recording, RecordingNotFoundError, RecordingsAccessor, RecordingsClient, type RecordingsClientOptions, RecordingsError, RecordingsUnauthorizedError, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionFailedError, SessionFailureKind, Session$1 as SessionInterface, SessionPhase, SessionStatus, SessionStream$1 as SessionStream, Store, StoreOptions, StreamChunkOptions, StreamDirectionConflict, type VideoStreamOptions, type WhenLiveOptions, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, isDurationString, normalizeRetention, sessionFailureFromMediaError, videoStream, whenLive };
376
+ export { App, App$1 as AppInterface, AppOptions, AttachOptions, ChunkReadable, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_WHEN_LIVE_TIMEOUT_MS, FOREGROUND_COALESCE_MS, InvalidDurationError, PermanentLockedError, type PhaseObservable, PinRequiresActiveTempError, Presence, Recording, RecordingNotFoundError, RecordingsAccessor, RecordingsClient, type RecordingsClientOptions, RecordingsError, RecordingsUnauthorizedError, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionFailedError, SessionFailureKind, Session$1 as SessionInterface, SessionPhase, SessionPhaseName, SessionStatus, SessionStream$1 as SessionStream, Store, StoreOptions, StreamChunkOptions, StreamDirectionConflict, type VideoStreamOptions, type WhenLiveOptions, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, isDurationString, isWakingPhase, normalizeRetention, observePageLifecycle, sessionFailureFromMediaError, videoStream, whenLive };