@urun-sh/core 0.6.41 → 0.6.42
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/adapter/index.js +1 -1
- package/dist/adapter/index.mjs +1 -1
- package/dist/{app-WK7H3ZNF.mjs → app-U6KWURCN.mjs} +1 -1
- package/dist/{chunk-EWKKEBQJ.mjs → chunk-3WZFSRFA.mjs} +1 -1
- package/dist/index.browser.js +1 -1
- package/dist/index.browser.mjs +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/adapter/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
|
|
2
|
-
import"../chunk-NLAOQUYQ.mjs";var p="serve";function d(n,o){let e=`[urun/${o.adapter}]`,r=n.baseUrl!==void 0||n.orgId!==void 0||n.app!==void 0||n.functionName!==void 0;if(n.session&&r)throw new Error(`${e} pass EITHER a \`session\` (BYO) OR connection settings (\`baseUrl\`/\`orgId\`/\`app\`) \u2014 not both.`);let u,c=()=>{if(n.session){let s=n.session;return Promise.resolve(typeof s=="function"?s():s)}let{baseUrl:i,orgId:t,app:a}=n;if(!i||!t||!a)throw new Error(`${e} missing connection settings: \`baseUrl\`, \`orgId\` and \`app\` are required (or pass a \`session\`).`);return l({...n,baseUrl:i,orgId:t,app:a})};return()=>u??=c()}async function l(n){let{App:o}=await import("../app-
|
|
2
|
+
import"../chunk-NLAOQUYQ.mjs";var p="serve";function d(n,o){let e=`[urun/${o.adapter}]`,r=n.baseUrl!==void 0||n.orgId!==void 0||n.app!==void 0||n.functionName!==void 0;if(n.session&&r)throw new Error(`${e} pass EITHER a \`session\` (BYO) OR connection settings (\`baseUrl\`/\`orgId\`/\`app\`) \u2014 not both.`);let u,c=()=>{if(n.session){let s=n.session;return Promise.resolve(typeof s=="function"?s():s)}let{baseUrl:i,orgId:t,app:a}=n;if(!i||!t||!a)throw new Error(`${e} missing connection settings: \`baseUrl\`, \`orgId\` and \`app\` are required (or pass a \`session\`).`);return l({...n,baseUrl:i,orgId:t,app:a})};return()=>u??=c()}async function l(n){let{App:o}=await import("../app-U6KWURCN.mjs"),e=o(n.app,{baseUrl:n.baseUrl,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}),r=n.functionName??p;return e[r]()}export{d as createSessionResolver};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
|
|
2
|
-
import{fa as a,ga as b}from"./chunk-
|
|
2
|
+
import{fa as a,ga as b}from"./chunk-3WZFSRFA.mjs";import"./chunk-JXGR4FYX.mjs";import"./chunk-NLAOQUYQ.mjs";export{b as App,a as sessionDirectory};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __urunCreateRequire } from 'node:module'; const require = globalThis.require ?? __urunCreateRequire(import.meta.url);
|
|
2
|
-
import{$ as Et,B as ae,H as de,I as gt,J as vt,K as xe,L as Oe,M as wt,N as yt,O as bt,P as kt,Q as Fe,R as St,S as _t,T as Tt,V as At,W as le,Y as Rt,b as se,c as z,ca as Dt,d as ct,e as Ie,f as Ce,g as ut,h as ht,i as pt,ia as ce,ka as ue,l as Pe,la as Lt,m as ft,ma as Wt,na as Ut,oa as It,r as Q,s as Me,w as mt,y as oe}from"./chunk-JXGR4FYX.mjs";var Ir=15e3,Cr=45e3,Pr=12e4,Ne="platform",Ct="activation",Pt="desired.activation";function bn(i){if(typeof i=="string"&&i.length>0)return i;if(i&&typeof i=="object"){let e=i.note;if(typeof e=="string"&&e.length>0)return e}}var kn=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],he=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let n of this._watches.values())this._arm(n)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let n={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,n),this._hookFirstMediaSignals(n),!n.done&&this._liveAt!==null&&this._arm(n)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=n=>{if(!(!n||e.done)){if(n.muted===!0&&typeof n.addEventListener=="function"){let r=()=>this._firstMedia(e);n.addEventListener("unmute",r,{once:!0}),e.cleanups.push(()=>n.removeEventListener?.("unmute",r));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",n=>t(n))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of kn){let n=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);n.unref?.(),e.timers.push(n)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,n){let r={state:t,elapsedMs:n,stream:e.name},s=bn(this._options.hint());s!==void 0&&(r.hint=s),e.lastEvent=r;for(let o of Array.from(this._handlers))o(r)}};var M=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",r){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,r!==void 0&&(this.cause=r),Object.setPrototypeOf(this,new.target.prototype)}},$e=class extends M{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},qe=class extends M{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function J(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function Or(i){return new X(i)}var X=class{_options;constructor(e){this._options=e}async list(e){let n=xt(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new M("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(Mt)}async getDownloadUrl(e,t){let n=xt(await this._request(t,`/${encodeURIComponent(e)}/download`)),r=n.download_url;if(typeof r!="string"||!_n(r))throw new M("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Mt(n.artifact),downloadUrl:r}}async _request(e,t){let n=gt(this._options.baseUrl,this._options.fallbackUrls),r=null;for(let s of n)try{return await this._requestFromBase(s,e,t)}catch(o){if(r=o instanceof Error?o:new Error(String(o)),r instanceof M&&Tn(r.status))throw r}throw r??new M("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let r=`${de(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,s=await this._resolveToken(),o=await fetch(r,{method:"GET",headers:this._headers(s)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await fetch(r,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw An(o.status,a,d)}try{return await o.json()}catch(a){throw new M(`[urun] runtime artifacts: invalid JSON response from ${de(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=de(t);try{let s=(await e.json()).error;if(s&&typeof s=="object"){let{code:o,message:a}=s;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 Mt(i){if(!i||typeof i!="object")throw new M("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=V(e,"artifact_id")||V(e,"id"),n=V(e,"filename"),r=V(e,"kind"),s=V(e,"status")||"ready",o=Sn(e,"size_bytes"),a=V(e,"sha256");if(!t||!n||!r||o==null||!a)throw new M("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:r,filename:n,contentType:V(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:s,createdAt:V(e,"created_at"),expiresAt:V(e,"expires_at")}}function V(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function Sn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function _n(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function Tn(i){return i===401||i===403}function An(i,e,t){return i===401?new $e(t,e):i===404?new qe(t,e):new M(t,i,e)}function xt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new M("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var H=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)}},pe=class extends H{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},He=class extends H{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Be=class extends H{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)}},je=class extends H{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)}},Ve=class extends H{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)}},Z=class extends H{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 Ot(i){return/^(\d+[smhdw])+$/.test(i)}function Nr(i){if(i==="pin")return{action:"pin"};if(Ot(i))return{action:"retain",duration:i};throw new Z(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Rn(i,e,t){let n=t||e||`HTTP ${i}`;if(i===401)return new pe(n,e??"unauthorized");if(i===404)return new He(n,e??"not_found");if(i===400)return new Z(n,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Be(n,e);case"pin_requires_active_temp":return new je(n,e);case"permanent_locked":return new Ve(n,e)}return new H(n,{status:i,code:e??`http_${i}`})}var ee=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(!Ot(t))throw new Z(`[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 H("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let r=this._buildUrl(t,n.params),s=await this._resolveToken(),o=await this._fetch(r,e,s,n.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(r,e,s,n.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw Rn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,r=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return r&&(n+=`?${r}`),n}_fetch(e,t,n,r){let s={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:s};return r!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(r)),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 pe("[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:r,message:s}=n;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function $r(i){return new ee(i)}var Hr=1e3,Br=12e3;function Ft(i,e,t={}){let n=null,r=0,s=0,o=null,a=-1,d=()=>{let p=i.get("desired.billing.generationSeconds");if(typeof p!="number"||!Number.isFinite(p)||p<=0)return null;let g=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:p,epoch:typeof g=="number"&&Number.isFinite(g)?g:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},l=()=>{if(n===null)return null;let p=Math.min(Math.max(0,Date.now()-r),s);return n+p/1e3},c=()=>{let p=t.creditsPerSecond;if(typeof p=="number"&&Number.isFinite(p)&&p>0)return p;let g=i.get("desired.billing.creditsPerSecond");return typeof g=="number"&&Number.isFinite(g)&&g>0?g:null},u=()=>{let p=l();if(p===null)return;let g=Math.floor(p);if(g<=a)return;a=g;let w={seconds:g},E=c();E!==null&&(w.estimatedCredits=g*E),e(w)},h=p=>{r=Date.now();let g=p===null?0:Math.max(0,r-p);s=Math.max(0,12e3-g)},m=()=>{let p=d();if(p!==null){if(o!==null&&p.epoch!==o){o=p.epoch,n=p.seconds,a=-1,h(p.updatedAtMs),u();return}n!==null&&p.seconds<=n||(o=p.epoch,n=p.seconds,h(p.updatedAtMs),u())}};m();let b=i.on("change",m),S=setInterval(u,1e3);return S.unref?.(),()=>{clearInterval(S),b()}}var En="activity",Dn="visibility",Vr=15e3,Nt=["pointerdown","pointermove","keydown","wheel","touchstart"];function $t(i){let e=i.now??Date.now,t=i.mode==="explicit",n=t?null:i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,r=t?null:i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let h=e();if(!(o!==void 0&&h-o<15e3)){o=h;try{i.awareness.setLocalStateField(En,{at:h})}catch{}}},d=()=>{if(!(s||!r||r.visibilityState===void 0))try{i.awareness.setLocalStateField(Dn,r.visibilityState)}catch{}},l=()=>a(),c=()=>{d(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&a()};if(n)for(let h of Nt)n.addEventListener(h,l,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",c);let u=null;return!t&&i.isProducing&&(u=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),u.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,n)for(let h of Nt)n.removeEventListener(h,l,{capture:!0});r&&r.removeEventListener("visibilitychange",c),u&&(clearInterval(u),u=null)}}}}var Ln="user_activity",Wn="focus",Gr=3e4;function qt(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var fe=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(qt(e.state));let t=e.on("stateChange",r=>{this._setState(qt(r))}),n=()=>{t(),this._transportUnsubs.delete(n)};return this._transportUnsubs.add(n),n}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(Wn,e)}catch{}}}_signal(){this._lastSignalAt=this._now();let e=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(e>=3e4){this._publishNow();return}if(this._trailing)return;let t=Math.max(3e4-e,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},t),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let e={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(e.visibility=this._visibility),this._focus!==void 0&&(e.focus=this._focus);try{this._awareness?.setLocalStateField(Ln,e)}catch{}}dispose(){if(!this._disposed){for(let e of Array.from(this._transportUnsubs))e();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}};var Yr=250;function Ht(i){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,i())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function Bt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=n=>{n.persisted||e||(e=!0,i())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function jt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{i()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Vt="video/mp4";function Kt(i,e={}){let t=e.timesliceMs??1e3,n=null,r=null,s=!1,o=(a,d,l)=>{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 u=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(Vt)?Vt:void 0),h=new MediaStream([a]),m=new c(h,u?{mimeType:u}:void 0);n=m;let b=Promise.resolve();m.ondataavailable=S=>{let p=S.data;s||!p||p.size===0||(b=b.then(async()=>{let g=new Uint8Array(await p.arrayBuffer());s||d(g)}))},m.onstop=()=>{b.then(()=>{s||l()})},m.onerror=()=>{b.then(()=>{s||l()})},m.start(t)};return{start(a,d){if(n||s)return;let l=i.track();if(l){o(l,a,d);return}r=i.onTrack(c=>{!c||n||s||(r?.(),r=null,o(c,a,d))})},stop(){if(s)return;s=!0,r?.(),r=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Un(i){let e=i;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=i.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 Gt(i,e){let t=null,n=!1,r=!1,s=new ReadableStream({pull(o){n||(n=!0,t=i(e),t.start(a=>{if(!r)try{o.enqueue(a)}catch{}},()=>{if(!r){r=!0;try{o.close()}catch{}}}))},cancel(){r=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Un(s)}import{encode as In,decode as Cn}from"@msgpack/msgpack";var Pn=65536;function Qt(i){let e=In(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var me=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(n>Pn)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+n)break;let r=this.buf.subarray(4,4+n);this.buf=this.buf.subarray(4+n),t.push(Object.assign(Cn(r),{raw:r}))}return t}};function Yt(i,e){let t=new DataView(i.buffer,i.byteOffset,i.byteLength),n=t.getUint8(0),r=(n&240)===128,s=n===222;if(!r&&!s&&!(n===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=r?n&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=r?1:s?3:5,l=[];l.push(i.subarray(0,d));for(let m=0;m<a;m++){let b=d,S=te(i,t,d);d=S.end;let g=te(i,t,d).end;if(Mn(t.getUint8(b))){let w=t.getUint8(b),E=(w&224)===160?1:w===217?2:w===218?3:5;if(new TextDecoder().decode(i.subarray(b+E,S.end))==="t"){l.push(i.subarray(b,S.end));let R=new TextEncoder().encode(e);if(R.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");l.push(new Uint8Array([160|R.byteLength]),R)}else l.push(i.subarray(b,g))}else l.push(i.subarray(b,g));d=g}let c=l.reduce((m,b)=>m+b.byteLength,0),u=new Uint8Array(c),h=0;for(let m of l)u.set(m,h),h+=m.byteLength;return u}function Mn(i){return(i&224)===160?!0:i===217||i===218||i===219}function te(i,e,t){let n=e.getUint8(t),r=t;if(n<=127||n>=224)return{start:r,end:t+1};if((n&224)===160)return{start:r,end:t+1+(n&31)};if((n&240)===128||(n&240)===144){let o=n&15;t+=1;let a=(n&240)===128?o*2:o;for(let d=0;d<a;d++)t=te(i,e,t).end;return{start:r,end:t}}let s={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(s[n]!==void 0)return{start:r,end:t+1+s[n]};if(n===217||n===196)return{start:r,end:t+2+e.getUint8(t+1)};if(n===218||n===197)return{start:r,end:t+3+e.getUint16(t+1,!1)};if(n===219||n===198)return{start:r,end:t+5+e.getUint32(t+1,!1)};if(n===220||n===221){let o=n===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===220?3:5;for(let a=0;a<o;a++)t=te(i,e,t).end;return{start:r,end:t}}if(n===222||n===223){let o=n===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===222?3:5;for(let a=0;a<o*2;a++)t=te(i,e,t).end;return{start:r,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${n.toString(16)} at byte ${r}`)}var x=12,Ke=1,xn=0,ge=1,zt=2;function ve(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&Ke)===Ke,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function Xt(i){let e=new Uint8Array(x),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?Ke:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??xn),e}var On=100,Jt=100,we=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??On}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<x)return;let t=ve(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(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 n=this.pending.get(t.frameSeq);if(n||(n={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n)),!n.chunks[t.fragIndex]){n.chunks[t.fragIndex]=e.subarray(x),n.received++,n.received===n.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,n));for(let r of this.pending.keys())r<t.frameSeq-1&&(this.pending.delete(r),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-Jt?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Jt}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let n=t.chunks.reduce((o,a)=>o+a.byteLength,0),r=new Uint8Array(n),s=0;for(let o of t.chunks)r.set(o,s),s+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:r})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Fn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Nn(i){return Fn.test(i)?null:`codec ${JSON.stringify(i)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function Ge(i,e){let t=Nn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var $n=1,Qe=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}if(this.name===null){if(this.buf.byteLength<2)return[];let n=this.buf[0];if(n!==$n)throw new Error(`[urun] wt data stream: unknown header version 0x${n.toString(16)} \u2014 rejecting stream`);let r=this.buf[1];if(r===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+r)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+r)),this.buf=this.buf.subarray(2+r)}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+n)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let r=Et(this.buf.subarray(4,4+n));this.buf=this.buf.subarray(4+n),r===Rt&&(this.ended=!0),t.push({name:this.name,payload:r})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function Zt(i,e){let t=i.getReader();for(;;){let{value:n,done:r}=await t.read();if(r)return;n&&qn(n,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function qn(i,e){let t=i.getReader(),n=new Qe;try{for(;;){let{value:r,done:s}=await t.read();if(s)break;if(!(!r||r.byteLength===0))for(let{name:o,payload:a}of n.push(r))e.onData(o,a)}n.finish()}catch(r){try{await t.cancel?.(r)}catch{}throw r}}var Ye="wt-playout",Hn=class extends(globalThis.AudioWorkletProcessor??Object){holdN=96;fadeN=192;cap=24e3;primeSamples=0;primeWall=12e3;rings=[];held=new Float32Array(0);read=0;depth=0;started=!1;starve=1e9;hadContent=!1;born=!0;xfadeLeft=0;xfadeFrom=new Float32Array(0);constructor(){super(),this.wire()}wire(){let i=this.port;i&&(i.onmessage=e=>this.onMessage(e.data))}post(i){this.port?.postMessage(i)}ensure(i){if(!(this.rings.length===i&&this.held.length===i&&this.rings[0]?.length===this.cap)){this.rings=[];for(let e=0;e<i;e++)this.rings.push(new Float32Array(this.cap));this.held=new Float32Array(i),this.xfadeFrom=new Float32Array(i)}}onMessage(i){if(i.type==="init"){this.holdN=Math.max(1,Math.round(2*i.rate/1e3)),this.fadeN=Math.max(1,Math.round(4*i.rate/1e3)),this.cap=Math.max(1,Math.round(500*i.rate/1e3)),this.primeSamples=Math.max(0,Math.round(i.primeSamples)),this.primeWall=Math.round(250*i.rate/1e3),this.ensure(1);return}if(i.type==="reset"){this.ensure(1),this.read=0,this.depth=0,this.held.fill(0),this.starve=this.holdN+this.fadeN+1,this.hadContent=!1,this.xfadeLeft=0;return}if(i.type!=="pcm")return;let e=i.bufs.map(r=>new Float32Array(r)),t=i.frames;if(this.ensure(e.length),this.depth+t>this.cap){let r=this.depth+t-this.cap;this.read=(this.read+r)%this.cap,this.depth-=r,this.post({type:"overflow",dropped:r})}let n=(this.read+this.depth)%this.cap;for(let r=0;r<t;r++){for(let s=0;s<e.length;s++)this.rings[s][n]=e[s][r];n=n+1===this.cap?0:n+1}this.depth+=t}process(i,e){let t=e[0];if(!t||t.length===0)return!0;this.ensure(t.length);let n=t[0].length;if(!this.started)if(this.depth>=this.primeSamples||this.primeWall<=0)this.started=!0;else{this.primeWall-=n;for(let o of t)o.fill(0);return!0}let r=t.length,s=this.fadeN;for(let o=0;o<n;o++)if(this.depth>0){if(this.starve>0){this.xfadeFrom.set(this.held);for(let a=0;a<r;a++)this.xfadeFrom[a]*=this.holdGain(this.starve);this.xfadeLeft=s,this.born?this.born=!1:this.post({type:"resume"}),this.starve=0}if(this.xfadeLeft>0){let a=1-this.xfadeLeft/s;for(let d=0;d<r;d++){let l=this.rings[d][this.read];this.held[d]=l,t[d][o]=this.xfadeFrom[d]*(1-a)+l*a}this.xfadeLeft--}else for(let a=0;a<r;a++){let d=this.rings[a][this.read];this.held[a]=d,t[a][o]=d}this.read=this.read+1===this.cap?0:this.read+1,this.depth--,this.hadContent=!0}else{this.hadContent&&(this.hadContent=!1,this.post({type:"underrun"})),this.starve++;let a=this.holdGain(this.starve);for(let d=0;d<r;d++)t[d][o]=this.held[d]*a}return!0}holdGain(i){return i<=this.holdN?1:i<=this.holdN+this.fadeN?1-(i-this.holdN)/this.fadeN:0}};function Bn(){return`registerProcessor(${JSON.stringify(Ye)}, ${Hn.toString()})`}function en(){let i=globalThis;return typeof i.Blob!="function"||typeof i.URL?.createObjectURL!="function"?null:i.URL.createObjectURL(new Blob([Bn()],{type:"text/javascript"}))}var ze=40,tn=2,B=48e3,jn=12,Vn=64,Kn=100,Xe=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<x)return;let t=ve(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Kn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let n=this.pending.get(t.frameSeq);if(!n)for(n={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n);this.pending.size>Vn;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=n.fragCount||n.chunks[t.fragIndex]||(n.chunks[t.fragIndex]=e.subarray(x),n.received++,n.received<n.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let r=n.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(r),o=0;for(let a of n.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:n.timestamp,data:s})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},ye=class{constructor(e,t){this.config=e;this.seam=t;let n=this.seam.jitterBufferTargetMs??ze;Number.isFinite(n)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${n} is not finite \u2014 using default ${ze}ms`),n=ze),this.targetS=Math.max(0,n)/1e3}config;seam;decoder=null;ctx=null;ownsCtx=!1;resumeAttempts=0;resumeInFlight=!1;notRunningFrames=0;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;contentBaseS=null;wallBaseS=0;reanchorLogged=!1;lastTsS=null;pendingTs=[];liveSources=new Set;bridgeTrack=null;consumerTrack=null;consumerTrackOf=null;scheduledCount=0;lastScheduledAt=0;lastFrameArrivalAt=0;lastReplyStart=null;rebuildTimes=[];rebuildBudgetLoggedAt=-1e4;lastRemote=null;assembler=new Xe(e=>this.decodeFrame(e));workletNode=null;workletState="legacy";pendingPcm=[];workletStale=!1;underruns=0;resumeFades=0;ringOverflow=0;rateMismatchDropped=0;pendingDropped=0;start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");if(this.seam.ctx)this.ctx=this.seam.ctx,this.ownsCtx=!1;else{if(typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.ownsCtx=!0}this.dest=this.ctx.createMediaStreamDestination(),this.armCtxRearm();try{this.initDecoder(e)}catch(r){throw this.ownsCtx&&this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,r}this.trackSurfaced=!0,this.resumeLoudly("start");let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] playout start produced no bridge track");this.startWorkletLoad(),this.surfaceTrack(n)}startWorkletLoad(){let e=this.ctx;if(!e||!e.audioWorklet)return;let t=globalThis.AudioWorkletNode;if(typeof t!="function")return;let n=en();n!==null&&(this.workletState="loading",e.audioWorklet.addModule(n).then(()=>{if(this.stopped||this.ctx!==e||this.workletState!=="loading")return;let r=new t(e,Ye,{numberOfInputs:0,outputChannelCount:[this.config.channels]});r.connect(this.dest),r.connect(e.destination),r.port.onmessage=s=>this.onWorkletEvent(s.data),this.workletNode=r,this.workletState="ready",r.port.postMessage({type:"init",rate:e.sampleRate,primeSamples:Math.round(this.targetS*e.sampleRate)}),this.flushPendingPcm("ready"),console.info(`[urun] WT audio playout: worklet ring engaged (underrun hold+fade shaping, lead=${(this.targetS*1e3).toFixed(0)}ms, channels=${this.config.channels})`)}).catch(r=>{this.stopped||this.ctx!==e||this.workletState!=="loading"||(this.workletState="legacy",console.warn(`[urun] WT audio worklet module FAILED to load (${r instanceof Error?r.message:String(r)}) \u2014 falling back to the per-frame buffer scheduler: underruns will re-anchor (the crackle the ring player removes)`),this.flushPendingPcm("legacy"))}))}flushPendingPcm(e){let t=this.pendingPcm;this.pendingPcm=[];for(let n of t)e==="ready"?this.pushWorklet(n.planes,n.frames,n.sampleRate,n.timestamp):this.scheduleLegacy(n.planes,n.frames,n.sampleRate,n.timestamp)}onWorkletEvent(e){e.type==="underrun"?this.underruns++:e.type==="resume"?this.resumeFades++:e.type==="overflow"&&(this.ringOverflow+=e.dropped)}armCtxRearm(){let e=this.ctx;if(!e)return;let t=()=>{this.ctx&&this.ctx.state!=="running"&&this.resumeLoudly("statechange")},n=e;typeof n.addEventListener=="function"?n.addEventListener("statechange",t):e.onstatechange=t}resumeLoudly(e){let t=this.ctx;if(!t||!t.resume||this.resumeInFlight)return;let r=t.state!=="running"?++this.resumeAttempts:0;this.resumeInFlight=!0,t.resume().catch(s=>{console.warn(`[urun] WT audio playout context ${e}: resume FAILED (state=${t.state}, attempt=${r||"n/a"}): ${s instanceof Error?s.message:String(s)} \u2014 decoded reply audio would be scheduled into a graph that never renders; retrying per frame`)}).finally(()=>{this.resumeInFlight=!1})}stop(){if(this.stopped)return;this.stopped=!0,this.stopScheduledSources();let e=this.workletNode;if(e){this.workletNode=null,this.workletState="legacy";try{e.port.postMessage({type:"reset"})}catch{}try{e.disconnect()}catch{}}this.pendingPcm=[];try{this.seam.renderHop?.setSource(null)}catch{}this.trackSurfaced&&(this.trackSurfaced=!1,this.deliverSurface(null));try{this.decoder?.close()}catch{}this.ownsCtx&&this.ctx?.close().catch(()=>{})}initDecoder(e){let t=new e({output:n=>this.schedule(n,this.pendingTs.shift()),error:n=>this.onDecoderError(n)});t.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=t}decodeFrame(e){let t=globalThis.EncodedAudioChunk;if(typeof t!="function"||this.stopped)return;if(!this.decoder){let r=globalThis.AudioDecoder;if(typeof r!="function")return;try{this.initDecoder(r)}catch{return}}let n=this.decoder;n&&(this.lastFrameArrivalAt=performance.now(),this.pendingTs.push(e.timestamp),n.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/B)),data:e.data})))}schedule(e,t){let n=this.ctx,r=this.dest;if(!n||!r||this.stopped){e.close();return}if(n.state!=="running"){e.close(),this.contentBaseS=null,this.lastTsS=null,this.notRunningFrames++,(this.notRunningFrames===1||this.notRunningFrames%50===0)&&console.warn(`[urun] WT audio playout context not RUNNING (state=${n.state}): dropping decoded frames instead of scheduling into a graph that never renders \u2014 resume re-armed per frame (attempts=${this.resumeAttempts}, dropped=${this.notRunningFrames})`),this.resumeLoudly("per-frame"),this.workletNode&&!this.workletStale&&(this.workletStale=!0,this.workletNode.port.postMessage({type:"reset"}));return}let s=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),a=e.sampleRate,d=[];for(let l=0;l<o;l++){let c=new Float32Array(s);e.copyTo(c,{planeIndex:l,format:"f32-planar"}),d.push(c)}if(e.close(),this.workletState==="ready"&&this.workletNode){this.pushWorklet(d,s,a,t);return}if(this.workletState==="loading"){this.stashPendingPcm(d,s,a,t);return}this.scheduleLegacy(d,s,a,t)}pushWorklet(e,t,n,r){let s=this.workletNode,o=this.ctx;if(!s||!o||this.stopped)return;if(n!==o.sampleRate||e.length!==Math.max(1,this.config.channels)){this.rateMismatchDropped++,this.rateMismatchDropped===1&&console.warn(`[urun] WT audio decoded frame shape mismatch (rate=${n} vs ctx=${o.sampleRate}, channels=${e.length} vs configured=${this.config.channels}) \u2014 dropped for the ring player`);return}let a=this.lastTsS;if(r!==void 0){let c=r/B;a!==null&&c<a&&(s.port.postMessage({type:"reset"}),this.workletStale=!1,this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout: producer timeline RESTART (${(a-c).toFixed(3)}s backward) \u2014 worklet ring flushed, new content fades in`))),this.lastTsS=c}let d=e.map(c=>c.buffer);s.port.postMessage({type:"pcm",frames:t,bufs:d},d),this.workletStale=!1,this.scheduledCount++;let l=performance.now();if(this.lastScheduledAt===0||l-this.lastScheduledAt>500){let c=this.lastScheduledAt===0?-1:l-this.lastScheduledAt,u=r!==void 0&&a!==null?(r/B-a)*1e3:null;this.lastReplyStart={at:l,idleMs:c,tsJumpMs:u,anchor:"worklet",leadMs:this.targetS*1e3,arrivalToScheduledMs:l-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start (ring): idle=${c.toFixed(0)}ms tsJump=${u===null?"n/a":u.toFixed(0)+"ms"} anchor=worklet lead=${(this.targetS*1e3).toFixed(0)}ms arrival\u2192scheduled=${(l-this.lastFrameArrivalAt).toFixed(1)}ms target=${(this.targetS*1e3).toFixed(0)}ms droppedNotRunning=${this.notRunningFrames}`)}this.lastScheduledAt=l}stashPendingPcm(e,t,n,r){for(this.pendingPcm.push({planes:e,frames:t,sampleRate:n,timestamp:r});this.pendingPcm.length>jn;)this.pendingPcm.shift(),this.pendingDropped===0&&console.warn("[urun] WT audio worklet module still loading past the stash cap \u2014 dropping the oldest stashed frames (the reply opening may clip)"),this.pendingDropped++}scheduleLegacy(e,t,n,r){let s=this.ctx,o=this.dest;if(!s||!o||this.stopped)return;let a=e.length,d=s.createBuffer(a,t,n);for(let b=0;b<a;b++)d.copyToChannel(e[b],b);let l=t/n,c=s.createBufferSource();c.buffer=d,c.connect(o),c.connect(s.destination);let u,h="ride";if(r===void 0)u=Math.max(this.playhead,s.currentTime+this.targetS),h="arrival-fallback";else{this.contentBaseS===null&&(this.contentBaseS=r/B,this.wallBaseS=s.currentTime+this.targetS,h="fresh-anchor"),u=this.wallBaseS+r/B-this.contentBaseS;let b=null;this.lastTsS!==null&&(r<this.lastTsS?(u=s.currentTime+this.targetS,b=`backward ts step ${(this.lastTsS-r/B).toFixed(3)}s (producer clock reset)`):u>s.currentTime+this.targetS+Math.max(l,this.targetS)&&(b=`forward jump ${(u-s.currentTime).toFixed(3)}s out (lead + ${l.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),b&&(h=b.startsWith("backward")?"backward":"surplus",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${b} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=r/B,this.wallBaseS=s.currentTime+this.targetS,u=this.wallBaseS)),u<s.currentTime&&(h="deficit",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored ${(s.currentTime-u).toFixed(3)}s past its content position (arrival deficit exceeded the lead) \u2014 the gap is honest silence at rate 1.0, never a catch-up stretch`)),this.contentBaseS=r/B,this.wallBaseS=s.currentTime+this.targetS,u=this.wallBaseS)}c.start(u),this.liveSources.add(c),c.onended=()=>{this.liveSources.delete(c)},this.scheduledCount++;let m=performance.now();if(this.lastScheduledAt===0||m-this.lastScheduledAt>500){let b=this.lastScheduledAt===0?-1:m-this.lastScheduledAt,S=r!==void 0&&this.lastTsS!==null?(r/B-this.lastTsS)*1e3:null;this.lastReplyStart={at:m,idleMs:b,tsJumpMs:S,anchor:h,leadMs:(u-s.currentTime)*1e3,arrivalToScheduledMs:m-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start: idle=${b.toFixed(0)}ms tsJump=${S===null?"n/a":S.toFixed(0)+"ms"} anchor=${h} lead=${((u-s.currentTime)*1e3).toFixed(0)}ms arrival\u2192scheduled=${(m-this.lastFrameArrivalAt).toFixed(1)}ms target=${(this.targetS*1e3).toFixed(0)}ms droppedNotRunning=${this.notRunningFrames}`)}this.lastScheduledAt=m,r!==void 0&&(this.lastTsS=r/B),this.playhead=u+l}armBridgeEndedWatch(e){e.addEventListener?.("ended",()=>{this.stopped||this.bridgeTrack!==e||console.warn("[urun] WT audio bridge track ended \u2014 inert: playout rides the AudioContext destination (direct-out); the bridge track was the AEC render-hop reference and the element routing surface only. Echo cancellation degrades until the next rebuild re-delivers, the reply does not.")},{once:!0})}playoutProgress(){return{scheduled:this.scheduledCount,lastScheduledAt:this.lastScheduledAt,surfaced:this.trackSurfaced&&this.ctx?.state==="running",droppedNotRunning:this.notRunningFrames,ctxState:this.ctx?.state??"closed",lastReplyStart:this.lastReplyStart,underruns:this.underruns,resumeFades:this.resumeFades,ringOverflow:this.ringOverflow}}rebuildSurface(){if(this.stopped)return;let e=performance.now();if(this.rebuildTimes=this.rebuildTimes.filter(r=>e-r<1e4),this.rebuildTimes.length>=tn){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${tn} in 10s) \u2014 standing down; the media-dead playout-progress verdict escalates to a re-dial if the surface stays dead`));return}this.rebuildTimes.push(e),this.stopScheduledSources();let t=this.ctx;if(t?.state==="closed"&&(console.warn("[urun] WT audio playout rebuild: the retained context is CLOSED (closed behind the lane's back) \u2014 constructing a fresh lane-owned context instead of minting a destination on a dead graph"),t=null,this.ctx=null),!t){let r=globalThis.AudioContext;if(typeof r!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");t=new r({sampleRate:this.config.sampleRate}),this.ctx=t,this.ownsCtx=!0,this.armCtxRearm()}if(t.state!=="running"&&this.resumeLoudly("rebuild"),this.dest=t.createMediaStreamDestination(),this.playhead=0,this.contentBaseS!==null&&this.ctx!==t&&(this.contentBaseS=null,this.lastTsS=null),this.ctx!==t){if(this.workletNode){try{this.workletNode.disconnect()}catch{}this.workletNode=null}this.workletState="legacy",this.workletStale=!1,this.pendingPcm=[],this.startWorkletLoad()}else if(this.workletNode){try{this.workletNode.disconnect()}catch{}this.workletNode.connect(this.dest),this.workletNode.connect(t.destination)}this.trackSurfaced=!0;let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] rebuilt playout produced no bridge track");this.surfaceTrack(n)}deliverSurface(e){if(!e){try{this.consumerTrack?.stop()}catch{}this.consumerTrack=null,this.consumerTrackOf=null,this.seam.onTrack(null);return}if(this.consumerTrackOf===e&&this.consumerTrack&&this.consumerTrack.readyState!=="ended"){this.seam.onTrack(this.consumerTrack);return}try{this.consumerTrack?.stop()}catch{}this.consumerTrack=e.clone(),this.consumerTrackOf=e,this.seam.onTrack(this.consumerTrack)}stopScheduledSources(){for(let e of this.liveSources)try{e.stop()}catch{}this.liveSources.clear()}surfaceTrack(e){this.bridgeTrack=e,this.armBridgeEndedWatch(e),this.lastRemote&&this.lastRemote.readyState==="live"?this.deliverSurface(this.lastRemote):this.deliverSurface(e);let t=this.seam.renderHop;t&&(t.onRemote(n=>{if(this.stopped)return;if(n?this.lastRemote=n:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),n){this.deliverSurface(n);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.deliverSurface(this.lastRemote);return}let r=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.deliverSurface(r)}),t.setSource(e))}onDecoderError(e){if(this.stopped)return;console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=globalThis.AudioDecoder;if(typeof t=="function")try{this.initDecoder(t)}catch(n){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${n instanceof Error?n.message:String(n)}`)}}};var ne=1200;function Je(i,e,t,n,r){let s=n-x;if(s<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/s));if(o>255)return null;let a=[];for(let d=0;d<o;d++){let l=t.subarray(d*s,Math.min((d+1)*s,t.byteLength)),c=Xt({groupId:e>>>0,frameSeq:i>>>0,keyframe:r?.keyframe??!0,fragIndex:d,fragCount:o,lane:r?.lane??ge}),u=new Uint8Array(x+l.byteLength);u.set(c,0),u.set(l,x),a.push(u)}return a}var Gn=`
|
|
2
|
+
import{$ as Et,B as ae,H as de,I as gt,J as vt,K as xe,L as Oe,M as wt,N as yt,O as bt,P as kt,Q as Fe,R as St,S as _t,T as Tt,V as At,W as le,Y as Rt,b as se,c as z,ca as Dt,d as ct,e as Ie,f as Ce,g as ut,h as ht,i as pt,ia as ce,ka as ue,l as Pe,la as Lt,m as ft,ma as Wt,na as Ut,oa as It,r as Q,s as Me,w as mt,y as oe}from"./chunk-JXGR4FYX.mjs";var Ir=15e3,Cr=45e3,Pr=12e4,Ne="platform",Ct="activation",Pt="desired.activation";function bn(i){if(typeof i=="string"&&i.length>0)return i;if(i&&typeof i=="object"){let e=i.note;if(typeof e=="string"&&e.length>0)return e}}var kn=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],he=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let n of this._watches.values())this._arm(n)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let n={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,n),this._hookFirstMediaSignals(n),!n.done&&this._liveAt!==null&&this._arm(n)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=n=>{if(!(!n||e.done)){if(n.muted===!0&&typeof n.addEventListener=="function"){let r=()=>this._firstMedia(e);n.addEventListener("unmute",r,{once:!0}),e.cleanups.push(()=>n.removeEventListener?.("unmute",r));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",n=>t(n))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of kn){let n=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);n.unref?.(),e.timers.push(n)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,n){let r={state:t,elapsedMs:n,stream:e.name},s=bn(this._options.hint());s!==void 0&&(r.hint=s),e.lastEvent=r;for(let o of Array.from(this._handlers))o(r)}};var M=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",r){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,r!==void 0&&(this.cause=r),Object.setPrototypeOf(this,new.target.prototype)}},$e=class extends M{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},qe=class extends M{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function J(i){return{baseUrl:i.baseUrl,fallbackUrls:i.fallbackUrls,orgId:i.orgId,jwt:i.jwt,getAccessToken:i.getAccessToken,authProvider:i.authProvider}}function Or(i){return new X(i)}var X=class{_options;constructor(e){this._options=e}async list(e){let n=xt(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new M("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(Mt)}async getDownloadUrl(e,t){let n=xt(await this._request(t,`/${encodeURIComponent(e)}/download`)),r=n.download_url;if(typeof r!="string"||!_n(r))throw new M("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Mt(n.artifact),downloadUrl:r}}async _request(e,t){let n=gt(this._options.baseUrl,this._options.fallbackUrls),r=null;for(let s of n)try{return await this._requestFromBase(s,e,t)}catch(o){if(r=o instanceof Error?o:new Error(String(o)),r instanceof M&&Tn(r.status))throw r}throw r??new M("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let r=`${de(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,s=await this._resolveToken(),o=await fetch(r,{method:"GET",headers:this._headers(s)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await fetch(r,{method:"GET",headers:this._headers(s)}))}if(!o.ok){let{code:a,message:d}=await this._readError(o,e);throw An(o.status,a,d)}try{return await o.json()}catch(a){throw new M(`[urun] runtime artifacts: invalid JSON response from ${de(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=de(t);try{let s=(await e.json()).error;if(s&&typeof s=="object"){let{code:o,message:a}=s;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 Mt(i){if(!i||typeof i!="object")throw new M("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=i,t=V(e,"artifact_id")||V(e,"id"),n=V(e,"filename"),r=V(e,"kind"),s=V(e,"status")||"ready",o=Sn(e,"size_bytes"),a=V(e,"sha256");if(!t||!n||!r||o==null||!a)throw new M("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:r,filename:n,contentType:V(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:s,createdAt:V(e,"created_at"),expiresAt:V(e,"expires_at")}}function V(i,e){let t=i[e];return typeof t=="string"&&t.length>0?t:void 0}function Sn(i,e){let t=i[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function _n(i){try{return new URL(i).protocol==="https:"}catch{return!1}}function Tn(i){return i===401||i===403}function An(i,e,t){return i===401?new $e(t,e):i===404?new qe(t,e):new M(t,i,e)}function xt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new M("[urun] runtime artifacts: malformed response",0,"bad_response");return i}var H=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)}},pe=class extends H{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},He=class extends H{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Be=class extends H{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)}},je=class extends H{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)}},Ve=class extends H{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)}},Z=class extends H{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 Ot(i){return/^(\d+[smhdw])+$/.test(i)}function Nr(i){if(i==="pin")return{action:"pin"};if(Ot(i))return{action:"retain",duration:i};throw new Z(`[urun] recordings: "${i}" is not a duration or "pin"`)}function Rn(i,e,t){let n=t||e||`HTTP ${i}`;if(i===401)return new pe(n,e??"unauthorized");if(i===404)return new He(n,e??"not_found");if(i===400)return new Z(n,e??"bad_request",400);if(i===409)switch(e){case"retain_not_temp":return new Be(n,e);case"pin_requires_active_temp":return new je(n,e);case"permanent_locked":return new Ve(n,e)}return new H(n,{status:i,code:e??`http_${i}`})}var ee=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(!Ot(t))throw new Z(`[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 H("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let r=this._buildUrl(t,n.params),s=await this._resolveToken(),o=await this._fetch(r,e,s,n.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==s&&(s=a,o=await this._fetch(r,e,s,n.body))}if(!o.ok){let{code:a,message:d}=await this._readError(o);throw Rn(o.status,a,d)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,r=Object.entries(t??{}).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).join("&");return r&&(n+=`?${r}`),n}_fetch(e,t,n,r){let s={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:s};return r!==void 0&&(s["Content-Type"]="application/json",o.body=JSON.stringify(r)),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 pe("[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:r,message:s}=n;return{code:typeof r=="string"?r:void 0,message:typeof s=="string"?s:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function $r(i){return new ee(i)}var Hr=1e3,Br=12e3;function Ft(i,e,t={}){let n=null,r=0,s=0,o=null,a=-1,d=()=>{let p=i.get("desired.billing.generationSeconds");if(typeof p!="number"||!Number.isFinite(p)||p<=0)return null;let g=i.get("desired.billing.epoch"),w=i.get("desired.billing.updatedAtMs");return{seconds:p,epoch:typeof g=="number"&&Number.isFinite(g)?g:0,updatedAtMs:typeof w=="number"&&Number.isFinite(w)?w:null}},l=()=>{if(n===null)return null;let p=Math.min(Math.max(0,Date.now()-r),s);return n+p/1e3},c=()=>{let p=t.creditsPerSecond;if(typeof p=="number"&&Number.isFinite(p)&&p>0)return p;let g=i.get("desired.billing.creditsPerSecond");return typeof g=="number"&&Number.isFinite(g)&&g>0?g:null},u=()=>{let p=l();if(p===null)return;let g=Math.floor(p);if(g<=a)return;a=g;let w={seconds:g},E=c();E!==null&&(w.estimatedCredits=g*E),e(w)},h=p=>{r=Date.now();let g=p===null?0:Math.max(0,r-p);s=Math.max(0,12e3-g)},m=()=>{let p=d();if(p!==null){if(o!==null&&p.epoch!==o){o=p.epoch,n=p.seconds,a=-1,h(p.updatedAtMs),u();return}n!==null&&p.seconds<=n||(o=p.epoch,n=p.seconds,h(p.updatedAtMs),u())}};m();let b=i.on("change",m),S=setInterval(u,1e3);return S.unref?.(),()=>{clearInterval(S),b()}}var En="activity",Dn="visibility",Vr=15e3,Nt=["pointerdown","pointermove","keydown","wheel","touchstart"];function $t(i){let e=i.now??Date.now,t=i.mode==="explicit",n=t?null:i.windowTarget!==void 0?i.windowTarget:typeof window<"u"?window:null,r=t?null:i.documentTarget!==void 0?i.documentTarget:typeof document<"u"?document:null,s=!1,o,a=()=>{if(s)return;let h=e();if(!(o!==void 0&&h-o<15e3)){o=h;try{i.awareness.setLocalStateField(En,{at:h})}catch{}}},d=()=>{if(!(s||!r||r.visibilityState===void 0))try{i.awareness.setLocalStateField(Dn,r.visibilityState)}catch{}},l=()=>a(),c=()=>{d(),(!r||r.visibilityState===void 0||r.visibilityState==="visible")&&a()};if(n)for(let h of Nt)n.addEventListener(h,l,{passive:!0,capture:!0});r&&r.addEventListener("visibilitychange",c);let u=null;return!t&&i.isProducing&&(u=setInterval(()=>{if(!s)try{i.isProducing?.()&&a()}catch{}},15e3),u.unref?.()),a(),d(),{touch:a,dispose(){if(!s){if(s=!0,n)for(let h of Nt)n.removeEventListener(h,l,{capture:!0});r&&r.removeEventListener("visibilitychange",c),u&&(clearInterval(u),u=null)}}}}var Ln="user_activity",Wn="focus",Gr=3e4;function qt(i){switch(i){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var fe=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(qt(e.state));let t=e.on("stateChange",r=>{this._setState(qt(r))}),n=()=>{t(),this._transportUnsubs.delete(n)};return this._transportUnsubs.add(n),n}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(Wn,e)}catch{}}}_signal(){this._lastSignalAt=this._now();let e=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(e>=3e4){this._publishNow();return}if(this._trailing)return;let t=Math.max(3e4-e,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},t),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let e={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(e.visibility=this._visibility),this._focus!==void 0&&(e.focus=this._focus);try{this._awareness?.setLocalStateField(Ln,e)}catch{}}dispose(){if(!this._disposed){for(let e of Array.from(this._transportUnsubs))e();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}};var Yr=250;function Ht(i){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,i())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function Bt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=n=>{n.persisted||e||(e=!0,i())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function jt(i){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{i()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Vt="video/mp4";function Kt(i,e={}){let t=e.timesliceMs??1e3,n=null,r=null,s=!1,o=(a,d,l)=>{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 u=e.mimeType??(typeof c.isTypeSupported=="function"&&c.isTypeSupported(Vt)?Vt:void 0),h=new MediaStream([a]),m=new c(h,u?{mimeType:u}:void 0);n=m;let b=Promise.resolve();m.ondataavailable=S=>{let p=S.data;s||!p||p.size===0||(b=b.then(async()=>{let g=new Uint8Array(await p.arrayBuffer());s||d(g)}))},m.onstop=()=>{b.then(()=>{s||l()})},m.onerror=()=>{b.then(()=>{s||l()})},m.start(t)};return{start(a,d){if(n||s)return;let l=i.track();if(l){o(l,a,d);return}r=i.onTrack(c=>{!c||n||s||(r?.(),r=null,o(c,a,d))})},stop(){if(s)return;s=!0,r?.(),r=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Un(i){let e=i;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=i.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 Gt(i,e){let t=null,n=!1,r=!1,s=new ReadableStream({pull(o){n||(n=!0,t=i(e),t.start(a=>{if(!r)try{o.enqueue(a)}catch{}},()=>{if(!r){r=!0;try{o.close()}catch{}}}))},cancel(){r=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Un(s)}import{encode as In,decode as Cn}from"@msgpack/msgpack";var Pn=65536;function Qt(i){let e=In(i),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var me=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(n>Pn)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+n)break;let r=this.buf.subarray(4,4+n);this.buf=this.buf.subarray(4+n),t.push(Object.assign(Cn(r),{raw:r}))}return t}};function Yt(i,e){let t=new DataView(i.buffer,i.byteOffset,i.byteLength),n=t.getUint8(0),r=(n&240)===128,s=n===222;if(!r&&!s&&!(n===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=r?n&15:s?t.getUint16(1,!1):t.getUint32(1,!1),d=r?1:s?3:5,l=[];l.push(i.subarray(0,d));for(let m=0;m<a;m++){let b=d,S=te(i,t,d);d=S.end;let g=te(i,t,d).end;if(Mn(t.getUint8(b))){let w=t.getUint8(b),E=(w&224)===160?1:w===217?2:w===218?3:5;if(new TextDecoder().decode(i.subarray(b+E,S.end))==="t"){l.push(i.subarray(b,S.end));let R=new TextEncoder().encode(e);if(R.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");l.push(new Uint8Array([160|R.byteLength]),R)}else l.push(i.subarray(b,g))}else l.push(i.subarray(b,g));d=g}let c=l.reduce((m,b)=>m+b.byteLength,0),u=new Uint8Array(c),h=0;for(let m of l)u.set(m,h),h+=m.byteLength;return u}function Mn(i){return(i&224)===160?!0:i===217||i===218||i===219}function te(i,e,t){let n=e.getUint8(t),r=t;if(n<=127||n>=224)return{start:r,end:t+1};if((n&224)===160)return{start:r,end:t+1+(n&31)};if((n&240)===128||(n&240)===144){let o=n&15;t+=1;let a=(n&240)===128?o*2:o;for(let d=0;d<a;d++)t=te(i,e,t).end;return{start:r,end:t}}let s={192:0,194:0,195:0,204:1,205:2,206:4,207:8,208:1,209:2,210:4,211:8,202:4,203:8};if(s[n]!==void 0)return{start:r,end:t+1+s[n]};if(n===217||n===196)return{start:r,end:t+2+e.getUint8(t+1)};if(n===218||n===197)return{start:r,end:t+3+e.getUint16(t+1,!1)};if(n===219||n===198)return{start:r,end:t+5+e.getUint32(t+1,!1)};if(n===220||n===221){let o=n===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===220?3:5;for(let a=0;a<o;a++)t=te(i,e,t).end;return{start:r,end:t}}if(n===222||n===223){let o=n===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=n===222?3:5;for(let a=0;a<o*2;a++)t=te(i,e,t).end;return{start:r,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${n.toString(16)} at byte ${r}`)}var x=12,Ke=1,xn=0,ge=1,zt=2;function ve(i){let e=i.getUint8(8);return{groupId:i.getUint32(0,!0),frameSeq:i.getUint32(4,!0),keyframe:(e&Ke)===Ke,fragIndex:i.getUint8(9),fragCount:i.getUint8(10),lane:i.getUint8(11)}}function Xt(i){let e=new Uint8Array(x),t=new DataView(e.buffer);return t.setUint32(0,i.groupId,!0),t.setUint32(4,i.frameSeq,!0),t.setUint8(8,i.keyframe?Ke:0),t.setUint8(9,i.fragIndex),t.setUint8(10,i.fragCount),t.setUint8(11,i.lane??xn),e}var On=100,Jt=100,we=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??On}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<x)return;let t=ve(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(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 n=this.pending.get(t.frameSeq);if(n||(n={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n)),!n.chunks[t.fragIndex]){n.chunks[t.fragIndex]=e.subarray(x),n.received++,n.received===n.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,n));for(let r of this.pending.keys())r<t.frameSeq-1&&(this.pending.delete(r),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-Jt?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Jt}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let n=t.chunks.reduce((o,a)=>o+a.byteLength,0),r=new Uint8Array(n),s=0;for(let o of t.chunks)r.set(o,s),s+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:r})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var Fn=/^avc[13]\.[0-9a-fA-F]{6}$/;function Nn(i){return Fn.test(i)?null:`codec ${JSON.stringify(i)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function Ge(i,e){let t=Nn(i);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var $n=1,Qe=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}if(this.name===null){if(this.buf.byteLength<2)return[];let n=this.buf[0];if(n!==$n)throw new Error(`[urun] wt data stream: unknown header version 0x${n.toString(16)} \u2014 rejecting stream`);let r=this.buf[1];if(r===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+r)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+r)),this.buf=this.buf.subarray(2+r)}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+n)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let r=Et(this.buf.subarray(4,4+n));this.buf=this.buf.subarray(4+n),r===Rt&&(this.ended=!0),t.push({name:this.name,payload:r})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function Zt(i,e){let t=i.getReader();for(;;){let{value:n,done:r}=await t.read();if(r)return;n&&qn(n,e).catch(s=>{e.onLaneError(s instanceof Error?s:new Error(String(s)))})}}async function qn(i,e){let t=i.getReader(),n=new Qe;try{for(;;){let{value:r,done:s}=await t.read();if(s)break;if(!(!r||r.byteLength===0))for(let{name:o,payload:a}of n.push(r))e.onData(o,a)}n.finish()}catch(r){try{await t.cancel?.(r)}catch{}throw r}}var Ye="wt-playout",Hn=class extends(globalThis.AudioWorkletProcessor??Object){holdN=96;fadeN=192;cap=24e3;primeSamples=0;primeWall=12e3;rings=[];held=new Float32Array(0);read=0;depth=0;started=!1;starve=1e9;hadContent=!1;born=!0;xfadeLeft=0;xfadeFrom=new Float32Array(0);constructor(){super(),this.wire()}wire(){let i=this.port;i&&(i.onmessage=e=>this.onMessage(e.data))}post(i){this.port?.postMessage(i)}ensure(i){if(!(this.rings.length===i&&this.held.length===i&&this.rings[0]?.length===this.cap)){this.rings=[];for(let e=0;e<i;e++)this.rings.push(new Float32Array(this.cap));this.held=new Float32Array(i),this.xfadeFrom=new Float32Array(i)}}onMessage(i){if(i.type==="init"){this.holdN=Math.max(1,Math.round(2*i.rate/1e3)),this.fadeN=Math.max(1,Math.round(4*i.rate/1e3)),this.cap=Math.max(1,Math.round(500*i.rate/1e3)),this.primeSamples=Math.max(0,Math.round(i.primeSamples)),this.primeWall=Math.round(250*i.rate/1e3),this.ensure(1);return}if(i.type==="reset"){this.ensure(1),this.read=0,this.depth=0,this.held.fill(0),this.starve=this.holdN+this.fadeN+1,this.hadContent=!1,this.xfadeLeft=0;return}if(i.type!=="pcm")return;let e=i.bufs.map(r=>new Float32Array(r)),t=i.frames;if(this.ensure(e.length),this.depth+t>this.cap){let r=this.depth+t-this.cap;this.read=(this.read+r)%this.cap,this.depth-=r,this.post({type:"overflow",dropped:r})}let n=(this.read+this.depth)%this.cap;for(let r=0;r<t;r++){for(let s=0;s<e.length;s++)this.rings[s][n]=e[s][r];n=n+1===this.cap?0:n+1}this.depth+=t}process(i,e){let t=e[0];if(!t||t.length===0)return!0;this.ensure(t.length);let n=t[0].length;if(!this.started)if(this.depth>=this.primeSamples||this.primeWall<=0)this.started=!0;else{this.primeWall-=n;for(let o of t)o.fill(0);return!0}let r=t.length,s=this.fadeN;for(let o=0;o<n;o++)if(this.depth>0){if(this.starve>0){this.xfadeFrom.set(this.held);for(let a=0;a<r;a++)this.xfadeFrom[a]*=this.holdGain(this.starve);this.xfadeLeft=s,this.born?this.born=!1:this.post({type:"resume"}),this.starve=0}if(this.xfadeLeft>0){let a=1-this.xfadeLeft/s;for(let d=0;d<r;d++){let l=this.rings[d][this.read];this.held[d]=l,t[d][o]=this.xfadeFrom[d]*(1-a)+l*a}this.xfadeLeft--}else for(let a=0;a<r;a++){let d=this.rings[a][this.read];this.held[a]=d,t[a][o]=d}this.read=this.read+1===this.cap?0:this.read+1,this.depth--,this.hadContent=!0}else{this.hadContent&&(this.hadContent=!1,this.post({type:"underrun"})),this.starve++;let a=this.holdGain(this.starve);for(let d=0;d<r;d++)t[d][o]=this.held[d]*a}return!0}holdGain(i){return i<=this.holdN?1:i<=this.holdN+this.fadeN?1-(i-this.holdN)/this.fadeN:0}};function Bn(){return`registerProcessor(${JSON.stringify(Ye)}, ${Hn.toString()})`}function en(){let i=globalThis;return typeof i.Blob!="function"||typeof i.URL?.createObjectURL!="function"?null:i.URL.createObjectURL(new Blob([Bn()],{type:"text/javascript"}))}var ze=40,tn=2,B=48e3,jn=12,Vn=64,Kn=100,Xe=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<x)return;let t=ve(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-Kn)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let n=this.pending.get(t.frameSeq);if(!n)for(n={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n);this.pending.size>Vn;){let a=1/0;for(let d of this.pending.keys())d<a&&(a=d);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=n.fragCount||n.chunks[t.fragIndex]||(n.chunks[t.fragIndex]=e.subarray(x),n.received++,n.received<n.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let r=n.chunks.reduce((a,d)=>a+(d?.byteLength??0),0),s=new Uint8Array(r),o=0;for(let a of n.chunks)s.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:n.timestamp,data:s})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},ye=class{constructor(e,t){this.config=e;this.seam=t;let n=this.seam.jitterBufferTargetMs??ze;Number.isFinite(n)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${n} is not finite \u2014 using default ${ze}ms`),n=ze),this.targetS=Math.max(0,n)/1e3}config;seam;decoder=null;ctx=null;ownsCtx=!1;resumeAttempts=0;resumeInFlight=!1;notRunningFrames=0;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;contentBaseS=null;wallBaseS=0;reanchorLogged=!1;lastTsS=null;pendingTs=[];liveSources=new Set;bridgeTrack=null;consumerTrack=null;consumerTrackOf=null;scheduledCount=0;lastScheduledAt=0;lastFrameArrivalAt=0;lastReplyStart=null;rebuildTimes=[];rebuildBudgetLoggedAt=-1e4;lastRemote=null;assembler=new Xe(e=>this.decodeFrame(e));workletNode=null;workletState="legacy";pendingPcm=[];workletStale=!1;underruns=0;resumeFades=0;ringOverflow=0;rateMismatchDropped=0;pendingDropped=0;start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");if(this.seam.ctx)this.ctx=this.seam.ctx,this.ownsCtx=!1;else{if(typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.ownsCtx=!0}this.dest=this.ctx.createMediaStreamDestination(),this.armCtxRearm();try{this.initDecoder(e)}catch(r){throw this.ownsCtx&&this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,r}this.trackSurfaced=!0,this.resumeLoudly("start");let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] playout start produced no bridge track");this.startWorkletLoad(),this.surfaceTrack(n)}startWorkletLoad(){let e=this.ctx;if(!e||!e.audioWorklet)return;if(e.sampleRate!==this.config.sampleRate){console.warn(`[urun] WT audio playout: caller context runs at ${e.sampleRate} Hz but the lane decodes at ${this.config.sampleRate} Hz \u2014 the worklet ring player cannot resample, riding the legacy per-frame scheduler (which resamples in-graph)`);return}let t=globalThis.AudioWorkletNode;if(typeof t!="function")return;let n=en();n!==null&&(this.workletState="loading",e.audioWorklet.addModule(n).then(()=>{if(this.stopped||this.ctx!==e||this.workletState!=="loading")return;let r=new t(e,Ye,{numberOfInputs:0,outputChannelCount:[this.config.channels]});r.connect(this.dest),r.connect(e.destination),r.port.onmessage=s=>this.onWorkletEvent(s.data),this.workletNode=r,this.workletState="ready",r.port.postMessage({type:"init",rate:e.sampleRate,primeSamples:Math.round(this.targetS*e.sampleRate)}),this.flushPendingPcm("ready"),console.info(`[urun] WT audio playout: worklet ring engaged (underrun hold+fade shaping, lead=${(this.targetS*1e3).toFixed(0)}ms, channels=${this.config.channels})`)}).catch(r=>{this.stopped||this.ctx!==e||this.workletState!=="loading"||(this.workletState="legacy",console.warn(`[urun] WT audio worklet module FAILED to load (${r instanceof Error?r.message:String(r)}) \u2014 falling back to the per-frame buffer scheduler: underruns will re-anchor (the crackle the ring player removes)`),this.flushPendingPcm("legacy"))}))}flushPendingPcm(e){let t=this.pendingPcm;this.pendingPcm=[];for(let n of t)e==="ready"?this.pushWorklet(n.planes,n.frames,n.sampleRate,n.timestamp):this.scheduleLegacy(n.planes,n.frames,n.sampleRate,n.timestamp)}onWorkletEvent(e){e.type==="underrun"?this.underruns++:e.type==="resume"?this.resumeFades++:e.type==="overflow"&&(this.ringOverflow+=e.dropped)}armCtxRearm(){let e=this.ctx;if(!e)return;let t=()=>{this.ctx&&this.ctx.state!=="running"&&this.resumeLoudly("statechange")},n=e;typeof n.addEventListener=="function"?n.addEventListener("statechange",t):e.onstatechange=t}resumeLoudly(e){let t=this.ctx;if(!t||!t.resume||this.resumeInFlight)return;let r=t.state!=="running"?++this.resumeAttempts:0;this.resumeInFlight=!0,t.resume().catch(s=>{console.warn(`[urun] WT audio playout context ${e}: resume FAILED (state=${t.state}, attempt=${r||"n/a"}): ${s instanceof Error?s.message:String(s)} \u2014 decoded reply audio would be scheduled into a graph that never renders; retrying per frame`)}).finally(()=>{this.resumeInFlight=!1})}stop(){if(this.stopped)return;this.stopped=!0,this.stopScheduledSources();let e=this.workletNode;if(e){this.workletNode=null,this.workletState="legacy";try{e.port.postMessage({type:"reset"})}catch{}try{e.disconnect()}catch{}}this.pendingPcm=[];try{this.seam.renderHop?.setSource(null)}catch{}this.trackSurfaced&&(this.trackSurfaced=!1,this.deliverSurface(null));try{this.decoder?.close()}catch{}this.ownsCtx&&this.ctx?.close().catch(()=>{})}initDecoder(e){let t=new e({output:n=>this.schedule(n,this.pendingTs.shift()),error:n=>this.onDecoderError(n)});t.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels}),this.decoder=t}decodeFrame(e){let t=globalThis.EncodedAudioChunk;if(typeof t!="function"||this.stopped)return;if(!this.decoder){let r=globalThis.AudioDecoder;if(typeof r!="function")return;try{this.initDecoder(r)}catch{return}}let n=this.decoder;n&&(this.lastFrameArrivalAt=performance.now(),this.pendingTs.push(e.timestamp),n.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/B)),data:e.data})))}schedule(e,t){let n=this.ctx,r=this.dest;if(!n||!r||this.stopped){e.close();return}if(n.state!=="running"){e.close(),this.contentBaseS=null,this.lastTsS=null,this.notRunningFrames++,(this.notRunningFrames===1||this.notRunningFrames%50===0)&&console.warn(`[urun] WT audio playout context not RUNNING (state=${n.state}): dropping decoded frames instead of scheduling into a graph that never renders \u2014 resume re-armed per frame (attempts=${this.resumeAttempts}, dropped=${this.notRunningFrames})`),this.resumeLoudly("per-frame"),this.workletNode&&!this.workletStale&&(this.workletStale=!0,this.workletNode.port.postMessage({type:"reset"}));return}let s=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),a=e.sampleRate,d=[];for(let l=0;l<o;l++){let c=new Float32Array(s);e.copyTo(c,{planeIndex:l,format:"f32-planar"}),d.push(c)}if(e.close(),this.workletState==="ready"&&this.workletNode){this.pushWorklet(d,s,a,t);return}if(this.workletState==="loading"){this.stashPendingPcm(d,s,a,t);return}this.scheduleLegacy(d,s,a,t)}pushWorklet(e,t,n,r){let s=this.workletNode,o=this.ctx;if(!s||!o||this.stopped)return;if(n!==o.sampleRate||e.length!==Math.max(1,this.config.channels)){this.rateMismatchDropped++,this.rateMismatchDropped===1&&console.warn(`[urun] WT audio decoded frame shape mismatch (rate=${n} vs ctx=${o.sampleRate}, channels=${e.length} vs configured=${this.config.channels}) \u2014 dropped for the ring player`);return}let a=this.lastTsS;if(r!==void 0){let c=r/B;a!==null&&c<a&&(s.port.postMessage({type:"reset"}),this.workletStale=!1,this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout: producer timeline RESTART (${(a-c).toFixed(3)}s backward) \u2014 worklet ring flushed, new content fades in`))),this.lastTsS=c}let d=e.map(c=>c.buffer);s.port.postMessage({type:"pcm",frames:t,bufs:d},d),this.workletStale=!1,this.scheduledCount++;let l=performance.now();if(this.lastScheduledAt===0||l-this.lastScheduledAt>500){let c=this.lastScheduledAt===0?-1:l-this.lastScheduledAt,u=r!==void 0&&a!==null?(r/B-a)*1e3:null;this.lastReplyStart={at:l,idleMs:c,tsJumpMs:u,anchor:"worklet",leadMs:this.targetS*1e3,arrivalToScheduledMs:l-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start (ring): idle=${c.toFixed(0)}ms tsJump=${u===null?"n/a":u.toFixed(0)+"ms"} anchor=worklet lead=${(this.targetS*1e3).toFixed(0)}ms arrival\u2192scheduled=${(l-this.lastFrameArrivalAt).toFixed(1)}ms target=${(this.targetS*1e3).toFixed(0)}ms droppedNotRunning=${this.notRunningFrames}`)}this.lastScheduledAt=l}stashPendingPcm(e,t,n,r){for(this.pendingPcm.push({planes:e,frames:t,sampleRate:n,timestamp:r});this.pendingPcm.length>jn;)this.pendingPcm.shift(),this.pendingDropped===0&&console.warn("[urun] WT audio worklet module still loading past the stash cap \u2014 dropping the oldest stashed frames (the reply opening may clip)"),this.pendingDropped++}scheduleLegacy(e,t,n,r){let s=this.ctx,o=this.dest;if(!s||!o||this.stopped)return;let a=e.length,d=s.createBuffer(a,t,n);for(let b=0;b<a;b++)d.copyToChannel(e[b],b);let l=t/n,c=s.createBufferSource();c.buffer=d,c.connect(o),c.connect(s.destination);let u,h="ride";if(r===void 0)u=Math.max(this.playhead,s.currentTime+this.targetS),h="arrival-fallback";else{this.contentBaseS===null&&(this.contentBaseS=r/B,this.wallBaseS=s.currentTime+this.targetS,h="fresh-anchor"),u=this.wallBaseS+r/B-this.contentBaseS;let b=null;this.lastTsS!==null&&(r<this.lastTsS?(u=s.currentTime+this.targetS,b=`backward ts step ${(this.lastTsS-r/B).toFixed(3)}s (producer clock reset)`):u>s.currentTime+this.targetS+Math.max(l,this.targetS)&&(b=`forward jump ${(u-s.currentTime).toFixed(3)}s out (lead + ${l.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),b&&(h=b.startsWith("backward")?"backward":"surplus",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${b} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=r/B,this.wallBaseS=s.currentTime+this.targetS,u=this.wallBaseS)),u<s.currentTime&&(h="deficit",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored ${(s.currentTime-u).toFixed(3)}s past its content position (arrival deficit exceeded the lead) \u2014 the gap is honest silence at rate 1.0, never a catch-up stretch`)),this.contentBaseS=r/B,this.wallBaseS=s.currentTime+this.targetS,u=this.wallBaseS)}c.start(u),this.liveSources.add(c),c.onended=()=>{this.liveSources.delete(c)},this.scheduledCount++;let m=performance.now();if(this.lastScheduledAt===0||m-this.lastScheduledAt>500){let b=this.lastScheduledAt===0?-1:m-this.lastScheduledAt,S=r!==void 0&&this.lastTsS!==null?(r/B-this.lastTsS)*1e3:null;this.lastReplyStart={at:m,idleMs:b,tsJumpMs:S,anchor:h,leadMs:(u-s.currentTime)*1e3,arrivalToScheduledMs:m-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start: idle=${b.toFixed(0)}ms tsJump=${S===null?"n/a":S.toFixed(0)+"ms"} anchor=${h} lead=${((u-s.currentTime)*1e3).toFixed(0)}ms arrival\u2192scheduled=${(m-this.lastFrameArrivalAt).toFixed(1)}ms target=${(this.targetS*1e3).toFixed(0)}ms droppedNotRunning=${this.notRunningFrames}`)}this.lastScheduledAt=m,r!==void 0&&(this.lastTsS=r/B),this.playhead=u+l}armBridgeEndedWatch(e){e.addEventListener?.("ended",()=>{this.stopped||this.bridgeTrack!==e||console.warn("[urun] WT audio bridge track ended \u2014 inert: playout rides the AudioContext destination (direct-out); the bridge track was the AEC render-hop reference and the element routing surface only. Echo cancellation degrades until the next rebuild re-delivers, the reply does not.")},{once:!0})}playoutProgress(){return{scheduled:this.scheduledCount,lastScheduledAt:this.lastScheduledAt,surfaced:this.trackSurfaced&&this.ctx?.state==="running",droppedNotRunning:this.notRunningFrames,ctxState:this.ctx?.state??"closed",lastReplyStart:this.lastReplyStart,underruns:this.underruns,resumeFades:this.resumeFades,ringOverflow:this.ringOverflow}}rebuildSurface(){if(this.stopped)return;let e=performance.now();if(this.rebuildTimes=this.rebuildTimes.filter(r=>e-r<1e4),this.rebuildTimes.length>=tn){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${tn} in 10s) \u2014 standing down; the media-dead playout-progress verdict escalates to a re-dial if the surface stays dead`));return}this.rebuildTimes.push(e),this.stopScheduledSources();let t=this.ctx;if(t?.state==="closed"&&(console.warn("[urun] WT audio playout rebuild: the retained context is CLOSED (closed behind the lane's back) \u2014 constructing a fresh lane-owned context instead of minting a destination on a dead graph"),t=null,this.ctx=null),!t){let r=globalThis.AudioContext;if(typeof r!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");t=new r({sampleRate:this.config.sampleRate}),this.ctx=t,this.ownsCtx=!0,this.armCtxRearm()}if(t.state!=="running"&&this.resumeLoudly("rebuild"),this.dest=t.createMediaStreamDestination(),this.playhead=0,this.contentBaseS!==null&&this.ctx!==t&&(this.contentBaseS=null,this.lastTsS=null),this.ctx!==t){if(this.workletNode){try{this.workletNode.disconnect()}catch{}this.workletNode=null}this.workletState="legacy",this.workletStale=!1,this.pendingPcm=[],this.startWorkletLoad()}else if(this.workletNode){try{this.workletNode.disconnect()}catch{}this.workletNode.connect(this.dest),this.workletNode.connect(t.destination)}this.trackSurfaced=!0;let n=this.dest.stream.getAudioTracks()[0];if(!n)throw new Error("[urun] rebuilt playout produced no bridge track");this.surfaceTrack(n)}deliverSurface(e){if(!e){try{this.consumerTrack?.stop()}catch{}this.consumerTrack=null,this.consumerTrackOf=null,this.seam.onTrack(null);return}if(this.consumerTrackOf===e&&this.consumerTrack&&this.consumerTrack.readyState!=="ended"){this.seam.onTrack(this.consumerTrack);return}try{this.consumerTrack?.stop()}catch{}this.consumerTrack=e.clone(),this.consumerTrackOf=e,this.seam.onTrack(this.consumerTrack)}stopScheduledSources(){for(let e of this.liveSources)try{e.stop()}catch{}this.liveSources.clear()}surfaceTrack(e){this.bridgeTrack=e,this.armBridgeEndedWatch(e),this.lastRemote&&this.lastRemote.readyState==="live"?this.deliverSurface(this.lastRemote):this.deliverSurface(e);let t=this.seam.renderHop;t&&(t.onRemote(n=>{if(this.stopped)return;if(n?this.lastRemote=n:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),n){this.deliverSurface(n);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.deliverSurface(this.lastRemote);return}let r=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.deliverSurface(r)}),t.setSource(e))}onDecoderError(e){if(this.stopped)return;console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=globalThis.AudioDecoder;if(typeof t=="function")try{this.initDecoder(t)}catch(n){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${n instanceof Error?n.message:String(n)}`)}}};var ne=1200;function Je(i,e,t,n,r){let s=n-x;if(s<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/s));if(o>255)return null;let a=[];for(let d=0;d<o;d++){let l=t.subarray(d*s,Math.min((d+1)*s,t.byteLength)),c=Xt({groupId:e>>>0,frameSeq:i>>>0,keyframe:r?.keyframe??!0,fragIndex:d,fragCount:o,lane:r?.lane??ge}),u=new Uint8Array(x+l.byteLength);u.set(c,0),u.set(l,x),a.push(u)}return a}var Gn=`
|
|
3
3
|
self.onrtctransform = (event) => {
|
|
4
4
|
const transformer = event.transformer
|
|
5
5
|
if (transformer.options?.role === 'sender') {
|