@urun-sh/core 0.2.14 → 0.2.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-ESLF63FX.mjs → chunk-AEIZ6XUT.mjs} +2 -2
- package/dist/{chunk-SHMKV7WG.mjs → chunk-GKS24GDI.mjs} +5 -5
- package/dist/index.browser.d.mts +268 -3
- package/dist/index.browser.d.ts +268 -3
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +268 -3
- package/dist/index.d.ts +268 -3
- package/dist/index.js +5 -5
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.d.mts +1 -1
- package/dist/internal.browser.d.ts +1 -1
- package/dist/internal.browser.js +2 -2
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +5 -5
- package/dist/internal.mjs +1 -1
- package/dist/{stream-data-GIyoXg7t.d.mts → stream-data-D8AOc7CR.d.mts} +7 -1
- package/dist/{stream-data-GIyoXg7t.d.ts → stream-data-D8AOc7CR.d.ts} +7 -1
- package/package.json +2 -1
package/dist/index.browser.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
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-ESLF63FX.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
|
+
import{B as je,C as $e,D as We,E as Be,F as Ke,a as Fe,b as V,c as G,d as de,e as le,f as pe,g as lt,h as pt,i as H,j as me,k as mt,l as ft,m as ht,n as A,o as gt,p as wt,q as fe,r as vt,s as z,u as Y,v as J,x as Ne,z as X}from"./chunk-AEIZ6XUT.mjs";var yt="session-api.prod.cloud.urun.sh",bt=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function _(n){return n.trim().replace(/\/+$/,"")}function ee(n,e){let t=[],r=s=>{if(!s)return;let i=_(s);i&&!t.includes(i)&&t.push(i)};r(n);for(let s of e??[])r(s);for(let s of Dt(n))r(s);return t}function Ve(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var kt=120,St=1e3,_t=20,Rt=5,Tt=500,Ge=1e4,At=3;function Ct(n){if(!n)return null;try{let e=new URL(n),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return _(`${e.origin}${t}`)}catch{return null}}async function He(n){let e=ee(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s of e)try{return await Pt(s,n,{pollAttempts:kt,retryAfterLimitMs:r?St:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof C)throw t}throw t??new Error("[urun] session allocation failed")}async function Pt(n,e,t){let r,s,i,o=n,a=0,c=new Set,u=Date.now()+t.pollAttempts*Ge;for(let d=0;d<t.pollAttempts;d++){s=i??await Z(e),i=void 0;let g=Math.max(1,Math.min(_t,Math.floor((u-Date.now())/1e3))),p=!!r,h=Date.now(),l=r?await fetch(`${o}/api/session-requests/${encodeURIComponent(r)}?wait_s=${g}`,{headers:Q(e,s),signal:Ut((g+Rt)*1e3)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Q(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(It(e))});if(!r&&(l.status===307||l.status===308)){let v=Ct(l.headers.get("location"));if(v&&v!==o&&a<At){a+=1,o=v;continue}throw new A(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:l.status})}let m=await he(l);if(l.ok&&(m.status==="allocated"||!m.status&&!!m.session_id)&&!!m.session_id){let v=m.session_id;if(!m.ws_url)throw new C(`[urun] gateway allocated session ${v} without ws_url`);if(!Ye(m.ws_url))throw new C(`[urun] gateway allocated session ${v} with non-absolute ws_url`);return{baseUrl:o,sessionId:v,wsUrl:m.ws_url,endsAt:Ve(m.ends_at),response:m}}if(l.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(xt(m,r))}catch{}let v=Date.now()-h<Tt;p&&v&&await Ot(Mt(l,m,t.retryAfterLimitMs));continue}if((l.status===401||l.status===403)&&e.getAccessToken){let v=s??"";c.add(v);let k=await Z(e,{forceRefresh:!0,reason:"unauthorized"});if(k&&!c.has(k)){i=k,r=void 0;continue}}let b=m.error_message||m.error_code||`HTTP ${l.status}`;throw new A(`[urun] session allocation failed at ${o}: ${b}`,{httpStatus:l.status})}throw new A(`[urun] timed out waiting for session allocation at ${o}`)}function Q(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 Z(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function It(n){return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey}}async function ze(n){let e=ee(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 Z(s),o=await fetch(`${_(r)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:Q(s,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${o.status}`);let a=await he(o);if(!a.ws_url||!Ye(a.ws_url))throw new C(`[urun] viewer-connect returned no usable ws_url for ${n.sessionId}`);return{baseUrl:_(r),sessionId:n.sessionId,wsUrl:a.ws_url,endsAt:Ve(a.ends_at),response:a}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof C)throw t}throw t??new Error("[urun] viewer-connect failed")}async function Et(n){try{let e=_(n.baseUrl),t=await Z(n),r=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...Q(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 he(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 he(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function xt(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 Mt(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),i=t??Ge;return Number.isFinite(s)&&s>0?Math.min(s*1e3,i):1e3}function Ot(n){return new Promise(e=>setTimeout(e,n))}function Ut(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var C=class extends Error{};function Ye(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function Dt(n){try{return new URL(n).hostname!==yt?[]:bt}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)}},te=class extends y{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},re=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 D(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function Lt(n){return new P(n)}var P=class{_options;constructor(e){this._options=e}async list(e){let r=Xe(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new y("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Je)}async getDownloadUrl(e,t){let r=Xe(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!Ft(s))throw new y("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Je(r.artifact),downloadUrl:s}}async _request(e,t){let r=ee(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&&Nt(s.status))throw s}throw s??new y("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${_(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:c}=await this._readError(o,e);throw jt(o.status,a,c)}try{return await o.json()}catch(a){throw new y(`[urun] runtime artifacts: invalid JSON response from ${_(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=_(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 y("[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=qt(e,"size_bytes"),a=R(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: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 qt(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function Ft(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function Nt(n){return n===401||n===403}function jt(n,e,t){return n===401?new te(t,e):n===404?new re(t,e):new y(t,n,e)}function Xe(n){if(!n||typeof n!="object"||Array.isArray(n))throw new y("[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)}},ne=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)}},se=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)}},ie=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)}},oe=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)}},x=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 ge(n){return/^(\d+[smhdw])+$/.test(n)}function $t(n){if(n==="pin")return{action:"pin"};if(ge(n))return{action:"retain",duration:n};throw new x(`[urun] recordings: "${n}" is not a duration or "pin"`)}function Wt(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new L(r,e??"unauthorized");if(n===404)return new ne(r,e??"not_found");if(n===400)return new x(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new se(r,e);case"pin_requires_active_temp":return new ie(r,e);case"permanent_locked":return new oe(r,e)}return new S(r,{status:n,code:e??`http_${n}`})}var M=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(!ge(t))throw new x(`[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:c}=await this._readError(o);throw Wt(o.status,a,c)}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 Bt(n){return new M(n)}var Qe="activity",Kt=15e3,we=["pointerdown","pointermove","keydown","wheel","touchstart"];function ve(n){let e=n.now??Date.now,t=n.windowTarget!==void 0?n.windowTarget:typeof window<"u"?window:null,r=n.documentTarget!==void 0?n.documentTarget:typeof document<"u"?document:null,s=!1,i,o=()=>{if(s)return;let d=e();if(!(i!==void 0&&d-i<15e3)){i=d;try{n.awareness.setLocalStateField(Qe,{at:d})}catch{}}},a=()=>o(),c=()=>{(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&o()};if(t)for(let d of we)t.addEventListener(d,a,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",c);let u=null;return n.isProducing&&(u=setInterval(()=>{if(!s)try{n.isProducing?.()&&o()}catch{}},15e3),u.unref?.()),o(),{touch:o,dispose(){if(!s){if(s=!0,t)for(let d of we)t.removeEventListener(d,a,{capture:!0});r&&r.removeEventListener("visibilitychange",c),u&&(clearInterval(u),u=null)}}}}var Vt=250;function ye(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 Ze="video/mp4";function be(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,i=!1,o=(a,c,u)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let g=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(Ze)?Ze:void 0),p=new MediaStream([a]),h=new d(p,g?{mimeType:g}:void 0);r=h;let l=Promise.resolve();h.ondataavailable=m=>{let w=m.data;i||!w||w.size===0||(l=l.then(async()=>{let b=new Uint8Array(await w.arrayBuffer());i||c(b)}))},h.onstop=()=>{l.then(()=>{i||u()})},h.onerror=()=>{l.then(()=>{i||u()})},h.start(t)};return{start(a,c){if(r||i)return;let u=n.track();if(u){o(u,a,c);return}s=n.onTrack(d=>{!d||r||i||(s?.(),s=null,o(d,a,c))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Gt(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 et(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 Gt(i)}var Ht=new Set;function _e(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var zt="rpc",rt=3e4,Yt="rpc-resp";function Jt(n){return`${Yt}:${n}`}function ke(){return J()}function Xt(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 Qt(n,e,t,r,s,i,o,a,c,u){let d=[],g=null,p=!1,h=null,l=!1,m,w,b=new Promise((f,T)=>{m=f,w=T});b.catch(()=>{});let v=o(),k=null,O=null,U=null,W=null,B=!0,Me=()=>{U&&(clearTimeout(U),U=null),W&&(W(),W=null)},Oe=!1,Ue=()=>{Oe||!l||(Oe=!0,n.set({rpc:{[e]:null}}))},K=()=>{B=!1,Me(),k?.(),k=null,O?.(),O=null,a?.removeEventListener("abort",Le),v.dispose(),Ue()},ue=()=>{if(g){if(d.length>0){let f=g;g=null,f.resolve({value:d.shift(),done:!1})}else if(h!==null){let f=g;g=null,f.reject(h)}else if(p){let f=g;g=null,f.resolve({value:void 0,done:!0})}}},ct=f=>{p||(d.push(f),ue())},I=f=>{p||(h=f,p=!0,w(f),K(),ue())},De=f=>{p||(p=!0,m(f),K(),ue())},Le=()=>{let f=a?.reason;I(f instanceof G?f:new H(e))},ut=f=>{if(!(p||!f||typeof f!="object"))switch(Ue(),f.t){case"delta":typeof f.delta=="string"&&ct(f.delta);break;case"response":De(f.body);break;case"error":{let{message:T,code:E}=Xt(f.body);I(new G(T,{requestId:e,code:f.code??E}));break}}},dt=()=>{let f=v.messages()[Symbol.asyncIterator]();k=()=>{f.return?.(void 0)};let T=()=>{B&&f.next().then(E=>{if(B){if(E.done){p||De(void 0);return}ut(E.value),T()}},E=>{B&&I(E)})};T()},qe=()=>{if(!l){if(l=!0,a){if(a.aborted){I(new H(e));return}a.addEventListener("abort",Le,{once:!0})}O=c?.(f=>I(f))??null,dt(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),u&&u>0&&!n.synced&&(U=setTimeout(()=>{U=null,!p&&!n.synced&&I(new le(u,e))},u),W=n.onSynced(()=>Me()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(qe(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(h!==null){let f=h;return h=null,Promise.reject(f)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((f,T)=>{g={resolve:f,reject:T}})},return(){return p||(p=!0,m(void 0),K()),Promise.resolve({value:void 0,done:!0})},throw(f){return p||(p=!0,w(f),K()),Promise.reject(f)}}}},body:b,start:qe}}function tt(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 Zt(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 c=tt(i);c&&(a.rt=c);let u=tt(o);return u&&(a.br=u),a}var Se=class{constructor(e,t,r,s,i){this._name=e;this._transport=t;this._streamData=r;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],r=null,s=!1,i={push(a){if(!s)if(r){let c=r;r=null,c({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._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=Zt(t,this._name),s=r?.br;if(s?.by==="runtime")throw new pe(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._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??be;return et(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._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 We;_streamData;_presence=null;_activity=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=Ne(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=ye(()=>this.recover()),this._activity=ve({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 r=await ze({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 V,o=new X({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,_e(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),z()&&await Y(),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 fe(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: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 P(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new P(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 Se(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 Be(e,this._sessionId,Ht.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ke(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs($e({serverUrl:je(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=ke(),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 de(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){this._activity?.touch();let o=this.doc(zt),a=Jt(e);return Qt(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??rt)}requestStream(e,t={}){let r=ke();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=ke(),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._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 me)}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 er=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function tr(n,e){return new Proxy({},{get(t,r){if(!(er.has(r)||typeof r!="string"))return s=>{let i=s??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),c=new V,u=new X({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),d=new q(a,c,u,_e(e),D(e)),g=async p=>{let h=await He({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:p,onAdmission:m=>u.reportAdmission(m)}),l=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return d.setSessionId(h.sessionId),d.setArtifactsAuth(D({...e,baseUrl:h.baseUrl})),u.setEndsAt(h.endsAt),{url:h.wsUrl,sessionId:h.sessionId,jwt:l,iceServers:h.response.ice_servers,endsAt:h.endsAt}};return u.setConnectionResolver(()=>g(o())),u.on("connected",()=>{u.multiplexer&&c.setTarget(u.multiplexer)}),(async()=>{let p;try{p=await g(a)}catch(h){console.error(`[urun] Failed to create session for ${r}:`,h);let l=h instanceof Error?h:new Error(String(h)),m=h instanceof A?h.httpStatus:void 0;u.reportAllocationFailure(l,m);return}u.setAuth({jwt:p.jwt,authProvider:e.authProvider,orgId:e.orgId}),u.setConnection({url:p.url,sessionId:p.sessionId,iceServers:p.iceServers}),z()&&await Y(),d.setDocTransport({wsUrl:p.url,token:p.jwt}),await u.connect({app:n,functionName:r,args:i})})().catch(p=>{console.error(`[urun] Failed to connect session for ${r}:`,p)}),d}}})}var nt=3e4,st="stream:",Re=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=`${st}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${st}${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 ${nt}ms`)))},nt);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function rr(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 Fe(s);return new Re(s,i)}var nr='video/mp4; codecs="avc1.42E01E"';function sr(n,e){let t=e?.codec??nr,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 p;try{p=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 h=n.getReader();function l(){return p.updating?new Promise(w=>{p.addEventListener("updateend",()=>w(),{once:!0})}):Promise.resolve()}async function m(){try{for(;;){let{done:w,value:b}=await h.read();if(w){await l(),s.readyState==="open"&&s.endOfStream();return}await l();try{p.appendBuffer(b)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let k=p.buffered;if(k.length>0){let O=k.start(k.length-1);p.remove(0,O),await l(),p.appendBuffer(b)}else throw v}else throw v}}}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 c=a.call(r),u=c.getTracks(),d=0,g=u.length;if(g===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=g&&URL.revokeObjectURL(i)});return c}function ir(n){return n.status.startsWith("pending_")}var ae=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 it(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function or(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function ar(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function Te(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var ce=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,Te(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 ae;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(${it(r)}) failed`,c=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 d=new Error(`${a} \u2014 ${u.kind} capture lost: ${c||o}`);d.cause=o,Te(u,d)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=or(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${it(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw c;Te(o,c);continue}if(o.track=a,o.stream=ar(s,a),o!==e)for(let c of[...o.trackListeners])try{c(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}},cr=null;function ur(){return cr??=new ce}var ot="input",dr=30;function lr(n){let e=n.now??Date.now,t=n.field??ot,r=1e3/Math.max(n.hz??30,.001),s=new Set,i=0,o=0,a=0,c=0,u,d=null,g=!1,p=()=>{if(g)return;u=e(),c+=1;let l={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:c,at:u};try{n.awareness.setLocalStateField(t,l)}catch{}},h=()=>{if(g)return;let l=e();if(u===void 0||l-u>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let m=Math.max(r-(l-u),0);d=setTimeout(()=>{d=null,p()},m),d.unref?.()};return{keyDown(l){let m=String(l).toLowerCase();s.has(m)||(s.add(m),h())},keyUp(l){let m=String(l).toLowerCase();s.delete(m)&&h()},setButtons(l){let m=Number.isFinite(l)?Number(l):0;m!==i&&(i=m,h())},movePointer(l,m){let w=Number.isFinite(l)?Number(l):0,b=Number.isFinite(m)?Number(m):0;w===0&&b===0||(o+=w,a+=b,h())},heldKeys(){return[...s]},clear(){g||(s.clear(),i=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(g)return;let l=s.size>0||i!==0;s.clear(),i=0,d&&(clearTimeout(d),d=null),l&&p(),g=!0}}}import{encode as pr,decode as mr}from"@msgpack/msgpack";var at=65536;function Ce(n){let e=pr(n),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var F=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>at)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let s=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(mr(s))}return t}},N=12,Ae=1;function Pe(n){let e=n.getUint8(8);return{groupId:n.getUint32(0,!0),frameSeq:n.getUint32(4,!0),keyframe:(e&Ae)===Ae,fragIndex:n.getUint8(9),fragCount:n.getUint8(10)}}function fr(n){let e=new Uint8Array(N),t=new DataView(e.buffer);return t.setUint32(0,n.groupId,!0),t.setUint32(4,n.frameSeq,!0),t.setUint8(8,n.keyframe?Ae:0),t.setUint8(9,n.fragIndex),t.setUint8(10,n.fragCount),t.setUint8(11,0),e}var hr=100,j=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??hr}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(e){if(e.byteLength<N)return;let t=Pe(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray(N),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let s of this.pending.keys())s<t.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let r=t.chunks.reduce((o,a)=>o+a.byteLength,0),s=new Uint8Array(r),i=0;for(let o of t.chunks)s.set(o,i),i+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:s})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var gr=250,$=class{constructor(e,t,r){this.offer=e;this.sessionId=t;this.canvas=r}offer;sessionId;canvas;kind="webtransport";wt;decoder=null;writer;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;reassembler=new j({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};firstFrameResolve=null;firstFrameReject=null;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=new Promise((c,u)=>{this.firstFrameResolve=c,this.firstFrameReject=u});this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(c=>({algorithm:"sha-256",value:Uint8Array.from(atob(c),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let r=await this.wt.createBidirectionalStream();this.writer=r.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let s=r.readable.getReader(),i=new F,o=[],a=await this.readControl(s,i,o);if(a?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");this.initDecoder(a.codec,a.width,a.height),this.controlLoop(s,i,o).catch(c=>this.die(`control loop: ${c}`)),this.datagramLoop().catch(c=>this.die(`datagram loop: ${c}`)),this.feedbackLoop(),this.wt.closed.then(()=>this.die("connection closed")).catch(c=>this.die(`connection error: ${c}`)),await t}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}onDead(e){this.deadCb=e}stats(){return this.lastStats}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoder=new s({output:o=>{this.canvas.width=o.displayWidth,this.canvas.height=o.displayHeight,i.drawImage(o,0,0),o.close()},error:o=>this.die(`decoder: ${o.message}`)}),this.decoder.configure({codec:e,codedWidth:t,codedHeight:r,optimizeForLatency:!0,hardwareAcceleration:"prefer-hardware"})}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;!this.decoder||typeof s!="function"||(this.decoder.decode(new s({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}async sendControl(e){await this.writer.write(Ce(e))}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&r.push(...t.push(i))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;s.t==="ping"&&this.sendControl({t:"pong",ts:s.ts}).catch(()=>{})}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:i>0?100*s.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},gr)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null;try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var wr=2500,vr=["av01.0.08M.08","avc1.640028"],Ie=class{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;get activeTransport(){return this.session?.kind??null}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&r&&s,webcodecs:r,codecs:vr};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i});let o=i.webtransport&&!!this.offer.webtransport;if(o){let a=null;try{return a=this.createWebTransportSession(),await yr(a.start(),this.opts.quicDeadlineMs??wr,"quic connect deadline"),this.session=a,this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(c){console.warn("[urun] webtransport failed, falling back to webrtc:",c),a?.stop().catch(()=>{}),this.notifyEstablished("webrtc",String(c instanceof Error?c.message:c))}}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){await this.session?.stop(),this.session=null}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new $(e,this.sessionId,this.opts.canvas)}async startWebRtc(){let e=this.opts.createWebRtcSession();return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}armFailover(){this.session.onDead(e=>{console.warn("[urun] quic died mid-session, failing over to webrtc:",e),(async()=>{try{this.session=await this.startWebRtc(),this.notifyEstablished("webrtc",`failover: ${e}`),this.opts.onTransportChange?.("webrtc",e)}catch(t){this.session=null,console.error("[urun] failover to webrtc also failed:",t)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function yr(n,e,t){return new Promise((r,s)=>{let i=setTimeout(()=>s(new Error(t)),e);n.then(o=>{clearTimeout(i),r(o)},o=>{clearTimeout(i),s(o)})})}var br="video",Ee=class{constructor(e,t=br){this.transport=e;this.streamName=t}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];async start(){this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),!this.transport.getTrackByName(this.streamName)&&await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.deadCb?.(e))}};var kr=1e4,xe=class{constructor(e,t=kr){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let r=J();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:u,requestId:d,...g}=c;s(g)});this.carrier.sendSignal({type:e,requestId:r,...t})})}notify(e,t){this.carrier.sendSignal({type:e,...t})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};export{we as ACTIVITY_DOM_EVENTS,Qe as ACTIVITY_FIELD,Kt as ACTIVITY_STAMP_MIN_INTERVAL_MS,tr as App,ce as CaptureController,ae as CaptureUnavailableError,rt as DEFAULT_DOC_SYNC_TIMEOUT_MS,lt as DEFAULT_PRODUCE_ACK_TIMEOUT_MS,wt as DEFAULT_WHEN_LIVE_TIMEOUT_MS,N as DGRAM_HEADER_BYTES,Vt as FOREGROUND_COALESCE_MS,j as FrameReassembler,dr as INPUT_PRESENCE_DEFAULT_HZ,ot as INPUT_PRESENCE_FIELD,x as InvalidDurationError,oe as PermanentLockedError,ie as PinRequiresActiveTempError,pt as ProduceAckTimeoutError,ne as RecordingNotFoundError,M as RecordingsClient,S as RecordingsError,L as RecordingsUnauthorizedError,H as RequestAbortError,me as RequestCancelledError,le as RequestDocSyncError,G as RequestError,de as RequestTimeoutError,se as RetainNotTempError,re as RuntimeArtifactNotFoundError,P as RuntimeArtifactsClient,y as RuntimeArtifactsError,te as RuntimeArtifactsUnauthorizedError,q as Session,A as SessionAllocationError,ft as SessionFailedError,pe as StreamDirectionConflict,Ie as TransportNegotiator,xe as TransportSessionSignaling,at as WT_CONTROL_FRAME_MAX,Ee as WebRtcSession,$ as WebTransportSession,F as WtControlDecoder,ve as createActivityTracker,lr as createInputPresencePublisher,Bt as createRecordingsClient,Lt as createRuntimeArtifactsClient,rr as createStore,mt as describeSessionFailure,vt as describeSessionPhase,Ce as encodeWtControlFrame,ge as isDurationString,ir as isPendingRecording,gt as isWakingPhase,be as mediaRecorderChunkSource,$t as normalizeRetention,ye as observePageLifecycle,Pe as parseDgramHeader,Et as prewake,ht as sessionFailureFromMediaError,ur as sharedCaptureController,sr as videoStream,fe as whenLive,fr as writeDgramHeader};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { b as AppOptions, a as App$1, K as SessionPhase, T as SessionStatus, O as SessionPhaseName, A as AccessTokenOptions$1, 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-
|
|
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,
|
|
1
|
+
import { b as AppOptions, a as App$1, K as SessionPhase, T as SessionStatus, O as SessionPhaseName, A as AccessTokenOptions$1, 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, a0 as TransportState } from './stream-data-D8AOc7CR.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, a4 as isPendingRecording, a5 as mediaRecorderChunkSource } from './stream-data-D8AOc7CR.mjs';
|
|
3
3
|
import 'yjs';
|
|
4
4
|
import 'y-protocols/awareness';
|
|
5
5
|
|
|
@@ -375,6 +375,21 @@ declare class StreamDirectionConflict extends Error {
|
|
|
375
375
|
constructor(stream: string, owner: 'runtime' | 'browser', attempted: 'runtime' | 'browser');
|
|
376
376
|
}
|
|
377
377
|
|
|
378
|
+
declare const DEFAULT_PRODUCE_ACK_TIMEOUT_MS = 15000;
|
|
379
|
+
|
|
380
|
+
declare class ProduceAckTimeoutError extends Error {
|
|
381
|
+
|
|
382
|
+
readonly kind: 'audio' | 'video';
|
|
383
|
+
|
|
384
|
+
readonly stream: string;
|
|
385
|
+
|
|
386
|
+
readonly timeoutMs: number;
|
|
387
|
+
constructor(kind: 'audio' | 'video', options?: {
|
|
388
|
+
stream?: string;
|
|
389
|
+
timeoutMs?: number;
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
378
393
|
declare class RequestAbortError extends RequestError {
|
|
379
394
|
constructor(requestId?: string);
|
|
380
395
|
}
|
|
@@ -533,4 +548,254 @@ interface InputPresencePublisher {
|
|
|
533
548
|
|
|
534
549
|
declare function createInputPresencePublisher(options: InputPresencePublisherOptions): InputPresencePublisher;
|
|
535
550
|
|
|
536
|
-
|
|
551
|
+
interface MediaSession {
|
|
552
|
+
readonly kind: 'webtransport' | 'webrtc';
|
|
553
|
+
start(): Promise<void>;
|
|
554
|
+
stop(): Promise<void>;
|
|
555
|
+
|
|
556
|
+
onDead(cb: (reason: string) => void): void;
|
|
557
|
+
|
|
558
|
+
stats(): {
|
|
559
|
+
recvBps: number;
|
|
560
|
+
lossPct: number;
|
|
561
|
+
jitterMs: number;
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
interface Signaling {
|
|
566
|
+
request<T = unknown>(method: string, params?: unknown): Promise<T>;
|
|
567
|
+
notify(method: string, params?: unknown): void;
|
|
568
|
+
|
|
569
|
+
on(method: string, handler: (params: Record<string, unknown>) => void): () => void;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
interface SignalCarrier {
|
|
573
|
+
|
|
574
|
+
sendSignal(msg: Record<string, unknown>): void;
|
|
575
|
+
|
|
576
|
+
onSignal(handler: (msg: Record<string, unknown>) => void): () => void;
|
|
577
|
+
}
|
|
578
|
+
declare class TransportSessionSignaling implements Signaling {
|
|
579
|
+
private carrier;
|
|
580
|
+
private requestTimeoutMs;
|
|
581
|
+
constructor(carrier: SignalCarrier, requestTimeoutMs?: number);
|
|
582
|
+
request<T = unknown>(method: string, params?: unknown): Promise<T>;
|
|
583
|
+
notify(method: string, params?: unknown): void;
|
|
584
|
+
on(method: string, handler: (params: Record<string, unknown>) => void): () => void;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
interface TransportOfferRequest {
|
|
588
|
+
sessionId: string;
|
|
589
|
+
capabilities: {
|
|
590
|
+
|
|
591
|
+
webtransport: boolean;
|
|
592
|
+
|
|
593
|
+
webcodecs: boolean;
|
|
594
|
+
|
|
595
|
+
codecs: string[];
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
interface TransportOfferResponse {
|
|
599
|
+
|
|
600
|
+
webrtc: {
|
|
601
|
+
routerRtpCapabilities: unknown;
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
webtransport?: {
|
|
605
|
+
url: string;
|
|
606
|
+
|
|
607
|
+
certHashes: string[];
|
|
608
|
+
|
|
609
|
+
token: string;
|
|
610
|
+
codec: string;
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
interface TransportEstablishedNotify {
|
|
614
|
+
sessionId: string;
|
|
615
|
+
transport: 'webtransport' | 'webrtc';
|
|
616
|
+
|
|
617
|
+
fallbackReason?: string;
|
|
618
|
+
}
|
|
619
|
+
type WtControlMessage = {
|
|
620
|
+
t: 'hello';
|
|
621
|
+
token: string;
|
|
622
|
+
sessionId: string;
|
|
623
|
+
} | {
|
|
624
|
+
t: 'hello-ack';
|
|
625
|
+
codec: string;
|
|
626
|
+
width: number;
|
|
627
|
+
height: number;
|
|
628
|
+
} | {
|
|
629
|
+
t: 'ping';
|
|
630
|
+
ts: number;
|
|
631
|
+
} | {
|
|
632
|
+
t: 'pong';
|
|
633
|
+
ts: number;
|
|
634
|
+
} | {
|
|
635
|
+
t: 'keyframe-request';
|
|
636
|
+
} | {
|
|
637
|
+
t: 'feedback';
|
|
638
|
+
recvBps: number;
|
|
639
|
+
lossPct: number;
|
|
640
|
+
jitterMs: number;
|
|
641
|
+
};
|
|
642
|
+
|
|
643
|
+
declare const WT_CONTROL_FRAME_MAX: number;
|
|
644
|
+
|
|
645
|
+
declare function encodeWtControlFrame(msg: WtControlMessage): Uint8Array;
|
|
646
|
+
|
|
647
|
+
declare class WtControlDecoder {
|
|
648
|
+
private buf;
|
|
649
|
+
push(bytes: Uint8Array): WtControlMessage[];
|
|
650
|
+
}
|
|
651
|
+
declare const DGRAM_HEADER_BYTES = 12;
|
|
652
|
+
interface DgramHeader {
|
|
653
|
+
groupId: number;
|
|
654
|
+
frameSeq: number;
|
|
655
|
+
keyframe: boolean;
|
|
656
|
+
fragIndex: number;
|
|
657
|
+
fragCount: number;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
declare function parseDgramHeader(view: DataView): DgramHeader;
|
|
661
|
+
|
|
662
|
+
declare function writeDgramHeader(h: DgramHeader): Uint8Array;
|
|
663
|
+
|
|
664
|
+
interface NegotiatorOptions {
|
|
665
|
+
|
|
666
|
+
quicDeadlineMs?: number;
|
|
667
|
+
|
|
668
|
+
allowWebTransport?: boolean;
|
|
669
|
+
onTransportChange?: (kind: MediaSession['kind'], reason?: string) => void;
|
|
670
|
+
|
|
671
|
+
canvas?: HTMLCanvasElement;
|
|
672
|
+
|
|
673
|
+
createWebRtcSession: () => MediaSession;
|
|
674
|
+
createWebTransportSession?: (offer: NonNullable<TransportOfferResponse['webtransport']>) => MediaSession;
|
|
675
|
+
}
|
|
676
|
+
declare class TransportNegotiator {
|
|
677
|
+
private signaling;
|
|
678
|
+
private sessionId;
|
|
679
|
+
private opts;
|
|
680
|
+
private session;
|
|
681
|
+
private offer;
|
|
682
|
+
constructor(signaling: Signaling, sessionId: string, opts: NegotiatorOptions);
|
|
683
|
+
get activeTransport(): MediaSession['kind'] | null;
|
|
684
|
+
connect(): Promise<MediaSession>;
|
|
685
|
+
disconnect(): Promise<void>;
|
|
686
|
+
private createWebTransportSession;
|
|
687
|
+
private startWebRtc;
|
|
688
|
+
|
|
689
|
+
private armFailover;
|
|
690
|
+
private notifyEstablished;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
declare class WebTransportSession implements MediaSession {
|
|
694
|
+
private offer;
|
|
695
|
+
private sessionId;
|
|
696
|
+
private canvas;
|
|
697
|
+
readonly kind: "webtransport";
|
|
698
|
+
private wt;
|
|
699
|
+
private decoder;
|
|
700
|
+
private writer;
|
|
701
|
+
private deadCb;
|
|
702
|
+
private deadFired;
|
|
703
|
+
private stopped;
|
|
704
|
+
private feedbackTimer;
|
|
705
|
+
private reassembler;
|
|
706
|
+
private lastArrivalTs;
|
|
707
|
+
private jitterEwmaMs;
|
|
708
|
+
private lastStats;
|
|
709
|
+
private firstFrameResolve;
|
|
710
|
+
private firstFrameReject;
|
|
711
|
+
constructor(offer: NonNullable<TransportOfferResponse['webtransport']>, sessionId: string, canvas: HTMLCanvasElement);
|
|
712
|
+
|
|
713
|
+
start(): Promise<void>;
|
|
714
|
+
stop(): Promise<void>;
|
|
715
|
+
onDead(cb: (reason: string) => void): void;
|
|
716
|
+
stats(): {
|
|
717
|
+
recvBps: number;
|
|
718
|
+
lossPct: number;
|
|
719
|
+
jitterMs: number;
|
|
720
|
+
};
|
|
721
|
+
private initDecoder;
|
|
722
|
+
private datagramLoop;
|
|
723
|
+
private decodeFrame;
|
|
724
|
+
private sendControl;
|
|
725
|
+
private readControl;
|
|
726
|
+
private controlLoop;
|
|
727
|
+
|
|
728
|
+
private feedbackLoop;
|
|
729
|
+
private die;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
interface ConsumingTransport {
|
|
733
|
+
getTrackByName(name: string): MediaStreamTrack | undefined;
|
|
734
|
+
on(event: 'track', handler: (track: MediaStreamTrack) => void): () => void;
|
|
735
|
+
on(event: 'stateChange', handler: (state: TransportState) => void): () => void;
|
|
736
|
+
}
|
|
737
|
+
declare class WebRtcSession implements MediaSession {
|
|
738
|
+
private transport;
|
|
739
|
+
private streamName;
|
|
740
|
+
readonly kind: "webrtc";
|
|
741
|
+
private deadCb;
|
|
742
|
+
private deadFired;
|
|
743
|
+
private unsubscribers;
|
|
744
|
+
constructor(transport: ConsumingTransport, streamName?: string);
|
|
745
|
+
|
|
746
|
+
start(): Promise<void>;
|
|
747
|
+
|
|
748
|
+
stop(): Promise<void>;
|
|
749
|
+
onDead(cb: (reason: string) => void): void;
|
|
750
|
+
stats(): {
|
|
751
|
+
recvBps: number;
|
|
752
|
+
lossPct: number;
|
|
753
|
+
jitterMs: number;
|
|
754
|
+
};
|
|
755
|
+
private die;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
interface ReassembledFrame {
|
|
759
|
+
seq: number;
|
|
760
|
+
groupId: number;
|
|
761
|
+
keyframe: boolean;
|
|
762
|
+
data: Uint8Array;
|
|
763
|
+
}
|
|
764
|
+
interface ReassemblerCallbacks {
|
|
765
|
+
|
|
766
|
+
onFrame(frame: ReassembledFrame): void;
|
|
767
|
+
|
|
768
|
+
onKeyframeNeeded(): void;
|
|
769
|
+
}
|
|
770
|
+
interface ReassemblerOptions {
|
|
771
|
+
|
|
772
|
+
now?: () => number;
|
|
773
|
+
|
|
774
|
+
keyframeRequestDebounceMs?: number;
|
|
775
|
+
}
|
|
776
|
+
declare class FrameReassembler {
|
|
777
|
+
private cb;
|
|
778
|
+
private pending;
|
|
779
|
+
private newestGroupSeen;
|
|
780
|
+
private newestFrameDelivered;
|
|
781
|
+
private needKeyframe;
|
|
782
|
+
private kfRequestedAt;
|
|
783
|
+
private now;
|
|
784
|
+
private debounceMs;
|
|
785
|
+
private bytesInWindow;
|
|
786
|
+
private framesDelivered;
|
|
787
|
+
private framesAbandoned;
|
|
788
|
+
constructor(cb: ReassemblerCallbacks, opts?: ReassemblerOptions);
|
|
789
|
+
|
|
790
|
+
push(chunk: Uint8Array): void;
|
|
791
|
+
|
|
792
|
+
drainWindow(): {
|
|
793
|
+
bytes: number;
|
|
794
|
+
delivered: number;
|
|
795
|
+
abandoned: number;
|
|
796
|
+
};
|
|
797
|
+
private deliver;
|
|
798
|
+
private requestKeyframe;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
export { ACTIVITY_DOM_EVENTS, ACTIVITY_FIELD, ACTIVITY_STAMP_MIN_INTERVAL_MS, type ActivityAwareness, type ActivityTracker, type ActivityTrackerOptions, App, App$1 as AppInterface, AppOptions, AttachOptions, type CaptureClaim, CaptureController, type CaptureControllerOptions, type CaptureKind, CaptureUnavailableError, ChunkReadable, type ConsumingTransport, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_PRODUCE_ACK_TIMEOUT_MS, DEFAULT_WHEN_LIVE_TIMEOUT_MS, DGRAM_HEADER_BYTES, type DgramHeader, FOREGROUND_COALESCE_MS, FrameReassembler, INPUT_PRESENCE_DEFAULT_HZ, INPUT_PRESENCE_FIELD, type InputPresenceAwareness, type InputPresencePublisher, type InputPresencePublisherOptions, type InputPresenceState, InvalidDurationError, type MediaSession, type NegotiatorOptions, PermanentLockedError, type PhaseObservable, PinRequiresActiveTempError, Presence, type PrewakeOptions, type PrewakeResult, type PrewakeStatus, ProduceAckTimeoutError, type ReassembledFrame, type ReassemblerCallbacks, type ReassemblerOptions, 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, type SignalCarrier, type Signaling, Store, StoreOptions, StreamChunkOptions, StreamDirectionConflict, type TransportEstablishedNotify, TransportNegotiator, type TransportOfferRequest, type TransportOfferResponse, TransportSessionSignaling, TransportState, type VideoStreamOptions, WT_CONTROL_FRAME_MAX, WebRtcSession, WebTransportSession, type WhenLiveOptions, WtControlDecoder, type WtControlMessage, createActivityTracker, createInputPresencePublisher, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, encodeWtControlFrame, isDurationString, isWakingPhase, normalizeRetention, observePageLifecycle, parseDgramHeader, prewake, sessionFailureFromMediaError, sharedCaptureController, videoStream, whenLive, writeDgramHeader };
|