@urun-sh/core 0.6.40 → 0.6.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/index.js +2 -2
- package/dist/adapter/index.mjs +1 -1
- package/dist/{app-MGYVBX2I.mjs → app-WK7H3ZNF.mjs} +1 -1
- package/dist/{chunk-UVRSEGB2.mjs → chunk-2QAHTS3L.mjs} +1 -1
- package/dist/{chunk-2WN3OQWP.mjs → chunk-EWKKEBQJ.mjs} +2 -2
- package/dist/{chunk-WVJ4Y5IW.mjs → chunk-JXGR4FYX.mjs} +1 -1
- package/dist/index.browser.d.mts +5 -0
- package/dist/index.browser.d.ts +5 -0
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +2 -2
- package/dist/index.d.mts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.js +1 -1
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.js +1 -1
- package/dist/internal.mjs +1 -1
- package/package.json +1 -1
package/dist/index.browser.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";var Rl=Object.create;var pn=Object.defineProperty;var Cl=Object.getOwnPropertyDescriptor;var El=Object.getOwnPropertyNames;var Pl=Object.getPrototypeOf,xl=Object.prototype.hasOwnProperty;var U=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Dl=(n,e)=>{for(var t in e)pn(n,t,{get:e[t],enumerable:!0})},xo=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of El(e))!xl.call(n,s)&&s!==t&&pn(n,s,{get:()=>e[s],enumerable:!(r=Cl(e,s))||r.enumerable});return n};var Ns=(n,e,t)=>(t=n!=null?Rl(Pl(n)):{},xo(e||!n||!n.__esModule?pn(t,"default",{value:n,enumerable:!0}):t,n)),Al=n=>xo(pn({},"__esModule",{value:!0}),n);var la=U((Eg,da)=>{"use strict";var Ot=1e3,Ut=Ot*60,Nt=Ut*60,lt=Nt*24,Ru=lt*7,Cu=lt*365.25;da.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return Eu(n);if(t==="number"&&isFinite(n))return e.long?xu(n):Pu(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function Eu(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Cu;case"weeks":case"week":case"w":return t*Ru;case"days":case"day":case"d":return t*lt;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Nt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ut;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ot;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Pu(n){var e=Math.abs(n);return e>=lt?Math.round(n/lt)+"d":e>=Nt?Math.round(n/Nt)+"h":e>=Ut?Math.round(n/Ut)+"m":e>=Ot?Math.round(n/Ot)+"s":n+"ms"}function xu(n){var e=Math.abs(n);return e>=lt?kn(n,e,lt,"day"):e>=Nt?kn(n,e,Nt,"hour"):e>=Ut?kn(n,e,Ut,"minute"):e>=Ot?kn(n,e,Ot,"second"):n+" ms"}function kn(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var pa=U((Pg,ua)=>{"use strict";function Du(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=la(),t.destroy=l,Object.keys(n).forEach(d=>{t[d]=n[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let u=0;for(let p=0;p<d.length;p++)u=(u<<5)-u+d.charCodeAt(p),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(d){let u,p=null,f,g;function h(...m){if(!h.enabled)return;let _=h,v=Number(new Date),S=v-(u||v);_.diff=S,_.prev=u,_.curr=v,u=v,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let w=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(T,y)=>{if(T==="%%")return"%";w++;let E=t.formatters[y];if(typeof E=="function"){let N=m[w];T=E.call(_,N),m.splice(w,1),w--}return T}),t.formatArgs.call(_,m),(_.log||t.log).apply(_,m)}return h.namespace=d,h.useColors=t.useColors(),h.color=t.selectColor(d),h.extend=r,h.destroy=t.destroy,Object.defineProperty(h,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(f!==t.namespaces&&(f=t.namespaces,g=t.enabled(d)),g),set:m=>{p=m}}),typeof t.init=="function"&&t.init(h),h}function r(d,u){let p=t(this.namespace+(typeof u>"u"?":":u)+d);return p.log=this.log,p}function s(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let u=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of u)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function i(d,u){let p=0,f=0,g=-1,h=0;for(;p<d.length;)if(f<u.length&&(u[f]===d[p]||u[f]==="*"))u[f]==="*"?(g=f,h=p,f++):(p++,f++);else if(g!==-1)f=g+1,h++,p=h;else return!1;for(;f<u.length&&u[f]==="*";)f++;return f===u.length}function o(){let d=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),d}function a(d){for(let u of t.skips)if(i(d,u))return!1;for(let u of t.names)if(i(d,u))return!0;return!1}function c(d){return d instanceof Error?d.stack||d.message:d}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}ua.exports=Du});var Ur=U((me,Tn)=>{"use strict";me.formatArgs=Iu;me.save=Lu;me.load=Mu;me.useColors=Au;me.storage=Ou();me.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();me.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Au(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Iu(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Tn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,r=0;n[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),n.splice(r,0,e)}me.log=console.debug||console.log||(()=>{});function Lu(n){try{n?me.storage.setItem("debug",n):me.storage.removeItem("debug")}catch{}}function Mu(){let n;try{n=me.storage.getItem("debug")||me.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Ou(){try{return localStorage}catch{}}Tn.exports=pa()(me);var{formatters:Uu}=Tn.exports;Uu.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var fa=U(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0})});var ce=U(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.Logger=void 0;var Wt=Ur(),Ft="media-client",Ys=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Wt.default)(`${Ft}:${e}`),this._warn=(0,Wt.default)(`${Ft}:WARN:${e}`),this._error=(0,Wt.default)(`${Ft}:ERROR:${e}`)):(this._debug=(0,Wt.default)(Ft),this._warn=(0,Wt.default)(`${Ft}:WARN`),this._error=(0,Wt.default)(`${Ft}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Rn.Logger=Ys});var Ra=U((Ag,Qs)=>{"use strict";var $t=typeof Reflect=="object"?Reflect:null,ma=$t&&typeof $t.apply=="function"?$t.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)},Cn;$t&&typeof $t.ownKeys=="function"?Cn=$t.ownKeys:Object.getOwnPropertySymbols?Cn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Cn=function(e){return Object.getOwnPropertyNames(e)};function Nu(n){console&&console.warn&&console.warn(n)}var _a=Number.isNaN||function(e){return e!==e};function H(){H.init.call(this)}Qs.exports=H;Qs.exports.once=ju;H.EventEmitter=H;H.prototype._events=void 0;H.prototype._eventsCount=0;H.prototype._maxListeners=void 0;var ga=10;function En(n){if(typeof n!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof n)}Object.defineProperty(H,"defaultMaxListeners",{enumerable:!0,get:function(){return ga},set:function(n){if(typeof n!="number"||n<0||_a(n))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+n+".");ga=n}});H.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};H.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||_a(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function va(n){return n._maxListeners===void 0?H.defaultMaxListeners:n._maxListeners}H.prototype.getMaxListeners=function(){return va(this)};H.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var s=e==="error",i=this._events;if(i!==void 0)s=s&&i.error===void 0;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=i[e];if(c===void 0)return!1;if(typeof c=="function")ma(c,this,t);else for(var l=c.length,d=ka(c,l),r=0;r<l;++r)ma(d[r],this,t);return!0};function wa(n,e,t,r){var s,i,o;if(En(t),i=n._events,i===void 0?(i=n._events=Object.create(null),n._eventsCount=0):(i.newListener!==void 0&&(n.emit("newListener",e,t.listener?t.listener:t),i=n._events),o=i[e]),o===void 0)o=i[e]=t,++n._eventsCount;else if(typeof o=="function"?o=i[e]=r?[t,o]:[o,t]:r?o.unshift(t):o.push(t),s=va(n),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=n,a.type=e,a.count=o.length,Nu(a)}return n}H.prototype.addListener=function(e,t){return wa(this,e,t,!1)};H.prototype.on=H.prototype.addListener;H.prototype.prependListener=function(e,t){return wa(this,e,t,!0)};function Wu(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ya(n,e,t){var r={fired:!1,wrapFn:void 0,target:n,type:e,listener:t},s=Wu.bind(r);return s.listener=t,r.wrapFn=s,s}H.prototype.once=function(e,t){return En(t),this.on(e,ya(this,e,t)),this};H.prototype.prependOnceListener=function(e,t){return En(t),this.prependListener(e,ya(this,e,t)),this};H.prototype.removeListener=function(e,t){var r,s,i,o,a;if(En(t),s=this._events,s===void 0)return this;if(r=s[e],r===void 0)return this;if(r===t||r.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,r.listener||t));else if(typeof r!="function"){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;i===0?r.shift():Fu(r,i),r.length===1&&(s[e]=r[0]),s.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};H.prototype.off=H.prototype.removeListener;H.prototype.removeAllListeners=function(e){var t,r,s;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var i=Object.keys(r),o;for(s=0;s<i.length;++s)o=i[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=r[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this};function ba(n,e,t){var r=n._events;if(r===void 0)return[];var s=r[e];return s===void 0?[]:typeof s=="function"?t?[s.listener||s]:[s]:t?$u(s):ka(s,s.length)}H.prototype.listeners=function(e){return ba(this,e,!0)};H.prototype.rawListeners=function(e){return ba(this,e,!1)};H.listenerCount=function(n,e){return typeof n.listenerCount=="function"?n.listenerCount(e):Sa.call(n,e)};H.prototype.listenerCount=Sa;function Sa(n){var e=this._events;if(e!==void 0){var t=e[n];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}H.prototype.eventNames=function(){return this._eventsCount>0?Cn(this._events):[]};function ka(n,e){for(var t=new Array(e),r=0;r<e;++r)t[r]=n[r];return t}function Fu(n,e){for(;e+1<n.length;e++)n[e]=n[e+1];n.pop()}function $u(n){for(var e=new Array(n.length),t=0;t<e.length;++t)e[t]=n[t].listener||n[t];return e}function ju(n,e){return new Promise(function(t,r){function s(o){n.removeListener(e,i),r(o)}function i(){typeof n.removeListener=="function"&&n.removeListener("error",s),t([].slice.call(arguments))}Ta(n,e,i,{once:!0}),e!=="error"&&qu(n,s,{once:!0})})}function qu(n,e,t){typeof n.on=="function"&&Ta(n,"error",e,t)}function Ta(n,e,t,r){if(typeof n.on=="function")r.once?n.once(e,t):n.on(e,t);else if(typeof n.addEventListener=="function")n.addEventListener(e,function s(i){r.once&&n.removeEventListener(e,s),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof n)}});var ge=U(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.EnhancedEventEmitter=void 0;var Bu=Ra(),Hu=ce(),Vu=new Hu.Logger("EnhancedEventEmitter"),Js=class extends Bu.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(r){Vu.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,r);try{super.emit("listenererror",e,r)}catch{}return!!super.listenerCount(e)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}};Pn.EnhancedEventEmitter=Js});var Se=U(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.InvalidStateError=jt.UnsupportedError=void 0;var Xs=class n extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,n):this.stack=new Error(e).stack}};jt.UnsupportedError=Xs;var Zs=class n extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,n):this.stack=new Error(e).stack}};jt.InvalidStateError=Zs});var ut=U(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.clone=zu;Nr.generateRandomNumber=Gu;Nr.deepFreeze=Ca;function zu(n){if(n!==void 0)return Number.isNaN(n)?NaN:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}function Gu(){return Math.round(Math.random()*1e7)}function Ca(n){let e=Reflect.ownKeys(n);for(let t of e){let r=n[t];(r&&typeof r=="object"||typeof r=="function")&&Ca(r)}return Object.freeze(n)}});var Ea=U(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.Logger=void 0;var qt=Ur(),Bt="h264-profile-level-id",ei=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,qt.default)(`${Bt}:${e}`),this._warn=(0,qt.default)(`${Bt}:WARN:${e}`),this._error=(0,qt.default)(`${Bt}:ERROR:${e}`)):(this._debug=(0,qt.default)(Bt),this._warn=(0,qt.default)(`${Bt}:WARN`),this._error=(0,qt.default)(`${Bt}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};xn.Logger=ei});var La=U(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.ProfileLevelId=re.Level=re.Profile=void 0;re.parseProfileLevelId=Aa;re.profileLevelIdToString=Ia;re.profileToString=Ju;re.levelToString=Xu;re.parseSdpProfileLevelId=pt;re.isSameProfile=Zu;re.isSameProfileAndLevel=ep;re.generateProfileLevelIdStringForAnswer=tp;re.supportedLevel=rp;var Ku=Ea(),Ie=new Ku.Logger,V;(function(n){n[n.ConstrainedBaseline=1]="ConstrainedBaseline",n[n.Baseline=2]="Baseline",n[n.Main=3]="Main",n[n.ConstrainedHigh=4]="ConstrainedHigh",n[n.High=5]="High",n[n.PredictiveHigh444=6]="PredictiveHigh444"})(V||(re.Profile=V={}));var R;(function(n){n[n.L1_b=0]="L1_b",n[n.L1=10]="L1",n[n.L1_1=11]="L1_1",n[n.L1_2=12]="L1_2",n[n.L1_3=13]="L1_3",n[n.L2=20]="L2",n[n.L2_1=21]="L2_1",n[n.L2_2=22]="L2_2",n[n.L3=30]="L3",n[n.L3_1=31]="L3_1",n[n.L3_2=32]="L3_2",n[n.L4=40]="L4",n[n.L4_1=41]="L4_1",n[n.L4_2=42]="L4_2",n[n.L5=50]="L5",n[n.L5_1=51]="L5_1",n[n.L5_2=52]="L5_2"})(R||(re.Level=R={}));var Ht=class{profile;level;constructor(e,t){this.profile=e,this.level=t}};re.ProfileLevelId=Ht;var Yu=new Ht(V.ConstrainedBaseline,R.L3_1),De=class{mask;masked_value;constructor(e){this.mask=~xa("x",e),this.masked_value=xa("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}},Ae=class{profile_idc;profile_iop;profile;constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}},Qu=[new Ae(66,new De("x1xx0000"),V.ConstrainedBaseline),new Ae(77,new De("1xxx0000"),V.ConstrainedBaseline),new Ae(88,new De("11xx0000"),V.ConstrainedBaseline),new Ae(66,new De("x0xx0000"),V.Baseline),new Ae(88,new De("10xx0000"),V.Baseline),new Ae(77,new De("0x0x0000"),V.Main),new Ae(100,new De("00000000"),V.High),new Ae(100,new De("00001100"),V.ConstrainedHigh),new Ae(244,new De("00000000"),V.PredictiveHigh444)],Pa=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:R.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:R.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:R.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:R.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:R.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:R.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:R.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:R.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:R.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:R.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:R.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:R.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:R.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:R.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:R.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:R.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:R.L5_2}];function Aa(n){if(typeof n!="string"||n.length!==6)return;let t=parseInt(n,16);if(t===0)return;let r=t&255,s=t>>8&255,i=t>>16&255,o;switch(r){case R.L1_1:{o=(s&16)!==0?R.L1_b:R.L1_1;break}case R.L1:case R.L1_2:case R.L1_3:case R.L2:case R.L2_1:case R.L2_2:case R.L3:case R.L3_1:case R.L3_2:case R.L4:case R.L4_1:case R.L4_2:case R.L5:case R.L5_1:case R.L5_2:{o=r;break}default:{Ie.warn(`parseProfileLevelId() | unrecognized level_idc [str:${n}, level_idc:${r}]`);return}}for(let a of Qu)if(i===a.profile_idc&&a.profile_iop.isMatch(s))return Ie.debug(`parseProfileLevelId() | result [str:${n}, profile:${a.profile}, level:${o}]`),new Ht(a.profile,o);Ie.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${n}, profile_idc:${i}, profile_iop:${s}]`)}function Ia(n){if(n.level==R.L1_b)switch(n.profile){case V.ConstrainedBaseline:return"42f00b";case V.Baseline:return"42100b";case V.Main:return"4d100b";default:{Ie.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${n.profile}`);return}}let e;switch(n.profile){case V.ConstrainedBaseline:{e="42e0";break}case V.Baseline:{e="4200";break}case V.Main:{e="4d00";break}case V.ConstrainedHigh:{e="640c";break}case V.High:{e="6400";break}case V.PredictiveHigh444:{e="f400";break}default:{Ie.warn(`profileLevelIdToString() | unrecognized profile ${n.profile}`);return}}let t=n.level.toString(16);return t.length===1&&(t=`0${t}`),`${e}${t}`}function Ju(n){switch(n){case V.ConstrainedBaseline:return"ConstrainedBaseline";case V.Baseline:return"Baseline";case V.Main:return"Main";case V.ConstrainedHigh:return"ConstrainedHigh";case V.High:return"High";case V.PredictiveHigh444:return"PredictiveHigh444";default:{Ie.warn(`profileToString() | unrecognized profile ${n}`);return}}}function Xu(n){switch(n){case R.L1_b:return"1b";case R.L1:return"1";case R.L1_1:return"1.1";case R.L1_2:return"1.2";case R.L1_3:return"1.3";case R.L2:return"2";case R.L2_1:return"2.1";case R.L2_2:return"2.2";case R.L3:return"3";case R.L3_1:return"3.1";case R.L3_2:return"3.2";case R.L4:return"4";case R.L4_1:return"4.1";case R.L4_2:return"4.2";case R.L5:return"5";case R.L5_1:return"5.1";case R.L5_2:return"5.2";default:{Ie.warn(`levelToString() | unrecognized level ${n}`);return}}}function pt(n={}){let e=n["profile-level-id"];return e?Aa(e):Yu}function Zu(n={},e={}){let t=pt(n),r=pt(e);return!!(t&&r&&t.profile===r.profile)}function ep(n={},e={}){let t=pt(n),r=pt(e);return!!(t&&r&&t.profile===r.profile&&t.level==r.level)}function tp(n={},e={}){if(!n["profile-level-id"]&&!e["profile-level-id"]){Ie.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");return}let t=pt(n),r=pt(e);if(!t)throw new TypeError("invalid local_profile_level_id");if(!r)throw new TypeError("invalid remote_profile_level_id");if(t.profile!==r.profile)throw new TypeError("H264 Profile mismatch");let s=Da(n)&&Da(e),i=t.level,o=r.level,a=sp(i,o),c=s?i:a;return Ie.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${t.profile}, level:${c}]`),Ia(new Ht(t.profile,c))}function rp(n,e){for(let r=Pa.length-1;r>=0;--r){let s=Pa[r];if(s.max_macroblock_frame_size*256<=n&&s.max_macroblocks_per_second<=e*s.max_macroblock_frame_size)return Ie.debug(`supportedLevel() | result [max_frame_pixel_count:${n}, max_fps:${e}, level:${s.level}]`),s.level}Ie.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${n}, max_fps:${e}]`)}function xa(n,e){return+(e[0]===n)<<7|+(e[1]===n)<<6|+(e[2]===n)<<5|+(e[3]===n)<<4|+(e[4]===n)<<3|+(e[5]===n)<<2|+(e[6]===n)<<1|+(e[7]===n)<<0}function np(n,e){return n===R.L1_b?e!==R.L1&&e!==R.L1_b:e===R.L1_b?n!==R.L1:n<e}function sp(n,e){return np(n,e)?n:e}function Da(n={}){let e=n["level-asymmetry-allowed"];return e===!0||e===1||e==="1"}});var Ne=U(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.validateAndNormalizeRtpCapabilities=dp;de.validateAndNormalizeRtpParameters=ri;de.validateAndNormalizeSctpStreamParameters=lp;de.validateSctpCapabilities=up;de.getExtendedRtpCapabilities=pp;de.getRecvRtpCapabilities=hp;de.getSendRtpCapabilities=fp;de.getSendingRtpParameters=mp;de.getSendingRemoteRtpParameters=gp;de.reduceCodecs=_p;de.generateProbatorRtpParameters=vp;de.canSend=wp;de.canReceive=yp;var Ma=La(),ip=ut(),op="probator",ap=1234,cp=127;function dp(n){if(typeof n!="object")throw new TypeError("caps is not an object");if(n.codecs&&!Array.isArray(n.codecs))throw new TypeError("caps.codecs is not an array");n.codecs||(n.codecs=[]);for(let e of n.codecs)bp(e);if(n.headerExtensions&&!Array.isArray(n.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");n.headerExtensions||(n.headerExtensions=[]);for(let e of n.headerExtensions)Sp(e)}function ri(n){if(typeof n!="object")throw new TypeError("params is not an object");if(n.mid&&typeof n.mid!="string")throw new TypeError("params.mid is not a string");if(!Array.isArray(n.codecs))throw new TypeError("missing params.codecs");for(let e of n.codecs)kp(e);if(n.headerExtensions&&!Array.isArray(n.headerExtensions))throw new TypeError("params.headerExtensions is not an array");n.headerExtensions||(n.headerExtensions=[]);for(let e of n.headerExtensions)Tp(e);if(n.encodings&&!Array.isArray(n.encodings))throw new TypeError("params.encodings is not an array");n.encodings||(n.encodings=[]);for(let e of n.encodings)Rp(e);if(n.rtcp&&typeof n.rtcp!="object")throw new TypeError("params.rtcp is not an object");n.rtcp||(n.rtcp={}),Cp(n.rtcp)}function lp(n){if(typeof n!="object")throw new TypeError("params is not an object");if(typeof n.streamId!="number")throw new TypeError("missing params.streamId");let e=!1;if(typeof n.ordered=="boolean"?e=!0:n.ordered=!0,n.maxPacketLifeTime&&typeof n.maxPacketLifeTime!="number")throw new TypeError("invalid params.maxPacketLifeTime");if(n.maxRetransmits&&typeof n.maxRetransmits!="number")throw new TypeError("invalid params.maxRetransmits");if(n.maxPacketLifeTime&&n.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(e&&n.ordered&&(n.maxPacketLifeTime||n.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(!e&&(n.maxPacketLifeTime||n.maxRetransmits)&&(n.ordered=!1),n.label&&typeof n.label!="string")throw new TypeError("invalid params.label");if(n.protocol&&typeof n.protocol!="string")throw new TypeError("invalid params.protocol")}function up(n){if(typeof n!="object")throw new TypeError("caps is not an object");if(!n.numStreams||typeof n.numStreams!="object")throw new TypeError("missing caps.numStreams");Ep(n.numStreams)}function pp(n,e,t){let r={codecs:[],headerExtensions:[]};if(t)for(let s of n.codecs??[]){if(Vt(s))continue;let i=(e.codecs??[]).find(a=>ti(a,s,{strict:!0,modify:!0}));if(!i)continue;let o={kind:s.kind,mimeType:s.mimeType,clockRate:s.clockRate,channels:s.channels,localPayloadType:s.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:s.parameters??{},remoteParameters:i.parameters??{},rtcpFeedback:Oa(s,i)};r.codecs.push(o)}else for(let s of e.codecs??[]){if(Vt(s))continue;let i=(n.codecs??[]).find(a=>ti(a,s,{strict:!0,modify:!0}));if(!i)continue;let o={kind:i.kind,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,localPayloadType:i.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:s.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:i.parameters??{},remoteParameters:s.parameters??{},rtcpFeedback:Oa(i,s)};r.codecs.push(o)}for(let s of r.codecs){let i=n.codecs.find(a=>Vt(a)&&a.parameters?.apt===s.localPayloadType),o=e.codecs.find(a=>Vt(a)&&a.parameters?.apt===s.remotePayloadType);i&&o&&(s.localRtxPayloadType=i.preferredPayloadType,s.remoteRtxPayloadType=o.preferredPayloadType)}for(let s of e.headerExtensions){let i=n.headerExtensions.find(a=>Pp(a,s));if(!i)continue;let o={kind:s.kind,uri:s.uri,sendId:i.preferredId,recvId:s.preferredId,encrypt:i.preferredEncrypt??!1,direction:"sendrecv"};switch(s.direction){case"sendrecv":{o.direction="sendrecv";break}case"recvonly":{o.direction="sendonly";break}case"sendonly":{o.direction="recvonly";break}case"inactive":{o.direction="inactive";break}}r.headerExtensions.push(o)}return r}function hp(n){return Na({direction:"recvonly",extendedRtpCapabilities:n})}function fp(n){return Na({direction:"sendonly",extendedRtpCapabilities:n})}function mp(n,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let r of e.codecs){if(r.kind!==n)continue;let s={mimeType:r.mimeType,payloadType:r.localPayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(s),r.localRtxPayloadType){let i={mimeType:`${r.kind}/rtx`,payloadType:r.localRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let r of e.headerExtensions){if(r.kind&&r.kind!==n||r.direction!=="sendrecv"&&r.direction!=="sendonly")continue;let s={uri:r.uri,id:r.sendId,encrypt:r.encrypt,parameters:{}};t.headerExtensions.push(s)}return t}function gp(n,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let r of e.codecs){if(r.kind!==n)continue;let s={mimeType:r.mimeType,payloadType:r.localPayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.remoteParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(s),r.localRtxPayloadType){let i={mimeType:`${r.kind}/rtx`,payloadType:r.localRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let r of e.headerExtensions){if(r.kind&&r.kind!==n||r.direction!=="sendrecv"&&r.direction!=="sendonly")continue;let s={uri:r.uri,id:r.sendId,encrypt:r.encrypt,parameters:{}};t.headerExtensions.push(s)}if(t.headerExtensions.some(r=>r.uri==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))for(let r of t.codecs)r.rtcpFeedback=(r.rtcpFeedback??[]).filter(s=>s.type!=="goog-remb");else if(t.headerExtensions.some(r=>r.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"))for(let r of t.codecs)r.rtcpFeedback=(r.rtcpFeedback??[]).filter(s=>s.type!=="transport-cc");else for(let r of t.codecs)r.rtcpFeedback=(r.rtcpFeedback??[]).filter(s=>s.type!=="transport-cc"&&s.type!=="goog-remb");return t}function _p(n,e){let t=[];if(!e)t.push(n[0]),Vt(n[1])&&t.push(n[1]);else{for(let r=0;r<n.length;++r)if(ti(n[r],e,{strict:!0})){t.push(n[r]),Vt(n[r+1])&&t.push(n[r+1]);break}if(t.length===0)throw new TypeError("no matching codec found")}return t}function vp(n){n=ip.clone(n),ri(n);let e={mid:op,codecs:[],headerExtensions:[],encodings:[{ssrc:ap}],rtcp:{cname:"probator"}};return e.codecs.push(n.codecs[0]),e.codecs[0].payloadType=cp,e.headerExtensions=n.headerExtensions,e}function wp(n,e){return(e.codecs??[]).some(t=>t.kind===n)}function yp(n,e){if(ri(n),n.codecs.length===0)return!1;let t=n.codecs[0];return(e.codecs??[]).some(r=>r.preferredPayloadType===t.payloadType)}function bp(n){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof n!="object")throw new TypeError("codec is not an object");if(!n.mimeType||typeof n.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(n.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(n.kind=t[1].toLowerCase(),typeof n.preferredPayloadType!="number")throw new TypeError("missing codec.preferredPayloadType");if(typeof n.clockRate!="number")throw new TypeError("missing codec.clockRate");n.kind==="audio"?typeof n.channels!="number"&&(n.channels=1):delete n.channels,(!n.parameters||typeof n.parameters!="object")&&(n.parameters={});for(let r of Object.keys(n.parameters)){let s=n.parameters[r];if(s===void 0&&(n.parameters[r]="",s=""),typeof s!="string"&&typeof s!="number")throw new TypeError(`invalid codec parameter [key:${r}s, value:${s}]`);if(r==="apt"&&typeof s!="number")throw new TypeError("invalid codec apt parameter")}(!n.rtcpFeedback||!Array.isArray(n.rtcpFeedback))&&(n.rtcpFeedback=[]);for(let r of n.rtcpFeedback)Ua(r)}function Ua(n){if(typeof n!="object")throw new TypeError("fb is not an object");if(!n.type||typeof n.type!="string")throw new TypeError("missing fb.type");(!n.parameter||typeof n.parameter!="string")&&(n.parameter="")}function Sp(n){if(typeof n!="object")throw new TypeError("ext is not an object");if(n.kind!=="audio"&&n.kind!=="video")throw new TypeError("invalid ext.kind");if(!n.uri||typeof n.uri!="string")throw new TypeError("missing ext.uri");if(typeof n.preferredId!="number")throw new TypeError("missing ext.preferredId");if(n.preferredEncrypt&&typeof n.preferredEncrypt!="boolean")throw new TypeError("invalid ext.preferredEncrypt");if(n.preferredEncrypt||(n.preferredEncrypt=!1),n.direction&&typeof n.direction!="string")throw new TypeError("invalid ext.direction");n.direction||(n.direction="sendrecv")}function kp(n){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof n!="object")throw new TypeError("codec is not an object");if(!n.mimeType||typeof n.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(n.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(typeof n.payloadType!="number")throw new TypeError("missing codec.payloadType");if(typeof n.clockRate!="number")throw new TypeError("missing codec.clockRate");t[1].toLowerCase()==="audio"?typeof n.channels!="number"&&(n.channels=1):delete n.channels,(!n.parameters||typeof n.parameters!="object")&&(n.parameters={});for(let s of Object.keys(n.parameters)){let i=n.parameters[s];if(i===void 0&&(n.parameters[s]="",i=""),typeof i!="string"&&typeof i!="number")throw new TypeError(`invalid codec parameter [key:${s}s, value:${i}]`);if(s==="apt"&&typeof i!="number")throw new TypeError("invalid codec apt parameter")}(!n.rtcpFeedback||!Array.isArray(n.rtcpFeedback))&&(n.rtcpFeedback=[]);for(let s of n.rtcpFeedback)Ua(s)}function Tp(n){if(typeof n!="object")throw new TypeError("ext is not an object");if(!n.uri||typeof n.uri!="string")throw new TypeError("missing ext.uri");if(typeof n.id!="number")throw new TypeError("missing ext.id");if(n.encrypt&&typeof n.encrypt!="boolean")throw new TypeError("invalid ext.encrypt");n.encrypt||(n.encrypt=!1),(!n.parameters||typeof n.parameters!="object")&&(n.parameters={});for(let e of Object.keys(n.parameters)){let t=n.parameters[e];if(t===void 0&&(n.parameters[e]="",t=""),typeof t!="string"&&typeof t!="number")throw new TypeError("invalid header extension parameter")}}function Rp(n){if(typeof n!="object")throw new TypeError("encoding is not an object");if(n.ssrc&&typeof n.ssrc!="number")throw new TypeError("invalid encoding.ssrc");if(n.rid&&typeof n.rid!="string")throw new TypeError("invalid encoding.rid");if(n.rtx&&typeof n.rtx!="object")throw new TypeError("invalid encoding.rtx");if(n.rtx&&typeof n.rtx.ssrc!="number")throw new TypeError("missing encoding.rtx.ssrc");if((!n.dtx||typeof n.dtx!="boolean")&&(n.dtx=!1),n.scalabilityMode&&typeof n.scalabilityMode!="string")throw new TypeError("invalid encoding.scalabilityMode")}function Cp(n){if(typeof n!="object")throw new TypeError("rtcp is not an object");if(n.cname&&typeof n.cname!="string")throw new TypeError("invalid rtcp.cname");(!n.reducedSize||typeof n.reducedSize!="boolean")&&(n.reducedSize=!0)}function Ep(n){if(typeof n!="object")throw new TypeError("numStreams is not an object");if(typeof n.OS!="number")throw new TypeError("missing numStreams.OS");if(typeof n.MIS!="number")throw new TypeError("missing numStreams.MIS")}function Na({direction:n,extendedRtpCapabilities:e}){let t={codecs:[],headerExtensions:[]};for(let r of e.codecs){let s={kind:r.kind,mimeType:r.mimeType,preferredPayloadType:r.remotePayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(s),!r.remoteRtxPayloadType)continue;let i={kind:r.kind,mimeType:`${r.kind}/rtx`,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(let r of e.headerExtensions){if(r.direction!=="sendrecv"&&r.direction!==n)continue;let s={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt??!1,direction:r.direction};t.headerExtensions.push(s)}return t}function Vt(n){return n?/.+\/rtx$/i.test(n.mimeType):!1}function ti(n,e,{strict:t=!1,modify:r=!1}={}){let s=n.mimeType.toLowerCase(),i=e.mimeType.toLowerCase();if(s!==i||n.clockRate!==e.clockRate||n.channels!==e.channels)return!1;switch(s){case"video/h264":{if(t){let o=n.parameters["packetization-mode"]??0,a=e.parameters["packetization-mode"]??0;if(o!==a||!Ma.isSameProfile(n.parameters,e.parameters))return!1;let c;try{c=Ma.generateProfileLevelIdStringForAnswer(n.parameters,e.parameters)}catch{return!1}r&&(c?(n.parameters["profile-level-id"]=c,e.parameters["profile-level-id"]=c):(delete n.parameters["profile-level-id"],delete e.parameters["profile-level-id"]))}break}case"video/vp9":{if(t){let o=n.parameters["profile-id"]??0,a=e.parameters["profile-id"]??0;if(o!==a)return!1}break}}return!0}function Pp(n,e){return!(n.kind&&e.kind&&n.kind!==e.kind||n.uri!==e.uri)}function Oa(n,e){let t=[];for(let r of n.rtcpFeedback??[]){let s=(e.rtcpFeedback??[]).find(i=>i.type===r.type&&(i.parameter===r.parameter||!i.parameter&&!r.parameter));s&&t.push(s)}return t}});var Wa=U(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.Logger=void 0;var zt=Ur(),Gt="awaitqueue",ni=class{_debug;_warn;_error;constructor(e){e?(this._debug=zt(`${Gt}:${e}`),this._warn=zt(`${Gt}:WARN:${e}`),this._error=zt(`${Gt}:ERROR:${e}`)):(this._debug=zt(Gt),this._warn=zt(`${Gt}:WARN`),this._error=zt(`${Gt}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Dn.Logger=ni});var oi=U(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.AwaitQueueRemovedTaskError=Kt.AwaitQueueStoppedError=void 0;var si=class n extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n)}};Kt.AwaitQueueStoppedError=si;var ii=class n extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n)}};Kt.AwaitQueueRemovedTaskError=ii});var Fa=U(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.AwaitQueue=void 0;var xp=Wa(),ai=oi(),Ve=new xp.Logger("AwaitQueue"),ci=class{pendingTasks=new Map;nextTaskId=0;constructor(){Ve.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,r){if(t=t??e.name,Ve.debug(`push() [name:${t}, options:%o]`,r),typeof e!="function")throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch{}return new Promise((s,i)=>{if(t&&r?.removeOngoingTasksWithSameName)for(let a of this.pendingTasks.values())a.name===t&&a.reject(new ai.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});let o={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),Ve.debug(`resolving task [name:${o.name}]`),s(a);let[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:(a,{canExecuteNextTask:c})=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),Ve.debug(`rejecting task [name:${o.name}]: %s`,String(a)),i(a),c)){let[l]=this.pendingTasks.values();l&&!l.executedAt&&this.execute(l)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){Ve.debug("stop()");for(let e of this.pendingTasks.values())Ve.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new ai.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){Ve.debug(`remove() [taskIdx:${e}]`);let t=Array.from(this.pendingTasks.values())[e];if(!t){Ve.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}t.reject(new ai.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0})}dump(){let e=Date.now(),t=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0}))}async execute(e){if(Ve.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}};An.AwaitQueue=ci});var ja=U(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.AwaitQueueRemovedTaskError=Ze.AwaitQueueStoppedError=Ze.AwaitQueue=void 0;var Dp=Fa();Object.defineProperty(Ze,"AwaitQueue",{enumerable:!0,get:function(){return Dp.AwaitQueue}});var $a=oi();Object.defineProperty(Ze,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return $a.AwaitQueueStoppedError}});Object.defineProperty(Ze,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return $a.AwaitQueueRemovedTaskError}})});var Ba=U(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.Producer=void 0;var Ap=ce(),qa=ge(),Yt=Se(),We=new Ap.Logger("Producer"),di=class extends qa.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new qa.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:s,rtpParameters:i,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:l}){super(),We.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=s,this._kind=s.kind,this._rtpParameters=i,this._paused=a?!s.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=o,this._disableTrackOnPause=a,this._zeroRtpOnPause=c,this._appData=l??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(We.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(We.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Yt.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(We.debug("pause()"),this._closed){We.error("pause() | Producer closed");return}this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@pause",e,t)}).catch(()=>{}),this._observer.safeEmit("pause")}resume(){if(We.debug("resume()"),this._closed){We.error("resume() | Producer closed");return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@resume",e,t)}).catch(()=>{}),this._observer.safeEmit("resume")}async replaceTrack({track:e}){if(We.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch{}throw new Yt.InvalidStateError("closed")}else if(e?.readyState==="ended")throw new Yt.InvalidStateError("track ended");if(e===this._track){We.debug("replaceTrack() | same track, ignored");return}await new Promise((t,r)=>{this.safeEmit("@replacetrack",e,t,r)}),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()}async setMaxSpatialLayer(e){if(this._closed)throw new Yt.InvalidStateError("closed");if(this._kind!=="video")throw new Yt.UnsupportedError("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise((t,r)=>{this.safeEmit("@setmaxspatiallayer",e,t,r)}).catch(()=>{}),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Yt.InvalidStateError("closed");if(typeof e!="object")throw new TypeError("invalid params");await new Promise((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)})}onTrackEnded(){We.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch{}}};In.Producer=di});var Va=U(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.Consumer=void 0;var Ip=ce(),Ha=ge(),Lp=Se(),Fe=new Ip.Logger("Consumer"),li=class extends Ha.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new Ha.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:s,track:i,rtpParameters:o,appData:a}){super(),Fe.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=s,this._track=i,this._rtpParameters=o,this._paused=!i.enabled,this._appData=a??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Fe.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Fe.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Lp.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Fe.debug("pause()"),this._closed){Fe.error("pause() | Consumer closed");return}if(this._paused){Fe.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(Fe.debug("resume()"),this._closed){Fe.error("resume() | Consumer closed");return}if(!this._paused){Fe.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){Fe.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch{}}};Ln.Consumer=li});var Ga=U(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.DataProducer=void 0;var Mp=ce(),za=ge(),Op=Se(),ze=new Mp.Logger("DataProducer"),ui=class extends za.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new za.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:s}){super(),ze.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=s??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(ze.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(ze.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(ze.debug("send()"),this._closed)throw new Op.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(ze.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?ze.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):ze.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(ze.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||ze.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};Mn.DataProducer=ui});var Ya=U(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.DataConsumer=void 0;var Up=ce(),Ka=ge(),ht=new Up.Logger("DataConsumer"),pi=class extends Ka.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Ka.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:s,appData:i}){super(),ht.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=s,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(ht.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(ht.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(ht.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?ht.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):ht.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(ht.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",e=>{this._closed||this.safeEmit("message",e.data)})}};On.DataConsumer=pi});var Ja=U(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.Transport=void 0;var Np=ja(),Wp=ce(),Qa=ge(),ee=Se(),hi=ut(),Wr=Ne(),Fp=Ba(),$p=Va(),jp=Ga(),qp=Ya(),J=new Wp.Logger("Transport"),fi=class{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((t,r)=>{this.resolve=t,this.reject=r})}},mi=class extends Qa.EnhancedEventEmitter{_id;_closed=!1;_direction;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind;_maxSctpMessageSize;_handler;_iceGatheringState="new";_connectionState="new";_appData;_producers=new Map;_consumers=new Map;_dataProducers=new Map;_dataConsumers=new Map;_probatorConsumerCreated=!1;_awaitQueue=new Np.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new Qa.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:r,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:l,appData:d,handlerFactory:u,getSendExtendedRtpCapabilities:p,recvRtpCapabilities:f,canProduceByKind:g}){super(),J.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=p,this._recvRtpCapabilities=f,this._canProduceByKind=g,this._maxSctpMessageSize=o?.maxMessageSize;let h=hi.clone(l)??{};delete h.iceServers,delete h.iceTransportPolicy,delete h.bundlePolicy,delete h.rtcpMuxPolicy,this._handler=u.factory({direction:e,iceParameters:r,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:h,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=d??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){J.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(let e of this._producers.values())e.transportClosed();this._producers.clear();for(let e of this._consumers.values())e.transportClosed();this._consumers.clear();for(let e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(let e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new ee.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(J.debug("restartIce()"),this._closed)throw new ee.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(e),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(J.debug("updateIceServers()"),this._closed)throw new ee.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(e),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:r,codecOptions:s,headerExtensionOptions:i,codec:o,stopTracks:a=!0,disableTrackOnPause:c=!0,zeroRtpOnPause:l=!1,onRtpSender:d,appData:u={}}={}){if(J.debug("produce() [track:%o]",e),this._closed)throw new ee.InvalidStateError("closed");if(e){if(this._direction!=="send")throw new ee.UnsupportedError("not a sending Transport");if(this._canProduceByKind[e.kind]){if(e.readyState==="ended")throw new ee.InvalidStateError("track ended");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(u&&typeof u!="object")throw new TypeError("if given, appData must be an object")}else throw new ee.UnsupportedError(`cannot produce ${e.kind}`)}else throw new TypeError("missing track");return this._awaitQueue.push(async()=>{let p;if(r&&!Array.isArray(r))throw TypeError("encodings must be an array");r?.length===0?p=void 0:r&&(p=r.map(m=>{let _={active:!0};return m.active===!1&&(_.active=!1),typeof m.dtx=="boolean"&&(_.dtx=m.dtx),typeof m.scalabilityMode=="string"&&(_.scalabilityMode=m.scalabilityMode),typeof m.scaleResolutionDownBy=="number"&&(_.scaleResolutionDownBy=m.scaleResolutionDownBy),typeof m.maxBitrate=="number"&&(_.maxBitrate=m.maxBitrate),typeof m.maxFramerate=="number"&&(_.maxFramerate=m.maxFramerate),typeof m.adaptivePtime=="boolean"&&(_.adaptivePtime=m.adaptivePtime),typeof m.priority=="string"&&(_.priority=m.priority),typeof m.networkPriority=="string"&&(_.networkPriority=m.networkPriority),_}));let{localId:f,rtpParameters:g,rtpSender:h}=await this._handler.send({track:e,streamId:t,encodings:p,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:d});try{Wr.validateAndNormalizeRtpParameters(g);let{id:m}=await new Promise((v,S)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:g,appData:u},v,S)}),_=new Fp.Producer({id:m,localId:f,rtpSender:h,track:e,rtpParameters:g,stopTracks:a,disableTrackOnPause:c,zeroRtpOnPause:l,appData:u});return this._producers.set(_.id,_),this.handleProducer(_),this._observer.safeEmit("newproducer",_),_}catch(m){throw this._handler.stopSending(f).catch(()=>{}),m}},"transport.produce()").catch(p=>{if(a)try{e.stop()}catch{}throw p})}async consume({id:e,producerId:t,kind:r,rtpParameters:s,streamId:i,onRtpReceiver:o,appData:a={}}){if(J.debug("consume()"),this._closed)throw new ee.InvalidStateError("closed");if(this._direction!=="recv")throw new ee.UnsupportedError("not a receiving Transport");if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing producerId");if(r!=="audio"&&r!=="video")throw new TypeError(`invalid kind '${r}'`);if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object");let c=hi.clone(s);if(!Wr.canReceive(c,this._recvRtpCapabilities))throw new ee.UnsupportedError("cannot consume this Producer");let d=new fi({id:e,producerId:t,kind:r,rtpParameters:c,streamId:i,onRtpReceiver:o,appData:a});return this._pendingConsumerTasks.push(d),queueMicrotask(()=>{this._closed||this._consumerCreationInProgress===!1&&this.createPendingConsumers()}),d.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:s="",protocol:i="",appData:o={}}={}){if(J.debug("produceData()"),this._closed)throw new ee.InvalidStateError("closed");if(this._direction!=="send")throw new ee.UnsupportedError("not a sending Transport");if(this._maxSctpMessageSize){if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("producedata")===0)throw new TypeError('no "producedata" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new ee.UnsupportedError("SCTP not enabled by remote Transport");return(t||r)&&(e=!1),this._awaitQueue.push(async()=>{let{dataChannel:a,sctpStreamParameters:c}=await this._handler.sendDataChannel({sctpStreamParameters:{ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:s,protocol:i}});Wr.validateAndNormalizeSctpStreamParameters(c);let{id:l}=await new Promise((u,p)=>{this.safeEmit("producedata",{sctpStreamParameters:c,label:s,protocol:i,appData:o},u,p)}),d=new jp.DataProducer({id:l,dataChannel:a,sctpStreamParameters:c,appData:o});return this._dataProducers.set(d.id,d),this.handleDataProducer(d),this._observer.safeEmit("newdataproducer",d),d},"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:r,label:s="",protocol:i="",appData:o={}}){if(J.debug("consumeData()"),this._closed)throw new ee.InvalidStateError("closed");if(this._direction!=="recv")throw new ee.UnsupportedError("not a receiving Transport");if(this._maxSctpMessageSize){if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing dataProducerId");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new ee.UnsupportedError("SCTP not enabled by remote Transport");let a=hi.clone(r);return Wr.validateAndNormalizeSctpStreamParameters(a),this._awaitQueue.push(async()=>{let{dataChannel:c}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:a,label:s,protocol:i}),l=new qp.DataConsumer({id:e,dataProducerId:t,dataChannel:c,sctpStreamParameters:a,appData:o});return this._dataConsumers.set(l.id,l),this.handleDataConsumer(l),this._observer.safeEmit("newdataconsumer",l),l},"transport.consumeData()")}getDataChannelMaxMessageSize(){return this._handler.getDataChannelMaxMessageSize()}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingConsumerTasks.length===0){J.debug("createPendingConsumers() | there is no Consumer to be created");return}let e=[...this._pendingConsumerTasks];this._pendingConsumerTasks=[];let t,r=[];for(let s of e){let{id:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:l}=s.consumerOptions;r.push({trackId:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:l})}try{let s=await this._handler.receive(r);for(let i=0;i<s.length;++i){let o=e[i],a=s[i],{id:c,producerId:l,kind:d,rtpParameters:u,appData:p}=o.consumerOptions,{localId:f,rtpReceiver:g,track:h}=a,m=new $p.Consumer({id:c,localId:f,producerId:l,rtpReceiver:g,track:h,rtpParameters:u,appData:p});this._consumers.set(m.id,m),this.handleConsumer(m),!this._probatorConsumerCreated&&!t&&d==="video"&&(t=m),this._observer.safeEmit("newconsumer",m),o.resolve(m)}}catch(s){for(let i of e)i.reject(s)}if(t)try{let s=Wr.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:s}]),J.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(s){J.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",s)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingPauseConsumers.size===0){J.debug("pausePendingConsumers() | there is no Consumer to be paused");return}let e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{let t=e.map(r=>r.localId);await this._handler.pauseReceiving(t)}catch(t){J.error("pausePendingConsumers() | failed to pause Consumers:",t)}},"transport.pausePendingConsumers()").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingResumeConsumers.size===0){J.debug("resumePendingConsumers() | there is no Consumer to be resumed");return}let e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{let t=e.map(r=>r.localId);await this._handler.resumeReceiving(t)}catch(t){J.error("resumePendingConsumers() | failed to resume Consumers:",t)}},"transport.resumePendingConsumers()").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingCloseConsumers.size===0){J.debug("closePendingConsumers() | there is no Consumer to be closed");return}let e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(t=>t.localId))}catch(t){J.error("closePendingConsumers() | failed to close Consumers:",t)}},"transport.closePendingConsumers()").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){let e=this._handler;e.on("@connect",({dtlsParameters:t},r,s)=>{if(this._closed){s(new ee.InvalidStateError("closed"));return}this.safeEmit("connect",{dtlsParameters:t},r,s)}),e.on("@icegatheringstatechange",t=>{t!==this._iceGatheringState&&(J.debug("ICE gathering state changed to %s",t),this._iceGatheringState=t,this._closed||this.safeEmit("icegatheringstatechange",t))}),e.on("@icecandidateerror",t=>{J.warn(`ICE candidate error [url:${t.url}, localAddress:${t.address}, localPort:${t.port}]: ${t.errorCode} "${t.errorText}"`),this.safeEmit("icecandidateerror",t)}),e.on("@connectionstatechange",t=>{t!==this._connectionState&&(J.debug("connection state changed to %s",t),this._connectionState=t,this._closed||this.safeEmit("connectionstatechange",t))})}handleProducer(e){e.on("@close",()=>{this._producers.delete(e.id),!this._closed&&this._awaitQueue.push(async()=>await this._handler.stopSending(e.localId),"producer @close event").catch(t=>J.warn("producer.close() failed:%o",t))}),e.on("@pause",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(e.localId),"producer @pause event").then(t).catch(r)}),e.on("@resume",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(e.localId),"producer @resume event").then(t).catch(r)}),e.on("@replacetrack",(t,r,s)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(r).catch(s)}),e.on("@setmaxspatiallayer",(t,r,s)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(r).catch(s)}),e.on("@setrtpencodingparameters",(t,r,s)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(r).catch(s)}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new ee.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(r)})}handleConsumer(e){e.on("@close",()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),!this._closed&&(this._pendingCloseConsumers.set(e.id,e),this._consumerCloseInProgress===!1&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerPauseInProgress===!1&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerResumeInProgress===!1&&this.resumePendingConsumers()})}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new ee.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(r)})}handleDataProducer(e){e.on("@close",()=>{this._dataProducers.delete(e.id)})}handleDataConsumer(e){e.on("@close",()=>{this._dataConsumers.delete(e.id)})}};Un.Transport=mi});var Nn=U((Gg,Za)=>{"use strict";var Xa=Za.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(n){return n.encoding?"rtpmap:%d %s/%s/%s":n.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(n){return n.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(n){return n.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(n){return"extmap:%d"+(n.direction?"/%s":"%v")+(n["encrypt-uri"]?" %s":"%v")+" %s"+(n.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(n){return n.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(n){var e="candidate:%s %d %s %d %s %d typ %s";return e+=n.raddr!=null?" raddr %s rport %d":"%v%v",e+=n.tcptype!=null?" tcptype %s":"%v",n.generation!=null&&(e+=" generation %d"),e+=n["network-id"]!=null?" network-id %d":"%v",e+=n["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(n){var e="ssrc:%d";return n.attribute!=null&&(e+=" %s",n.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(n){return n.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(n){return n.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(n){return"imageattr:%s %s %s"+(n.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(n){return"simulcast:%s %s"+(n.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(n){return"ts-refclk:%s"+(n.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(n){var e="mediaclk:";return e+=n.id!=null?"id=%s %s":"%v%s",e+=n.mediaClockValue!=null?"=%s":"",e+=n.rateNumerator!=null?" rate=%s":"",e+=n.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Xa).forEach(function(n){var e=Xa[n];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})})});var rc=U(Ge=>{"use strict";var Qt=function(n){return String(Number(n))===n?Number(n):n},Bp=function(n,e,t,r){if(r&&!t)e[r]=Qt(n[1]);else for(var s=0;s<t.length;s+=1)n[s+1]!=null&&(e[t[s]]=Qt(n[s+1]))},Hp=function(n,e,t){var r=n.name&&n.names;n.push&&!e[n.push]?e[n.push]=[]:r&&!e[n.name]&&(e[n.name]={});var s=n.push?{}:r?e[n.name]:e;Bp(t.match(n.reg),s,n.names,n.name),n.push&&e[n.push].push(s)},ec=Nn(),Vp=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Ge.parse=function(n){var e={},t=[],r=e;return n.split(/(\r\n|\r|\n)/).filter(Vp).forEach(function(s){var i=s[0],o=s.slice(2);i==="m"&&(t.push({rtp:[],fmtp:[]}),r=t[t.length-1]);for(var a=0;a<(ec[i]||[]).length;a+=1){var c=ec[i][a];if(c.reg.test(o))return Hp(c,r,o)}}),e.media=t,e};var tc=function(n,e){var t=e.split(/=(.+)/,2);return t.length===2?n[t[0]]=Qt(t[1]):t.length===1&&e.length>1&&(n[t[0]]=void 0),n};Ge.parseParams=function(n){return n.split(/;\s?/).reduce(tc,{})};Ge.parseFmtpConfig=Ge.parseParams;Ge.parsePayloads=function(n){return n.toString().split(" ").map(Number)};Ge.parseRemoteCandidates=function(n){for(var e=[],t=n.split(" ").map(Qt),r=0;r<t.length;r+=3)e.push({component:t[r],ip:t[r+1],port:t[r+2]});return e};Ge.parseImageAttributes=function(n){return n.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(tc,{})})};Ge.parseSimulcastStreamList=function(n){return n.split(";").map(function(e){return e.split(",").map(function(t){var r,s=!1;return t[0]!=="~"?r=Qt(t):(r=Qt(t.substring(1,t.length)),s=!0),{scid:r,paused:s}})})}});var sc=U((Yg,nc)=>{"use strict";var gi=Nn(),zp=/%[sdv%]/g,Gp=function(n){var e=1,t=arguments,r=t.length;return n.replace(zp,function(s){if(e>=r)return s;var i=t[e];switch(e+=1,s){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},Fr=function(n,e,t){var r=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,s=[n+"="+r];if(e.names)for(var i=0;i<e.names.length;i+=1){var o=e.names[i];e.name?s.push(t[e.name][o]):s.push(t[e.names[i]])}else s.push(t[e.name]);return Gp.apply(null,s)},Kp=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Yp=["i","c","b","a"];nc.exports=function(n,e){e=e||{},n.version==null&&(n.version=0),n.name==null&&(n.name=" "),n.media.forEach(function(i){i.payloads==null&&(i.payloads="")});var t=e.outerOrder||Kp,r=e.innerOrder||Yp,s=[];return t.forEach(function(i){gi[i].forEach(function(o){o.name in n&&n[o.name]!=null?s.push(Fr(i,o,n)):o.push in n&&n[o.push]!=null&&n[o.push].forEach(function(a){s.push(Fr(i,o,a))})})}),n.media.forEach(function(i){s.push(Fr("m",gi.m[0],i)),r.forEach(function(o){gi[o].forEach(function(a){a.name in i&&i[a.name]!=null?s.push(Fr(o,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(c){s.push(Fr(o,a,c))})})})}),s.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var Ke=U($e=>{"use strict";var ft=rc(),Qp=sc(),Jp=Nn();$e.grammar=Jp;$e.write=Qp;$e.parse=ft.parse;$e.parseParams=ft.parseParams;$e.parseFmtpConfig=ft.parseFmtpConfig;$e.parsePayloads=ft.parsePayloads;$e.parseRemoteCandidates=ft.parseRemoteCandidates;$e.parseImageAttributes=ft.parseImageAttributes;$e.parseSimulcastStreamList=ft.parseSimulcastStreamList});var mt=U(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.parse=Zp;var Xp=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function Zp(n){let e=Xp.exec(n??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var ac=U(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.OfferMediaSection=et.AnswerMediaSection=et.MediaSection=void 0;var eh=Ke(),ic=ut(),$r=class{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(let s of t){let i={foundation:s.foundation,component:1,ip:s.address??s.ip,port:s.port,priority:s.priority,transport:s.protocol,type:s.type};s.tcpType&&(i.tcptype=s.tcpType),this._mediaObject.candidates.push(i)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}};et.MediaSection=$r;var vi=class extends $r{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:s,plainRtpParameters:i,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:l}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let d of c.codecs){let u={payload:d.payloadType,codec:oc(d),rate:d.clockRate};d.channels>1&&(u.encoding=d.channels),this._mediaObject.rtp.push(u);let p=ic.clone(d.parameters)??{},f=ic.clone(d.rtcpFeedback)??[];if(l){let{opusStereo:h,opusFec:m,opusDtx:_,opusMaxPlaybackRate:v,opusMaxAverageBitrate:S,opusPtime:w,opusNack:b,videoGoogleStartBitrate:T,videoGoogleMaxBitrate:y,videoGoogleMinBitrate:E}=l,N=a.codecs.find(Q=>Q.payloadType===d.payloadType);switch(d.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{h!==void 0&&(N.parameters["sprop-stereo"]=h?1:0,p.stereo=h?1:0),m!==void 0&&(N.parameters.useinbandfec=m?1:0,p.useinbandfec=m?1:0),_!==void 0&&(N.parameters.usedtx=_?1:0,p.usedtx=_?1:0),v!==void 0&&(p.maxplaybackrate=v),S!==void 0&&(p.maxaveragebitrate=S),w!==void 0&&(N.parameters.ptime=w,p.ptime=w),b||(N.rtcpFeedback=N.rtcpFeedback.filter(Q=>Q.type!=="nack"||Q.parameter),f=f.filter(Q=>Q.type!=="nack"||Q.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{T!==void 0&&(p["x-google-start-bitrate"]=T),y!==void 0&&(p["x-google-max-bitrate"]=y),E!==void 0&&(p["x-google-min-bitrate"]=E);break}}}let g={payload:d.payloadType,config:""};for(let h of Object.keys(p))g.config&&(g.config+=";"),g.config+=`${h}=${p[h]}`;g.config&&this._mediaObject.fmtp.push(g);for(let h of f)this._mediaObject.rtcpFb.push({payload:d.payloadType,type:h.type,subtype:h.parameter})}this._mediaObject.payloads=c.codecs.map(d=>d.payloadType).join(" "),this._mediaObject.ext=[];for(let d of c.headerExtensions)(o.ext??[]).some(p=>p.uri===d.uri)&&this._mediaObject.ext.push({uri:d.uri,value:d.id});if(o.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(let d of o.rids??[])d.direction==="send"&&this._mediaObject.rids.push({id:d.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let d of o.rids??[])d.direction==="send"&&this._mediaObject.rids.push({id:d.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof o.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=s.port,this._mediaObject.maxMessageSize=s.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=String(s.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:s.port,maxMessageSize:s.maxMessageSize});break}}}setDtlsRole(e){switch(e){case"client":{this._mediaObject.setup="active";break}case"server":{this._mediaObject.setup="passive";break}case"auto":{this._mediaObject.setup="actpass";break}}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;let t={};for(let i of e)i.rid&&(t[i.rid]=i);let r=this._mediaObject.simulcast.list1,s=eh.parseSimulcastStreamList(r);for(let i of s)for(let o of i)o.paused=!t[o.scid]?.active;this._mediaObject.simulcast.list1=s.map(i=>i.map(o=>`${o.paused?"~":""}${o.scid}`).join(",")).join(";")}};et.AnswerMediaSection=vi;var wi=class extends $r{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:s,plainRtpParameters:i,mid:o,kind:a,offerRtpParameters:c,streamId:l,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(o),this._mediaObject.type=a,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},s?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:l,appdata:d}];for(let g of c.codecs){let h={payload:g.payloadType,codec:oc(g),rate:g.clockRate};g.channels>1&&(h.encoding=g.channels),this._mediaObject.rtp.push(h);let m={payload:g.payloadType,config:""};for(let _ of Object.keys(g.parameters??{}))m.config&&(m.config+=";"),m.config+=`${_}=${g.parameters[_]}`;m.config&&this._mediaObject.fmtp.push(m);for(let _ of g.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:g.payloadType,type:_.type,subtype:_.parameter})}this._mediaObject.payloads=c.codecs.map(g=>g.payloadType).join(" "),this._mediaObject.ext=[];for(let g of c.headerExtensions)this._mediaObject.ext.push({uri:g.uri,value:g.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let u=c.encodings[0],p=u.ssrc,f=u.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],p&&c.rtcp.cname&&this._mediaObject.ssrcs.push({id:p,attribute:"cname",value:c.rtcp.cname}),f&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:f,attribute:"cname",value:c.rtcp.cname}),p&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${p} ${f}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=s.port,this._mediaObject.maxMessageSize=s.maxMessageSize;break}}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};et.OfferMediaSection=wi;function oc(n){let t=new RegExp("^(audio|video)/(.+)","i").exec(n.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var Jt=U($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.RemoteSdp=void 0;var th=Ke(),rh=ce(),Wn=ac(),nh=bi(),sh=["av1","h264"],Fn=new rh.Logger("RemoteSdp"),yi=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:s,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=s,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${nh.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let o=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[o-1].algorithm,hash:r.fingerprints[o-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){Fn.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(let t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){Fn.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){Fn.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){let t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:s,codecOptions:i}){let o=new Wn.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:s,codecOptions:i}),a=o.getObject();a.rtp.find(l=>sh.includes(l.codec.toLowerCase()))||(a.ext=a.ext?.filter(l=>l.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),t?this.replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this.replaceMediaSection(o):this.addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:s,trackId:i}){this.setSessionExtmapAllowMixed();let o=new Wn.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:r,streamId:s,trackId:i}),a=this._mediaSections.find(c=>c.closed&&c.getObject().type===t);a?this.replaceMediaSection(o,a.mid):this.addMediaSection(o)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){let t=this.findMediaSection(e);return e===this._firstMid?(Fn.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){let r=this.findMediaSection(e);r.muxSimulcastStreams(t),this.replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){let t=new Wn.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){let e=new Wn.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,th.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if(typeof t=="string"){let r=this._midToIndex.get(t);if(r===void 0)throw new Error(`no media section found for reuseMid '${t}'`);let s=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(s.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this.regenerateBundleMids()}else{let r=this._midToIndex.get(e.mid);if(r===void 0)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[r]=e,this._sdpObject.media[r]=e.getObject()}}findMediaSection(e){let t=this._midToIndex.get(e);if(t===void 0)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};$n.RemoteSdp=yi});var Xt=U(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.extractRtpCapabilities=ih;gt.extractDtlsParameters=oh;gt.getCname=ah;gt.applyCodecParameters=ch;gt.addHeaderExtension=dh;var cc=Ke();function ih({sdpObject:n}){let e=new Map,t=new Map;for(let s of n.media){let i=s.type;switch(i){case"audio":case"video":break;default:continue}for(let o of s.rtp){let a={kind:i,mimeType:`${i}/${o.codec}`,preferredPayloadType:o.payload,clockRate:o.rate,channels:o.encoding,parameters:{},rtcpFeedback:[]};e.set(a.preferredPayloadType,a)}for(let o of s.fmtp??[]){let a=cc.parseParams(o.config),c=e.get(o.payload);c&&(a?.hasOwnProperty("profile-level-id")&&(a["profile-level-id"]=String(a["profile-level-id"])),c.parameters=a)}for(let o of s.rtcpFb??[]){let a={type:o.type,parameter:o.subtype};if(a.parameter||delete a.parameter,o.payload!=="*"){let c=e.get(Number(o.payload));if(!c)continue;c.rtcpFeedback.push(a)}else for(let c of e.values())c.kind===i&&!/.+\/rtx$/i.test(c.mimeType)&&c.rtcpFeedback.push(a)}for(let o of s.ext??[]){if(o["encrypt-uri"])continue;let a={kind:i,uri:o.uri,preferredId:o.value};t.set(a.preferredId,a)}}return{codecs:Array.from(e.values()),headerExtensions:Array.from(t.values())}}function oh({sdpObject:n}){let e=n.setup,t=n.fingerprint;if(!e||!t){let i=(n.media??[]).find(o=>o.port!==0);i&&(e=e??i.setup,t=t??i.fingerprint)}if(e){if(!t)throw new Error("no a=fingerprint found at SDP session or media level")}else throw new Error("no a=setup found at SDP session or media level");let r;switch(e){case"active":{r="client";break}case"passive":{r="server";break}case"actpass":{r="auto";break}}return{role:r,fingerprints:[{algorithm:t.type,value:t.hash}]}}function ah({offerMediaObject:n}){let e=(n.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function ch({offerRtpParameters:n,answerMediaObject:e}){for(let t of n.codecs){let r=t.mimeType.toLowerCase();if(r!=="audio/opus"||!(e.rtp??[]).find(a=>a.payload===t.payloadType))continue;e.fmtp=e.fmtp??[];let i=e.fmtp.find(a=>a.payload===t.payloadType);i||(i={payload:t.payloadType,config:""},e.fmtp.push(i));let o=cc.parseParams(i.config);if(r==="audio/opus"){let a=t.parameters?.["sprop-stereo"];a!==void 0&&(o.stereo=Number(a)?1:0)}i.config="";for(let a of Object.keys(o))i.config&&(i.config+=";"),i.config+=`${a}=${o[a]}`}}function dh({offerMediaObject:n,headerExtensionUri:e,headerExtensionId:t}){n.ext||(n.ext=[]),n.ext.push({uri:e,value:t})}});var Zt=U(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.getRtpEncodings=lh;jn.addLegacySimulcast=uh;function lh({offerMediaObject:n,codecs:e}){let t=new Set;for(let i of n.ssrcs??[]){let o=i.id;o&&t.add(o)}if(t.size===0)throw new Error("no a=ssrc lines found");let r=new Map;for(let i of n.ssrcGroups??[]){if(i.semantics!=="FID")continue;let o=i.ssrcs.split(/\s+/),a=Number(o[0]),c=Number(o[1]);t.has(a)&&(t.delete(a),t.delete(c),r.set(a,c))}for(let i of t)r.set(i,void 0);let s=[];for(let[i,o]of r){let a={ssrc:i};o&&e.length>1&&(a.rtx={ssrc:o}),s.push(a)}return s}function uh({offerMediaObject:n,numStreams:e}){if(e<=1)throw new TypeError("numStreams must be greater than 1");let t=(n.ssrcs??[]).find(u=>u.attribute==="msid");if(!t)throw new Error("a=ssrc line with msid information not found");let[r,s]=t.value.split(" "),i=Number(t.id),o;(n.ssrcGroups??[]).some(u=>{if(u.semantics!=="FID")return!1;let p=u.ssrcs.split(/\s+/);return Number(p[0])===i?(o=Number(p[1]),!0):!1});let a=(n.ssrcs??[]).find(u=>u.attribute==="cname");if(!a)throw new Error("a=ssrc line with cname information not found");let c=a.value,l=[],d=[];for(let u=0;u<e;++u)l.push(i+u),o&&d.push(o+u);n.ssrcGroups=[],n.ssrcs=[],n.ssrcGroups.push({semantics:"SIM",ssrcs:l.join(" ")});for(let u of l)n.ssrcs.push({id:u,attribute:"cname",value:c}),n.ssrcs.push({id:u,attribute:"msid",value:`${r} ${s}`});for(let u=0;u<d.length;++u){let p=l[u],f=d[u];n.ssrcs.push({id:f,attribute:"cname",value:c}),n.ssrcs.push({id:f,attribute:"msid",value:`${r} ${s}`}),n.ssrcGroups.push({semantics:"FID",ssrcs:`${p} ${f}`})}}});var er=U(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.addNackSupportForOpus=ph;jr.addHeaderExtensionSupport=hh;jr.getMsidStreamIdAndTrackId=fh;function ph(n){for(let e of n.codecs??[])(e.mimeType.toLowerCase()==="audio/opus"||e.mimeType.toLowerCase()==="audio/multiopus")&&!e.rtcpFeedback?.some(t=>t.type==="nack"&&!t.parameter)&&(e.rtcpFeedback||(e.rtcpFeedback=[]),e.rtcpFeedback.push({type:"nack"}))}function hh(n,e){let t,r=n.headerExtensions?.find(i=>i.uri===e.uri);if(r){if(r.kind===e.kind)return;t=r.preferredId}if(n.headerExtensions||(n.headerExtensions=[]),t===void 0){t=1;let i=new Set(n.headerExtensions.map(o=>o.preferredId));for(;i.has(t);)++t}let s={kind:e.kind,uri:e.uri,preferredId:t,preferredEncrypt:!1,direction:e.direction};n.headerExtensions.push(s)}function fh(n){if(!n||typeof n!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[e,t]=n.trim().split(/\s+/);return e?{msidStreamId:e,msidTrackId:t}:{msidStreamId:void 0,msidTrackId:void 0}}});var pc=U(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.Chrome111=void 0;var je=Ke(),mh=ge(),gh=ce(),qr=Ne(),_h=Se(),vh=mt(),wh=Jt(),Br=Xt(),dc=Zt(),Si=er(),L=new gh.Logger("Chrome111"),lc="Chrome111",uc={OS:65535,MIS:65535},ki=class n extends mh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:lc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{L.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let s=je.parse(r.sdp);return n.getLocalRtpCapabilities(s)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(L.debug("getNativeSctpCapabilities()"),{numStreams:uc})}}static getLocalRtpCapabilities(e,t=[]){let r=Br.extractRtpCapabilities({sdpObject:e});qr.validateAndNormalizeRtpCapabilities(r),Si.addNackSupportForOpus(r);for(let s of t)Si.addHeaderExtensionSupport(r,s);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),L.debug("constructor()"),this._direction=e,this._remoteSdp=new wh.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(L.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return lc}close(){if(L.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),L.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),L.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});L.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();L.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){if(this.assertNotClosed(),this.assertSendDirection(),L.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1){let w=1;for(let b of r){let T=b.scalabilityMode?(0,vh.parse)(b.scalabilityMode).temporalLayers:3;T>w&&(w=T)}r.forEach((b,T)=>{b.rid=`r${T}`,b.scalabilityMode=`L1T${w}`})}let c=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});a&&a(l.sender);let d=await this._pc.createOffer(),u=je.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=n.getLocalRtpCapabilities(u,p),g=this._getSendExtendedRtpCapabilities(f),h=qr.getSendingRtpParameters(e.kind,g);h.codecs=qr.reduceCodecs(h.codecs,o);let m=qr.getSendingRemoteRtpParameters(e.kind,g);if(m.codecs=qr.reduceCodecs(m.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u}),i?.absCaptureTime){let w=u.media[c.idx];Br.addHeaderExtension({offerMediaObject:w,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find(b=>b.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:je.write(u)}}L.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let _=l.mid;h.mid=_,u=je.parse(this._pc.localDescription.sdp);let v=u.media[c.idx];if(h.rtcp.cname=Br.getCname({offerMediaObject:v}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=dc.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});else if(r.length===1){let w=dc.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});Object.assign(w[0],r[0]),h.encodings=w}else h.encodings=r;this._remoteSdp.send({offerMediaObject:v,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:m,codecOptions:s});let S={type:"answer",sdp:this._remoteSdp.getSdp()};return L.debug("send() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.set(_,l),{localId:_,rtpParameters:h,rtpSender:l.sender}}async stopSending(e){if(this.assertSendDirection(),L.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();L.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),L.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();L.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),L.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();L.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?L.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):L.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),L.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();L.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),L.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();L.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};L.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%uc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=je.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),L.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;L.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=Si.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:l}=a;if(l){let d=r.get(c),u=this._pc.getTransceivers().find(p=>p.mid===d);if(!u)throw new Error("transceiver not found");l(u.receiver)}}let i=await this._pc.createAnswer(),o=je.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Br.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u})}i={type:"answer",sdp:je.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),L.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(d)this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){L.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();L.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){L.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();L.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){L.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();L.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};L.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=je.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:je.write(f)},L.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=je.parse(this._pc.localDescription.sdp));let r=Br.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new _h.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};qn.Chrome111=ki});var mc=U(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Chrome74=void 0;var ke=Ke(),yh=ce(),bh=ge(),Hr=Ne(),Sh=Se(),kh=mt(),Th=Jt(),Vr=Xt(),Ti=Zt(),Ri=er(),A=new yh.Logger("Chrome74"),hc="Chrome74",fc={OS:1024,MIS:1024},Ci=class n extends bh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:hc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{A.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let s=ke.parse(r.sdp);return n.getLocalRtpCapabilities(s)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(A.debug("getNativeSctpCapabilities()"),{numStreams:fc})}}static getLocalRtpCapabilities(e,t=[]){let r=Vr.extractRtpCapabilities({sdpObject:e});Hr.validateAndNormalizeRtpCapabilities(r),Ri.addNackSupportForOpus(r);for(let s of t)Ri.addHeaderExtensionSupport(r,s);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),A.debug("constructor()"),this._direction=e,this._remoteSdp=new Th.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(A.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return hc}close(){if(A.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),A.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),A.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});A.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();A.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,headerExtensionOptions:i,codec:o}){this.assertNotClosed(),this.assertSendDirection(),A.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((b,T)=>{b.rid=`r${T}`});let a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r}),l=await this._pc.createOffer(),d=ke.parse(l.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let p=n.getLocalRtpCapabilities(d,u),f=this._getSendExtendedRtpCapabilities(p),g=Hr.getSendingRtpParameters(e.kind,f);g.codecs=Hr.reduceCodecs(g.codecs,o);let h=Hr.getSendingRemoteRtpParameters(e.kind,f);h.codecs=Hr.reduceCodecs(h.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:d});let m=!1,_=(0,kh.parse)((r??[{}])[0].scalabilityMode),v;r?.length===1&&_.spatialLayers>1&&g.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(A.debug("send() | enabling legacy simulcast for VP9 SVC"),m=!0,d=ke.parse(l.sdp),v=d.media[a.idx],Ti.addLegacySimulcast({offerMediaObject:v,numStreams:_.spatialLayers}),l={type:"offer",sdp:ke.write(d)}),A.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),i?.absCaptureTime&&(v=d.media[a.idx],Vr.addHeaderExtension({offerMediaObject:v,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:h.headerExtensions.find(b=>b.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),l={type:"offer",sdp:ke.write(d)}),await this._pc.setLocalDescription(l);let S=c.mid;if(g.mid=S,d=ke.parse(this._pc.localDescription.sdp),v=d.media[a.idx],g.rtcp.cname=Vr.getCname({offerMediaObject:v}),g.msid=`${t??this._sendStream.id} ${e.id}`,!r)g.encodings=Ti.getRtpEncodings({offerMediaObject:v,codecs:g.codecs});else if(r.length===1){let b=Ti.getRtpEncodings({offerMediaObject:v,codecs:g.codecs});Object.assign(b[0],r[0]),m&&(b=[b[0]]),g.encodings=b}else g.encodings=r;if(g.encodings.length>1&&(g.codecs[0].mimeType.toLowerCase()==="video/vp8"||g.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let b of g.encodings)b.scalabilityMode?b.scalabilityMode=`L1T${_.temporalLayers}`:b.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:v,reuseMid:a.reuseMid,offerRtpParameters:g,answerRtpParameters:h,codecOptions:s});let w={type:"answer",sdp:this._remoteSdp.getSdp()};return A.debug("send() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w),this._mapMidTransceiver.set(S,c),{localId:S,rtpParameters:g,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),A.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();A.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),A.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();A.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),A.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();A.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?A.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):A.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),A.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();A.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),A.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();A.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};A.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%fc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ke.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),A.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;A.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=Ri.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);let i=await this._pc.createAnswer(),o=ke.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Vr.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u})}i={type:"answer",sdp:ke.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),A.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(d)this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){A.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();A.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){A.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();A.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){A.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();A.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};A.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=ke.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:ke.write(f)},A.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ke.parse(this._pc.localDescription.sdp));let r=Vr.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Sh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Bn.Chrome74=Ci});var yc=U(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.Firefox120=void 0;var Ye=Ke(),Rh=ge(),Ch=ce(),gc=Se(),zr=Ne(),Eh=mt(),Ph=Jt(),Hn=Xt(),_c=Zt(),xh=er(),M=new Ch.Logger("Firefox120"),vc="Firefox120",wc={OS:16,MIS:2048},Ei=class n extends Rh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:vc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{M.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),r=document.createElement("canvas");r.getContext("2d");let i=r.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(i,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let o=await t.createOffer();try{r.remove()}catch{}try{i.stop()}catch{}try{t.close()}catch{}t=void 0;let a=Ye.parse(o.sdp);return n.getLocalRtpCapabilities(a)}catch(o){try{r.remove()}catch{}try{i.stop()}catch{}try{t?.close()}catch{}throw t=void 0,o}},getNativeSctpCapabilities:async()=>(M.debug("getNativeSctpCapabilities()"),{numStreams:wc})}}static getLocalRtpCapabilities(e){let t=Hn.extractRtpCapabilities({sdpObject:e});return zr.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),M.debug("constructor()"),this._direction=e,this._remoteSdp=new Ph.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(M.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return vc}close(){if(M.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){throw this.assertNotClosed(),new gc.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),M.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});M.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();M.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,codec:i,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),M.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((v,S)=>{v.rid=`r${S}`});let a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(a.sender);let c=await this._pc.createOffer(),l=Ye.parse(c.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let d=n.getLocalRtpCapabilities(l),u=this._getSendExtendedRtpCapabilities(d),p=zr.getSendingRtpParameters(e.kind,u);p.codecs=zr.reduceCodecs(p.codecs,i);let f=zr.getSendingRemoteRtpParameters(e.kind,u);f.codecs=zr.reduceCodecs(f.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:l});let g=(0,Eh.parse)((r??[{}])[0].scalabilityMode);M.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);let h=a.mid;p.mid=h,l=Ye.parse(this._pc.localDescription.sdp);let m=l.media[l.media.length-1];if(p.rtcp.cname=Hn.getCname({offerMediaObject:m}),p.msid=`${t??this._sendStream.id} ${e.id}`,!r)p.encodings=_c.getRtpEncodings({offerMediaObject:m,codecs:p.codecs});else if(r.length===1){let v=_c.getRtpEncodings({offerMediaObject:m,codecs:p.codecs});Object.assign(v[0],r[0]),p.encodings=v}else p.encodings=r;if(p.encodings.length>1&&(p.codecs[0].mimeType.toLowerCase()==="video/vp8"||p.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let v of p.encodings)v.scalabilityMode?v.scalabilityMode=`L1T${g.temporalLayers}`:v.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,offerRtpParameters:p,answerRtpParameters:f,codecOptions:s});let _={type:"answer",sdp:this._remoteSdp.getSdp()};return M.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:p,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),M.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);let r=await this._pc.createOffer();M.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),M.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();M.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),M.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let r=await this._pc.createOffer();M.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?M.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):M.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),M.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();M.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),M.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();M.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};M.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%wc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Ye.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),M.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;M.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=xh.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:l}=a;if(l){let d=r.get(c),u=this._pc.getTransceivers().find(p=>p.mid===d);if(!u)throw new Error("transceiver not found");l(u.receiver)}}let i=await this._pc.createAnswer(),o=Ye.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Hn.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u}),i={type:"answer",sdp:Ye.write(o)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),M.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(!d)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){M.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();M.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){M.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();M.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){M.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();M.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};M.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=Ye.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:f}),p={type:"answer",sdp:Ye.write(f)},M.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ye.parse(this._pc.localDescription.sdp));let r=Hn.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new gc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Vn.Firefox120=Ei});var Tc=U(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.Safari12=void 0;var Te=Ke(),Dh=ge(),Ah=ce(),Gr=Ne(),Ih=Se(),Lh=mt(),Mh=Jt(),Kr=Xt(),bc=Zt(),Pi=er(),I=new Ah.Logger("Safari12"),Sc="Safari12",kc={OS:65535,MIS:65535},xi=class n extends Dh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Sc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{I.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let s=Te.parse(r.sdp);return n.getLocalRtpCapabilities(s)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(I.debug("getNativeSctpCapabilities()"),{numStreams:kc})}}static getLocalRtpCapabilities(e,t=[]){let r=Kr.extractRtpCapabilities({sdpObject:e});Gr.validateAndNormalizeRtpCapabilities(r),Pi.addNackSupportForOpus(r);for(let s of t)Pi.addHeaderExtensionSupport(r,s);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),I.debug("constructor()"),this._direction=e,this._remoteSdp=new Mh.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",d=>{this.emit("@icecandidateerror",d)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(I.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Sc}close(){if(I.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),I.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),I.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});I.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();I.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),I.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);let c=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});a&&a(l.sender);let d=await this._pc.createOffer(),u=Te.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=n.getLocalRtpCapabilities(u,p),g=this._getSendExtendedRtpCapabilities(f),h=Gr.getSendingRtpParameters(e.kind,g);h.codecs=Gr.reduceCodecs(h.codecs,o);let m=Gr.getSendingRemoteRtpParameters(e.kind,g);m.codecs=Gr.reduceCodecs(m.codecs,o);let _;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let v=(0,Lh.parse)((r??[{}])[0].scalabilityMode);r&&r.length>1&&(I.debug("send() | enabling legacy simulcast"),u=Te.parse(d.sdp),_=u.media[c.idx],bc.addLegacySimulcast({offerMediaObject:_,numStreams:r.length}),d={type:"offer",sdp:Te.write(u)}),i?.absCaptureTime&&(_=u.media[c.idx],Kr.addHeaderExtension({offerMediaObject:_,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find(b=>b.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Te.write(u)}),I.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let S=l.mid;if(h.mid=S,u=Te.parse(this._pc.localDescription.sdp),_=u.media[c.idx],h.rtcp.cname=Kr.getCname({offerMediaObject:_}),h.msid=`${t??this._sendStream.id} ${e.id}`,h.encodings=bc.getRtpEncodings({offerMediaObject:_,codecs:h.codecs}),r)for(let b=0;b<h.encodings.length;++b)r[b]&&Object.assign(h.encodings[b],r[b]);if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let b of h.encodings)b.scalabilityMode?b.scalabilityMode=`L1T${v.temporalLayers}`:b.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:_,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:m,codecOptions:s});let w={type:"answer",sdp:this._remoteSdp.getSdp()};return I.debug("send() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w),this._mapMidTransceiver.set(S,l),{localId:S,rtpParameters:h,rtpSender:l.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;I.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();I.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),I.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();I.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),I.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let r=await this._pc.createOffer();I.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?I.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):I.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),I.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();I.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),I.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();I.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};I.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%kc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Te.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),I.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;I.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=Pi.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:l}=a;if(l){let d=r.get(c),u=this._pc.getTransceivers().find(p=>p.mid===d);if(!u)throw new Error("transceiver not found");l(u.receiver)}}let i=await this._pc.createAnswer(),o=Te.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Kr.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u})}i={type:"answer",sdp:Te.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),I.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(!d)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){I.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();I.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){I.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();I.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){I.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();I.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};I.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=Te.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:Te.write(f)},I.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Te.parse(this._pc.localDescription.sdp));let r=Kr.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Ih.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};zn.Safari12=xi});var Ec=U(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.ReactNative106=void 0;var Re=Ke(),Oh=ge(),Uh=ce(),Yr=Ne(),Nh=Se(),Wh=mt(),Fh=Jt(),Qr=Xt(),Di=Zt(),Ai=er(),P=new Uh.Logger("ReactNative106"),Rc="ReactNative106",Cc={OS:65535,MIS:65535},Ii=class n extends Oh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Rc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{P.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let s=Re.parse(r.sdp);return n.getLocalRtpCapabilities(s)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(P.debug("getNativeSctpCapabilities()"),{numStreams:Cc})}}static getLocalRtpCapabilities(e,t=[]){let r=Qr.extractRtpCapabilities({sdpObject:e});Yr.validateAndNormalizeRtpCapabilities(r),Ai.addNackSupportForOpus(r);for(let s of t)Ai.addHeaderExtensionSupport(r,s);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),P.debug("constructor()"),this._direction=e,this._remoteSdp=new Fh.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(P.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Rc}close(){if(P.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),P.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),P.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});P.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();P.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),P.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((T,y)=>{T.rid=`r${y}`});let c=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});a&&a(l.sender);let d=await this._pc.createOffer(),u=Re.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=n.getLocalRtpCapabilities(u,p),g=this._getSendExtendedRtpCapabilities(f),h=Yr.getSendingRtpParameters(e.kind,g);h.codecs=Yr.reduceCodecs(h.codecs,o);let m=Yr.getSendingRemoteRtpParameters(e.kind,g);m.codecs=Yr.reduceCodecs(m.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let _=!1,v=(0,Wh.parse)((r??[{}])[0].scalabilityMode),S;r?.length===1&&v.spatialLayers>1&&h.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(P.debug("send() | enabling legacy simulcast for VP9 SVC"),_=!0,u=Re.parse(d.sdp),S=u.media[c.idx],Di.addLegacySimulcast({offerMediaObject:S,numStreams:v.spatialLayers}),d={type:"offer",sdp:Re.write(u)}),i?.absCaptureTime&&(S=u.media[c.idx],Qr.addHeaderExtension({offerMediaObject:S,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find(T=>T.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Re.write(u)}),P.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let w=l.mid??void 0;if(w||P.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),h.mid=w,u=Re.parse(this._pc.localDescription.sdp),S=u.media[c.idx],h.rtcp.cname=Qr.getCname({offerMediaObject:S}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=Di.getRtpEncodings({offerMediaObject:S,codecs:h.codecs});else if(r.length===1){let T=Di.getRtpEncodings({offerMediaObject:S,codecs:h.codecs});Object.assign(T[0],r[0]),_&&(T=[T[0]]),h.encodings=T}else h.encodings=r;if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let T of h.encodings)T.scalabilityMode?T.scalabilityMode=`L1T${v.temporalLayers}`:T.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:S,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:m,codecOptions:s});let b={type:"answer",sdp:this._remoteSdp.getSdp()};return P.debug("send() | calling pc.setRemoteDescription() [answer:%o]",b),await this._pc.setRemoteDescription(b),w||(w=l.mid,h.mid=w),this._mapMidTransceiver.set(w,l),{localId:w,rtpParameters:h,rtpSender:l.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;P.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();P.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),P.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();P.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),P.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();P.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?P.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):P.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),P.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();P.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),P.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();P.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};P.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Cc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Re.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),P.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;P.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=Ai.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:l}=a;if(l){let d=r.get(c),u=this._pc.getTransceivers().find(p=>p.mid===d);if(!u)throw new Error("transceiver not found");l(u.receiver)}}let i=await this._pc.createAnswer(),o=Re.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Qr.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u})}i={type:"answer",sdp:Re.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),P.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(d)this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){P.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();P.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){P.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();P.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){P.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();P.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};P.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=Re.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:Re.write(f)},P.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Re.parse(this._pc.localDescription.sdp));let r=Qr.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Nh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Gn.ReactNative106=Ii});var Ac=U(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.Device=void 0;tr.detectDevice=Pc;tr.detectDeviceAsync=xc;var $h=ce(),jh=ge(),tt=Se(),Kn=ut(),ve=Ne(),qh=Ja(),Bh=pc(),Hh=mc(),Vh=yc(),zh=Tc(),Gh=Ec(),C=new $h.Logger("Device");function Pc(n,e){return C.debug("detectDevice()"),!n&&typeof navigator=="object"&&(n=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),Dc(n,e)}async function xc(n,e){return C.debug("detectDeviceAsync()"),!n&&typeof navigator=="object"&&(n=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),Dc(n,e)}var Li=class n{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new jh.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(C.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&(e=await xc(),!e))throw new tt.UnsupportedError("device not supported");return new n({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(C.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)C.debug("constructor() | handler given: %s",e);else if(e=Pc(),e)C.debug("constructor() | detected handler: %s",e);else throw new tt.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=Bh.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=Hh.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=Vh.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=zh.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=Gh.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new tt.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new tt.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new tt.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(C.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new tt.InvalidStateError("already loaded");let r=Kn.clone(e);ve.validateAndNormalizeRtpCapabilities(r);let{getNativeRtpCapabilities:s,getNativeSctpCapabilities:i}=this._handlerFactory,o=Kn.clone(await s({direction:"recvonly"}));C.debug("load() | got native receiving RTP capabilities:%o",o),ve.validateAndNormalizeRtpCapabilities(o);let a=Kn.clone(await s({direction:"sendonly"}));C.debug("load() | got native sending RTP capabilities:%o",a),ve.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=d=>Kn.clone(ve.getExtendedRtpCapabilities(d,r,t));let c=ve.getExtendedRtpCapabilities(o,r,!1);this._recvRtpCapabilities=ve.getRecvRtpCapabilities(c),C.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),ve.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let l=ve.getExtendedRtpCapabilities(a,r,t);this._sendRtpCapabilities=ve.getSendRtpCapabilities(l),C.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),ve.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=ve.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=ve.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),ve.validateSctpCapabilities(this._sctpCapabilities),C.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),C.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(this._loaded){if(e!=="audio"&&e!=="video")throw new TypeError(`invalid kind "${e}"`)}else throw new tt.InvalidStateError("not loaded");return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:l}){return C.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:l})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:l}){return C.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:l})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:l,appData:d}){if(this._loaded){if(typeof t!="string")throw new TypeError("missing id");if(typeof r!="object")throw new TypeError("missing iceParameters");if(Array.isArray(s)){if(typeof i!="object")throw new TypeError("missing dtlsParameters");if(o&&typeof o!="object")throw new TypeError("wrong sctpParameters");if(d&&typeof d!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new tt.InvalidStateError("not loaded");let u=new qh.Transport({direction:e,id:t,iceParameters:r,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:l,appData:d,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",u),u}};tr.Device=Li;function Dc(n,e){C.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',n,e);let t=Kh(n,e);if(t){if(t>=111)return C.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(t>=74)return C.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";C.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let r=Yh(n);if(r){if(r>=120)return C.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";C.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let s=Qh(n);if(s){if(s>=605)return C.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";C.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let i=Jh(n);if(i){if(i>=605)return C.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";C.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(Jr()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return C.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";C.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}C.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',n,e)}function Kh(n,e){if(C.debug("getChromiumMajorVersion()"),Yn(n,e)){C.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(Jr()){C.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(e){let s=(Array.isArray(e.brands)?e.brands:[]).find(i=>i.brand==="Chromium");if(s){let i=Number(s.version);return C.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${i}`),i}}let t=n?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(t?.[1]){let r=Number(t[1]);return C.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${r}`),r}C.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function Yh(n){if(C.debug("getFirefoxMajorVersion()"),Yn(n)){C.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(Jr()){C.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let e=n?.match(/\bFirefox\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return C.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${t}`),t}C.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function Qh(n){if(C.debug("getMacOSWebKitMajorVersion()"),Yn(n)){C.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(Jr()){C.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(n&&/\bSafari\b/i.test(n)&&!/\bChrome\b/i.test(n)&&!/\bChromium\b/i.test(n)&&!/\bFirefox\b/i.test(n))){C.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let t=n.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){let r=Number(t[1]);return C.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${r}`),r}C.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function Jh(n){if(C.debug("getIOSWebKitMajorVersion()"),!Yn(n)){C.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(Jr()){C.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let e=n?.match(/AppleWebKit\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return C.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${t}`),t}C.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function Yn(n,e){return C.debug("isIOS()"),e?.platform==="iOS"?(C.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):e?.platform?(C.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):n&&/iPad|iPhone|iPod/.test(n)?(C.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(C.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(C.debug("isIOS() | this is not iOS => false"),!1)}function Jr(){return C.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(C.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(C.debug("isReactNative() | this is not React-Native => false"),!1)}});var Lc=U(Ic=>{"use strict";var _t=256,Jn=[],Qn;for(;_t--;)Jn[_t]=(_t+256).toString(16).substring(1);function Xh(){var n=0,e,t="";if(!Qn||_t+16>256){for(Qn=Array(n=256);n--;)Qn[n]=256*Math.random()|0;n=_t=0}for(;n<16;n++)e=Qn[_t+n],n==6?t+=Jn[e&15|64]:n==8?t+=Jn[e&63|128]:t+=Jn[e],n&1&&n>1&&n<11&&(t+="-");return _t++,t}Ic.v4=Xh});var Mc=U(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.FakeEventTarget=void 0;var Mi=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof r=="object"&&r.once===!0}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(s=>s.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let r of[...t]){try{r.callback.call(this,e)}catch(s){setTimeout(()=>{throw s},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};Xn.FakeEventTarget=Mi});var Oc=U(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.FakeEvent=void 0;var Oi=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=this.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,r){}};Zn.FakeEvent=Oi});var Uc=U(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.clone=Zh;function Zh(n){if(n!==void 0)return Number.isNaN(n)?NaN:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}});var Wc=U(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.FakeMediaStreamTrack=void 0;var Nc=Lc(),ef=Mc(),rr=Oc(),es=Uc(),Ni=class n extends ef.FakeEventTarget{#m;#u;#p;#e;#r;#t;#n;#h;#s;#f;#i;#o=null;#a=null;#c=null;#d=null;#l=null;constructor({kind:e,id:t,label:r,contentHint:s,enabled:i,muted:o,readyState:a,capabilities:c,constraints:l,settings:d,data:u}){super(),this.#m=t??(0,Nc.v4)(),this.#u=e,this.#p=r??"",this.#n=s??"",this.#r=i??!0,this.#t=o??!1,this.#e=a??"live",this.#h=c??{},this.#s=l??{},this.#f=d??{},this.#i=u??{}}get id(){return this.#m}get kind(){return this.#u}get label(){return this.#p}get contentHint(){return this.#n}set contentHint(e){this.#n=e}get enabled(){return this.#r}set enabled(e){let t=this.#r!==e;this.#r=e,t&&this.dispatchEvent(new rr.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(e){this.#i=e}get onmute(){return this.#o}set onmute(e){this.#o&&this.removeEventListener("mute",this.#o),this.#o=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#a}set onunmute(e){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#c}set onended(e){this.#c&&this.removeEventListener("ended",this.#c),this.#c=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#d}set onenabledchange(e){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#l}set onstopped(e){this.#l&&this.removeEventListener("stopped",this.#l),this.#l=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new rr.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new n({id:e??(0,Nc.v4)(),kind:this.#u,label:this.#p,contentHint:this.#n,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,es.clone)(this.#h),constraints:(0,es.clone)(this.#s),settings:(0,es.clone)(this.#f),data:t??(0,es.clone)(this.#i)})}getCapabilities(){return this.#h}getConstraints(){return this.#s}async applyConstraints(e={}){return this.#s=e,Promise.resolve()}getSettings(){return this.#f}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new rr.FakeEvent("stopped")),this.dispatchEvent(new rr.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new rr.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new rr.FakeEvent("unmute")))}};ts.FakeMediaStreamTrack=Ni});var Fc=U(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.FakeEventTarget=void 0;var Wi=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof r=="object"&&r.once===!0}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(s=>s.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let r of[...t]){try{r.callback.call(this,e)}catch(s){setTimeout(()=>{throw s},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};rs.FakeEventTarget=Wi});var qc=U(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.FakeHandler=void 0;var tf=Wc(),rf=ge(),nf=ce(),nr=ut(),Fi=Ne(),jc=Se(),sf=Fc(),ne=new nf.Logger("FakeHandler"),$c="FakeHandler",$i=class n extends rf.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${nr.generateRandomNumber()}`;_defaultSendStreamId=`${nr.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:$c,factory:t=>new n(t,e),getNativeRtpCapabilities:async({direction:t})=>(ne.debug("getNativeRtpCapabilities() [direction:%o]",t),n.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(ne.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){let t=e.generateNativeRtpCapabilities();return Fi.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),ne.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return $c}close(){ne.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),ne.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),ne.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:r,codecOptions:s,codec:i}){this.assertNotClosed(),ne.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let o=n.getLocalRtpCapabilities(this._fakeParameters),a=this._getSendExtendedRtpCapabilities(o),c=Fi.getSendingRtpParameters(e.kind,a);c.codecs=Fi.reduceCodecs(c.codecs,i);let l=c.codecs.some(u=>/.+\/rtx$/i.test(u.mimeType));c.mid=`mid-${nr.generateRandomNumber()}`,c.msid=`${t??"-"} ${e.id}`,r||(r=[{}]);for(let u of r)u.ssrc=nr.generateRandomNumber(),l&&(u.rtx={ssrc:nr.generateRandomNumber()});c.encodings=r,c.rtcp={cname:this._cname,reducedSize:!0,mux:!0},c.msid=`${t??this._defaultSendStreamId} ${e.id}`;let d=this._nextLocalId++;return this._tracks.set(d,e),{localId:String(d),rtpParameters:c}}async stopSending(e){if(ne.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?ne.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ne.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),ne.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),ne.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),ne.debug("sendDataChannel()");let t=new ns({id:this._nextSctpStreamId++,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:e.label,protocol:e.protocol}),r={streamId:this._nextSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits};return{dataChannel:t,sctpStreamParameters:r}}async receive(e){this.assertNotClosed();let t=[];for(let r of e){let{trackId:s,kind:i}=r;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),ne.debug("receive() [trackId:%s, kind:%s]",s,i);let o=this._nextLocalId++,a=new tf.FakeMediaStreamTrack({kind:i});this._tracks.set(o,a),t.push({localId:String(o),track:a})}return t}async stopReceiving(e){if(!this._closed)for(let t of e)ne.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),ne.debug("receiveDataChannel()"),{dataChannel:new ns({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:e,localSdpObject:t}){let r=nr.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(r.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((s,i)=>this.emit("@connect",{dtlsParameters:r},s,i)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new jc.InvalidStateError("method called in a closed handler")}};ss.FakeHandler=$i;var ns=class extends sf.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:e,ordered:t=!0,maxPacketLifeTime:r=null,maxRetransmits:s=null,label:i="",protocol:o=""}){super(),ne.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${r}, maxRetransmits:${s}, label:${i}, protocol:${o}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=r,this._maxRetransmits=s,this._label=i,this._protocol=o}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if(this._readyState!=="open")throw new jc.InvalidStateError("not open")}}});var Bc=U(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.generateRouterRtpCapabilities=of;Le.generateNativeRtpCapabilities=af;Le.generateNativeSctpCapabilities=cf;Le.generateLocalDtlsParameters=df;Le.generateTransportRemoteParameters=lf;Le.generateProducerRemoteParameters=uf;Le.generateConsumerRemoteParameters=pf;Le.generateDataProducerRemoteParameters=hf;Le.generateDataConsumerRemoteParameters=ff;var le=ut();function we(){return String(le.generateRandomNumber())}function of(){return le.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})}function af(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}}function cf(){return le.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function df(){return le.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})}function lf(){return{id:we(),iceParameters:le.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:le.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:le.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:le.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function uf(){return le.deepFreeze({id:we()})}function pf({id:n,codecMimeType:e}={}){switch(e){case"audio/opus":return{id:n??we(),producerId:we(),kind:"audio",rtpParameters:le.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:n??we(),producerId:we(),kind:"audio",rtpParameters:le.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:n??we(),producerId:we(),kind:"video",rtpParameters:le.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:n??we(),producerId:we(),kind:"video",rtpParameters:le.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${e}'`)}}function hf(){return le.deepFreeze({id:we()})}function ff({id:n}={}){return{id:n??we(),dataProducerId:we(),sctpStreamParameters:le.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var bi=U(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.debug=K.testFakeParameters=K.FakeHandler=K.enhancedEvents=K.ortc=K.parseScalabilityMode=K.detectDeviceAsync=K.detectDevice=K.Device=K.version=K.types=void 0;var mf=Ur();K.debug=mf.default;K.types=fa();K.version="3.20.0";var ji=Ac();Object.defineProperty(K,"Device",{enumerable:!0,get:function(){return ji.Device}});Object.defineProperty(K,"detectDevice",{enumerable:!0,get:function(){return ji.detectDevice}});Object.defineProperty(K,"detectDeviceAsync",{enumerable:!0,get:function(){return ji.detectDeviceAsync}});var gf=mt();Object.defineProperty(K,"parseScalabilityMode",{enumerable:!0,get:function(){return gf.parse}});K.ortc=Ne();K.enhancedEvents=ge();var _f=qc();Object.defineProperty(K,"FakeHandler",{enumerable:!0,get:function(){return _f.FakeHandler}});K.testFakeParameters=Bc()});var Vc=U((v_,qi)=>{"use strict";var vf=Object.prototype.hasOwnProperty,ue="~";function Xr(){}Object.create&&(Xr.prototype=Object.create(null),new Xr().__proto__||(ue=!1));function wf(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function Hc(n,e,t,r,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new wf(t,r||n,s),o=ue?ue+e:e;return n._events[o]?n._events[o].fn?n._events[o]=[n._events[o],i]:n._events[o].push(i):(n._events[o]=i,n._eventsCount++),n}function is(n,e){--n._eventsCount===0?n._events=new Xr:delete n._events[e]}function ie(){this._events=new Xr,this._eventsCount=0}ie.prototype.eventNames=function(){var e=[],t,r;if(this._eventsCount===0)return e;for(r in t=this._events)vf.call(t,r)&&e.push(ue?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};ie.prototype.listeners=function(e){var t=ue?ue+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,i=r.length,o=new Array(i);s<i;s++)o[s]=r[s].fn;return o};ie.prototype.listenerCount=function(e){var t=ue?ue+e:e,r=this._events[t];return r?r.fn?1:r.length:0};ie.prototype.emit=function(e,t,r,s,i,o){var a=ue?ue+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,d,u;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,s),!0;case 5:return c.fn.call(c.context,t,r,s,i),!0;case 6:return c.fn.call(c.context,t,r,s,i,o),!0}for(u=1,d=new Array(l-1);u<l;u++)d[u-1]=arguments[u];c.fn.apply(c.context,d)}else{var p=c.length,f;for(u=0;u<p;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,r);break;case 4:c[u].fn.call(c[u].context,t,r,s);break;default:if(!d)for(f=1,d=new Array(l-1);f<l;f++)d[f-1]=arguments[f];c[u].fn.apply(c[u].context,d)}}return!0};ie.prototype.on=function(e,t,r){return Hc(this,e,t,r,!1)};ie.prototype.once=function(e,t,r){return Hc(this,e,t,r,!0)};ie.prototype.removeListener=function(e,t,r,s){var i=ue?ue+e:e;if(!this._events[i])return this;if(!t)return is(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!s||o.once)&&(!r||o.context===r)&&is(this,i);else{for(var a=0,c=[],l=o.length;a<l;a++)(o[a].fn!==t||s&&!o[a].once||r&&o[a].context!==r)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:is(this,i)}return this};ie.prototype.removeAllListeners=function(e){var t;return e?(t=ue?ue+e:e,this._events[t]&&is(this,t)):(this._events=new Xr,this._eventsCount=0),this};ie.prototype.off=ie.prototype.removeListener;ie.prototype.addListener=ie.prototype.on;ie.prefixed=ue;ie.EventEmitter=ie;typeof qi<"u"&&(qi.exports=ie)});var lg={};Dl(lg,{ACTIVATION_COLD_BOOT_AFTER_MS:()=>Uo,ACTIVATION_DEGRADED_AFTER_MS:()=>No,ACTIVATION_HINT_PATH:()=>mn,ACTIVATION_STILL_AFTER_MS:()=>Oo,ACTIVITY_DOM_EVENTS:()=>vs,ACTIVITY_FIELD:()=>Ji,ACTIVITY_STAMP_MIN_INTERVAL_MS:()=>Ed,ActivationMonitor:()=>xt,App:()=>el,BACKOFF_BASE_MS:()=>kr,BACKOFF_MAX_ATTEMPTS:()=>it,BACKOFF_MAX_MS:()=>At,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:()=>hn,CaptureController:()=>un,CaptureUnavailableError:()=>ln,ClientTokenError:()=>rt,CreditsClient:()=>dn,CreditsError:()=>wt,CreditsUnauthorizedError:()=>wr,DATA_CHANNEL_MESSAGE_CEILING:()=>gl,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>vo,DEFAULT_GATEWAY_URL:()=>So,DEFAULT_PRODUCE_ACK_TIMEOUT_MS:()=>Pt,DEFAULT_REFERENCE_JPEG_QUALITY:()=>ml,DEFAULT_REFERENCE_MAX_SIZE:()=>fl,DEFAULT_WHEN_LIVE_TIMEOUT_MS:()=>Ws,DERIVED_LEG_SEP:()=>ar,DGRAM_HEADER_BYTES:()=>pe,DOC_LIVE_GATE_TIMEOUT_MS:()=>Ls,ENVELOPE_KIND:()=>se,FOCUS_FIELD:()=>eo,FOREGROUND_COALESCE_MS:()=>Dd,FrameReassembler:()=>pr,GENERATION_TICK_EMIT_INTERVAL_MS:()=>Rd,GENERATION_TICK_MAX_EXTRAPOLATION_MS:()=>Cd,INPUT_PRESENCE_DEFAULT_HZ:()=>ll,INPUT_PRESENCE_FIELD:()=>Co,InvalidDurationError:()=>ct,LEGACY_ACTIVATION_HINT_PATH:()=>gn,PLATFORM_DOC_NAME:()=>Sr,PermanentLockedError:()=>Or,PinRequiresActiveTempError:()=>Mr,PresenceTracker:()=>dr,ProduceAckTimeoutError:()=>Ct,RecordingNotFoundError:()=>Ir,RecordingsClient:()=>dt,RecordingsError:()=>be,RecordingsUnauthorizedError:()=>Mt,RequestAbortError:()=>nt,RequestCancelledError:()=>Et,RequestDocSyncError:()=>Tt,RequestError:()=>Ce,RequestTimeoutError:()=>kt,RetainNotTempError:()=>Lr,RuntimeArtifactNotFoundError:()=>Dr,RuntimeArtifactsClient:()=>Xe,RuntimeArtifactsError:()=>ae,RuntimeArtifactsUnauthorizedError:()=>xr,SIGNALING_PROTOCOL_VERSION:()=>Vi,STREAM_END:()=>vt,Session:()=>_r,SessionAllocationError:()=>q,SessionDirectory:()=>vr,SessionDirectoryError:()=>_e,SessionEndError:()=>oe,SessionEndUnavailableError:()=>Oe,SessionFailedError:()=>Ue,StreamDirectionConflict:()=>Rt,StreamFragmentReassembler:()=>or,TransportNegotiator:()=>fr,TransportSessionMismatchError:()=>st,TransportSessionSignaling:()=>mr,URUN_DEV_ENV:()=>ko,USER_ACTIVITY_FIELD:()=>Zi,USER_ACTIVITY_MIN_INTERVAL_MS:()=>xd,VISIBILITY_FIELD:()=>Xi,WIRE_MESSAGE_BUDGET:()=>_l,WT_CONTROL_FRAME_MAX:()=>ro,WT_DATA_STREAM_VERSION:()=>so,WebRtcSession:()=>gr,WebTransportSession:()=>hr,WtControlDecoder:()=>lr,WtDataStreamParser:()=>on,activationHintFrom:()=>Fs,cameraCaptureAvailable:()=>bl,captureStillFromVideo:()=>Sl,computeBackoffDelay:()=>It,consumeWtDataStreams:()=>Ps,createActivityTracker:()=>ws,createCameraWarp:()=>kl,createClientToken:()=>tl,createCreditsClient:()=>al,createInputPresencePublisher:()=>ul,createRecordingsClient:()=>ca,createRuntimeArtifactsClient:()=>oa,createStore:()=>sl,decodeStreamEnvelope:()=>ds,derivedLegName:()=>_d,derivedLegRole:()=>ps,describeSessionFailure:()=>br,describeSessionPhase:()=>Mo,encodeStreamEnvelope:()=>Zr,encodeStreamFragments:()=>cs,encodeWtControlFrame:()=>Rs,fitWithin:()=>Us,isDurationString:()=>Sn,isPausedPhase:()=>Lo,isPendingRecording:()=>ol,isRetryableSessionError:()=>Tr,isWakingPhase:()=>Be,mediaRecorderChunkSource:()=>ks,normalizeReferenceImage:()=>wl,normalizeRetention:()=>aa,observeLeaveConfirm:()=>Ss,observePageLifecycle:()=>ys,observePageTeardown:()=>bs,parseDgramHeader:()=>ur,prewake:()=>ra,referenceImageErrorMessage:()=>yl,releaseSessionBeacon:()=>Pr,sessionDirectory:()=>Zd,sessionFailureFromMediaError:()=>Io,sharedCaptureController:()=>dl,videoStream:()=>il,watchGenerationTick:()=>_s,whenLive:()=>fn,writeDgramHeader:()=>Es});module.exports=Al(lg);var bt=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let r;try{r=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!r.channel)return;let s=this._handlers.get(r.channel);if(s)for(let i of s)i(r)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r.delete(t),r.size===0&&this._handlers.delete(e)}}emit(e,t){if(this._disposed)return;let r=JSON.stringify({channel:e,...t});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(r);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(r),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},St=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[r,s]of this._handlers)for(let i of s)this._targetUnsubscribes.push(e.on(r,i));let t=this._pendingSends;this._pendingSends=[];for(let r of t)e.emit(r.channel,r.data)}rewriteSessionChannels(e,t){if(e===t)return;let r=`session:${e}:`,s=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(r)?s+o.slice(r.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(r)?s+o.channel.slice(r.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let r=this._handlers.get(e);r||(r=new Set,this._handlers.set(e,r)),r.add(t);let s=this._target?.on(e,t);return s&&this._targetUnsubscribes.push(s),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e),s?.(),s&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==s))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}};var Oe=class extends Error{code="session_end_unavailable";constructor(e="[urun] this session handle cannot terminally end the session; disconnect the viewer instead",t){super(e),this.name="SessionEndUnavailableError",t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends Error{code;httpStatus;requestId;sessionId;constructor(e,t){super(e),this.name="SessionEndError",this.code=t.code??"session_end_failed",this.httpStatus=t.httpStatus,this.requestId=t.requestId,this.sessionId=t.sessionId,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},_e=class extends Error{code;httpStatus;constructor(e,t){super(e),this.name="SessionDirectoryError",this.code=t?.code??"session_directory_failed",this.httpStatus=t?.httpStatus,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},Ce=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},kt=class extends Ce{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},Tt=class extends Ce{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},Rt=class extends Error{stream;owner;attempted;constructor(e,t,r){super(`[urun] stream "${e}" is already produced by the ${t}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},Pt=15e3,Ct=class extends Error{kind;stream;timeoutMs;constructor(e,t){let r=t?.timeoutMs??Pt,s=t?.stream??e,i=s!==e?` "${s}"`:"";super(`[urun] SFU did not ack producer ${e}${i} within ${Math.round(r/1e3)}s \u2014 the server never replied to 'produce'. The runtime's inbound port for this stream is likely unadvertised (a cold or capacity-queued runtime), so the SFU has nothing to forward the track to; the published track never reached the runtime.`),this.name="ProduceAckTimeout",this.kind=e,this.stream=s,this.timeoutMs=r,Object.setPrototypeOf(this,new.target.prototype)}},nt=class extends Ce{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},Et=class extends Ce{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}},Il=/^\[urun\] (?:timed out waiting for session allocation at|session allocation wait expired at|session allocation poll failed at|session allocation failed at|session allocation at|session create at) \S+(?::[ \t]+|[ \t]+|$)/;function Ll(n){return n.replace(/\bhttps?:\/\/[^\s)]+/g,"the session gateway")}function Do(n){let e=n.replace(Il,"");return Ll(e||n.replace(/^\[urun\] /,""))}function Ao(n){let e=n.error?.httpStatus;if(e===401||e===403)return"The backend rejected this client \u2014 sign in again or check the auth token / org access.";if(n.error?.code==="session_archived")return"This session is archived \u2014 call directory.unarchive(sessionId) (the session directory's un-archive verb), then reconnect with the same id.";let t=n.error?.retryAfterSeconds,r=t!==void 0?` It asked for ${Math.round(t)}s.`:"";return e===429?`The backend is shedding load \u2014 its admission queue is full, so this is capacity, not your request.${r} The SDK already retried with backoff; try again in a moment.`:e===408?`The request timed out before the backend answered \u2014 that is a timeout, not a verdict on your request.${r} The SDK already retried with backoff; try again in a moment.`:e!==void 0&&e>=500?"The backend is having an outage (nothing is wrong with your request) \u2014 the SDK already retried with backoff, so try again shortly and report the status above if it persists.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."}function br(n,e){let t=e.error?.reason,r=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(n){case"create-failed":{let s=e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:"",i=e.error?.code;return i==="queue_ttl_expired"||i==="stale_poll_expired"?{message:`[urun] the queued session REQUEST timed out while waiting${s} (${i}) \u2014 the session itself is untouched`,hint:"Nothing was lost and nothing needs replacing: connect again with the same session and the control plane re-admits the request (a poll that arrives in time re-drives it on its own)."}:i==="session_archived"?{message:`[urun] this session is archived${s} \u2014 un-archive it before resuming`+(t?`: ${Do(t)}`:""),hint:Ao(e)}:i==="client_release"?{message:`[urun] the session's admission request was closed (client_release)${s} \u2014 this dial cannot attach through it`,hint:"The request row is terminal; retrying the same dial only repeats the 410. Create a fresh session (a new dial). The SDK itself never closes a request \u2014 a whenLive timeout only rejects."}:{message:`[urun] session create failed${s}${t?`: ${Do(t)}`:""}`,hint:Ao(e)}}case"never-live":{let s=r!==void 0?` after ${r}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`,o=e.lastServerStatus!==void 0&&["requested","queued","pending","allocating","provisioning","waking","waiting_for_capacity","unavailable","allocated","starting"].includes(e.lastServerStatus);return e.error?.code==="expired"?o?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before a runtime picked it up${s}${i} \u2014 the backend never dispatched the session (no runtime pulled it), so no media transport could ever connect`,hint:"Not a network problem \u2014 the session was still waiting for a runtime. Retry in a moment; if it persists, the backend dispatch lane is stuck."}:{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${s} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?o?{message:`[urun] session ${e.sessionId} was created but no runtime ever picked it up${s}${i} \u2014 the backend has not dispatched the session yet (a runtime pulls the demand, then the session server exists)`,hint:"Waiting for a runtime \u2014 not a network, VPN, or firewall problem. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] session ${e.sessionId} was created but never went live${s}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${s} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${t?`: ${t}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${t?`: ${t}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"runtime-failed":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} failed at runtime${t?`: ${t}`:""}`,hint:"The session function crashed on the backend \u2014 check the app logs. The session itself is parked, not gone: attach to it again once the app is fixed."};case"produce-timeout":return{message:`[urun] publishing a track timed out${t?`: ${t}`:""} \u2014 the SFU never acked the produce (the runtime\u2019s inbound port for the stream was not advertised in time)`,hint:"The runtime was still cold or the backend was at capacity when the track was published. Retry in a moment; if it persists, the backend never opened the stream to receive it."};case"insufficient-credits":return{message:`[urun] session create refused${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""} \u2014 the org has insufficient credits${t?`: ${t}`:""}`,hint:"Out of credits \u2014 add credits to keep running sessions."}}}var Ue=class extends Error{kind;status;hint;constructor(e,t,r){let{message:s,hint:i}=br(e,t);super(s),this.name="SessionFailedError",this.kind=e,this.status=t,this.hint=i,r?.cause!==void 0&&(this.cause=r.cause),Object.setPrototypeOf(this,new.target.prototype)}};function Io(n,e){if(n instanceof Ue)return n;let t=n instanceof Error?n:new Error(String(n)),r={phase:e?.phase??"idle",transportState:e?.transportState??"disconnected",...e,error:{reason:t.message,code:t.name,kind:"media-permission"}};return new Ue("media-permission",r,{cause:n})}var st=class extends Error{code="transport_session_mismatch";connectedSessionId;requestedSessionId;constructor(e,t){super(`[urun] cannot retarget a connected transport to a different session: this leg is live on ${e??"(unknown)"} but setConnection() asked for ${t} \u2014 disconnect() this leg first (or use a fresh session handle)`),this.name="TransportSessionMismatchError",this.connectedSessionId=e,this.requestedSessionId=t,Object.setPrototypeOf(this,new.target.prototype)}},q=class extends Error{httpStatus;code;balanceCredits;platformStatus;retryAfterSeconds;constructor(e,t){super(e),this.name="SessionAllocationError",this.httpStatus=t?.httpStatus,this.code=t?.code,this.balanceCredits=t?.balanceCredits,this.platformStatus=t?.platformStatus,this.retryAfterSeconds=t?.retryAfterSeconds,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}};function Be(n){if(!n)return!1;let e=typeof n=="string"?n:n.name;return e==="queued"||e==="unavailable"||e==="provisioning"||e==="waiting_for_capacity"}function Lo(n){return n?(typeof n=="string"?n:n.name)==="paused":!1}var Ws=45e3,hn=6e5;function fn(n,e={}){let{signal:t}=e;return new Promise((r,s)=>{if(t?.aborted){s(t.reason instanceof Error?t.reason:new Error("whenLive aborted"));return}if(n.phase?.name==="live"){r();return}if(n.phase?.name==="error"){let w=n.phase,b=n.status??{phase:w.name,transportState:"disconnected",sessionId:w.sessionId,requestId:w.requestId,queue:w.queue,error:w.error,region:w.region};s(new Ue(w.error?.kind??"transport-failed",b));return}let o,a,c=!1,l=w=>{c||(c=!0,a!==void 0&&clearTimeout(a),t?.removeEventListener("abort",d),o?.(),w?s(w):r())},d=()=>{l(t?.reason instanceof Error?t.reason:new Error("whenLive aborted"))};t?.addEventListener("abort",d,{once:!0});let u=()=>{let w=n.phase;return n.status??{phase:w?.name??"idle",transportState:"disconnected",sessionId:w?.sessionId,requestId:w?.requestId,queue:w?.queue,error:w?.error,region:w?.region}},p=w=>l(new Ue(w,u())),f=e.timeout!==void 0,g=Date.now(),h=f?e.timeout:Ws,m=()=>{a!==void 0&&(clearTimeout(a),a=void 0)},_=()=>{if(c||h<=0)return;clearTimeout(a);let w=g+h-Date.now();a=setTimeout(()=>{if(!f&&Be(n.phase?.name)){a=void 0;return}let b=u();b.elapsedMs===void 0&&(b.elapsedMs=h),a=void 0,t?.removeEventListener("abort",d),o?.(),o=void 0,l(new Ue("never-live",b))},Math.max(0,w))},v=w=>{!f||c||h<=0||w?.runtime?.wake?.expectedWakePath==="cold-boot"&&(hn<=h||(h=hn,_()))},S=w=>{if(!c){if(!f&&Be(w?.name)){m();return}if(f){v(w),a===void 0&&h>0&&_();return}a===void 0&&(g=Date.now(),_())}};o=n.onPhase(w=>{w?.name==="live"?l():w?.name==="error"?p(w.error?.kind??"transport-failed"):S(w)}),c||S(n.phase),c&&o()})}function Mo(n){switch(n.name){case"idle":return"Initializing\u2026";case"unavailable":return"Starting the app\u2026";case"queued":return n.queue?`Waiting in queue (position ${n.queue.position} of ${n.queue.depth})\u2026`:n.runtime?.state==="busy"?"All runtimes are busy \u2014 waiting for capacity\u2026":"Waiting for capacity\u2026";case"provisioning":return n.runtime?.state==="starting"?"Starting model\u2026":"Provisioning\u2026";case"waiting_for_capacity":return n.queue?`Waiting for GPU capacity (position ${n.queue.position} of ${n.queue.depth})\u2026`:"Waiting for GPU capacity";case"connecting":return n.reason==="docs_connecting"?"Connecting session data\u2026":"Connecting\u2026";case"degraded":return"The runtime stopped responding \u2014 recovering\u2026";case"live":return"Live";case"paused":return Ml(n.reason);case"error":{if(n.error?.kind==="insufficient-credits")return"Out of credits \u2014 add credits to keep running sessions.";let e=n.error?.kind;if(e){let{message:t,hint:r}=br(e,{phase:n.name,transportState:"disconnected",sessionId:n.sessionId,requestId:n.requestId,queue:n.queue,error:n.error});return`${t.replace(/^\[urun\] /,"")} \u2014 ${r}`}return n.error?.reason?`Session failed \u2014 ${n.error.reason}`:"Session failed"}case"unknown":return n.reason?`Session in an unrecognized state ("${n.reason}") \u2014 the client SDK may be out of date`:"Session in an unrecognized state \u2014 the client SDK may be out of date"}}function Ml(n){switch(n){case"client_ended":return"Paused \u2014 you hung up. Resume any time.";case"client_paused":return"Paused \u2014 you paused it. Resume any time.";case"client_detached":return"Paused \u2014 this device let go. Resume any time.";case"client_gone":return"Paused \u2014 every device disconnected. Resume any time.";case"session_ended":case"ended":case"closed":return"Paused \u2014 the compute was released. Resume any time.";case"idle_timeout":return"Paused \u2014 idle. Resume any time.";case"max_session_age":return"Paused \u2014 reached its maximum length. Resume any time.";case"credits_exhausted":return"Paused \u2014 out of credits. Add credits, then resume.";case"capacity_pressure":return"Paused \u2014 the GPU was reclaimed while the platform was under load. Resume any time.";case"control_plane_release":return"Paused \u2014 the platform reclaimed the compute. Resume any time.";case"superseded":return"Paused \u2014 another client attached. Resume any time.";case"superseded_by_redial":return"Paused \u2014 a newer connection from this session took over. Resume any time.";case"connect_deadline":return"Paused \u2014 the runtime never finished connecting in time. Resume to try again.";case"adoption_expired":return"Paused \u2014 the runtime was assigned but never picked the session up. Resume to try again.";case"media_lane_bind_failed":return"Paused \u2014 the audio/video lane could not be set up. Resume to try again.";case"lease_lost":return"Paused \u2014 the runtime stopped renewing its lease. Resume any time.";case"presence_unconfirmed":return"Paused \u2014 the platform could not confirm anyone was still attached. Resume any time.";case"runtime_inert":case"assignment_unconfirmable":return"Paused \u2014 the runtime never acknowledged its assignment. Resume to try again.";case"runtime_unreachable":return"Paused \u2014 the platform could not reach the runtime. Resume to try again.";case"runtime_silent":return"Paused \u2014 the runtime stopped sending audio/video. Resume to try again.";case"assignment_undelivered":return"Paused \u2014 the assignment never reached a runtime. Resume to try again.";case"dispatch_released":return"Paused \u2014 the worker finished and gave its GPU seat back. Resume any time.";case"dispatch_parked":return"Paused \u2014 the worker finished and parked the session. Resume any time.";case"runtime_swap_exhausted":return"Paused \u2014 the platform ran out of runtimes to try. Resume any time.";case"dispatch_failed":return"Paused \u2014 handing the session to a worker did not succeed. Resume to try again.";default:return n?`Paused \u2014 ${n}. Resume any time.`:"Paused \u2014 resume any time."}}var Oo=15e3,Uo=45e3,No=12e4,Sr="platform",mn="activation",gn="desired.activation";function Fs(n){if(typeof n=="string"&&n.length>0)return n;if(n&&typeof n=="object"){let e=n.note;if(typeof e=="string"&&e.length>0)return e}}var Ol=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],xt=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="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 r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let s=()=>this._firstMedia(e);r.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",s));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of Ol){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let s={state:t,elapsedMs:r,stream:e.name},i=Fs(this._options.hint());i!==void 0&&(s.hint=i),e.lastEvent=s;for(let o of Array.from(this._handlers))o(s)}};function Qe(){return typeof process<"u"&&process.stdout!=null&&typeof process.stdout.write=="function"}function Je(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function Wo(){return Je()?"Chrome111":void 0}function Fo(){return typeof globalThis.RTCPeerConnection<"u"?null:"the WebRTC peer globals (RTCPeerConnection) are not installed in this runtime"}function Dt(){if(!Je())return Promise.resolve();throw new Error("[urun-sh/core] Node WebRTC transport is not available in the browser build. The browser uses native WebRTC/WebSocket globals; import the Node build to use the werift-backed transport.")}var kr=500,At=15e3,it=6;function It(n,e=Math.random){if(!Number.isFinite(n)||n<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${n}`);let t=Math.min(At,kr*2**n);return Math.round(e()*t)}function Tr(n){if(n instanceof q){let e=n.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return n instanceof Error?n.name==="TypeError"||n.name==="TimeoutError"||n.name==="AbortError":!1}var $o=10,Ul=.5,_n=$o;function $s(){return _n<1?!1:(_n-=1,!0)}function js(){_n=Math.min($o,_n+Ul)}var Nl="session-api.prod.cloud.urun.sh",Wl=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Y(n){return n.trim().replace(/\/+$/,"")}function Er(n,e){let t=[],r=s=>{if(!s)return;let i=Y(s);i&&!t.includes(i)&&t.push(i)};r(n);for(let s of e??[])r(s);for(let s of wu(n))r(s);return t}var Fl="/v1";function wn(n){try{return new URL(Y(n)).pathname===Fl}catch{return!1}}function Pr(n){try{if(typeof fetch!="function")return;let e=Y(n.baseUrl),t=n.sessionId?`${e}/api/sessions/${encodeURIComponent(n.sessionId)}/end`:`${e}/api/session-requests/${encodeURIComponent(n.requestId)}/cancel`;fetch(t,{method:"POST",headers:n.reason!==void 0?{...xe(n,n.jwt),"Content-Type":"application/json"}:xe(n,n.jwt),...n.reason!==void 0?{body:JSON.stringify({reason:n.reason})}:{},keepalive:!0}).catch(()=>{})}catch{}}async function qs(n){try{let e=`${Y(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/cancel`,t=await Pe(n);if(n.getAccessToken&&!t)throw new oe("[urun] session request cancel refused: getAccessToken resolved no token (an unauthenticated cancel is never sent)",{requestId:n.requestId,code:"no_access_token"});let r=await fetch(e,{method:"POST",headers:xe(n,t),keepalive:!0});if((r.status===401||r.status===403)&&n.getAccessToken){let o=await Pe(n,{forceRefresh:!0,reason:"unauthorized"});o&&o!==t&&(r=await fetch(e,{method:"POST",headers:xe(n,o),keepalive:!0}))}let s=await Lt(r);if(!r.ok)throw new oe(`[urun] session request cancel failed: ${bn(s,r.status)}`,{requestId:n.requestId,code:s.error_code,httpStatus:r.status});let i=String(s.status??"");if(i==="cancelled"||i==="canceled"||i==="closed")return{status:"canceled",requestId:n.requestId};if(i==="failed"||i==="rejected"||i==="expired")return{status:"canceled",requestId:n.requestId,platformStatus:i};throw new oe(`[urun] session request cancel returned an unrecognized request status ${JSON.stringify(i)} (recognized: cancelled/canceled, closed, failed, rejected, expired)`,{requestId:n.requestId,code:"invalid_release_response",httpStatus:r.status})}catch(e){throw e instanceof oe?e:new oe("[urun] session request cancel failed",{requestId:n.requestId,cause:e})}}async function Bs(n){let e;try{e=await yn(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/end`,{method:"POST",keepalive:!0},"session end")}catch(a){if(a instanceof oe)throw a;let c=a;throw new oe(c?.message??"[urun] session end request failed",{sessionId:n.sessionId,...c?.code!==void 0?{code:c.code}:{},...c?.httpStatus!==void 0?{httpStatus:c.httpStatus}:{},cause:a})}let t=zs(e)?e:{},r=String(t.status??""),s=typeof t.pause_reason=="string"?t.pause_reason:void 0,i=typeof t.terminal_reason=="string"?t.terminal_reason:void 0,o=Cr(s)?s:Cr(i)?i:void 0;if(r==="paused")return{status:"paused",sessionId:String(t.logical_id??t.id??n.sessionId),...o!==void 0?{reason:o}:{}};throw new oe(`[urun] session end returned ${JSON.stringify(r)} for session ${n.sessionId} \u2014 an end PARKS the session, so the only contract-valid answer is "paused" (a terminal word on this route would be a session-plane terminal write, which is forbidden)`,{sessionId:n.sessionId,code:"invalid_end_response"})}function zo(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var $l=120,jl=1e3,ql=20,Bl=5,Hl=5e3;function Hs(n,e=Date.now()){if(!n)return null;let t=n.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),s=r.padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return typeof i.exp!="number"||!Number.isFinite(i.exp)?null:i.exp*1e3-e}catch{return null}}var Vl=500,Go=1e4,zl=new Set([502,503,504]),Gl=2,Kl=50,jo=1e4;async function qo(n,e){let t=Date.now()+jo;for(;;){await ot(Kl);let r=await Pe(n);if(r)return r;if(Date.now()>=t)throw new q(`[urun] session allocation at ${e} never got an access token: the wired getAccessToken resolved nothing within ${Math.round(jo/1e3)}s (no unauthenticated request was sent)`)}}function Yl(n,e){if(!n)return null;try{let t=new URL(n),r=e?new URL(Y(e)):null,s=t.pathname==="/api/sessions/create"||t.pathname==="/api/sessions/create/";return t.protocol!=="https:"||!s||!Zl(t,r)?null:Y(t.origin)}catch{return null}}function Ql(n,e){if(!n||!n.trim())return{outcome:"absent"};if(!Jl(e))return{outcome:"bootstrap-only"};let t=n.includes("://")?n:`https://${n}`,r;try{r=new URL(t)}catch{return{outcome:"rejected",reason:"not a parseable URL or host"}}return r.protocol!=="https:"?{outcome:"rejected",reason:`scheme ${r.protocol} is not https:`}:r.pathname!=="/"&&r.pathname!==""?{outcome:"rejected",reason:`expected a bare origin, got path ${r.pathname}`}:vn(r.hostname)?{outcome:"pinned",base:Y(r.origin)}:{outcome:"rejected",reason:`host ${r.hostname} is outside the urun.sh trust set`}}function Jl(n){if(!n)return!1;try{let e=new URL(Y(n));return e.protocol==="https:"&&vn(e.hostname)}catch{return!1}}function Xl(n){let e=Y(n);try{return Y(new URL(e).origin)}catch{return e}}function Zl(n,e){return vn(n.hostname)&&(!e||vn(e.hostname))}function vn(n){let e=n.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}function eu(n){let e=n instanceof q?n.retryAfterSeconds:void 0;return e===void 0||!Number.isFinite(e)||e<=0?0:Math.min(e*1e3,At)}function Ko(n,e){let t=eu(e);return t>0?Math.max(n,Date.now()+t):n}async function Yo(n){if(wn(n.baseUrl))return ou(n);let e=Er(n.baseUrl,n.fallbackUrls),t=null,r=0,s=e.length>1;for(let i=0;i<it;i++){for(let o of e)try{let a=await au(o,n,{pollAttempts:$l,retryAfterLimitMs:s?jl:void 0});return js(),a}catch(a){if(t=a instanceof Error?a:new Error(String(a)),r=Ko(r,t),t instanceof Ee||t instanceof at||lu(t))throw t}if(!Tr(t))break;if(i+1<it){if(!$s())break;await ot(Math.max(It(i),r-Date.now()))}}throw t??new Error("[urun] session allocation failed")}var tu=500,ru=9e5,nu=6e4,su=6e5,iu={queued:!0,claimed:!0,starting:!0,retry_pending:!0};async function ou(n){let e=Y(n.baseUrl),t=n.jwt??await n.getAccessToken?.({reason:"background"})??void 0;if(!t)throw new q("[urun] hub allocation requires a client token (jwt or getAccessToken)",{httpStatus:401});let r=await fetch(`${e}/sessions`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({...wn(n.baseUrl)?{shape:n.shape??"cpu:1"}:{resource_class:"cpu"},idempotency_key:n.idempotencyKey,metadata:{app:n.app,function:n.functionName,org:n.orgId,...n.sessionKey?{logical_id:n.sessionKey}:{}}})}),s=await r.text();if(!r.ok)throw new q(`[urun] hub create failed (${r.status}): ${s.slice(0,300)}`,{httpStatus:r.status});let i=JSON.parse(s),o=null;for(;iu[i.state];){let c=Date.now();if(i.state==="queued"||i.state==="retry_pending"){o=null;let d=i.queue_deadline_at===null?null:typeof i.queue_deadline_at=="number"&&i.queue_deadline_at>0?i.queue_deadline_at:c+ru;if(d!==null&&c>=d+nu)throw new q(`[urun] hub session ${i.session_id} is still ${i.state} past the hub's queue deadline (${i.last_error??i.pause_reason??"hub reported no reason"})`,{httpStatus:504,platformStatus:i.state})}else if(o??=c+su,c>=o)throw new q(`[urun] hub session ${i.session_id} stuck ${i.state} past the boot patience window (${i.last_error??"hub reported no reason"})`,{httpStatus:504,platformStatus:i.state});n.onAdmission?.({status:i.state,sessionId:i.session_id}),await ot(tu);let l=await fetch(`${e}/sessions/${encodeURIComponent(i.session_id)}`,{headers:{authorization:`Bearer ${t}`}});if(!l.ok){if(l.status===404)throw new q(`[urun] hub session ${i.session_id} disappeared (${l.status})`,{httpStatus:l.status});continue}i=await l.json()}if(i.state==="failed"||i.state==="completed")throw new q(`[urun] hub session ${i.session_id} reached ${i.state} (${i.last_error??i.terminal_reason??"no reason recorded"})`,{httpStatus:503,platformStatus:i.state});if(i.state==="paused")throw new q(`[urun] hub session ${i.session_id} is parked (${i.pause_reason??i.last_error??"no reason recorded"})`,{httpStatus:503,platformStatus:i.state});if(i.state!=="running"||!i.sfu_endpoint)throw new q(`[urun] hub session ${i.session_id} ended in state=${i.state} without an sfu_endpoint (${i.last_error??i.terminal_reason??"no reason recorded"})`,{httpStatus:504,platformStatus:i.state});let a=Qo(i);if(!a)throw new q(`[urun] hub session ${i.session_id} is running but carried no sfu_attach credential (hub deployment predates lane 52, or HUB_GRANT_SECRET is unset)`,{httpStatus:502,platformStatus:i.state});return{baseUrl:e,sessionId:i.session_id,wsUrl:i.sfu_endpoint,endsAt:null,sfuAttach:a,response:i}}function Qo(n){let e=n.sfu_attach;if(!(!e||typeof e.token!="string"||typeof e.gen!="number"||!Number.isInteger(e.gen)||e.gen<0||e.token.length===0))return{url:n.sfu_endpoint??"",token:e.token,gen:e.gen}}async function Jo(n){let e=Y(n.baseUrl),t=await fetch(`${e}/sessions/${encodeURIComponent(n.sessionId)}`,{headers:n.jwt?{authorization:`Bearer ${n.jwt}`}:{}});if(t.status===401||t.status===403)throw new q(`[urun] hub session view refresh refused (${t.status}) for ${n.sessionId}`,{httpStatus:t.status});if(!t.ok)return null;let r=await t.json();if(r.session_id!==n.sessionId||r.state!=="running"||!r.sfu_endpoint)return null;let s=Qo(r);return s?{url:r.sfu_endpoint,sessionId:r.session_id,sfuAttach:s}:null}async function au(n,e,t){let r,s,i,o,a=Xl(n),c=0,l=new Set,d=Date.now(),u=d+t.pollAttempts*Go,p=!1,f=12e4,g=10080*60,h=S=>{if(typeof S!="number"||!Number.isFinite(S)||S<=0||S>g)return;let w=d+S*1e3+f;w>u&&(u=w,p=!0)},m=()=>p?Number.POSITIVE_INFINITY:t.pollAttempts,_=8,v=0;for(let S=0;S<m();S++){if(p&&Date.now()>=u)throw Rr(a,!!r,o);s=i??await Pe(e),i=void 0,e.getAccessToken&&!s&&(s=await qo(e,a));let w=!!r,b=Date.now(),T;if(r){let F=0,$=G=>{let X=Math.min(At,kr*2**F),he=Math.max(Math.ceil(X/2),It(F));return F+=1,Math.min(Math.max(G,he),Math.max(0,u-Date.now()))};for(;;){let G=u-Date.now();if(G<=0)throw Rr(a,!0,o);let X=Math.max(1,Math.min(ql,Math.floor(G/1e3)));{let Z=Hs(s);if(Z!==null&&Z<X*1e3+Hl)try{let Me=await Pe(e,{forceRefresh:!0});Me&&Me!==s&&(s=Me)}catch{}}b=Date.now();try{T=await fetch(`${a}/api/session-requests/${encodeURIComponent(r)}?wait_s=${X}`,{headers:xe(e,s),redirect:"manual",signal:gu((X+Bl)*1e3)})}catch{let Z=$(0);if(Z<=0)throw Rr(a,!0,o);await ot(Z);continue}if(o=`HTTP ${T.status}`,!zl.has(T.status))break;try{await T.body?.cancel()}catch(Z){throw new at(`[urun] session allocation poll response cleanup failed at ${a}`,{cause:Z})}let he=$(Ho(T,{},t.retryAfterLimitMs));if(he<=0)throw Rr(a,!0,o);await ot(he)}}else T=await fetch(`${a}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...xe(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(cu(e))});if(T.type==="opaqueredirect"||T.status>=300&&T.status<400){try{await T.body?.cancel()}catch{}throw new Ee(`[urun] ${w?"session poll":"session create"} at ${a} answered an HTTP redirect (status ${T.status}) \u2014 browsers cannot follow a cross-origin redirect with credentials; the control plane must emit the JSON redirect envelope ({status:"redirect", location})`)}let y=await Lt(T);if(o=typeof y.status=="string"&&y.status?y.status:`HTTP ${T.status}`,T.status!==401&&T.status!==403&&(v=0),!r&&y.status==="redirect"){let F=Yl(y.location,a);if(!F)throw new q(`[urun] session create at ${a} answered a redirect envelope without a usable location (${JSON.stringify(y.location??null)}) \u2014 refusing to re-issue an authenticated create to an untrusted target`);if(F===a)throw new q(`[urun] session create at ${a} redirected to ITSELF \u2014 control-plane region apex map misconfiguration`);if(c>=Gl)throw new q(`[urun] session create followed ${c} region redirects and was redirected AGAIN (${a} -> ${F}) \u2014 region forward loop, giving up loudly`);c+=1,a=F;continue}if(y.request_id)try{e.onRequest?.({requestId:y.request_id,baseUrl:a,...y.session_id?{sessionId:y.session_id}:{}})}catch{}if(T.ok&&(y.status==="allocated"||!y.status&&!!y.session_id)&&!!y.session_id){let F=y.session_id,$=Ql(y.session_api_base,a);if($.outcome==="rejected")throw new Ee(`[urun] gateway allocated session ${y.session_id} with an unusable session_api_base (${JSON.stringify(y.session_api_base)}): ${$.reason} \u2014 refusing to pin the session to a region it may not belong to`);if($.outcome==="pinned"&&$.base!==a&&(a=$.base,y.request_id))try{e.onRequest?.({requestId:y.request_id,baseUrl:a,...y.session_id?{sessionId:y.session_id}:{}})}catch{}let G=na(y.ws_url,a,F,"gateway allocated session");return{baseUrl:a,sessionId:F,wsUrl:G,endsAt:zo(y.ends_at),response:y}}if(T.status===202||y.status==="pending"||y.status==="queued"||y.queued){if(r=y.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(h(y.effective_max_queue_time_s),e.onAdmission)try{e.onAdmission(mu(y,r))}catch{}let F=Date.now()-b<Vl;w&&F&&await ot(Ho(T,y,t.retryAfterLimitMs));continue}if((T.status===401||T.status===403)&&e.getAccessToken&&y.error_code!=="session_name_not_yours"){let F=s??"";if(l.add(F),p&&(v+=1,v>_))throw new at(`[urun] session allocation failed at ${a}: authorization refused ${_} consecutive refreshes while the admission wait was extended (last server status: ${o??"none received"}) \u2014 the token provider keeps minting fresh tokens the control plane rejects`,{httpStatus:T.status,code:y.error_code,platformStatus:y.status});let $=await Pe(e,{forceRefresh:!0,reason:"unauthorized"});if($&&!l.has($)){i=$;continue}if($===void 0){let G=await qo(e,a);if(!l.has(G)){i=G;continue}}}let N=bn(y,T.status),Q=y.error_code??(T.status===402?"insufficient_credits":void 0),te=w?at:q;throw new te(`[urun] session allocation failed at ${a}: ${N}`,{httpStatus:T.status,code:Q,balanceCredits:typeof y.balance_credits=="number"?y.balance_credits:void 0,platformStatus:y.status,retryAfterSeconds:Ks(T,y)})}throw Rr(a,!!r,o)}function Rr(n,e=!1,t){let r=e?at:q;return new r(`[urun] session allocation wait expired at ${n} \u2014 the CLIENT-side wait budget elapsed (last server status: ${t??"none received"}; the gateway reported no failure)`)}function xe(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function Pe(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function cu(n){let e=n.priority==="preempt";return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey,...n.sessionKey&&!e?{logical_id:n.sessionKey}:{},...n.concurrencyKey&&!e?{concurrency_key:n.concurrencyKey}:{},...n.label&&!n.sessionKey?{label:n.label}:{},...e?{priority:"preempt"}:{},...n.sharedApp?{shared_app:!0}:{}}}async function yn(n,e,t,r){let s=await Pe(n);if(n.getAccessToken&&!s)throw new _e(`[urun] ${r} refused: getAccessToken resolved no token (an unauthenticated request is never sent)`,{code:"no_access_token"});let i=Er(n.baseUrl,n.fallbackUrls),o;for(let a of i){let c=`${Y(a)}${e}`,l=p=>fetch(c,{method:t.method,headers:t.body!==void 0?{...xe(n,p),"Content-Type":"application/json"}:xe(n,p),...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...t.keepalive?{keepalive:!0}:{}}),d;try{if(d=await l(s),(d.status===401||d.status===403)&&n.getAccessToken){let p=await Pe(n,{forceRefresh:!0,reason:"unauthorized"});p&&p!==s&&(d=await l(p))}}catch(p){o=p;continue}let u=await Lt(d);if(!d.ok)throw new _e(`[urun] ${r} failed: ${bn(u,d.status)}`,{code:u.error_code,httpStatus:d.status});return u}throw new _e(`[urun] ${r} request failed`,{cause:o})}async function Xo(n){let e=new URLSearchParams;n.app&&e.set("app",n.app),n.functionName&&e.set("function",n.functionName),n.includeArchived&&e.set("include_archived","true"),n.limit!==void 0&&e.set("limit",String(n.limit)),n.cursor&&e.set("cursor",n.cursor);let t=e.toString(),r=await yn(n,`/api/sessions${t?`?${t}`:""}`,{method:"GET"},"session list");if(!Array.isArray(r?.sessions))throw new _e("[urun] session list returned no `sessions` array \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_response"});return{rows:r.sessions,nextCursor:r.next_cursor??null}}async function Vs(n){let e=n.archived?"archive":"unarchive";await yn(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/${e}`,{method:"POST"},`session ${e}`)}async function Zo(n){await Bs(n)}async function ea(n){let e=n.name.trim();if(e.length===0)throw new _e("[urun] session name refused: a name is required (an empty name is not a rename)",{code:"invalid_session_name"});await yn(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/name`,{method:"POST",body:{name:e,...n.source?{source:n.source}:{}}},"session name")}async function ta(n){let e=Er(n.baseUrl,n.fallbackUrls),t=null,r=0;for(let s=0;s<it;s++){for(let i of e)try{let o={baseUrl:i,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},a=`${Y(i)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,c=await Pe(o);if(n.getAccessToken&&!c)throw new q(`[urun] viewer-connect for ${n.sessionId} refused: getAccessToken resolved no token (an unauthenticated viewer-connect is never sent)`);let l=await fetch(a,{headers:xe(o,c)});if((l.status===401||l.status===403)&&n.getAccessToken){let p=await Pe(o,{forceRefresh:!0,reason:"unauthorized"});p&&p!==c&&(l=await fetch(a,{headers:xe(o,p)}))}if(!l.ok){let p=await Lt(l);throw new q(`[urun] viewer-connect for ${n.sessionId} failed: `+bn(p,l.status),{httpStatus:l.status,retryAfterSeconds:Ks(l,p)})}let d=await Lt(l),u=na(d.ws_url,i,n.sessionId,"viewer-connect");return js(),{baseUrl:Y(i),sessionId:n.sessionId,wsUrl:u,endsAt:zo(d.ends_at),response:d}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),r=Ko(r,t),t instanceof Ee)throw t}if(!Tr(t))break;if(s+1<it){if(!$s())break;await ot(Math.max(It(s),r-Date.now()))}}throw t??new Error("[urun] viewer-connect failed")}async function ra(n){try{let e=Y(n.baseUrl),t=await Pe(n);if(n.getAccessToken&&!t)return{status:"unavailable"};let r=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...xe(n,t),"Content-Type":"application/json"},body:JSON.stringify({app:n.app,function:n.functionName})});if(r.status===404)return{status:"unknown-app"};if(!r.ok)return{status:"unavailable"};let s=await Lt(r),i={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(i.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(i.warmCapable=s.warm_capable),i}catch(e){return Qe()?console.warn("[urun] prewake failed (advisory, ignored):",e):console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function Lt(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function bn(n,e){let t=n.error_code,r=n.error_message||n.message||n.error,s=t&&r&&r!==t?`${t}: ${r}`:r||t;return s?`${s} (HTTP ${e})`:`HTTP ${e}`}var du=new Set([400,402,409]);function lu(n){return n instanceof q&&n.httpStatus!==void 0&&du.has(n.httpStatus)}var uu=new Set(["capture-attested","no-portable-golden","portable-golden-release-mismatch","portable-golden-attestation-invalid"]);function zs(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Cr(n){return typeof n=="string"&&n.trim().length>0}function Bo(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}function pu(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0}function hu(n){if(zs(n)&&!(!Cr(n.snapshot_id)||!Cr(n.snapshot_compat_key)||!Bo(n.artifact_size_bytes)||!Bo(n.durable_arena_bytes)||n.volatile_arena_bytes!==0||!pu(n.uncovered_weight_bytes)))return{snapshotId:n.snapshot_id,snapshotCompatKey:n.snapshot_compat_key,artifactSizeBytes:n.artifact_size_bytes,durableArenaBytes:n.durable_arena_bytes,volatileArenaBytes:0,uncoveredWeightBytes:n.uncovered_weight_bytes}}function fu(n){if(!zs(n)||n.schema!=="urun.runtime.wake.v1"||n.portability!=="portable"&&n.portability!=="none"||n.expected_wake_path!=="portable-golden-restore"&&n.expected_wake_path!=="cold-boot"||typeof n.reason_code!="string"||!uu.has(n.reason_code)||n.expectation_basis!=="snapshot-registry"||n.restore_observation!=="not-observed")return;let e=n.reason_code;if(n.portability==="portable"&&n.expected_wake_path==="portable-golden-restore"&&e==="capture-attested"){let t=hu(n.golden);return t?{schema:"urun.runtime.wake.v1",portability:"portable",expectedWakePath:"portable-golden-restore",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed",golden:t}:void 0}if(n.portability==="none"&&n.expected_wake_path==="cold-boot"&&e!=="capture-attested"&&n.golden===void 0)return{schema:"urun.runtime.wake.v1",portability:"none",expectedWakePath:"cold-boot",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed"}}function Gs(n){if("serving_region"in n)return typeof n.serving_region=="string"&&n.serving_region.length>0?n.serving_region:null}function mu(n,e){let r={status:typeof n.status=="string"&&n.status.length>0?n.status:n.queued?"queued":"pending",requestId:e};Cr(n.session_id)&&(r.sessionId=n.session_id);let s=Gs(n);s!==void 0&&(r.region=s),typeof n.runtime_ready=="boolean"&&(r.runtimeReady=n.runtime_ready),(n.runtime_status==="unbound"||n.runtime_status==="starting"||n.runtime_status==="ready")&&(r.runtimeStatus=n.runtime_status),typeof n.reason=="string"&&n.reason.length>0&&(r.reason=n.reason),typeof n.decision_reason=="string"&&n.decision_reason.length>0&&(r.decisionReason=n.decision_reason),typeof n.provisioning_refusal_source=="string"&&n.provisioning_refusal_source.length>0&&(r.refusalSource=n.provisioning_refusal_source),typeof n.provisioning_refusal_message=="string"&&n.provisioning_refusal_message.length>0&&(r.refusalMessage=n.provisioning_refusal_message),typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(r.queue={position:n.queue_position,depth:n.queue_depth});let i=n.runtime_state;if(i==="unavailable"||i==="starting"||i==="busy"){r.runtime={state:i},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(r.runtime.reason=n.runtime_reason);let o=fu(n.runtime_wake);o&&(r.runtime.wake=o)}return r}function Ks(n,e){let t=Number(n.headers.get("Retry-After")||""),r=Number(e.retry_after_seconds??t);return Number.isFinite(r)&&r>0?r:void 0}function Ho(n,e,t){let r=Ks(n,e),s=t??Go;return r!==void 0?Math.min(r*1e3,s):1e3}function ot(n){return new Promise(e=>setTimeout(e,n))}function gu(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var Ee=class extends Error{},at=class extends q{};function na(n,e,t,r){if(!n)throw new Ee(`[urun] ${r} ${t} without ws_url`);let s,i;try{s=new URL(n)}catch{throw new Ee(r==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${t}`:`[urun] ${r} ${t} with non-absolute ws_url`)}try{i=new URL(Y(e))}catch{throw new Ee(`[urun] ${r} ${t} has invalid gateway base URL`)}let o=_u(i.hostname)&&i.protocol==="http:";if(!(o&&s.protocol==="ws:"||s.protocol==="wss:"))throw new Ee(`[urun] ${r} ${t} with insecure ws_url`);if(!vu(s,i,o))throw new Ee(`[urun] ${r} ${t} with cross-origin ws_url`);return s.toString()}function _u(n){return n==="localhost"||n==="127.0.0.1"||n==="::1"||n.endsWith(".localhost")}function vu(n,e,t){return!!(t||n.hostname===e.hostname&&n.port===e.port||Vo(n.hostname)&&Vo(e.hostname))}function Vo(n){return n==="urun.sh"||n.endsWith(".urun.sh")}function wu(n){try{return new URL(n).hostname!==Nl?[]:Wl}catch{return[]}}var ae=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},xr=class extends ae{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Dr=class extends ae{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function Ar(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function oa(n){return new Xe(n)}var Xe=class{_options;constructor(e){this._options=e}async list(e){let r=ia(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new ae("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(sa)}async getDownloadUrl(e,t){let r=ia(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!bu(s))throw new ae("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:sa(r.artifact),downloadUrl:s}}async _request(e,t){let r=Er(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of r)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof ae&&Su(s.status))throw s}throw s??new ae("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${Y(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:c}=await this._readError(o,e);throw ku(o.status,a,c)}try{return await o.json()}catch(a){throw new ae(`[urun] runtime artifacts: invalid JSON response from ${Y(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let r=Y(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function sa(n){if(!n||typeof n!="object")throw new ae("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=He(e,"artifact_id")||He(e,"id"),r=He(e,"filename"),s=He(e,"kind"),i=He(e,"status")||"ready",o=yu(e,"size_bytes"),a=He(e,"sha256");if(!t||!r||!s||o==null||!a)throw new ae("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:He(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:He(e,"created_at"),expiresAt:He(e,"expires_at")}}function He(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function yu(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function bu(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function Su(n){return n===401||n===403}function ku(n,e,t){return n===401?new xr(t,e):n===404?new Dr(t,e):new ae(t,n,e)}function ia(n){if(!n||typeof n!="object"||Array.isArray(n))throw new ae("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var be=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)}},Mt=class extends be{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ir=class extends be{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Lr=class extends be{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)}},Mr=class extends be{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)}},Or=class extends be{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)}},ct=class extends be{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function Sn(n){return/^(\d+[smhdw])+$/.test(n)}function aa(n){if(n==="pin")return{action:"pin"};if(Sn(n))return{action:"retain",duration:n};throw new ct(`[urun] recordings: "${n}" is not a duration or "pin"`)}function Tu(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new Mt(r,e??"unauthorized");if(n===404)return new Ir(r,e??"not_found");if(n===400)return new ct(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new Lr(r,e);case"pin_requires_active_temp":return new Mr(r,e);case"permanent_locked":return new Or(r,e)}return new be(r,{status:n,code:e??`http_${n}`})}var dt=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!Sn(t))throw new ct(`[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 be("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,r.body))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw Tu(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let i={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new Mt("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function ca(n){return new dt(n)}var gd=Ns(bi());var Bi=Ns(Vc(),1);var zc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function yf(n){let e=globalThis.crypto,t=new Uint8Array(n);if(e?.getRandomValues)return e.getRandomValues(t),t;for(let r=0;r<n;r++)t[r]=Math.floor(Math.random()*256);return t}function sr(n=16){let e=yf(n),t="";for(let r=0;r<n;r++)t+=zc[e[r]%zc.length];return t}function Kc(n){return`stream:${n}`}var Yc="urun-stream-v1";var Hi=1,se={BINARY:0,TEXT:1,JSON:2,END:3,CHUNK:4},ir=2,Gc=253952,bf=[se.BINARY,se.TEXT,se.JSON],vt=Symbol("urun:stream:end");function Zr(n){if(n===vt)return Uint8Array.from([Hi,se.END]);let{kind:e,body:t}=Qc(n);return os(e,t)}function Qc(n){return n instanceof Uint8Array?{kind:se.BINARY,body:n}:n instanceof ArrayBuffer?{kind:se.BINARY,body:new Uint8Array(n)}:typeof n=="string"?{kind:se.TEXT,body:new TextEncoder().encode(n)}:{kind:se.JSON,body:new TextEncoder().encode(JSON.stringify(n))}}function os(n,e){let t=new Uint8Array(ir+e.length);return t[0]=Hi,t[1]=n,t.set(e,ir),t}function cs(n){if(n===vt)return[Zr(n)];let{kind:e,body:t}=Qc(n);if(t.length+ir<=Gc)return[os(e,t)];let r=Gc-ir,s=[],i=0;for(;t.length-i>r;)s.push(os(se.CHUNK,t.subarray(i,i+r))),i+=r;return s.push(os(e,t.subarray(i))),s}function ds(n){let{kind:e,body:t}=Jc(n);if(e===se.CHUNK)throw new Error("[urun] CHUNK envelope requires StreamFragmentReassembler (oversized payload)");return as(e,t)}function Jc(n){let e=n instanceof Uint8Array?n:new Uint8Array(n);if(e.length<ir||e[0]!==Hi)throw new Error(`[urun] bad stream envelope (version=${e[0]}, len=${e.length})`);return{kind:e[1],body:e.subarray(ir)}}function as(n,e){switch(n){case se.BINARY:return e.slice();case se.TEXT:return new TextDecoder().decode(e);case se.JSON:return JSON.parse(new TextDecoder().decode(e));case se.END:return vt;default:throw new Error(`[urun] unknown stream envelope KIND 0x${n.toString(16)}`)}}var or=class{_chunks=[];_bufferedLength=0;feed(e){let{kind:t,body:r}=Jc(e);if(t===se.CHUNK){this._chunks.push(r.slice()),this._bufferedLength+=r.length;return}if(bf.includes(t)){if(this._chunks.length===0)return as(t,r);let s=new Uint8Array(this._bufferedLength+r.length),i=0;for(let o of this._chunks)s.set(o,i),i+=o.length;return s.set(r,i),this._chunks=[],this._bufferedLength=0,as(t,s)}if(this._chunks.length>0)throw this._chunks=[],this._bufferedLength=0,new Error(`[urun] stream envelope KIND 0x${t.toString(16)} arrived mid-fragment-sequence; discarding partial payload`);return as(t,r)}};function Xc(n){return{get consumerId(){return n.consumerId},onData(e,t){return n.onStreamData(e,t)},sendData(e,t,r){return n.sendStreamData(e,t,r)}}}var Zc=[1e3,2e3,4e3,8e3,3e4],ed=5,Sf=15e3,ls=[250,500,1e3,2e3,4e3],kf=3e4,Tf={4401:!0,4403:!0};function td(n){let e=n?.dialCloseCode;return e!==void 0&&Tf[e]===!0}var rd={closed:!0,released:!0,releasing:!0,reaped:!0,expired:!0,superseded:!0,cancelled:!0,canceled:!0,max_session_age:!0},Rf=15e3,nd=15e3,sd=15e3,Cf=2e3,Ef=6e3,Pf=2e3,xf=300,id=4e3,Df=2,Af=750,od=3,us=[1e3,2e3,4e3],If=15e3;var ar="--",Lf=["video","audio"];function ps(n){let e=n.lastIndexOf(ar);if(e<=0)return;let t=n.slice(e+ar.length);return Lf.includes(t)?t:void 0}function _d(n,e){return`${n}${ar}${e}`}var Vi="v1";function Mf(n,e){return n.name!==e.name||n.reason!==e.reason||n.sessionId!==e.sessionId||n.requestId!==e.requestId||n.wakingSince!==e.wakingSince||n.region!==e.region||(n.endsAt?.getTime()??null)!==(e.endsAt?.getTime()??null)||n.queue?.position!==e.queue?.position||n.queue?.depth!==e.queue?.depth||n.runtime?.state!==e.runtime?.state||n.runtime?.reason!==e.runtime?.reason||n.runtime?.wake!==e.runtime?.wake?!1:n.error?.reason===e.error?.reason&&n.error?.code===e.error?.code&&n.error?.kind===e.error?.kind&&n.error?.httpStatus===e.error?.httpStatus&&n.error?.retryAfterSeconds===e.error?.retryAfterSeconds}var ad={requested:"provisioning",queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",waking:"provisioning",waiting_for_capacity:"waiting_for_capacity",allocated:"connecting",connecting:"connecting",establishing:"connecting",live:"live",running:"live",degraded:"degraded","no-runtime":"degraded",paused:"paused",error:"error",failed:"error",rejected:"error",expired:"paused",cancelled:"paused",canceled:"paused",closed:"paused",releasing:"paused",released:"paused",reaped:"paused",superseded:"paused"};function cd(n){return Object.prototype.hasOwnProperty.call(ad,n)?{phase:ad[n],unknown:!1}:{phase:"unknown",unknown:!0}}function Of(n){return n==="queued"||n==="pending"}function dd(n){return n==="credits_exhausted"}var ld=3,ud=4e3,pd=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}];function hd(n){if(!n)return;let e=/\/(?:ws\/)?rtc\/([^/?#]+)/.exec(n);if(e)try{return decodeURIComponent(e[1])}catch{return e[1]}}var cr=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Bi.default;_ws=null;_connectedUrl=null;_device=null;_mediaUnavailableReason=null;_mediaVerdictResolve;_mediaVerdict=new Promise(e=>{this._mediaVerdictResolve=e});_recvTransport=null;_pendingConsumeData=[];_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_publishedAudio=null;_publishedVideo=null;_wtMicUplink=null;_wtCamUplink=null;_wtDataUpSender=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_reconnectExhaustedWarned=!1;_intentionalDisconnect=!1;_reconnectTimer=null;_cancelPendingDial=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_connectionViewRefresher=null;_recvIceRestartAttempts=0;_recvIceRestartTimer=null;_sendIceRestartAttempts=0;_sendIceRestartTimer=null;_phase={name:"idle"};_requestId;_liveReached=!1;_lastServerStatus;_endsAt=null;_forceResolveOnNextConnect=!1;_connectStartedAt;_wakingSince;_mediaProbeTimer=null;_statsTimer=null;_statsSampleInFlight=!1;_joinProbes=new Map;_decodeDeathHandled=!1;_selectedCandidatePair=wd();_reportedCandidatePairKey=null;_candidatePairRefreshSeq=0;_diagnosticSinkFailed=!1;_currentEpoch=0;_selfEpochAdoptUntil=0;_pausedIncarnation=null;_consumerId=null;_streamDataHandlers=new Map;_streamDataLane="sctp";_dataProducers=new Map;_dataProducerPromises=new Map;_dataConsumers=new Map;_pendingDataProduce=new Map;_sendTransportWaiters=[];get consumerId(){return this._consumerId===null&&(this._consumerId=Uf()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get isProducingMedia(){let e=r=>r!==null&&!r.closed&&!r.paused,t=(r,s)=>r!==null&&s!==null&&s.track.readyState!=="ended"&&r.deliveredDatagrams()>0;return e(this._audioProducer)||e(this._videoProducer)||t(this._wtMicUplink,this._publishedAudio)||t(this._wtCamUplink,this._publishedVideo)}get endsAt(){return this._endsAt}setEndsAt(e){this._endsAt=e}seedRegion(e){e!==void 0&&this._setPhase(this._phase.name,{reason:this._phase.reason,queue:this._phase.queue,runtime:this._phase.runtime,error:this._phase.error,region:e})}_pastDeadline(){return this._endsAt!==null&&Date.now()>=this._endsAt.getTime()}get status(){let e={phase:this._phase.name,transportState:this._state};return this._sessionId&&(e.sessionId=this._sessionId),this._requestId&&(e.requestId=this._requestId),this._lastServerStatus!==void 0&&(e.lastServerStatus=this._lastServerStatus),this._connectStartedAt!==void 0&&(e.elapsedMs=Date.now()-this._connectStartedAt),this._endsAt!==null&&(e.endsAt=this._endsAt),this._phase.queue&&(e.queue=this._phase.queue),this._phase.runtime&&(e.runtime=this._phase.runtime),this._phase.wakingSince!==void 0&&(e.wakingSince=this._phase.wakingSince),this._phase.error&&(e.error=this._phase.error),this._phase.region!==void 0&&(e.region=this._phase.region),e}get region(){return this._phase.region}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws!==null&&this._ws.readyState===WebSocket.OPEN}signalingOpen(){return this.isOpen}onWtOnlyLegDeath(e){return this._wtOnlyLegDeath=e,()=>{this._wtOnlyLegDeath===e&&(this._wtOnlyLegDeath=null)}}_wtOnlyLegDeath=null;get connectedUrl(){return this._connectedUrl}get intentionalDisconnect(){return this._intentionalDisconnect}getTrackByName(e){if(ps(e)!==void 0)return;let t=this._tracksByName.get(e);if(t&&t.readyState!=="ended")return t;for(let r of this._tracks.values())if(!(r.kind!==e||r.readyState==="ended")&&this._streamNameOf(r)===void 0)return r;return t}_streamNameOf(e){for(let[t,r]of this._tracksByName)if(r===e)return t}setAuth(e){this._options={...this._options,...e},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(e){this._options=e??{url:""},e?.sessionId&&(this._sessionId=e.sessionId)}setConnection(e){if(this.isOpen){let t=hd(e.url);if(e.sessionId!==void 0&&e.sessionId!==this._sessionId)throw new st(this._sessionId,e.sessionId);if(t!==void 0&&t!==this._sessionId)throw new st(this._sessionId,t);this._options={...this._options,...e};return}this._options={...this._options,...e},e.sessionId&&(this._sessionId=e.sessionId)}setConnectionResolver(e){this._resolveConnection=e}setConnectionViewRefresher(e){this._connectionViewRefresher=e}applyControlDocState(e){let t=e&&typeof e=="object"?e.session:void 0,r=qf(t);if(r!==void 0&&this.setIncarnation(r),!t||typeof t!="object")return;let s=t,i=typeof s.status=="string"?s.status:void 0;if(i&&!this.isStaleClosedMarker(s)){if(i==="error"){let o=s.error_reason??s.errorReason,a=typeof o=="string"&&o?o:"session failed";this._setPhase("error",{error:{reason:a,code:"runtime-failed",kind:"runtime-failed"}})}else if(i==="closed"||i==="ended"||i==="paused"){let o=s.close_reason??s.closeReason??s.pause_reason??s.pauseReason;if(dd(o)){this._setPhase("paused",{reason:"credits_exhausted"});return}if(this._pastDeadline()){this._setPhase("paused",{reason:"max_session_age"});return}this._setPhase("paused",{reason:typeof o=="string"&&o?o:i})}}}setIncarnation(e){if(!Number.isFinite(e)||e<=this._currentEpoch)return;let t=this._currentEpoch>0,r=this._state==="connected";this._currentEpoch=e;let i=this._selfEpochAdoptUntil>0&&Date.now()<=this._selfEpochAdoptUntil;this._selfEpochAdoptUntil=0,!i&&t&&r&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(e){return Number.isFinite(e)?e<this._currentEpoch:!1}isStaleClosedMarker(e){if(!e)return!1;let t=typeof e.status=="string"?e.status:void 0;if(t!=="closed"&&t!=="ended"&&t!=="paused"&&t!=="error")return!1;let r=e.status_epoch??e.statusEpoch,s=typeof r=="number"?r:Number(r);return Number.isFinite(s)?s<this._currentEpoch:!1}_isStaleLivenessEvidence(){return this._phase.name!=="paused"||this._pausedIncarnation===null?!1:this._currentEpoch<=this._pausedIncarnation}async connect(e){if(this.isOpen&&this._state==="connected"&&!this._intentionalDisconnect){e!==void 0&&(this._lastStartOptions=e);return}this._lastStartOptions=e,this._intentionalDisconnect=!1,this._pausedIncarnation=null,this._connectStartedAt??=Date.now(),this._cancelPendingDial?.(new Error("TransportSession: connect superseded by a newer connect()"));let t=++this._generation,r=this._state==="reconnecting"||this._state==="renegotiating";r||this._setState("connecting");let s=null,i=()=>t!==this._generation||this._intentionalDisconnect,o=()=>{if(i())throw new Error("TransportSession: connect cancelled")},a=async()=>{for(let d of this._connectUrls()){o();try{return await this._connectOnce(d,t,e),!0}catch(u){s=u instanceof Error?u:new Error(String(u)),i()||this._cleanupSocket()}}return!1},c=this._forceResolveOnNextConnect&&this._resolveConnection!==null;if(this._forceResolveOnNextConnect=!1,c){let d=this._resolveConnection;for(let u=0;d&&u<od;u++){this._setState("reconnecting"),await en(us[Math.min(u,us.length-1)]),o();try{let p=await d();o(),this.setAuth({jwt:p.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:p.url,sessionId:p.sessionId,iceServers:p.iceServers??this._options.iceServers}),p.endsAt!==void 0&&(this._endsAt=p.endsAt)}catch(p){if(i())throw new Error("TransportSession: connect cancelled");s=p instanceof Error?p:new Error(String(p));continue}if(await a())return;if(s&&td(s))break}}else{let d=Date.now()+kf,u=0,p=0,f=0;for(;;){if(o(),await a())return;if(s&&td(s))break;p++,o();let g=null;if(this._connectionViewRefresher)try{g=await this._connectionViewRefresher(),o()}catch(m){if(i())throw new Error("TransportSession: connect cancelled");s=m instanceof Error?m:new Error(String(m))}if(g){if(Date.now()>=d)break;this.setAuth({jwt:g.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:g.url,sessionId:g.sessionId,iceServers:g.iceServers??this._options.iceServers,...g.sfuAttach?{sfuAttach:g.sfuAttach}:{}}),await en(ls[Math.min(u++,ls.length-1)]);continue}let h=this._resolveConnection?Df:1;if(p<h){await en(Af);continue}if(this._resolveConnection&&f<od){this._setState("reconnecting"),await en(us[Math.min(f,us.length-1)]),o(),f++;try{let m=await this._resolveConnection();o(),this.setAuth({jwt:m.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:m.url,sessionId:m.sessionId,iceServers:m.iceServers??this._options.iceServers}),m.endsAt!==void 0&&(this._endsAt=m.endsAt)}catch(m){if(i())throw new Error("TransportSession: connect cancelled");s=m instanceof Error?m:new Error(String(m));continue}continue}if(this._resolveConnection||Date.now()>=d)break;await en(ls[Math.min(u++,ls.length-1)])}}if(i())throw s??new Error("TransportSession: connect cancelled");this._setState("failed");let l=s??new Error("TransportSession: connect failed");throw r||this._emitError(l),l}leaveLeg(){if(!this.isOpen)return!1;this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null);try{this._send({type:"leave"})}catch{}try{this._ws?.close()}catch{}return!0}disconnect(e="client_detached"){this._generation+=1,this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._cancelPendingDial?.(new Error("TransportSession: connect cancelled by disconnect()")),this._stopMediaProbe(),this._stopStatsSampler(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0;try{this._publishedAudio?.track.stop()}catch{}try{this._publishedVideo?.track.stop()}catch{}if(this._publishedAudio=null,this._publishedVideo=null,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let t of this._consumers.values())try{t.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._settleSendTransportWaiters(null,new Error("[urun] sendStreamData: transport disconnected before the send transport arrived")),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}this._pendingConsumeData=[],this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce.reject(new Error("TransportSession: disconnected")),this._pendingProduce=null),this._device=null,this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null),this._cleanupSocket(),this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("paused",{reason:e}),this._emitter.emit("disconnected")}on(e,t){return this._emitter.on(e,t),()=>{this._emitter.off(e,t)}}_emitDiagnostic(e){let t=this._options.diagnosticSink;if(t)try{t(e)}catch(r){this._diagnosticSinkFailed||(this._diagnosticSinkFailed=!0,console.warn(`[urun] diagnosticSink threw (${String(r instanceof Error?r.message:r)}) \u2014 further diagnostics ride only the structured 'diagnostic' event`))}else e.level==="debug"?Qe()?console.warn(`[urun] ${e.message}`,e.detail??{}):console.debug(`[urun] ${e.message}`,e.detail??{}):e.level==="error"?console.error(`[urun] ${e.message}`,e.detail??{}):console.warn(`[urun] ${e.message}`,e.detail??{});this._emitter.emit("diagnostic",e)}sendInput(e,t){this._send({type:"input",data:e,sequence:t})}sendSignal(e){return this._send(e)}onSignal(e){return this.on("signal",e)}emitDiagnostic(e){this._emitDiagnostic(e)}onStreamData(e,t){let r=this._streamDataHandlers.get(e);return r||(r=new Set,this._streamDataHandlers.set(e,r)),r.add(t),()=>{let s=this._streamDataHandlers.get(e);s?.delete(t),s&&s.size===0&&this._streamDataHandlers.delete(e)}}sendStreamData(e,t,r){try{this._requireMediaSupport("sendStreamData")}catch(s){return Promise.reject(s)}return this._wtDataUpSender?this._wtDataUpSender.send(e,Zr(t)):this._ensureDataProducer(e).then(s=>{for(let i of cs(t))s.send(i)})}get wtDataUplinkSeam(){return{onUplink:e=>{this._wtDataUpSender=e},onUplinkLost:(e,t)=>{if(this._wtDataUpSender&&!(t&&this._wtDataUpSender!==t)){if(this._wtDataUpSender=null,!this._sendTransport){console.warn(`[urun-sh/core] WT data uplink lost (${e}) with NO WebRTC send transport \u2014 there is no SCTP to revert to; failing the WT leg so the re-dial ladder re-establishes it`),this._wtOnlyLegDeath?.(e);return}console.warn(`[urun-sh/core] WT data uplink lost (${e}) \u2014 data-up reverts to SCTP for this leg`)}}}}_awaitSendTransport(){return this._sendTransport?Promise.resolve(this._sendTransport):new Promise((e,t)=>{let r={resolve:i=>{clearTimeout(s),e(i)},reject:i=>{clearTimeout(s),t(i)}},s=setTimeout(()=>{let i=this._sendTransportWaiters.indexOf(r);i>=0&&this._sendTransportWaiters.splice(i,1),t(new Error(`[urun] no send transport after ${nd}ms (the server never offered createSendTransport \u2014 media/data produce is impossible on this leg)`))},nd);this._sendTransportWaiters.push(r)})}_settleSendTransportWaiters(e,t){let r=this._sendTransportWaiters;this._sendTransportWaiters=[];for(let s of r)e?s.resolve(e):s.reject(t??new Error("TransportSession: disconnected"))}_ensureDataProducer(e){let t=this._dataProducers.get(e);if(t&&!t.closed)return Promise.resolve(t);let r=this._dataProducerPromises.get(e);if(r)return r;let s=this._awaitSendTransport().then(i=>i.produceData({label:Kc(e),protocol:Yc,ordered:!0})).then(i=>this._awaitDataChannelOpen(i)).then(i=>(this._dataProducers.set(e,i),this._dataProducerPromises.delete(e),i)).catch(i=>{throw this._dataProducerPromises.delete(e),i});return this._dataProducerPromises.set(e,s),s}_awaitDataChannelOpen(e){if(e.closed)return Promise.reject(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"));let t=e.readyState;return t==="open"?Promise.resolve(e):t==="closing"||t==="closed"?Promise.reject(new Error(`[urun] sendStreamData: DataChannel is ${t} \u2014 cannot deliver data-up payloads`)):new Promise((r,s)=>{let i=()=>{l(),r(e)},o=u=>{d(new Error(`[urun] sendStreamData: DataChannel error before open: ${u.message}`))},a=()=>{l(),s(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"))},c=setTimeout(()=>{d(new Error(`[urun] sendStreamData: DataChannel not open after ${sd}ms (the SCTP handshake never completed \u2014 data-up produce is impossible on this channel)`))},sd),l=()=>{clearTimeout(c),e.off("open",i),e.off("error",o),e.observer.off("close",a)},d=u=>{l();try{e.close()}catch{}s(u)};e.on("open",i),e.on("error",o),e.observer.on("close",a)})}_dispatchStreamData(e,t){for(let r of this._streamDataHandlers.get(e)??[])r(t)}markStreamDataLaneQuic(){this._streamDataLane="quic"}noteQuicMediaFlowing(){this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")}noteMediaLegDeath(){this._intentionalDisconnect||this._phase.name==="live"&&this._setPhase("connecting",{reason:"reconnecting"})}dispatchQuicStreamData(e,t){this._dispatchStreamData(e,t)}raiseQuicStreamDataError(e){console.error(e.message),this._emitter.emit("error",e)}quicStreamDataLaneLost(e){if(this._streamDataLane!=="quic")return;this._streamDataLane="sctp";let t=[...this._streamDataHandlers.keys()];if(t.length===0)return;let r=new Error(`[urun] QUIC data lane lost mid-stream (${e}) \u2014 active named streams [${t.join(", ")}] resume over SCTP on the failover leg from now; envelopes in flight on the dead lane are gone (mid-stream-join semantics)`);console.error(r.message),this._emitter.emit("error",r)}_streamNameFromLabel(e){if(e)return e.startsWith("stream:")?e.slice(7):void 0}mediaUnavailableReason(){return this._mediaUnavailableReason}mediaAvailability(){return this._mediaVerdict}_requireMediaSupport(e){if(this._mediaUnavailableReason)throw new Error(`[urun-sh/core] ${e}: realtime media is unavailable in this process \u2014 ${this._mediaUnavailableReason}. This session joined in doc/KV-only mode (the media device was skipped); install the optional "werift" dependency to enable realtime media.`)}async addTrack(e,t){this._requireMediaSupport("addTrack"),await this._publishTrack(e,t)}async _publishTrack(e,t){let r=e.kind==="video";if(!r&&this._wtMicUplink){this._rememberPublishIntent(!1,e,t),this._wtMicUplink.setSource(e);return}if(r&&this._wtCamUplink){this._rememberPublishIntent(!0,e,t),this._wtCamUplink.setSource(e);return}let s=r?this._videoProducer:this._audioProducer;if(s&&!s.closed){if(s.track===e)return;await s.replaceTrack({track:e}),this._rememberPublishIntent(r,e,t);return}let o=await(await this._awaitSendTransport()).produce({track:e,...r?{}:{codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}},stopTracks:!1,...t?{appData:{name:t}}:{}});r?this._videoProducer=o:this._audioProducer=o,this._rememberPublishIntent(r,e,t)}_rememberPublishIntent(e,t,r){let s={track:t,...r!==void 0?{name:r}:{}};e?this._publishedVideo=s:this._publishedAudio=s}removeTrack(){let e=this._publishedAudio;if(this._publishedAudio=null,this._wtMicUplink){this._wtMicUplink.setSource(null);try{e?.track.stop()}catch{}}if(this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}this._audioProducer.close(),this._audioProducer=null}}async addVideoTrack(e,t){this._requireMediaSupport("addVideoTrack"),await this._publishTrack(e,t)}stopVideo(){let e=this._publishedVideo;if(this._publishedVideo=null,this._wtCamUplink){this._wtCamUplink.setSource(null);try{e?.track.stop()}catch{}}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}this._videoProducer.close(),this._videoProducer=null}}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(e,t){this._send({type:"stream.seek",stream:e,target:t})}async _handleMessage(e){switch(e.type){case"routerRtpCapabilities":await this._onRouterCapabilities(e.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(e);break;case"createSendTransport":await this._onCreateSendTransport(e);break;case"consume":await this._onConsume(e);break;case"consumerClosed":this._closeConsumer(e.consumerId);break;case"producerClosed":this._closeConsumersByProducer(e.producerId);break;case"consumerPaused":this._consumers.get(e.consumerId)?.pause();break;case"consumerResumed":this._consumers.get(e.consumerId)?.resume();break;case"iceRestarted":this._onIceRestarted(e);break;case"produced":if(this._pendingProduce){let t=this._pendingProduce;this._pendingProduce=null,clearTimeout(t.timeoutId),t.resolve(e.id)}break;case"dataProduced":{let t=e.label,r=t?this._pendingDataProduce.get(t):void 0;r&&t&&(this._pendingDataProduce.delete(t),r.resolve(e.id));break}case"consumeData":await this._onConsumeData(e);break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(e);break;case"stream.seeked":this._onStreamSeeked(e);break;case"error":this._onServerError(e);break;default:this._emitter.emit("signal",e);break}}_onServerError(e){let t=typeof e.message=="string"?e.message:"signaling error",r=typeof e.code=="string"?e.code:void 0;if(/connect\(\) already called/i.test(t)){if(this._resolveConnection){this._generation++;let s=this._ws;this._ws=null;try{s?.close()}catch{}this._cleanupMedia(),this._forceResolveOnNextConnect=!0,this._renegotiate();return}this._setPhase("error",{error:{reason:t,code:"transport-consumed",kind:"transport-failed"}}),this._emitter.emit("error",new Error(t));return}if(r==="TRANSPORT_BIND_FAILED"){this._emitError(new Error(t),r);return}if(r==="PROTOCOL_VERSION_UNSUPPORTED"){this._setPhase("error",{error:{reason:t,code:r,kind:"create-failed"},reason:t}),this._emitter.emit("error",new Error(t));return}console.warn("[urun] signaling error from server:",t)}_onStreamSeeked(e){let t=typeof e.stream=="string"?e.stream:void 0;if(!t)return;let r=e.target,s=r==="live"?"live":typeof r=="number"?r:Number(r);this._emitter.emit("seeked",t,s)}_reportUnknownServerStatus(e,t,r="signaling",s){let o=`server reported unrecognized ${r==="admission"?"admission response":"session status"} status ${JSON.stringify(e)}`+(t?` (reason: ${JSON.stringify(t)})`:"")+' \u2014 this @urun-sh/core build does not know this word; refusing to render it as "provisioning". The SDK may be out of date for this server.';this._emitDiagnostic({level:"error",kind:"unknown-server-status",message:o,detail:{status:e,origin:r,...t?{reason:t}:{}}}),!this._liveReached&&(this._lastServerStatus=e,this._setPhase("unknown",{reason:e,region:s}))}_onStatus(e){let t=e.request_id??e.requestId;t&&(this._requestId=t);let r=typeof e.status=="string"?e.status:void 0,s=typeof e.reason=="string"&&e.reason?e.reason:void 0,i="region"in e?typeof e.region=="string"&&e.region.length>0?e.region:null:void 0,o=r!==void 0?cd(r):void 0;if(r!==void 0&&o?.unknown){this._reportUnknownServerStatus(r,s,"signaling",i);return}let a=o?.phase??"provisioning";if(this._liveReached&&a!=="paused"&&a!=="error"&&a!=="degraded"){a==="live"&&i!==void 0&&i!==this._phase.region&&this._setPhase("live",{reason:s,region:i});return}if(a==="degraded"){this._setPhase("degraded",{reason:s,region:i});return}if(this._isStaleLivenessEvidence()&&a!=="live"&&a!=="paused"&&a!=="error")return;r!==void 0&&(this._lastServerStatus=r);let c=e.queue_position??e.queuePosition,l=e.queue_depth??e.queueDepth,d=typeof c=="number"&&typeof l=="number";if(a==="paused"){let u=e.reason??e.close_reason??e.closeReason??e.pause_reason??e.pauseReason,p=typeof u=="string"&&u?u:void 0,f=dd(u)?"credits_exhausted":this._pastDeadline()?"max_session_age":s??p??r??"paused";this._setPhase("paused",{reason:f,region:i??null}),this._stopMediaProbe();return}if(a==="error"){let u=s??r??"admission failed";this._setPhase("error",{error:{reason:u,code:r,kind:r==="error"?"runtime-failed":"create-failed"},reason:u,region:i});return}if(a==="queued"){this._setPhase("queued",{...d?{queue:{position:c,depth:l}}:{},reason:s,region:i});return}if(a==="waiting_for_capacity"){this._setPhase("waiting_for_capacity",{...d?{queue:{position:c,depth:l}}:{},reason:s,region:i});return}if(a==="connecting"){this._setPhase("connecting",{reason:s,region:i});return}if(a==="live"){this._setPhase("live",{reason:s,region:i});return}this._setPhase("provisioning",{reason:s,region:i})}_webRtcDialHeld=!1;_heldRouterCaps=null;holdWebRtcDial(){return this._webRtcDialHeld=!0,{proceed:e=>{if(!this._webRtcDialHeld)return;this._webRtcDialHeld=!1;let t=this._heldRouterCaps;this._heldRouterCaps=null,t&&(Qe()?console.warn(`[urun-sh/core] running the deferred WebRTC dial (${e})`):console.info(`[urun-sh/core] running the deferred WebRTC dial (${e})`),this._onRouterCapabilities(t).catch(r=>{console.error("[urun-sh/core] deferred WebRTC dial failed:",r)}))},skip:e=>{Qe()?console.warn(`[urun-sh/core] WebRTC dial SKIPPED (${e}) \u2014 WT-only leg, no RTCPeerConnection`):console.info(`[urun-sh/core] WebRTC dial SKIPPED (${e}) \u2014 WT-only leg, no RTCPeerConnection`)}}}async _onRouterCapabilities(e){if(this._webRtcDialHeld){this._heldRouterCaps=e;return}Je()&&await Dt();let t=Fo();if(t){this._mediaUnavailableReason=t,this._mediaVerdictResolve(t);return}this._mediaVerdictResolve(null);let r=Wo(),s=new gd.Device(r?{handlerName:r}:void 0);await s.load({routerRtpCapabilities:e}),this._device=s,this._send({type:"rtpCapabilities",rtpCapabilities:s.rtpCapabilities})}async _onCreateRecvTransport(e){this._device&&this._buildRecvTransport(e)}_buildRecvTransport(e){if(!this._device)return;let t=e.iceCandidates,r=this._device.createRecvTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:t,dtlsParameters:e.dtlsParameters,...e.sctpParameters?{sctpParameters:e.sctpParameters}:{},iceServers:this._options.iceServers??pd});this._recvIceRestartAttempts=0,this._clearRecvIceRestart();let s=this._generation;r.on("connect",({dtlsParameters:o},a,c)=>{try{this._send({type:"connectTransport",transportId:r.id,dtlsParameters:o}),a()}catch(l){c(l)}}),r.on("connectionstatechange",o=>{if(s===this._generation){if(o==="connected"){this._clearRecvIceRestart(),this._recvIceRestartAttempts=0,this._reportSelectedCandidatePair(r);return}if(!(this._intentionalDisconnect&&o==="closed")&&(o==="failed"||o==="disconnected")){if(this._tryRestartRecvIce())return;o==="failed"&&this._emitError(new Error(`media transport ${o}`),o),this._renegotiate()}}}),this._recvTransport=r;let i=this._pendingConsumeData.splice(0,this._pendingConsumeData.length);for(let o of i)this._onConsumeData(o).catch(()=>{})}async _reportSelectedCandidatePair(e){let t=++this._candidatePairRefreshSeq,r=null;if(typeof e.getStats=="function")try{r=await e.getStats()}catch{}if(this._recvTransport!==e||t!==this._candidatePairRefreshSeq)return;let s=jf(r);if(s.localType===null&&s.remoteType===null&&s.protocol===null&&s.remoteAddress===null&&s.remotePort===null&&this._reportedCandidatePairKey!==null)return;this._selectedCandidatePair=s;let o=JSON.stringify(s);if(this._reportedCandidatePairKey===o)return;this._reportedCandidatePairKey=o;let a=Object.values(this._selectedCandidatePair).some(c=>c!==null);this._emitDiagnostic({level:a?"info":"debug",kind:"ice-candidate-pair",message:`selected ICE candidate pair: local=${this._selectedCandidatePair.localType??"unknown"} remote=${this._selectedCandidatePair.remoteType??"unknown"} protocol=${this._selectedCandidatePair.protocol??"unknown"} remote=${this._selectedCandidatePair.remoteAddress??"unknown"}:${this._selectedCandidatePair.remotePort??"unknown"}`,detail:{sessionId:this._options.sessionId,...this._selectedCandidatePair}})}_tryRestartRecvIce(){let e=this._recvTransport;return!e||e.closed?!1:this._recvIceRestartTimer?!0:this._recvIceRestartAttempts>=ld?!1:(this._recvIceRestartAttempts++,this._armRecvIceRestartWatchdog(),this._requestIceRestart(e.id),!0)}_trySendIceRestart(){let e=this._sendTransport;return!e||e.closed?!1:this._sendIceRestartTimer?!0:this._sendIceRestartAttempts>=ld?!1:(this._sendIceRestartAttempts++,this._armSendIceRestartWatchdog(),this._requestIceRestart(e.id),!0)}_requestIceRestart(e){this._send({type:"restartIce",transportId:e})}_onIceRestarted(e){let t=e.transportId??e.id,r=e.iceParameters;if(!r)return;let s=!!this._recvTransport&&this._recvTransport.id===t,i=!s&&!!this._sendTransport&&this._sendTransport.id===t,o=s?this._recvTransport:i?this._sendTransport:null;o&&(Promise.resolve(o.restartIce({iceParameters:r})).catch(a=>{this._emitter.emit("error",a instanceof Error?a:new Error(String(a)))}),s&&this._recvIceRestartTimer?this._armRecvIceRestartWatchdog():i&&this._sendIceRestartTimer&&this._armSendIceRestartWatchdog())}_armRecvIceRestartWatchdog(){this._clearRecvIceRestart();let e=this._generation;this._recvIceRestartTimer=setTimeout(()=>{this._recvIceRestartTimer=null,!(e!==this._generation||this._intentionalDisconnect)&&this._recvTransport?.connectionState!=="connected"&&(this._emitError(new Error("media transport failed (ice restart timeout)"),"failed"),this._renegotiate())},ud)}_armSendIceRestartWatchdog(){this._clearSendIceRestart();let e=this._generation;this._sendIceRestartTimer=setTimeout(()=>{this._sendIceRestartTimer=null,!(e!==this._generation||this._intentionalDisconnect)&&this._sendTransport?.connectionState!=="connected"&&this._emitError(new Error("media send transport failed (ice restart timeout)"),"failed")},ud)}_clearRecvIceRestart(){this._recvIceRestartTimer&&(clearTimeout(this._recvIceRestartTimer),this._recvIceRestartTimer=null)}_clearSendIceRestart(){this._sendIceRestartTimer&&(clearTimeout(this._sendIceRestartTimer),this._sendIceRestartTimer=null)}async _onCreateSendTransport(e){if(!this._device)return;let t=this._device.createSendTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:e.iceCandidates,dtlsParameters:e.dtlsParameters,...e.sctpParameters?{sctpParameters:e.sctpParameters}:{},iceServers:this._options.iceServers??pd});this._sendIceRestartAttempts=0,this._clearSendIceRestart();let r=this._generation;t.on("connect",({dtlsParameters:s},i,o)=>{try{this._send({type:"connectSendTransport",transportId:t.id,dtlsParameters:s}),i()}catch(a){o(a)}}),t.on("produce",({kind:s,rtpParameters:i,appData:o},a,c)=>{if(this._pendingProduce){c(new Error("produce already pending"));return}let l=o&&typeof o.name=="string"?o.name:void 0,d=setTimeout(()=>{let u=this._pendingProduce;if(!u||u.timeoutId!==d)return;this._pendingProduce=null;let p=new Ct(s,{stream:l,timeoutMs:Pt});this._setPhase("error",{error:{reason:p.message,code:"produce-ack-timeout",kind:"produce-timeout"}}),this._emitter.emit("error",p),u.reject(p)},Pt);this._pendingProduce={timeoutId:d,resolve:u=>{a({id:u})},reject:c};try{this._send(l?{type:"produce",kind:s,name:l,rtpParameters:i}:{type:"produce",kind:s,rtpParameters:i})}catch(u){this._pendingProduce?.timeoutId===d&&(this._pendingProduce=null,clearTimeout(d)),c(u)}}),t.on("producedata",({sctpStreamParameters:s,label:i,protocol:o},a,c)=>{try{i&&this._pendingDataProduce.set(i,{resolve:l=>a({id:l}),reject:c}),this._send({type:"produceData",sctpStreamParameters:s,label:i,protocol:o})}catch(l){i&&this._pendingDataProduce.delete(i),c(l)}}),t.on("connectionstatechange",s=>{if(r===this._generation){if(s==="connected"){this._clearSendIceRestart(),this._sendIceRestartAttempts=0;return}this._intentionalDisconnect&&s==="closed"||(s==="failed"||s==="disconnected")&&this._trySendIceRestart()||(s==="failed"||s==="closed")&&this._emitError(new Error(`media send transport ${s}`),s)}}),this._sendTransport=t,this._settleSendTransportWaiters(t),this._emitter.emit("audioTransportReady"),this._republishPublishedTracks()}async _republishPublishedTracks(){let e=this._publishedAudio;if(e&&e.track.readyState!=="ended"&&(!this._audioProducer||this._audioProducer.closed))try{await this.addTrack(e.track,e.name)}catch(r){console.warn("[urun] republish: mic re-produce after reconnect failed",r)}else e&&e.track.readyState==="ended"&&console.warn("[urun] republish: published mic track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)");let t=this._publishedVideo;if(t&&t.track.readyState!=="ended"&&(!this._videoProducer||this._videoProducer.closed))try{await this.addVideoTrack(t.track,t.name)}catch(r){console.warn("[urun] republish: camera re-produce after reconnect failed",r)}else t&&t.track.readyState==="ended"&&console.warn("[urun] republish: published camera track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)")}async _onConsumeData(e){if(this._streamDataLane==="quic"){this.raiseQuicStreamDataError(new Error(`[urun] consumeData (label=${String(e.label)}) pushed on a leg whose data lane is QUIC \u2014 refusing (one canonical data path per leg, contract urun-infra#1605)`));return}let t=this._recvTransport;if(!t){this._pendingConsumeData.push(e);return}let r=e.label,s=this._streamNameFromLabel(r);if(!s){console.error(`[urun] consumeData pushed with an unparseable label ${JSON.stringify(r??null)} \u2014 no DataConsumer will be attached and no ack sent; the server egress will strand envelopes for this stream (expected label form: "stream:<name>")`),this._emitter.emit("error",new Error(`[urun] consumeData pushed with unparseable label ${JSON.stringify(r??null)}`));return}let i=this._generation,o;try{o=await t.consumeData({id:e.id,dataProducerId:e.dataProducerId,sctpStreamParameters:e.sctpStreamParameters,label:r,protocol:e.protocol})}catch(u){console.error(`[urun] consumeData for named stream "${s}" failed \u2014 no channel will open and no dataConsumerReady ack will be sent; the server egress will strand envelopes on this lane:`,u),this._emitter.emit("error",u instanceof Error?u:new Error(String(u)));return}if(i!==this._generation||this._recvTransport!==t||t.closed||this._intentionalDisconnect){try{o.close()}catch{}return}this._dataConsumers.set(s,o);let a=new or;o.on("message",u=>{try{let p=typeof u=="string"?new TextEncoder().encode(u):new Uint8Array(u),f=a.feed(p);f!==void 0&&this._dispatchStreamData(s,f)}catch(p){this._emitter.emit("error",p instanceof Error?p:new Error(String(p)))}});let c=!1,l=setTimeout(()=>{if(c||o.closed||o.readyState==="open")return;let u=new Error(`[urun] data channel for named stream "${s}" did not open within 10s (consumeData resolved at creation; the SCTP association never established) \u2014 no dataConsumerReady ack was sent and the server egress will strand envelopes on this lane`);console.error(u.message),this._emitter.emit("error",u)},1e4),d=()=>{c||o.closed||(c=!0,clearTimeout(l),this._send({type:"dataConsumerReady",id:e.id}))};o.readyState==="open"?d():o.on("open",d),o.once?.("close",()=>clearTimeout(l))}async _onConsume(e){let t=this._recvTransport;if(!t)return;let r=this._generation,s=await t.consume({id:e.id,producerId:e.producerId,kind:e.kind,rtpParameters:e.rtpParameters});if(r!==this._generation||this._recvTransport!==t||t.closed||this._intentionalDisconnect){try{s.close()}catch{}return}this._consumers.set(s.id,s),this._tracks.set(s.track.id,s.track),this._capJitterBuffer(s,s.kind==="video"?"video":"audio");let i=e.streamName??e.label;i&&this._tracksByName.set(i,s.track),s.track.addEventListener?.("unmute",()=>{r!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")},{once:!0}),this._emitter.emit("track",s.track);let o=s.id;s.track.addEventListener("ended",()=>{r!==this._generation||this._intentionalDisconnect||this._closeConsumer(o)},{once:!0}),this._send({type:"resumeConsumer",consumerId:s.id}),this._startMediaProbe(),this._startStatsSampler()}get audioPlayoutOptions(){return this._options.audioPlayout}get wtMicUplinkSeam(){return{onUplink:e=>{this._wtMicUplink=e;let t=this._publishedAudio;if(this._audioProducer&&!this._audioProducer.closed){console.warn("[urun-sh/core] WT mic uplink engaged \u2014 moving the mic from WebRTC produce to the QUIC lane"),this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}t&&t.track.readyState!=="ended"&&e.setSource(t.track)},onUplinkLost:(e,t)=>{if(!this._wtMicUplink||t&&this._wtMicUplink!==t)return;this._wtMicUplink=null;let r=this._publishedAudio;if(!(!r||r.track.readyState==="ended")){if(console.warn(`[urun-sh/core] WT mic uplink lost (${e}) \u2014 republishing the mic over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-mic-uplink-dead",message:`WT mic uplink lost (${e}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the mic is now DEAD until the WT uplink re-engages.`,detail:{reason:e}});return}this._publishTrack(r.track,r.name).catch(s=>{console.error("[urun-sh/core] mic republish over WebRTC failed:",s)})}}}}get wtCamUplinkSeam(){return{onUplink:e=>{this._wtCamUplink=e;let t=this._publishedVideo;if(this._videoProducer&&!this._videoProducer.closed){console.warn("[urun-sh/core] WT video uplink engaged \u2014 moving the camera from WebRTC produce to the QUIC lane"),this._send({type:"stopVideo"});try{this._videoProducer.close()}catch{}this._videoProducer=null}t&&t.track.readyState!=="ended"&&e.setSource(t.track)},onUplinkLost:(e,t)=>{if(!this._wtCamUplink||t&&this._wtCamUplink!==t)return;this._wtCamUplink=null;let r=this._publishedVideo;if(!(!r||r.track.readyState==="ended")){if(console.warn(`[urun-sh/core] WT video uplink lost (${e}) \u2014 republishing the camera over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-cam-uplink-dead",message:`WT camera uplink lost (${e}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the camera is now DEAD until the WT uplink re-engages.`,detail:{reason:e}});return}this._publishTrack(r.track,r.name).catch(s=>{console.error("[urun-sh/core] camera republish over WebRTC failed:",s)})}}}}_jitterBufferTargetMs(e){if(e==="audio"){let t=this._options.audioPlayout?.jitterBufferTargetMs;return t===void 0?xf:t}return this._options.videoPlayout?.jitterBufferTargetMs}_capJitterBuffer(e,t){let r=this._jitterBufferTargetMs(t);if(r===void 0)return;let s=t==="video"?"videoPlayout":"audioPlayout",i={mediaKind:t,transportId:this._recvTransport?.id??null};if(!Number.isFinite(r)){this._emitDiagnostic({level:"warning",kind:`${t}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be a finite number of milliseconds; got ${String(r)}. No jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:String(r),...i}});return}if(r<0||r>id){this._emitDiagnostic({level:"warning",kind:`${t}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be within the W3C jitterBufferTarget range 0-${id}ms; got ${r}. No jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:r,...i}});return}let o=e.rtpReceiver;if(!o){this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-unsupported`,message:`${t} consumer exposes no RTCRtpReceiver (node/werift leg); no jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:r,reason:"no-receiver",...i}});return}let a=[];if("jitterBufferTarget"in o&&(o.jitterBufferTarget=r,a.push("jitterBufferTarget")),"playoutDelayHint"in o&&(o.playoutDelayHint=r/1e3,a.push("playoutDelayHint")),a.length===0){this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-unsupported`,message:`${t==="audio"?"Audio":"Video"} receiver exposes neither jitterBufferTarget nor playoutDelayHint; standing ${t} playout delay is unbounded on this engine.`,detail:{consumerId:e.id,targetMs:r,...i}});return}this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-capped`,message:`${t==="audio"?"Audio":"Video"} receiver jitter buffer capped at ${r}ms.`,detail:{consumerId:e.id,targetMs:r,applied:a,...i}})}_closeConsumer(e){let t=this._consumers.get(e);if(!t)return;this._consumers.delete(e);let r=t.track;try{t.close()}catch{}if(r){this._tracks.delete(r.id);for(let[s,i]of this._tracksByName)i===r&&this._tracksByName.delete(s)}}_closeConsumersByProducer(e){for(let[t,r]of this._consumers)r.producerId===e&&this._closeConsumer(t)}_mediaPollMs(){let e=this._options.mediaLiveness?.pollMs;return e===void 0?Cf:e}_firstFrameWindowMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?Ef:e}_startMediaProbe(){let e=this._mediaPollMs();if(e<=0||this._mediaProbeTimer)return;let t=this._generation;this._mediaProbeTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._sampleMediaArrival(t)},e)}_stopMediaProbe(){this._mediaProbeTimer&&(clearInterval(this._mediaProbeTimer),this._mediaProbeTimer=null)}_statsPollMs(){let e=this._options.sessionStats;if(!e)return 0;let t=e.pollMs;return t===void 0?Pf:Number.isFinite(t)&&t>0?t:0}_startStatsSampler(){let e=this._statsPollMs();if(e<=0||this._statsTimer)return;let t=this._generation;this._statsTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._isParkedPhase()||this._statsSampleInFlight||(this._statsSampleInFlight=!0,this._sampleSessionStats(t).catch(r=>{try{this._emitter.emit("error",r instanceof Error?r:new Error(String(r)))}catch{}}).finally(()=>{this._statsSampleInFlight=!1}))},e)}_stopStatsSampler(){this._statsTimer&&(clearInterval(this._statsTimer),this._statsTimer=null),this._statsSampleInFlight=!1}_lanePairKey(e){let t=e.track,r=t?this._streamNameOf(t):void 0;if(r===void 0)return null;let s=ps(r);return s===void 0?r:r.slice(0,r.length-ar.length-s.length)}async _sampleSessionStats(e){if(this._consumers.size===0)return;let t=Array.from(this._consumers.values()),r=await Promise.all(t.map(async p=>({consumerId:p.id,kind:p.kind==="video"?"video":"audio",pairKey:this._lanePairKey(p),sample:await md(p)})));if(e!==this._generation||this._intentionalDisconnect||this._isParkedPhase())return;let s=r.filter(p=>p.pairKey===null),i=r.filter(p=>p.pairKey!==null),o=null,a=r;if(i.length>0){let p=new Map;for(let h of i){let m=h.pairKey,_=p.get(m);_?_.push(h):p.set(m,[h])}let f=-1,g=-1;for(let[h,m]of p){let _=new Set(m.map(S=>S.kind)).size>=2?1:0,v=m.reduce((S,w)=>S+w.sample.total,0);(_>f||_===f&&v>g)&&(f=_,g=v,o=h,a=[...m,...s])}}let c=p=>{let f=null,g=-1;for(let{consumerId:h,kind:m,sample:_}of a)m===p&&_.total>g&&(g=_.total,f={consumerId:h,..._});return f},l=c("audio"),d=c("video"),u=d?.estimatedPlayoutTimestamp!=null&&l?.estimatedPlayoutTimestamp!=null?d.estimatedPlayoutTimestamp-l.estimatedPlayoutTimestamp:null;this._emitter.emit("stats",{timestamp:Date.now(),stream:o,avSyncMs:u,audio:l,video:d})}_resetJoinProbes(){this._joinProbes.clear(),this._decodeDeathHandled=!1}async _sampleMediaArrival(e){if(this._consumers.size===0)return;let t=Array.from(this._consumers.entries()),r=await Promise.all(t.map(async([a,c])=>[a,await md(c)]));if(e!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence())return;for(let a of this._joinProbes.keys())this._consumers.has(a)||this._joinProbes.delete(a);let s=Date.now();!this._liveReached&&r.some(([,a])=>a.total>0)&&this._setPhase("live");let i=null,o=!1;for(let[a,c]of r){if(c.total<=0){o=!0;continue}let l=this._joinProbes.get(a);if(l||(l={firstBytesAt:s,startSample:c,settled:!1},this._joinProbes.set(a,l)),!l.settled){if(c.framesDecoded===null){l.settled=!0;continue}if(c.framesDecoded>0){l.settled=!0;continue}if(s-l.firstBytesAt>=this._firstFrameWindowMs()){i??={id:a,probe:l,sample:c};continue}o=!0}}if(i&&!this._decodeDeathHandled){this._decodeDeathHandled=!0;let a=this._firstFrameWindowMs(),c=$f(i.probe.startSample,i.sample),l=c.lossPct!==null&&c.lossPct>=5?" \u2014 consistent with network packet loss between the SFU and this browser":"";this._emitDiagnostic({level:"warning",kind:"decode-wall",message:`video is arriving but the decoder never produced its first frame within ${a/1e3}s of join (framesDecoded still 0) \u2014 no keyframe to start from${l}; re-consuming the stream`,detail:{sessionId:this._options.sessionId,consumerId:i.id,firstFrameWindowMs:a,inboundTotal:i.sample.total,framesDecoded:i.sample.framesDecoded,...Ff(i.sample),...c,likelyCause:c.lossPct!==null&&c.lossPct>=5?"network-packet-loss":null,...this._selectedCandidatePair}}),this._renegotiate();return}!o&&!i&&this._stopMediaProbe()}_renegotiate(){this._intentionalDisconnect||this._isExplicitEndPhase()||this._reconnectTimer||(this._stopMediaProbe(),this._stopStatsSampler(),this._setState("renegotiating"),this._attemptReconnect())}recover(){if(this._intentionalDisconnect||this._isExplicitEndPhase()||this._connectStartedAt===void 0||this._cancelPendingDial)return;if(!this.isOpen){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this._attemptReconnect(void 0,!0);return}let e=this._recvTransport?.connectionState;(e==="disconnected"||e==="failed")&&(this._recvIceRestartTimer||(this._recvIceRestartAttempts=0),this._tryRestartRecvIce()||this._renegotiate());let t=this._sendTransport?.connectionState;(t==="disconnected"||t==="failed")&&(this._sendIceRestartTimer||(this._sendIceRestartAttempts=0),this._trySendIceRestart())}_attemptReconnect(e,t=!1){if(this._intentionalDisconnect||this._isExplicitEndPhase()||this._reconnectTimer)return;this._reconnectAttempts>=ed&&(this._reconnectExhaustedWarned||(this._reconnectExhaustedWarned=!0,this._emitDiagnostic({level:"warning",kind:"signaling-reconnect-forever",message:`signaling reconnect budget spent (${ed} attempts) \u2014 retrying forever with capped backoff while the session lives`})));let r=t?0:Zc[Math.min(this._reconnectAttempts,Zc.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._replaceCurrentLegForReconnect();try{await this.connect(e??this._lastStartOptions)}catch(s){if(s instanceof Error&&s.message==="TransportSession: connect cancelled")return;this._attemptReconnect(e)}},r)}_connectUrls(){let e=[],t=r=>{if(!r)return;let s=hd(r)!==void 0,i=this._sessionId&&!s?`${r}${r.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:r,o=this._options.sfuAttach;if(o){if(!/[?&]token=/.test(i)){let u=`${i}${i.includes("?")?"&":"?"}token=${encodeURIComponent(o.token)}&gen=${o.gen}`;e.includes(u)||e.push(u);return}e.includes(i)||e.push(i);return}let a=this._options.jwt?.trim(),c=/[?&]token=/.test(i),l=a&&!c?`${i}${i.includes("?")?"&":"?"}token=${encodeURIComponent(a)}`:i;e.includes(l)||e.push(l)};t(this._options.url);for(let r of this._options.fallbackUrls??[])t(r);return e}_connectOnce(e,t,r){return new Promise((s,i)=>{let o=!1,a=!1,c=null,l=null,d,u=new WebSocket(e);this._ws=u;let p=()=>this._ws!==u||t!==this._generation,f=h=>{a||(a=!0,c&&clearTimeout(c),this._cancelPendingDial===g&&(this._cancelPendingDial=null),typeof d=="number"&&(h.dialCloseCode=d),i(h))},g=h=>{try{u.close()}catch{}f(h)};this._cancelPendingDial=g,c=setTimeout(()=>{try{u.close()}catch{}f(new Error("TransportSession: connect timed out"))},Sf),u.onopen=()=>{if(!a){if(p()){try{u.close()}catch{}f(new Error("TransportSession: connect superseded during dial"));return}o=!0,c&&clearTimeout(c),this._connectedUrl=e,this._multiplexer=new bt(u),u.send(JSON.stringify(this._startMessage(r))),this._scheduleReconnectBudgetReset(),this._selfEpochAdoptUntil=Date.now()+Rf,this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),a=!0,this._cancelPendingDial===g&&(this._cancelPendingDial=null),s()}},u.onerror=()=>{o||(l??=new Error("WebSocket connection error"))},u.onclose=h=>{if(!o){let m=h?.code;typeof m=="number"&&m!==1005&&(d=m),f(l??new Error("WebSocket closed before connecting"));return}if(!p()&&(this._clearReconnectBudgetReset(),c&&clearTimeout(c),this._setState("disconnected"),!this._intentionalDisconnect)){if(this._pastDeadline()&&this._phase.name!=="paused"){this._setPhase("paused",{reason:"max_session_age"}),this._emitter.emit("disconnected");return}this._emitter.emit("disconnected"),!this._isExplicitEndPhase()&&this._attemptReconnect(r)}},u.onmessage=h=>{if(!(this._ws!==u||t!==this._generation)&&typeof h.data=="string")try{this._handleMessage(JSON.parse(h.data)).catch(m=>{this._emitter.emit("error",m instanceof Error?m:new Error(String(m)))})}catch(m){this._emitter.emit("error",m instanceof Error?m:new Error(String(m)))}}})}_startMessage(e){let t={type:"start",version:Vi,video:e?.video??{width:854,height:480,frameRate:16}};return e?.prompt&&(t.prompt=e.prompt),e?.cameraControl&&(t.camera_control=e.cameraControl),e?.args&&(t.args=e.args),e?.app&&(t.app=e.app),e?.functionName&&(t.function=e.functionName),e?.role&&(t.role=e.role),this._options.orgId&&(t.orgId=this._options.orgId),this._options.jwt&&(t.jwt=this._options.jwt),this._options.authProvider&&(t.authProvider=this._options.authProvider),t}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let e=this._ws;this._ws=null,e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{e.close()}catch{}}_replaceCurrentLegForReconnect(){this._cleanupSocket(),this._cancelPendingDial?.(new Error("TransportSession: reconnect replacing current dial")),this._cleanupMedia()}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0,this._reconnectExhaustedWarned=!1},If))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupDataChannels(){for(let e of this._dataProducers.values())try{e.close()}catch{}this._dataProducers.clear(),this._dataProducerPromises.clear();for(let e of this._dataConsumers.values())try{e.close()}catch{}this._dataConsumers.clear();for(let e of this._pendingDataProduce.values())try{e.reject(new Error("TransportSession: disconnected"))}catch{}this._pendingDataProduce.clear()}_cleanupMedia(){this._stopMediaProbe(),this._stopStatsSampler(),this._resetJoinProbes();for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){try{this._videoProducer.close()}catch{}this._videoProducer=null}if(this._clearRecvIceRestart(),this._clearSendIceRestart(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._pendingConsumeData=[],this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce=null),this._device=null,this._tracks.clear(),this._tracksByName.clear(),this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null)}_send(e){return!this._ws||this._ws.readyState!==WebSocket.OPEN?!1:(this._ws.send(JSON.stringify(e)),!0)}_setState(e){this._state!==e&&(this._state=e,this._emitter.emit("stateChange",e))}_isParkedPhase(){return this._phase.name==="paused"?!0:this._phase.name!=="error"?!1:this._phase.error?.kind!=="transport-failed"}_isExplicitEndPhase(){if(this._phase.name==="paused"&&!this._isComputeReleasedPark())return!1;if(this._phase.name!=="error")return this._isComputeReleasedPark();let e=this._phase.error?.kind;return e!==void 0&&e!=="transport-failed"}_isComputeReleasedPark(){return this._phase.name!=="paused"?!1:rd[this._phase.reason??""]===!0}_setPhase(e,t){let r=this._liveReached;e==="live"?this._liveReached=!0:e==="paused"||e==="error"||e==="degraded"?(this._liveReached=!1,e==="paused"&&!r&&rd[t?.reason??""]!==!0&&(this._forceResolveOnNextConnect=!0,this._cancelPendingDial||this._attemptReconnect())):e==="connecting"&&r&&(this._liveReached=!1);let s={name:e};t?.queue&&(s.queue=t.queue),t?.runtime&&(s.runtime=t.runtime),t?.reason&&(s.reason=t.reason),s.region=t?.region!==void 0?t.region:this._phase.region,Be(e)?(this._wakingSince??=Date.now(),s.wakingSince=this._wakingSince):this._wakingSince=void 0,this._requestId&&(s.requestId=this._requestId),this._sessionId&&(s.sessionId=this._sessionId),this._endsAt!==null&&(s.endsAt=this._endsAt),t?.error&&(s.error=t.error),!Mf(this._phase,s)&&(this._phase=s,this._pausedIncarnation=e==="paused"?this._currentEpoch:null,this._isParkedPhase()&&(this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart()),this._emitter.emit("phase",s))}reportAdmission(e){e.requestId&&(this._requestId=e.requestId),this._lastServerStatus=e.status;let t=cd(e.status);if(t.unknown){this._reportUnknownServerStatus(e.status,e.reason,"admission",e.region);return}if(this._liveReached)return;e.sessionId&&!this._sessionId&&(this._sessionId=e.sessionId);let{runtime:r,queue:s}=e,i=e.decisionReason==="provisioning_refused"?e.refusalMessage??e.decisionReason:e.reason,o={runtime:r,queue:s,...i?{reason:i}:{},...e.region!==void 0?{region:e.region}:{}};if(Of(e.status)){if(r?.state==="unavailable"){this._setPhase("unavailable",o);return}if(r?.state==="starting"){this._setPhase("provisioning",o);return}if(r?.state==="busy"||e.status==="queued"){this._setPhase("queued",o);return}this._setPhase("provisioning",o);return}let a=e.runtimeReady===!1||e.runtimeStatus==="unbound"||e.runtimeStatus==="starting";if(t.phase==="connecting"&&a){this._setPhase("provisioning",o);return}this._setPhase(t.phase,t.phase==="paused"?{...o,region:o.region??null}:o)}_emitError(e,t){this._setPhase("error",{error:{reason:e.message,code:t,kind:"transport-failed"}}),this._emitter.emit("error",e)}reportAllocationFailure(e,t,r,s){r==="insufficient_credits"?this._setPhase("error",{error:{reason:e.message,code:r,kind:"insufficient-credits",httpStatus:t}}):this._setPhase("error",{error:{reason:e.message,code:r??"allocation-failed",kind:"create-failed",httpStatus:t,retryAfterSeconds:s}}),this._emitter.emit("error",e)}};function en(n){return new Promise(e=>setTimeout(e,n))}function Uf(){return sr()}var vd=["packetsReceived","packetsLost","nackCount","pliCount","firCount","keyFramesDecoded","framesReceived","framesDropped","retransmittedPacketsReceived","retransmittedBytesReceived","jitterBufferDelay","jitterBufferEmittedCount","estimatedPlayoutTimestamp","jitterBufferTargetDelay","jitterBufferMinimumDelay","concealedSamples","insertedSamplesForDeceleration"],Nf=new Set(["estimatedPlayoutTimestamp"]);function Wf(){return{total:0,framesDecoded:null,packetsReceived:null,packetsLost:null,nackCount:null,jitter:null,pliCount:null,firCount:null,keyFramesDecoded:null,framesReceived:null,framesDropped:null,retransmittedPacketsReceived:null,retransmittedBytesReceived:null,jitterBufferDelay:null,jitterBufferEmittedCount:null,estimatedPlayoutTimestamp:null,jitterBufferTargetDelay:null,jitterBufferMinimumDelay:null,concealedSamples:null,insertedSamplesForDeceleration:null}}function Ff(n){return Object.fromEntries(vd.map(e=>[e,n[e]]))}function fd(n,e){return n===null||e===null||e<n?null:e-n}function $f(n,e){let t=n.packetsLost!==null&&e.packetsLost!==null?e.packetsLost-n.packetsLost:null,r=fd(n.packetsReceived,e.packetsReceived),s=fd(n.nackCount,e.nackCount),i=t===null?null:Math.max(0,t),o=i!==null&&r!==null?i+r:0;return{packetsLostWindow:t,packetsReceivedWindow:r,nackCountWindow:s,jitterSec:e.jitter,lossPct:o>0&&i!==null?i/o*100:null}}function wd(){return{localType:null,remoteType:null,protocol:null,remoteAddress:null,remotePort:null}}function jf(n){let e=new Map;yd(n,a=>{let c=typeof a.id=="string"?a.id:null;c&&e.set(c,a)});let t=Array.from(e.values()).find(a=>a.type==="transport"),r=typeof t?.selectedCandidatePairId=="string"?t.selectedCandidatePairId:null,s=(r?e.get(r):void 0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.selected===!0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.nominated===!0);if(!s)return wd();let i=typeof s.localCandidateId=="string"?e.get(s.localCandidateId):void 0,o=typeof s.remoteCandidateId=="string"?e.get(s.remoteCandidateId):void 0;return{localType:typeof i?.candidateType=="string"?i.candidateType:null,remoteType:typeof o?.candidateType=="string"?o.candidateType:null,protocol:typeof i?.protocol=="string"?i.protocol:typeof o?.protocol=="string"?o.protocol:null,remoteAddress:typeof o?.address=="string"?o.address:typeof o?.ip=="string"?o.ip:null,remotePort:typeof o?.port=="number"?o.port:null}}function yd(n,e){let t=r=>{r&&typeof r=="object"&&e(r)};if(n instanceof Map)for(let[r,s]of n.entries()){if(!s||typeof s!="object")continue;let i=s;e(typeof i.id=="string"?i:{...i,id:r})}else(Array.isArray(n)||n&&typeof n.forEach=="function")&&n.forEach(t)}async function md(n){let e=Wf();if(typeof n.getStats!="function")return e;let t;try{t=await n.getStats()}catch{return e}return yd(t,s=>{if(s.type==="inbound-rtp"){let i=typeof s.bytesReceived=="number"?s.bytesReceived:0,o=typeof s.packetsReceived=="number"?s.packetsReceived:0;e.total+=i+o,typeof s.framesDecoded=="number"&&(e.framesDecoded=(e.framesDecoded??0)+s.framesDecoded),typeof s.jitter=="number"&&(e.jitter=e.jitter===null?s.jitter:Math.max(e.jitter,s.jitter));for(let a of vd)typeof s[a]=="number"&&(e[a]=Nf.has(a)?e[a]===null?s[a]:Math.max(e[a],s[a]):(e[a]??0)+s[a])}}),e}function qf(n){if(!n||typeof n!="object")return;let e=n.epoch,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0}var rn=Ns(require("yjs"));var bd=require("y-websocket"),Gi=require("y-protocols/awareness");var Bf=1,Hf=4401;function fs(n){let e=new URL(n);return`${e.protocol}//${e.host}/doc`}function Vf(n){let e=Hs(n);return e===null?void 0:Math.floor((Date.now()+e)/1e3)}var zf=2500,Gf=3e4,Kf=1e4,Yf=3;function Sd(n){let e=n.WebSocketPolyfill??globalThis.WebSocket;if(!e)throw new Error("[urun] no WebSocket implementation available for the yjs doc provider (browser global missing and no WebSocketPolyfill passed)");return(t,r,s)=>{let i=`${n.sessionId}/${t}`,o=typeof n.token=="function"?n.token:null,a=typeof n.token=="string"?n.token:void 0,c=new Set,l=(D,W)=>{let k=Vf(D);if(k===void 0||k*1e3>Date.now())return;let z=`${W}:${D}`;c.has(z)||(c.add(z),console.error(`[urun] doc dial for room ${i} would present an EXPIRED token (${W}; exp ${new Date(k*1e3).toISOString()} is in the past) \u2014 the token refresh lane returned a stale credential; dials will be refused once auth enforcement flips`))};l(a,"static");let d=n.maxBackoffTimeMs??zf,u=n.dialTimeoutMs??Gf,p=new bd.WebsocketProvider(n.serverUrl,i,r,{awareness:s,params:{dsv:String(Bf),...n.attach?{token:n.attach.token,gen:String(n.attach.gen)}:a?{token:a}:{}},WebSocketPolyfill:e,disableBc:!0,maxBackoffTime:d,resyncInterval:Kf,connect:o===null}),f=!1,g,h=!1,m=D=>{h||(h=!0,console.error(`[urun] doc token refresh failed for room ${i} (redialing with previous token):`,D))},_=D=>{if(o&&!n.attach){if(g)return g;try{let W=o({redial:D});if(typeof W=="string"){p.params.token=W,l(W,"minted"),h=!1;return}if(W&&typeof W.then=="function"){let z=W.then(j=>{typeof j=="string"&&(p.params.token=j,l(j,"minted"),h=!1)},j=>{m(j)}).finally(()=>{g===z&&(g=void 0)});return g=z,z}}catch(W){m(W)}}},v=n.resolveServerUrl,S=0,w=!1,b=D=>{if(typeof D!="string"||D==="")return;let W=D.replace(/\/+$/,"");W!==p.serverUrl&&(p.serverUrl=W,w=!1)},T=()=>{if(!v)return;let D=++S,W=k=>{w||(w=!0,console.error(`[urun] doc endpoint re-resolve failed for room ${i} (redialing previous host):`,k))};try{let k=v();if(k&&typeof k.then=="function")return k.then(z=>{D===S&&b(z)},W);b(k)}catch(k){W(k)}},y={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null},E=new Set,N=!1,Q=!1,te=()=>{let D={...y};for(let W of[...E])W(D)},F=null,$=()=>{F!==null&&(clearTimeout(F),F=null)},G=()=>{$(),F=setTimeout(()=>{if(F=null,!f&&p.wsconnecting&&p.ws)try{p.ws.close()}catch{}},u)},X=null,he=()=>{X!==null&&(clearTimeout(X),X=null)},Z=()=>{he(),X=setTimeout(()=>{if(X=null,!f&&p.shouldConnect&&!p.wsconnected&&!p.wsconnecting&&p.ws===null)try{p.connect()}catch(D){N||(N=!0,console.error(`[urun] doc connection redial threw for room ${i} (still retrying):`,D)),Z()}},d+500)},Me=({status:D})=>{if(D==="connecting"){he(),G();return}if(D==="connected"){$(),he(),y={...y,connected:!0},te();return}y.connected&&(y={...y,connected:!1},te())},x=D=>{D&&(N&&(Qe()?console.warn(`[urun] doc connection recovered for room ${i}`):console.info(`[urun] doc connection recovered for room ${i}`),N=!1),Q&&(Q=!1),y.consecutiveFailures!==0&&(y={...y,consecutiveFailures:0},te()))},O=D=>{$();let W=D?D.code:null,k=W===Hf;k&&!Q&&(Q=!0,console.error(`[urun] doc dial REFUSED: auth token expired (close ${W}${D?.reason?`, reason "${D.reason}"`:""}) for room ${i} \u2014 forcing a token refresh; the next dial presents a fresh credential`)),y={connected:!1,consecutiveFailures:y.consecutiveFailures+1,lastCloseCode:W,lastCloseReason:D&&D.reason?D.reason:null,authRefused:k},!N&&y.consecutiveFailures>=Yf&&(N=!0,console.error(`[urun] doc connection failing for room ${i}: ${y.consecutiveFailures} consecutive failures (last close ${y.lastCloseCode===null?"by provider liveness reap":`code ${y.lastCloseCode}`}${y.lastCloseReason?`, reason "${y.lastCloseReason}"`:""}). Still retrying \u2014 the doc provider never gives up.`)),te(),_(!0),T(),Z()};p.on("status",Me),p.on("sync",x),p.on("connection-close",O),p.wsconnecting?G():p.wsconnected&&(y={...y,connected:!0});let B=!1;return o!==null&&_(!1),B||p.connect(),{get awareness(){return p.awareness},get synced(){return p.synced},onSync(D){let W=k=>D(k);return p.on("sync",W),()=>p.off("sync",W)},onConnectionState(D){return E.add(D),D({...y}),()=>E.delete(D)},ensureConnected(){B=!1,p.wsconnected||p.connect()},disconnect(){B=!0,p.disconnect()},destroy(){f=!0,$(),he(),p.off("status",Me),p.off("sync",x),p.off("connection-close",O),E.clear(),p.destroy()}}}}var zi=class{constructor(e,t,r){this._name=e;this._doc=t;this.awareness=r}_name;_doc;awareness;_inner=null;_innerUnsub=null;_innerStateUnsub=null;_syncHandlers=new Set;_stateHandlers=new Set;_lastState={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};_destroyed=!1;_suspended=!1;get synced(){return this._inner?.synced??!1}get destroyed(){return this._destroyed}onSync(e){return this._syncHandlers.add(e),()=>this._syncHandlers.delete(e)}onConnectionState(e){return this._stateHandlers.add(e),e({...this._lastState}),()=>this._stateHandlers.delete(e)}attach(e){if(!this._destroyed){if(this._inner&&(this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner.destroy(),this._inner=null),this._inner=e(this._name,this._doc,this.awareness),this._innerUnsub=this._inner.onSync(t=>{for(let r of[...this._syncHandlers])r(t)}),this._inner.onConnectionState)this._innerStateUnsub=this._inner.onConnectionState(t=>{this._lastState=t;for(let r of[...this._stateHandlers])r(t)});else{this._innerStateUnsub=null,this._lastState={connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};for(let t of[...this._stateHandlers])t({...this._lastState})}if(this._suspended&&this._inner.disconnect?.(),this._inner.synced)for(let t of[...this._syncHandlers])t(!0)}}ensureConnected(){this._suspended=!1,this._inner?.ensureConnected?.()}get disconnect(){return this._inner?.disconnect?()=>{this._suspended=!0,this._inner.disconnect()}:void 0}destroy(){this._destroyed=!0,this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner?.destroy(),this._inner=null,this._syncHandlers.clear(),this._stateHandlers.clear()}},hs=class{_target=null;_bridges=[];connect=(e,t,r)=>{let s=new zi(e,t,r);return this._bridges.push(s),this._target&&s.attach(this._target),s};get connected(){return this._target!==null}setTarget(e){if(this._target!==e){this._target=e,this._bridges=this._bridges.filter(t=>!t.destroyed);for(let t of this._bridges)t.attach(e)}}};function nn(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var ms="$bytes";function Qf(n){return n instanceof Uint8Array||n instanceof ArrayBuffer}function Jf(n){if(!nn(n))return!1;let e=Object.keys(n);return e.length===1&&e[0]===ms&&typeof n[ms]=="string"}function Xf(n){return n instanceof ArrayBuffer?new Uint8Array(n):n}function Zf(n){if(typeof Buffer<"u")return Buffer.from(n).toString("base64");let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return btoa(e)}function em(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Ki(n){if(Qf(n))return{[ms]:Zf(Xf(n))};if(Array.isArray(n))return n.map(Ki);if(nn(n)){let e={};for(let[t,r]of Object.entries(n))e[t]=Ki(r);return e}return n}function tn(n){if(Jf(n))return em(n[ms]);if(Array.isArray(n))return n.map(tn);if(nn(n)){let e={};for(let[t,r]of Object.entries(n))e[t]=tn(r);return e}return n}var kd=Symbol("urun:doc:path-absent");function tm(n,e){let t=e.split("."),r=n;for(let s of t){if(r===null||typeof r!="object"||!(s in r))return kd;r=r[s]}return r}function rm(n,e){return n===e?!0:JSON.stringify(n)===JSON.stringify(e)}function Yi(n,e){for(let[t,r]of Object.entries(e))if(nn(r)){let s=n.get(t);if(!(s instanceof rn.Map)){let i=s;s=new rn.Map,n.set(t,s),nn(i)&&Yi(s,i)}Yi(s,r)}else{if(rm(n.get(t),r))continue;n.set(t,r)}}var nm=Symbol("urun:doc:local"),gs=class{_doc=new rn.Doc;_root=this._doc.getMap("session");_awareness=new Gi.Awareness(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(e,t,r){this._key=e,this._sessionId=t,this._root.observeDeep(this._observer),r?(this._connection=r(e,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(e){this._sessionId=e}get synced(){return this._synced}ensureConnected(){this._connection?.ensureConnected?.()}reconnect(){this.ensureConnected()}disconnect(){let e=this._connection;if(!e?.disconnect)throw new Error(`[urun-sh/core] doc('${this._key}').disconnect(): no disconnect-capable connection to sever (a local-only doc, or a connector with no live socket) \u2014 there is nothing to disconnect`);e.disconnect()}onConnectionState(e){return this._connection?.onConnectionState?this._connection.onConnectionState(e):(e({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){e=Ki(e),this.applyPatch(e)}get(e,t){let r=this.snapshot();if(!e)return tn(r);let s=tm(r,e);return s===kd?t:tn(s)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new Qi(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let e=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let t of e)t()}applyPatch(e){this._doc.transact(()=>{Yi(this._root,e)},nm)}snapshot(){return this._root.toJSON()}notify(){let e=tn(this.snapshot());for(let t of this._listeners)t(e)}},Qi=class{constructor(e){this._ytext=e;this._observer=t=>{for(let r of t.delta)if(typeof r.insert=="string"&&r.insert.length>0){let s=r.insert;for(let i of this._delta)i(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};function Td(n){return{get clientId(){return n.clientID},set(e){n.setLocalState(e)},setField(e,t){n.setLocalStateField(e,t)},getLocal(){return n.getLocalState()??null},getStates(){return n.getStates()},on(e,t){let r=()=>t(n.getStates());return n.on("change",r),r(),()=>n.off("change",r)}}}var Rd=1e3,Cd=12e3;function _s(n,e,t={}){let r=null,s=0,i=0,o=null,a=-1,c=()=>{let m=n.get("desired.billing.generationSeconds");if(typeof m!="number"||!Number.isFinite(m)||m<=0)return null;let _=n.get("desired.billing.epoch"),v=n.get("desired.billing.updatedAtMs");return{seconds:m,epoch:typeof _=="number"&&Number.isFinite(_)?_:0,updatedAtMs:typeof v=="number"&&Number.isFinite(v)?v:null}},l=()=>{if(r===null)return null;let m=Math.min(Math.max(0,Date.now()-s),i);return r+m/1e3},d=()=>{let m=t.creditsPerSecond;if(typeof m=="number"&&Number.isFinite(m)&&m>0)return m;let _=n.get("desired.billing.creditsPerSecond");return typeof _=="number"&&Number.isFinite(_)&&_>0?_:null},u=()=>{let m=l();if(m===null)return;let _=Math.floor(m);if(_<=a)return;a=_;let v={seconds:_},S=d();S!==null&&(v.estimatedCredits=_*S),e(v)},p=m=>{s=Date.now();let _=m===null?0:Math.max(0,s-m);i=Math.max(0,12e3-_)},f=()=>{let m=c();if(m!==null){if(o!==null&&m.epoch!==o){o=m.epoch,r=m.seconds,a=-1,p(m.updatedAtMs),u();return}r!==null&&m.seconds<=r||(o=m.epoch,r=m.seconds,p(m.updatedAtMs),u())}};f();let g=n.on("change",f),h=setInterval(u,1e3);return h.unref?.(),()=>{clearInterval(h),g()}}var Ji="activity",Xi="visibility",Ed=15e3,vs=["pointerdown","pointermove","keydown","wheel","touchstart"];function ws(n){let e=n.now??Date.now,t=n.mode==="explicit",r=t?null:n.windowTarget!==void 0?n.windowTarget:typeof window<"u"?window:null,s=t?null:n.documentTarget!==void 0?n.documentTarget:typeof document<"u"?document:null,i=!1,o,a=()=>{if(i)return;let p=e();if(!(o!==void 0&&p-o<15e3)){o=p;try{n.awareness.setLocalStateField(Ji,{at:p})}catch{}}},c=()=>{if(!(i||!s||s.visibilityState===void 0))try{n.awareness.setLocalStateField(Xi,s.visibilityState)}catch{}},l=()=>a(),d=()=>{c(),(!s||s.visibilityState===void 0||s.visibilityState==="visible")&&a()};if(r)for(let p of vs)r.addEventListener(p,l,{passive:!0,capture:!0});s&&s.addEventListener("visibilitychange",d);let u=null;return!t&&n.isProducing&&(u=setInterval(()=>{if(!i)try{n.isProducing?.()&&a()}catch{}},15e3),u.unref?.()),a(),c(),{touch:a,dispose(){if(!i){if(i=!0,r)for(let p of vs)r.removeEventListener(p,l,{capture:!0});s&&s.removeEventListener("visibilitychange",d),u&&(clearInterval(u),u=null)}}}}var Zi="user_activity",eo="focus",xd=3e4;function Pd(n){switch(n){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var dr=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(Pd(e.state));let t=e.on("stateChange",s=>{this._setState(Pd(s))}),r=()=>{t(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_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(eo,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(Zi,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 Dd=250;function ys(n){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let r=Date.now();r-e<250||(e=r,n())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function bs(n){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,n())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function Ss(n){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{n()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Ad="video/mp4";function ks(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,i=!1,o=(a,c,l)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let u=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(Ad)?Ad:void 0),p=new MediaStream([a]),f=new d(p,u?{mimeType:u}:void 0);r=f;let g=Promise.resolve();f.ondataavailable=h=>{let m=h.data;i||!m||m.size===0||(g=g.then(async()=>{let _=new Uint8Array(await m.arrayBuffer());i||c(_)}))},f.onstop=()=>{g.then(()=>{i||l()})},f.onerror=()=>{g.then(()=>{i||l()})},f.start(t)};return{start(a,c){if(r||i)return;let l=n.track();if(l){o(l,a,c);return}s=n.onTrack(d=>{!d||r||i||(s?.(),s=null,o(d,a,c))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function sm(n){let e=n;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=n.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Id(n,e){let t=null,r=!1,s=!1,i=new ReadableStream({pull(o){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return sm(i)}var Ts=require("@msgpack/msgpack"),ro=65536;function Rs(n){let e=(0,Ts.encode)(n),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var lr=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>ro)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let s=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(Object.assign((0,Ts.decode)(s),{raw:s}))}return t}};function Ld(n,e){let t=new DataView(n.buffer,n.byteOffset,n.byteLength),r=t.getUint8(0),s=(r&240)===128,i=r===222;if(!s&&!i&&!(r===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=s?r&15:i?t.getUint16(1,!1):t.getUint32(1,!1),c=s?1:i?3:5,l=[];l.push(n.subarray(0,c));for(let f=0;f<a;f++){let g=c,h=sn(n,t,c);c=h.end;let _=sn(n,t,c).end;if(im(t.getUint8(g))){let v=t.getUint8(g),S=(v&224)===160?1:v===217?2:v===218?3:5;if(new TextDecoder().decode(n.subarray(g+S,h.end))==="t"){l.push(n.subarray(g,h.end));let b=new TextEncoder().encode(e);if(b.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");l.push(new Uint8Array([160|b.byteLength]),b)}else l.push(n.subarray(g,_))}else l.push(n.subarray(g,_));c=_}let d=l.reduce((f,g)=>f+g.byteLength,0),u=new Uint8Array(d),p=0;for(let f of l)u.set(f,p),p+=f.byteLength;return u}function im(n){return(n&224)===160?!0:n===217||n===218||n===219}function sn(n,e,t){let r=e.getUint8(t),s=t;if(r<=127||r>=224)return{start:s,end:t+1};if((r&224)===160)return{start:s,end:t+1+(r&31)};if((r&240)===128||(r&240)===144){let o=r&15;t+=1;let a=(r&240)===128?o*2:o;for(let c=0;c<a;c++)t=sn(n,e,t).end;return{start:s,end:t}}let i={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(i[r]!==void 0)return{start:s,end:t+1+i[r]};if(r===217||r===196)return{start:s,end:t+2+e.getUint8(t+1)};if(r===218||r===197)return{start:s,end:t+3+e.getUint16(t+1,!1)};if(r===219||r===198)return{start:s,end:t+5+e.getUint32(t+1,!1)};if(r===220||r===221){let o=r===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===220?3:5;for(let a=0;a<o;a++)t=sn(n,e,t).end;return{start:s,end:t}}if(r===222||r===223){let o=r===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===222?3:5;for(let a=0;a<o*2;a++)t=sn(n,e,t).end;return{start:s,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${r.toString(16)} at byte ${s}`)}var pe=12,to=1,om=0,Cs=1,Md=2;function ur(n){let e=n.getUint8(8);return{groupId:n.getUint32(0,!0),frameSeq:n.getUint32(4,!0),keyframe:(e&to)===to,fragIndex:n.getUint8(9),fragCount:n.getUint8(10),lane:n.getUint8(11)}}function Es(n){let e=new Uint8Array(pe),t=new DataView(e.buffer);return t.setUint32(0,n.groupId,!0),t.setUint32(4,n.frameSeq,!0),t.setUint8(8,n.keyframe?to:0),t.setUint8(9,n.fragIndex),t.setUint8(10,n.fragCount),t.setUint8(11,n.lane??om),e}var am=100,Od=100,pr=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??am}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<pe)return;let t=ur(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 r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray(pe),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let s of this.pending.keys())s<t.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-Od?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Od}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 r=t.chunks.reduce((o,a)=>o+a.byteLength,0),s=new Uint8Array(r),i=0;for(let o of t.chunks)s.set(o,i),i+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:s})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var cm=/^avc[13]\.[0-9a-fA-F]{6}$/;function dm(n){return cm.test(n)?null:`codec ${JSON.stringify(n)} 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 no(n,e){let t=dm(n);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var so=1,on=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==so)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let s=this.buf[1];if(s===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+s)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+s)),this.buf=this.buf.subarray(2+s)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let s=ds(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),s===vt&&(this.ended=!0),t.push({name:this.name,payload:s})}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 Ps(n,e){let t=n.getReader();for(;;){let{value:r,done:s}=await t.read();if(s)return;r&&lm(r,e).catch(i=>{e.onLaneError(i instanceof Error?i:new Error(String(i)))})}}async function lm(n,e){let t=n.getReader(),r=new on;try{for(;;){let{value:s,done:i}=await t.read();if(i)break;if(!(!s||s.byteLength===0))for(let{name:o,payload:a}of r.push(s))e.onData(o,a)}r.finish()}catch(s){try{await t.cancel?.(s)}catch{}throw s}}var io="wt-playout",um=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 n=this.port;n&&(n.onmessage=e=>this.onMessage(e.data))}post(n){this.port?.postMessage(n)}ensure(n){if(!(this.rings.length===n&&this.held.length===n&&this.rings[0]?.length===this.cap)){this.rings=[];for(let e=0;e<n;e++)this.rings.push(new Float32Array(this.cap));this.held=new Float32Array(n),this.xfadeFrom=new Float32Array(n)}}onMessage(n){if(n.type==="init"){this.holdN=Math.max(1,Math.round(2*n.rate/1e3)),this.fadeN=Math.max(1,Math.round(4*n.rate/1e3)),this.cap=Math.max(1,Math.round(500*n.rate/1e3)),this.primeSamples=Math.max(0,Math.round(n.primeSamples)),this.primeWall=Math.round(250*n.rate/1e3),this.ensure(1);return}if(n.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(n.type!=="pcm")return;let e=n.bufs.map(s=>new Float32Array(s)),t=n.frames;if(this.ensure(e.length),this.depth+t>this.cap){let s=this.depth+t-this.cap;this.read=(this.read+s)%this.cap,this.depth-=s,this.post({type:"overflow",dropped:s})}let r=(this.read+this.depth)%this.cap;for(let s=0;s<t;s++){for(let i=0;i<e.length;i++)this.rings[i][r]=e[i][s];r=r+1===this.cap?0:r+1}this.depth+=t}process(n,e){let t=e[0];if(!t||t.length===0)return!0;this.ensure(t.length);let r=t[0].length;if(!this.started)if(this.depth>=this.primeSamples||this.primeWall<=0)this.started=!0;else{this.primeWall-=r;for(let o of t)o.fill(0);return!0}let s=t.length,i=this.fadeN;for(let o=0;o<r;o++)if(this.depth>0){if(this.starve>0){this.xfadeFrom.set(this.held);for(let a=0;a<s;a++)this.xfadeFrom[a]*=this.holdGain(this.starve);this.xfadeLeft=i,this.born?this.born=!1:this.post({type:"resume"}),this.starve=0}if(this.xfadeLeft>0){let a=1-this.xfadeLeft/i;for(let c=0;c<s;c++){let l=this.rings[c][this.read];this.held[c]=l,t[c][o]=this.xfadeFrom[c]*(1-a)+l*a}this.xfadeLeft--}else for(let a=0;a<s;a++){let c=this.rings[a][this.read];this.held[a]=c,t[a][o]=c}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 c=0;c<s;c++)t[c][o]=this.held[c]*a}return!0}holdGain(n){return n<=this.holdN?1:n<=this.holdN+this.fadeN?1-(n-this.holdN)/this.fadeN:0}};function pm(){return`registerProcessor(${JSON.stringify(io)}, ${um.toString()})`}function Ud(){let n=globalThis;return typeof n.Blob!="function"||typeof n.URL?.createObjectURL!="function"?null:n.URL.createObjectURL(new Blob([pm()],{type:"text/javascript"}))}var oo=40,Nd=2,qe=48e3,hm=12,fm=64,mm=100,ao=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<pe)return;let t=ur(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-mm)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let r=this.pending.get(t.frameSeq);if(!r)for(r={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r);this.pending.size>fm;){let a=1/0;for(let c of this.pending.keys())c<a&&(a=c);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(pe),r.received++,r.received<r.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let s=r.chunks.reduce((a,c)=>a+(c?.byteLength??0),0),i=new Uint8Array(s),o=0;for(let a of r.chunks)i.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:i})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},xs=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??oo;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${oo}ms`),r=oo),this.targetS=Math.max(0,r)/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 ao(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(s){throw this.ownsCtx&&this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,s}this.trackSurfaced=!0,this.resumeLoudly("start");let r=this.dest.stream.getAudioTracks()[0];if(!r)throw new Error("[urun] playout start produced no bridge track");this.startWorkletLoad(),this.surfaceTrack(r)}startWorkletLoad(){let e=this.ctx;if(!e||!e.audioWorklet)return;let t=globalThis.AudioWorkletNode;if(typeof t!="function")return;let r=Ud();r!==null&&(this.workletState="loading",e.audioWorklet.addModule(r).then(()=>{if(this.stopped||this.ctx!==e||this.workletState!=="loading")return;let s=new t(e,io,{numberOfInputs:0,outputChannelCount:[this.config.channels]});s.connect(this.dest),s.connect(e.destination),s.port.onmessage=i=>this.onWorkletEvent(i.data),this.workletNode=s,this.workletState="ready",s.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(s=>{this.stopped||this.ctx!==e||this.workletState!=="loading"||(this.workletState="legacy",console.warn(`[urun] WT audio worklet module FAILED to load (${s instanceof Error?s.message:String(s)}) \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 r of t)e==="ready"?this.pushWorklet(r.planes,r.frames,r.sampleRate,r.timestamp):this.scheduleLegacy(r.planes,r.frames,r.sampleRate,r.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")},r=e;typeof r.addEventListener=="function"?r.addEventListener("statechange",t):e.onstatechange=t}resumeLoudly(e){let t=this.ctx;if(!t||!t.resume||this.resumeInFlight)return;let s=t.state!=="running"?++this.resumeAttempts:0;this.resumeInFlight=!0,t.resume().catch(i=>{console.warn(`[urun] WT audio playout context ${e}: resume FAILED (state=${t.state}, attempt=${s||"n/a"}): ${i instanceof Error?i.message:String(i)} \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:r=>this.schedule(r,this.pendingTs.shift()),error:r=>this.onDecoderError(r)});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 s=globalThis.AudioDecoder;if(typeof s!="function")return;try{this.initDecoder(s)}catch{return}}let r=this.decoder;r&&(this.lastFrameArrivalAt=performance.now(),this.pendingTs.push(e.timestamp),r.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/qe)),data:e.data})))}schedule(e,t){let r=this.ctx,s=this.dest;if(!r||!s||this.stopped){e.close();return}if(r.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=${r.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 i=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),a=e.sampleRate,c=[];for(let l=0;l<o;l++){let d=new Float32Array(i);e.copyTo(d,{planeIndex:l,format:"f32-planar"}),c.push(d)}if(e.close(),this.workletState==="ready"&&this.workletNode){this.pushWorklet(c,i,a,t);return}if(this.workletState==="loading"){this.stashPendingPcm(c,i,a,t);return}this.scheduleLegacy(c,i,a,t)}pushWorklet(e,t,r,s){let i=this.workletNode,o=this.ctx;if(!i||!o||this.stopped)return;if(r!==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=${r} vs ctx=${o.sampleRate}, channels=${e.length} vs configured=${this.config.channels}) \u2014 dropped for the ring player`);return}let a=this.lastTsS;if(s!==void 0){let d=s/qe;a!==null&&d<a&&(i.port.postMessage({type:"reset"}),this.workletStale=!1,this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout: producer timeline RESTART (${(a-d).toFixed(3)}s backward) \u2014 worklet ring flushed, new content fades in`))),this.lastTsS=d}let c=e.map(d=>d.buffer);i.port.postMessage({type:"pcm",frames:t,bufs:c},c),this.workletStale=!1,this.scheduledCount++;let l=performance.now();if(this.lastScheduledAt===0||l-this.lastScheduledAt>500){let d=this.lastScheduledAt===0?-1:l-this.lastScheduledAt,u=s!==void 0&&a!==null?(s/qe-a)*1e3:null;this.lastReplyStart={at:l,idleMs:d,tsJumpMs:u,anchor:"worklet",leadMs:this.targetS*1e3,arrivalToScheduledMs:l-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start (ring): idle=${d.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,r,s){for(this.pendingPcm.push({planes:e,frames:t,sampleRate:r,timestamp:s});this.pendingPcm.length>hm;)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,r,s){let i=this.ctx,o=this.dest;if(!i||!o||this.stopped)return;let a=e.length,c=i.createBuffer(a,t,r);for(let g=0;g<a;g++)c.copyToChannel(e[g],g);let l=t/r,d=i.createBufferSource();d.buffer=c,d.connect(o),d.connect(i.destination);let u,p="ride";if(s===void 0)u=Math.max(this.playhead,i.currentTime+this.targetS),p="arrival-fallback";else{this.contentBaseS===null&&(this.contentBaseS=s/qe,this.wallBaseS=i.currentTime+this.targetS,p="fresh-anchor"),u=this.wallBaseS+s/qe-this.contentBaseS;let g=null;this.lastTsS!==null&&(s<this.lastTsS?(u=i.currentTime+this.targetS,g=`backward ts step ${(this.lastTsS-s/qe).toFixed(3)}s (producer clock reset)`):u>i.currentTime+this.targetS+Math.max(l,this.targetS)&&(g=`forward jump ${(u-i.currentTime).toFixed(3)}s out (lead + ${l.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),g&&(p=g.startsWith("backward")?"backward":"surplus",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${g} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=s/qe,this.wallBaseS=i.currentTime+this.targetS,u=this.wallBaseS)),u<i.currentTime&&(p="deficit",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored ${(i.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=s/qe,this.wallBaseS=i.currentTime+this.targetS,u=this.wallBaseS)}d.start(u),this.liveSources.add(d),d.onended=()=>{this.liveSources.delete(d)},this.scheduledCount++;let f=performance.now();if(this.lastScheduledAt===0||f-this.lastScheduledAt>500){let g=this.lastScheduledAt===0?-1:f-this.lastScheduledAt,h=s!==void 0&&this.lastTsS!==null?(s/qe-this.lastTsS)*1e3:null;this.lastReplyStart={at:f,idleMs:g,tsJumpMs:h,anchor:p,leadMs:(u-i.currentTime)*1e3,arrivalToScheduledMs:f-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start: idle=${g.toFixed(0)}ms tsJump=${h===null?"n/a":h.toFixed(0)+"ms"} anchor=${p} lead=${((u-i.currentTime)*1e3).toFixed(0)}ms arrival\u2192scheduled=${(f-this.lastFrameArrivalAt).toFixed(1)}ms target=${(this.targetS*1e3).toFixed(0)}ms droppedNotRunning=${this.notRunningFrames}`)}this.lastScheduledAt=f,s!==void 0&&(this.lastTsS=s/qe),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(s=>e-s<1e4),this.rebuildTimes.length>=Nd){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${Nd} 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 s=globalThis.AudioContext;if(typeof s!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");t=new s({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 r=this.dest.stream.getAudioTracks()[0];if(!r)throw new Error("[urun] rebuilt playout produced no bridge track");this.surfaceTrack(r)}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(r=>{if(this.stopped)return;if(r?this.lastRemote=r:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),r){this.deliverSurface(r);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.deliverSurface(this.lastRemote);return}let s=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.deliverSurface(s)}),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(r){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}};var an=1200;function co(n,e,t,r,s){let i=r-pe;if(i<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/i));if(o>255)return null;let a=[];for(let c=0;c<o;c++){let l=t.subarray(c*i,Math.min((c+1)*i,t.byteLength)),d=Es({groupId:e>>>0,frameSeq:n>>>0,keyframe:s?.keyframe??!0,fragIndex:c,fragCount:o,lane:s?.lane??Cs}),u=new Uint8Array(pe+l.byteLength);u.set(d,0),u.set(l,pe),a.push(u)}return a}var gm=`
|
|
3
|
+
`}});var Ke=U($e=>{"use strict";var ft=rc(),Qp=sc(),Jp=Nn();$e.grammar=Jp;$e.write=Qp;$e.parse=ft.parse;$e.parseParams=ft.parseParams;$e.parseFmtpConfig=ft.parseFmtpConfig;$e.parsePayloads=ft.parsePayloads;$e.parseRemoteCandidates=ft.parseRemoteCandidates;$e.parseImageAttributes=ft.parseImageAttributes;$e.parseSimulcastStreamList=ft.parseSimulcastStreamList});var mt=U(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.parse=Zp;var Xp=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function Zp(n){let e=Xp.exec(n??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var ac=U(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.OfferMediaSection=et.AnswerMediaSection=et.MediaSection=void 0;var eh=Ke(),ic=ut(),$r=class{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(let s of t){let i={foundation:s.foundation,component:1,ip:s.address??s.ip,port:s.port,priority:s.priority,transport:s.protocol,type:s.type};s.tcpType&&(i.tcptype=s.tcpType),this._mediaObject.candidates.push(i)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}};et.MediaSection=$r;var vi=class extends $r{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:s,plainRtpParameters:i,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:l}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let d of c.codecs){let u={payload:d.payloadType,codec:oc(d),rate:d.clockRate};d.channels>1&&(u.encoding=d.channels),this._mediaObject.rtp.push(u);let p=ic.clone(d.parameters)??{},f=ic.clone(d.rtcpFeedback)??[];if(l){let{opusStereo:h,opusFec:m,opusDtx:_,opusMaxPlaybackRate:v,opusMaxAverageBitrate:S,opusPtime:w,opusNack:b,videoGoogleStartBitrate:T,videoGoogleMaxBitrate:y,videoGoogleMinBitrate:E}=l,N=a.codecs.find(Q=>Q.payloadType===d.payloadType);switch(d.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{h!==void 0&&(N.parameters["sprop-stereo"]=h?1:0,p.stereo=h?1:0),m!==void 0&&(N.parameters.useinbandfec=m?1:0,p.useinbandfec=m?1:0),_!==void 0&&(N.parameters.usedtx=_?1:0,p.usedtx=_?1:0),v!==void 0&&(p.maxplaybackrate=v),S!==void 0&&(p.maxaveragebitrate=S),w!==void 0&&(N.parameters.ptime=w,p.ptime=w),b||(N.rtcpFeedback=N.rtcpFeedback.filter(Q=>Q.type!=="nack"||Q.parameter),f=f.filter(Q=>Q.type!=="nack"||Q.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{T!==void 0&&(p["x-google-start-bitrate"]=T),y!==void 0&&(p["x-google-max-bitrate"]=y),E!==void 0&&(p["x-google-min-bitrate"]=E);break}}}let g={payload:d.payloadType,config:""};for(let h of Object.keys(p))g.config&&(g.config+=";"),g.config+=`${h}=${p[h]}`;g.config&&this._mediaObject.fmtp.push(g);for(let h of f)this._mediaObject.rtcpFb.push({payload:d.payloadType,type:h.type,subtype:h.parameter})}this._mediaObject.payloads=c.codecs.map(d=>d.payloadType).join(" "),this._mediaObject.ext=[];for(let d of c.headerExtensions)(o.ext??[]).some(p=>p.uri===d.uri)&&this._mediaObject.ext.push({uri:d.uri,value:d.id});if(o.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(let d of o.rids??[])d.direction==="send"&&this._mediaObject.rids.push({id:d.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let d of o.rids??[])d.direction==="send"&&this._mediaObject.rids.push({id:d.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof o.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=s.port,this._mediaObject.maxMessageSize=s.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=String(s.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:s.port,maxMessageSize:s.maxMessageSize});break}}}setDtlsRole(e){switch(e){case"client":{this._mediaObject.setup="active";break}case"server":{this._mediaObject.setup="passive";break}case"auto":{this._mediaObject.setup="actpass";break}}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;let t={};for(let i of e)i.rid&&(t[i.rid]=i);let r=this._mediaObject.simulcast.list1,s=eh.parseSimulcastStreamList(r);for(let i of s)for(let o of i)o.paused=!t[o.scid]?.active;this._mediaObject.simulcast.list1=s.map(i=>i.map(o=>`${o.paused?"~":""}${o.scid}`).join(",")).join(";")}};et.AnswerMediaSection=vi;var wi=class extends $r{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:s,plainRtpParameters:i,mid:o,kind:a,offerRtpParameters:c,streamId:l,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(o),this._mediaObject.type=a,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},s?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:l,appdata:d}];for(let g of c.codecs){let h={payload:g.payloadType,codec:oc(g),rate:g.clockRate};g.channels>1&&(h.encoding=g.channels),this._mediaObject.rtp.push(h);let m={payload:g.payloadType,config:""};for(let _ of Object.keys(g.parameters??{}))m.config&&(m.config+=";"),m.config+=`${_}=${g.parameters[_]}`;m.config&&this._mediaObject.fmtp.push(m);for(let _ of g.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:g.payloadType,type:_.type,subtype:_.parameter})}this._mediaObject.payloads=c.codecs.map(g=>g.payloadType).join(" "),this._mediaObject.ext=[];for(let g of c.headerExtensions)this._mediaObject.ext.push({uri:g.uri,value:g.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let u=c.encodings[0],p=u.ssrc,f=u.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],p&&c.rtcp.cname&&this._mediaObject.ssrcs.push({id:p,attribute:"cname",value:c.rtcp.cname}),f&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:f,attribute:"cname",value:c.rtcp.cname}),p&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${p} ${f}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=s.port,this._mediaObject.maxMessageSize=s.maxMessageSize;break}}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};et.OfferMediaSection=wi;function oc(n){let t=new RegExp("^(audio|video)/(.+)","i").exec(n.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var Jt=U($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.RemoteSdp=void 0;var th=Ke(),rh=ce(),Wn=ac(),nh=bi(),sh=["av1","h264"],Fn=new rh.Logger("RemoteSdp"),yi=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:s,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=s,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${nh.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let o=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[o-1].algorithm,hash:r.fingerprints[o-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){Fn.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(let t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){Fn.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){Fn.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){let t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:s,codecOptions:i}){let o=new Wn.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:s,codecOptions:i}),a=o.getObject();a.rtp.find(l=>sh.includes(l.codec.toLowerCase()))||(a.ext=a.ext?.filter(l=>l.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),t?this.replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this.replaceMediaSection(o):this.addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:s,trackId:i}){this.setSessionExtmapAllowMixed();let o=new Wn.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:r,streamId:s,trackId:i}),a=this._mediaSections.find(c=>c.closed&&c.getObject().type===t);a?this.replaceMediaSection(o,a.mid):this.addMediaSection(o)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){let t=this.findMediaSection(e);return e===this._firstMid?(Fn.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){let r=this.findMediaSection(e);r.muxSimulcastStreams(t),this.replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){let t=new Wn.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){let e=new Wn.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,th.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if(typeof t=="string"){let r=this._midToIndex.get(t);if(r===void 0)throw new Error(`no media section found for reuseMid '${t}'`);let s=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(s.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this.regenerateBundleMids()}else{let r=this._midToIndex.get(e.mid);if(r===void 0)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[r]=e,this._sdpObject.media[r]=e.getObject()}}findMediaSection(e){let t=this._midToIndex.get(e);if(t===void 0)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};$n.RemoteSdp=yi});var Xt=U(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.extractRtpCapabilities=ih;gt.extractDtlsParameters=oh;gt.getCname=ah;gt.applyCodecParameters=ch;gt.addHeaderExtension=dh;var cc=Ke();function ih({sdpObject:n}){let e=new Map,t=new Map;for(let s of n.media){let i=s.type;switch(i){case"audio":case"video":break;default:continue}for(let o of s.rtp){let a={kind:i,mimeType:`${i}/${o.codec}`,preferredPayloadType:o.payload,clockRate:o.rate,channels:o.encoding,parameters:{},rtcpFeedback:[]};e.set(a.preferredPayloadType,a)}for(let o of s.fmtp??[]){let a=cc.parseParams(o.config),c=e.get(o.payload);c&&(a?.hasOwnProperty("profile-level-id")&&(a["profile-level-id"]=String(a["profile-level-id"])),c.parameters=a)}for(let o of s.rtcpFb??[]){let a={type:o.type,parameter:o.subtype};if(a.parameter||delete a.parameter,o.payload!=="*"){let c=e.get(Number(o.payload));if(!c)continue;c.rtcpFeedback.push(a)}else for(let c of e.values())c.kind===i&&!/.+\/rtx$/i.test(c.mimeType)&&c.rtcpFeedback.push(a)}for(let o of s.ext??[]){if(o["encrypt-uri"])continue;let a={kind:i,uri:o.uri,preferredId:o.value};t.set(a.preferredId,a)}}return{codecs:Array.from(e.values()),headerExtensions:Array.from(t.values())}}function oh({sdpObject:n}){let e=n.setup,t=n.fingerprint;if(!e||!t){let i=(n.media??[]).find(o=>o.port!==0);i&&(e=e??i.setup,t=t??i.fingerprint)}if(e){if(!t)throw new Error("no a=fingerprint found at SDP session or media level")}else throw new Error("no a=setup found at SDP session or media level");let r;switch(e){case"active":{r="client";break}case"passive":{r="server";break}case"actpass":{r="auto";break}}return{role:r,fingerprints:[{algorithm:t.type,value:t.hash}]}}function ah({offerMediaObject:n}){let e=(n.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function ch({offerRtpParameters:n,answerMediaObject:e}){for(let t of n.codecs){let r=t.mimeType.toLowerCase();if(r!=="audio/opus"||!(e.rtp??[]).find(a=>a.payload===t.payloadType))continue;e.fmtp=e.fmtp??[];let i=e.fmtp.find(a=>a.payload===t.payloadType);i||(i={payload:t.payloadType,config:""},e.fmtp.push(i));let o=cc.parseParams(i.config);if(r==="audio/opus"){let a=t.parameters?.["sprop-stereo"];a!==void 0&&(o.stereo=Number(a)?1:0)}i.config="";for(let a of Object.keys(o))i.config&&(i.config+=";"),i.config+=`${a}=${o[a]}`}}function dh({offerMediaObject:n,headerExtensionUri:e,headerExtensionId:t}){n.ext||(n.ext=[]),n.ext.push({uri:e,value:t})}});var Zt=U(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.getRtpEncodings=lh;jn.addLegacySimulcast=uh;function lh({offerMediaObject:n,codecs:e}){let t=new Set;for(let i of n.ssrcs??[]){let o=i.id;o&&t.add(o)}if(t.size===0)throw new Error("no a=ssrc lines found");let r=new Map;for(let i of n.ssrcGroups??[]){if(i.semantics!=="FID")continue;let o=i.ssrcs.split(/\s+/),a=Number(o[0]),c=Number(o[1]);t.has(a)&&(t.delete(a),t.delete(c),r.set(a,c))}for(let i of t)r.set(i,void 0);let s=[];for(let[i,o]of r){let a={ssrc:i};o&&e.length>1&&(a.rtx={ssrc:o}),s.push(a)}return s}function uh({offerMediaObject:n,numStreams:e}){if(e<=1)throw new TypeError("numStreams must be greater than 1");let t=(n.ssrcs??[]).find(u=>u.attribute==="msid");if(!t)throw new Error("a=ssrc line with msid information not found");let[r,s]=t.value.split(" "),i=Number(t.id),o;(n.ssrcGroups??[]).some(u=>{if(u.semantics!=="FID")return!1;let p=u.ssrcs.split(/\s+/);return Number(p[0])===i?(o=Number(p[1]),!0):!1});let a=(n.ssrcs??[]).find(u=>u.attribute==="cname");if(!a)throw new Error("a=ssrc line with cname information not found");let c=a.value,l=[],d=[];for(let u=0;u<e;++u)l.push(i+u),o&&d.push(o+u);n.ssrcGroups=[],n.ssrcs=[],n.ssrcGroups.push({semantics:"SIM",ssrcs:l.join(" ")});for(let u of l)n.ssrcs.push({id:u,attribute:"cname",value:c}),n.ssrcs.push({id:u,attribute:"msid",value:`${r} ${s}`});for(let u=0;u<d.length;++u){let p=l[u],f=d[u];n.ssrcs.push({id:f,attribute:"cname",value:c}),n.ssrcs.push({id:f,attribute:"msid",value:`${r} ${s}`}),n.ssrcGroups.push({semantics:"FID",ssrcs:`${p} ${f}`})}}});var er=U(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.addNackSupportForOpus=ph;jr.addHeaderExtensionSupport=hh;jr.getMsidStreamIdAndTrackId=fh;function ph(n){for(let e of n.codecs??[])(e.mimeType.toLowerCase()==="audio/opus"||e.mimeType.toLowerCase()==="audio/multiopus")&&!e.rtcpFeedback?.some(t=>t.type==="nack"&&!t.parameter)&&(e.rtcpFeedback||(e.rtcpFeedback=[]),e.rtcpFeedback.push({type:"nack"}))}function hh(n,e){let t,r=n.headerExtensions?.find(i=>i.uri===e.uri);if(r){if(r.kind===e.kind)return;t=r.preferredId}if(n.headerExtensions||(n.headerExtensions=[]),t===void 0){t=1;let i=new Set(n.headerExtensions.map(o=>o.preferredId));for(;i.has(t);)++t}let s={kind:e.kind,uri:e.uri,preferredId:t,preferredEncrypt:!1,direction:e.direction};n.headerExtensions.push(s)}function fh(n){if(!n||typeof n!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[e,t]=n.trim().split(/\s+/);return e?{msidStreamId:e,msidTrackId:t}:{msidStreamId:void 0,msidTrackId:void 0}}});var pc=U(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.Chrome111=void 0;var je=Ke(),mh=ge(),gh=ce(),qr=Ne(),_h=Se(),vh=mt(),wh=Jt(),Br=Xt(),dc=Zt(),Si=er(),L=new gh.Logger("Chrome111"),lc="Chrome111",uc={OS:65535,MIS:65535},ki=class n extends mh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:lc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{L.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let s=je.parse(r.sdp);return n.getLocalRtpCapabilities(s)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(L.debug("getNativeSctpCapabilities()"),{numStreams:uc})}}static getLocalRtpCapabilities(e,t=[]){let r=Br.extractRtpCapabilities({sdpObject:e});qr.validateAndNormalizeRtpCapabilities(r),Si.addNackSupportForOpus(r);for(let s of t)Si.addHeaderExtensionSupport(r,s);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),L.debug("constructor()"),this._direction=e,this._remoteSdp=new wh.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(L.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return lc}close(){if(L.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),L.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),L.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});L.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();L.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){if(this.assertNotClosed(),this.assertSendDirection(),L.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1){let w=1;for(let b of r){let T=b.scalabilityMode?(0,vh.parse)(b.scalabilityMode).temporalLayers:3;T>w&&(w=T)}r.forEach((b,T)=>{b.rid=`r${T}`,b.scalabilityMode=`L1T${w}`})}let c=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});a&&a(l.sender);let d=await this._pc.createOffer(),u=je.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=n.getLocalRtpCapabilities(u,p),g=this._getSendExtendedRtpCapabilities(f),h=qr.getSendingRtpParameters(e.kind,g);h.codecs=qr.reduceCodecs(h.codecs,o);let m=qr.getSendingRemoteRtpParameters(e.kind,g);if(m.codecs=qr.reduceCodecs(m.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u}),i?.absCaptureTime){let w=u.media[c.idx];Br.addHeaderExtension({offerMediaObject:w,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find(b=>b.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:je.write(u)}}L.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let _=l.mid;h.mid=_,u=je.parse(this._pc.localDescription.sdp);let v=u.media[c.idx];if(h.rtcp.cname=Br.getCname({offerMediaObject:v}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=dc.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});else if(r.length===1){let w=dc.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});Object.assign(w[0],r[0]),h.encodings=w}else h.encodings=r;this._remoteSdp.send({offerMediaObject:v,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:m,codecOptions:s});let S={type:"answer",sdp:this._remoteSdp.getSdp()};return L.debug("send() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.set(_,l),{localId:_,rtpParameters:h,rtpSender:l.sender}}async stopSending(e){if(this.assertSendDirection(),L.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();L.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),L.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();L.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),L.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();L.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?L.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):L.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),L.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();L.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),L.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();L.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};L.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%uc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=je.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),L.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};L.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;L.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=Si.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:l}=a;if(l){let d=r.get(c),u=this._pc.getTransceivers().find(p=>p.mid===d);if(!u)throw new Error("transceiver not found");l(u.receiver)}}let i=await this._pc.createAnswer(),o=je.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Br.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u})}i={type:"answer",sdp:je.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),L.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(d)this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){L.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();L.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){L.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();L.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){L.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();L.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};L.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};L.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=je.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:je.write(f)},L.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=je.parse(this._pc.localDescription.sdp));let r=Br.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new _h.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};qn.Chrome111=ki});var mc=U(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Chrome74=void 0;var ke=Ke(),yh=ce(),bh=ge(),Hr=Ne(),Sh=Se(),kh=mt(),Th=Jt(),Vr=Xt(),Ti=Zt(),Ri=er(),A=new yh.Logger("Chrome74"),hc="Chrome74",fc={OS:1024,MIS:1024},Ci=class n extends bh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:hc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{A.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let s=ke.parse(r.sdp);return n.getLocalRtpCapabilities(s)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(A.debug("getNativeSctpCapabilities()"),{numStreams:fc})}}static getLocalRtpCapabilities(e,t=[]){let r=Vr.extractRtpCapabilities({sdpObject:e});Hr.validateAndNormalizeRtpCapabilities(r),Ri.addNackSupportForOpus(r);for(let s of t)Ri.addHeaderExtensionSupport(r,s);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),A.debug("constructor()"),this._direction=e,this._remoteSdp=new Th.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(A.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return hc}close(){if(A.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),A.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),A.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});A.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();A.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,headerExtensionOptions:i,codec:o}){this.assertNotClosed(),this.assertSendDirection(),A.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((b,T)=>{b.rid=`r${T}`});let a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r}),l=await this._pc.createOffer(),d=ke.parse(l.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let u=[];u.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let p=n.getLocalRtpCapabilities(d,u),f=this._getSendExtendedRtpCapabilities(p),g=Hr.getSendingRtpParameters(e.kind,f);g.codecs=Hr.reduceCodecs(g.codecs,o);let h=Hr.getSendingRemoteRtpParameters(e.kind,f);h.codecs=Hr.reduceCodecs(h.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:d});let m=!1,_=(0,kh.parse)((r??[{}])[0].scalabilityMode),v;r?.length===1&&_.spatialLayers>1&&g.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(A.debug("send() | enabling legacy simulcast for VP9 SVC"),m=!0,d=ke.parse(l.sdp),v=d.media[a.idx],Ti.addLegacySimulcast({offerMediaObject:v,numStreams:_.spatialLayers}),l={type:"offer",sdp:ke.write(d)}),A.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),i?.absCaptureTime&&(v=d.media[a.idx],Vr.addHeaderExtension({offerMediaObject:v,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:h.headerExtensions.find(b=>b.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),l={type:"offer",sdp:ke.write(d)}),await this._pc.setLocalDescription(l);let S=c.mid;if(g.mid=S,d=ke.parse(this._pc.localDescription.sdp),v=d.media[a.idx],g.rtcp.cname=Vr.getCname({offerMediaObject:v}),g.msid=`${t??this._sendStream.id} ${e.id}`,!r)g.encodings=Ti.getRtpEncodings({offerMediaObject:v,codecs:g.codecs});else if(r.length===1){let b=Ti.getRtpEncodings({offerMediaObject:v,codecs:g.codecs});Object.assign(b[0],r[0]),m&&(b=[b[0]]),g.encodings=b}else g.encodings=r;if(g.encodings.length>1&&(g.codecs[0].mimeType.toLowerCase()==="video/vp8"||g.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let b of g.encodings)b.scalabilityMode?b.scalabilityMode=`L1T${_.temporalLayers}`:b.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:v,reuseMid:a.reuseMid,offerRtpParameters:g,answerRtpParameters:h,codecOptions:s});let w={type:"answer",sdp:this._remoteSdp.getSdp()};return A.debug("send() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w),this._mapMidTransceiver.set(S,c),{localId:S,rtpParameters:g,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),A.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();A.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),A.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();A.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),A.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();A.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?A.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):A.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),A.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();A.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),A.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();A.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};A.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%fc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ke.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),A.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;A.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=Ri.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);let i=await this._pc.createAnswer(),o=ke.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Vr.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u})}i={type:"answer",sdp:ke.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),A.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(d)this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){A.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();A.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){A.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();A.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){A.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();A.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};A.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=ke.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:ke.write(f)},A.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ke.parse(this._pc.localDescription.sdp));let r=Vr.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Sh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Bn.Chrome74=Ci});var yc=U(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.Firefox120=void 0;var Ye=Ke(),Rh=ge(),Ch=ce(),gc=Se(),zr=Ne(),Eh=mt(),Ph=Jt(),Hn=Xt(),_c=Zt(),xh=er(),M=new Ch.Logger("Firefox120"),vc="Firefox120",wc={OS:16,MIS:2048},Ei=class n extends Rh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:vc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{M.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),r=document.createElement("canvas");r.getContext("2d");let i=r.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(i,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let o=await t.createOffer();try{r.remove()}catch{}try{i.stop()}catch{}try{t.close()}catch{}t=void 0;let a=Ye.parse(o.sdp);return n.getLocalRtpCapabilities(a)}catch(o){try{r.remove()}catch{}try{i.stop()}catch{}try{t?.close()}catch{}throw t=void 0,o}},getNativeSctpCapabilities:async()=>(M.debug("getNativeSctpCapabilities()"),{numStreams:wc})}}static getLocalRtpCapabilities(e){let t=Hn.extractRtpCapabilities({sdpObject:e});return zr.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),M.debug("constructor()"),this._direction=e,this._remoteSdp=new Ph.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(M.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return vc}close(){if(M.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){throw this.assertNotClosed(),new gc.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),M.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});M.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();M.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,codec:i,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),M.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((v,S)=>{v.rid=`r${S}`});let a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});o&&o(a.sender);let c=await this._pc.createOffer(),l=Ye.parse(c.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let d=n.getLocalRtpCapabilities(l),u=this._getSendExtendedRtpCapabilities(d),p=zr.getSendingRtpParameters(e.kind,u);p.codecs=zr.reduceCodecs(p.codecs,i);let f=zr.getSendingRemoteRtpParameters(e.kind,u);f.codecs=zr.reduceCodecs(f.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:l});let g=(0,Eh.parse)((r??[{}])[0].scalabilityMode);M.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);let h=a.mid;p.mid=h,l=Ye.parse(this._pc.localDescription.sdp);let m=l.media[l.media.length-1];if(p.rtcp.cname=Hn.getCname({offerMediaObject:m}),p.msid=`${t??this._sendStream.id} ${e.id}`,!r)p.encodings=_c.getRtpEncodings({offerMediaObject:m,codecs:p.codecs});else if(r.length===1){let v=_c.getRtpEncodings({offerMediaObject:m,codecs:p.codecs});Object.assign(v[0],r[0]),p.encodings=v}else p.encodings=r;if(p.encodings.length>1&&(p.codecs[0].mimeType.toLowerCase()==="video/vp8"||p.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let v of p.encodings)v.scalabilityMode?v.scalabilityMode=`L1T${g.temporalLayers}`:v.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,offerRtpParameters:p,answerRtpParameters:f,codecOptions:s});let _={type:"answer",sdp:this._remoteSdp.getSdp()};return M.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:p,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),M.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);let r=await this._pc.createOffer();M.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),M.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();M.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),M.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let r=await this._pc.createOffer();M.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?M.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):M.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),M.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();M.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),M.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();M.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};M.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%wc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Ye.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),M.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};M.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;M.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=xh.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:l}=a;if(l){let d=r.get(c),u=this._pc.getTransceivers().find(p=>p.mid===d);if(!u)throw new Error("transceiver not found");l(u.receiver)}}let i=await this._pc.createAnswer(),o=Ye.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Hn.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u}),i={type:"answer",sdp:Ye.write(o)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),M.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(!d)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){M.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();M.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){M.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();M.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){M.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();M.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};M.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};M.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=Ye.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:f}),p={type:"answer",sdp:Ye.write(f)},M.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ye.parse(this._pc.localDescription.sdp));let r=Hn.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new gc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Vn.Firefox120=Ei});var Tc=U(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.Safari12=void 0;var Te=Ke(),Dh=ge(),Ah=ce(),Gr=Ne(),Ih=Se(),Lh=mt(),Mh=Jt(),Kr=Xt(),bc=Zt(),Pi=er(),I=new Ah.Logger("Safari12"),Sc="Safari12",kc={OS:65535,MIS:65535},xi=class n extends Dh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Sc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{I.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let s=Te.parse(r.sdp);return n.getLocalRtpCapabilities(s)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(I.debug("getNativeSctpCapabilities()"),{numStreams:kc})}}static getLocalRtpCapabilities(e,t=[]){let r=Kr.extractRtpCapabilities({sdpObject:e});Gr.validateAndNormalizeRtpCapabilities(r),Pi.addNackSupportForOpus(r);for(let s of t)Pi.addHeaderExtensionSupport(r,s);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),I.debug("constructor()"),this._direction=e,this._remoteSdp=new Mh.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",d=>{this.emit("@icecandidateerror",d)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(I.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Sc}close(){if(I.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),I.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),I.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});I.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();I.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),I.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);let c=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});a&&a(l.sender);let d=await this._pc.createOffer(),u=Te.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=n.getLocalRtpCapabilities(u,p),g=this._getSendExtendedRtpCapabilities(f),h=Gr.getSendingRtpParameters(e.kind,g);h.codecs=Gr.reduceCodecs(h.codecs,o);let m=Gr.getSendingRemoteRtpParameters(e.kind,g);m.codecs=Gr.reduceCodecs(m.codecs,o);let _;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let v=(0,Lh.parse)((r??[{}])[0].scalabilityMode);r&&r.length>1&&(I.debug("send() | enabling legacy simulcast"),u=Te.parse(d.sdp),_=u.media[c.idx],bc.addLegacySimulcast({offerMediaObject:_,numStreams:r.length}),d={type:"offer",sdp:Te.write(u)}),i?.absCaptureTime&&(_=u.media[c.idx],Kr.addHeaderExtension({offerMediaObject:_,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find(b=>b.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Te.write(u)}),I.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let S=l.mid;if(h.mid=S,u=Te.parse(this._pc.localDescription.sdp),_=u.media[c.idx],h.rtcp.cname=Kr.getCname({offerMediaObject:_}),h.msid=`${t??this._sendStream.id} ${e.id}`,h.encodings=bc.getRtpEncodings({offerMediaObject:_,codecs:h.codecs}),r)for(let b=0;b<h.encodings.length;++b)r[b]&&Object.assign(h.encodings[b],r[b]);if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let b of h.encodings)b.scalabilityMode?b.scalabilityMode=`L1T${v.temporalLayers}`:b.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:_,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:m,codecOptions:s});let w={type:"answer",sdp:this._remoteSdp.getSdp()};return I.debug("send() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w),this._mapMidTransceiver.set(S,l),{localId:S,rtpParameters:h,rtpSender:l.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;I.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();I.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),I.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();I.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),I.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let r=await this._pc.createOffer();I.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?I.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):I.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),I.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();I.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),I.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();I.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};I.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%kc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Te.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),I.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;I.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=Pi.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:l}=a;if(l){let d=r.get(c),u=this._pc.getTransceivers().find(p=>p.mid===d);if(!u)throw new Error("transceiver not found");l(u.receiver)}}let i=await this._pc.createAnswer(),o=Te.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Kr.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u})}i={type:"answer",sdp:Te.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),I.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(!d)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){I.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();I.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){I.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();I.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){I.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();I.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};I.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=Te.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:Te.write(f)},I.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Te.parse(this._pc.localDescription.sdp));let r=Kr.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Ih.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};zn.Safari12=xi});var Ec=U(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.ReactNative106=void 0;var Re=Ke(),Oh=ge(),Uh=ce(),Yr=Ne(),Nh=Se(),Wh=mt(),Fh=Jt(),Qr=Xt(),Di=Zt(),Ai=er(),P=new Uh.Logger("ReactNative106"),Rc="ReactNative106",Cc={OS:65535,MIS:65535},Ii=class n extends Oh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Rc,factory:e=>new n(e),getNativeRtpCapabilities:async({direction:e})=>{P.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let r=await t.createOffer();try{t.close()}catch{}t=void 0;let s=Re.parse(r.sdp);return n.getLocalRtpCapabilities(s)}catch(r){try{t?.close()}catch{}throw t=void 0,r}},getNativeSctpCapabilities:async()=>(P.debug("getNativeSctpCapabilities()"),{numStreams:Cc})}}static getLocalRtpCapabilities(e,t=[]){let r=Qr.extractRtpCapabilities({sdpObject:e});Yr.validateAndNormalizeRtpCapabilities(r),Ai.addNackSupportForOpus(r);for(let s of t)Ai.addHeaderExtensionSupport(r,s);return r}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:l}){super(),P.debug("constructor()"),this._direction=e,this._remoteSdp=new Fh.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=l,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(P.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Rc}close(){if(P.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),P.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),P.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});P.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let r={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",r),await this._pc.setRemoteDescription(r)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();P.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:r,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),P.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),r&&r.length>1&&r.forEach((T,y)=>{T.rid=`r${y}`});let c=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:r});a&&a(l.sender);let d=await this._pc.createOffer(),u=Re.parse(d.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=n.getLocalRtpCapabilities(u,p),g=this._getSendExtendedRtpCapabilities(f),h=Yr.getSendingRtpParameters(e.kind,g);h.codecs=Yr.reduceCodecs(h.codecs,o);let m=Yr.getSendingRemoteRtpParameters(e.kind,g);m.codecs=Yr.reduceCodecs(m.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let _=!1,v=(0,Wh.parse)((r??[{}])[0].scalabilityMode),S;r?.length===1&&v.spatialLayers>1&&h.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(P.debug("send() | enabling legacy simulcast for VP9 SVC"),_=!0,u=Re.parse(d.sdp),S=u.media[c.idx],Di.addLegacySimulcast({offerMediaObject:S,numStreams:v.spatialLayers}),d={type:"offer",sdp:Re.write(u)}),i?.absCaptureTime&&(S=u.media[c.idx],Qr.addHeaderExtension({offerMediaObject:S,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find(T=>T.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Re.write(u)}),P.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let w=l.mid??void 0;if(w||P.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),h.mid=w,u=Re.parse(this._pc.localDescription.sdp),S=u.media[c.idx],h.rtcp.cname=Qr.getCname({offerMediaObject:S}),h.msid=`${t??this._sendStream.id} ${e.id}`,!r)h.encodings=Di.getRtpEncodings({offerMediaObject:S,codecs:h.codecs});else if(r.length===1){let T=Di.getRtpEncodings({offerMediaObject:S,codecs:h.codecs});Object.assign(T[0],r[0]),_&&(T=[T[0]]),h.encodings=T}else h.encodings=r;if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let T of h.encodings)T.scalabilityMode?T.scalabilityMode=`L1T${v.temporalLayers}`:T.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:S,reuseMid:c.reuseMid,offerRtpParameters:h,answerRtpParameters:m,codecOptions:s});let b={type:"answer",sdp:this._remoteSdp.getSdp()};return P.debug("send() | calling pc.setRemoteDescription() [answer:%o]",b),await this._pc.setRemoteDescription(b),w||(w=l.mid,h.mid=w),this._mapMidTransceiver.set(w,l),{localId:w,rtpParameters:h,rtpSender:l.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;P.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();P.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),P.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let r=await this._pc.createOffer();P.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),P.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let r=await this._pc.createOffer();P.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);let s={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?P.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):P.debug("replaceTrack() [localId:%s, no track]",e);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),P.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();P.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),P.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");let s=r.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await r.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();P.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};P.debug("sendDataChannel() [options:%o]",t);let r=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Cc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Re.parse(i.sdp),a=o.media.find(l=>l.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),P.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:r,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],r=new Map;for(let a of e){let{trackId:c,kind:l,rtpParameters:d,streamId:u}=a;P.debug("receive() [trackId:%s, kind:%s]",c,l);let p=d.mid??String(this._mapMidTransceiver.size);r.set(c,p);let{msidStreamId:f}=Ai.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:l,offerRtpParameters:d,streamId:u??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:l}=a;if(l){let d=r.get(c),u=this._pc.getTransceivers().find(p=>p.mid===d);if(!u)throw new Error("transceiver not found");l(u.receiver)}}let i=await this._pc.createAnswer(),o=Re.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:l}=a,d=r.get(c),u=o.media.find(p=>String(p.mid)===d);Qr.applyCodecParameters({offerRtpParameters:l,answerMediaObject:u})}i={type:"answer",sdp:Re.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),P.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,l=r.get(c),d=this._pc.getTransceivers().find(u=>u.mid===l);if(d)this._mapMidTransceiver.set(l,d),t.push({localId:l,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){P.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();P.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){P.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();P.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){P.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let r=await this._pc.createAnswer();P.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:r,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,l={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};P.debug("receiveDataChannel() [options:%o]",l);let d=this._pc.createDataChannel(r,l);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let u={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",u),await this._pc.setRemoteDescription(u);let p=await this._pc.createAnswer(),f=Re.parse(p.sdp),g=f.media.find(h=>h.type==="application");g.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:Re.write(f)},P.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Re.parse(this._pc.localDescription.sdp));let r=Qr.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:r},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Nh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Gn.ReactNative106=Ii});var Ac=U(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.Device=void 0;tr.detectDevice=Pc;tr.detectDeviceAsync=xc;var $h=ce(),jh=ge(),tt=Se(),Kn=ut(),ve=Ne(),qh=Ja(),Bh=pc(),Hh=mc(),Vh=yc(),zh=Tc(),Gh=Ec(),C=new $h.Logger("Device");function Pc(n,e){return C.debug("detectDevice()"),!n&&typeof navigator=="object"&&(n=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),Dc(n,e)}async function xc(n,e){return C.debug("detectDeviceAsync()"),!n&&typeof navigator=="object"&&(n=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),Dc(n,e)}var Li=class n{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new jh.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(C.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&(e=await xc(),!e))throw new tt.UnsupportedError("device not supported");return new n({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(C.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)C.debug("constructor() | handler given: %s",e);else if(e=Pc(),e)C.debug("constructor() | detected handler: %s",e);else throw new tt.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=Bh.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=Hh.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=Vh.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=zh.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=Gh.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new tt.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new tt.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new tt.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(C.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new tt.InvalidStateError("already loaded");let r=Kn.clone(e);ve.validateAndNormalizeRtpCapabilities(r);let{getNativeRtpCapabilities:s,getNativeSctpCapabilities:i}=this._handlerFactory,o=Kn.clone(await s({direction:"recvonly"}));C.debug("load() | got native receiving RTP capabilities:%o",o),ve.validateAndNormalizeRtpCapabilities(o);let a=Kn.clone(await s({direction:"sendonly"}));C.debug("load() | got native sending RTP capabilities:%o",a),ve.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=d=>Kn.clone(ve.getExtendedRtpCapabilities(d,r,t));let c=ve.getExtendedRtpCapabilities(o,r,!1);this._recvRtpCapabilities=ve.getRecvRtpCapabilities(c),C.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),ve.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let l=ve.getExtendedRtpCapabilities(a,r,t);this._sendRtpCapabilities=ve.getSendRtpCapabilities(l),C.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),ve.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=ve.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=ve.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),ve.validateSctpCapabilities(this._sctpCapabilities),C.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),C.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(this._loaded){if(e!=="audio"&&e!=="video")throw new TypeError(`invalid kind "${e}"`)}else throw new tt.InvalidStateError("not loaded");return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:l}){return C.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:l})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:l}){return C.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:l})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:l,appData:d}){if(this._loaded){if(typeof t!="string")throw new TypeError("missing id");if(typeof r!="object")throw new TypeError("missing iceParameters");if(Array.isArray(s)){if(typeof i!="object")throw new TypeError("missing dtlsParameters");if(o&&typeof o!="object")throw new TypeError("wrong sctpParameters");if(d&&typeof d!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new tt.InvalidStateError("not loaded");let u=new qh.Transport({direction:e,id:t,iceParameters:r,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:l,appData:d,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",u),u}};tr.Device=Li;function Dc(n,e){C.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',n,e);let t=Kh(n,e);if(t){if(t>=111)return C.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(t>=74)return C.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";C.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let r=Yh(n);if(r){if(r>=120)return C.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";C.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let s=Qh(n);if(s){if(s>=605)return C.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";C.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let i=Jh(n);if(i){if(i>=605)return C.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";C.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(Jr()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return C.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";C.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}C.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',n,e)}function Kh(n,e){if(C.debug("getChromiumMajorVersion()"),Yn(n,e)){C.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(Jr()){C.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(e){let s=(Array.isArray(e.brands)?e.brands:[]).find(i=>i.brand==="Chromium");if(s){let i=Number(s.version);return C.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${i}`),i}}let t=n?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(t?.[1]){let r=Number(t[1]);return C.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${r}`),r}C.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function Yh(n){if(C.debug("getFirefoxMajorVersion()"),Yn(n)){C.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(Jr()){C.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let e=n?.match(/\bFirefox\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return C.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${t}`),t}C.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function Qh(n){if(C.debug("getMacOSWebKitMajorVersion()"),Yn(n)){C.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(Jr()){C.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(n&&/\bSafari\b/i.test(n)&&!/\bChrome\b/i.test(n)&&!/\bChromium\b/i.test(n)&&!/\bFirefox\b/i.test(n))){C.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let t=n.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){let r=Number(t[1]);return C.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${r}`),r}C.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function Jh(n){if(C.debug("getIOSWebKitMajorVersion()"),!Yn(n)){C.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(Jr()){C.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let e=n?.match(/AppleWebKit\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return C.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${t}`),t}C.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function Yn(n,e){return C.debug("isIOS()"),e?.platform==="iOS"?(C.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):e?.platform?(C.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):n&&/iPad|iPhone|iPod/.test(n)?(C.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(C.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(C.debug("isIOS() | this is not iOS => false"),!1)}function Jr(){return C.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(C.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(C.debug("isReactNative() | this is not React-Native => false"),!1)}});var Lc=U(Ic=>{"use strict";var _t=256,Jn=[],Qn;for(;_t--;)Jn[_t]=(_t+256).toString(16).substring(1);function Xh(){var n=0,e,t="";if(!Qn||_t+16>256){for(Qn=Array(n=256);n--;)Qn[n]=256*Math.random()|0;n=_t=0}for(;n<16;n++)e=Qn[_t+n],n==6?t+=Jn[e&15|64]:n==8?t+=Jn[e&63|128]:t+=Jn[e],n&1&&n>1&&n<11&&(t+="-");return _t++,t}Ic.v4=Xh});var Mc=U(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.FakeEventTarget=void 0;var Mi=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof r=="object"&&r.once===!0}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(s=>s.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let r of[...t]){try{r.callback.call(this,e)}catch(s){setTimeout(()=>{throw s},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};Xn.FakeEventTarget=Mi});var Oc=U(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.FakeEvent=void 0;var Oi=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=this.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,r){}};Zn.FakeEvent=Oi});var Uc=U(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.clone=Zh;function Zh(n){if(n!==void 0)return Number.isNaN(n)?NaN:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}});var Wc=U(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.FakeMediaStreamTrack=void 0;var Nc=Lc(),ef=Mc(),rr=Oc(),es=Uc(),Ni=class n extends ef.FakeEventTarget{#m;#u;#p;#e;#r;#t;#n;#h;#s;#f;#i;#o=null;#a=null;#c=null;#d=null;#l=null;constructor({kind:e,id:t,label:r,contentHint:s,enabled:i,muted:o,readyState:a,capabilities:c,constraints:l,settings:d,data:u}){super(),this.#m=t??(0,Nc.v4)(),this.#u=e,this.#p=r??"",this.#n=s??"",this.#r=i??!0,this.#t=o??!1,this.#e=a??"live",this.#h=c??{},this.#s=l??{},this.#f=d??{},this.#i=u??{}}get id(){return this.#m}get kind(){return this.#u}get label(){return this.#p}get contentHint(){return this.#n}set contentHint(e){this.#n=e}get enabled(){return this.#r}set enabled(e){let t=this.#r!==e;this.#r=e,t&&this.dispatchEvent(new rr.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(e){this.#i=e}get onmute(){return this.#o}set onmute(e){this.#o&&this.removeEventListener("mute",this.#o),this.#o=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#a}set onunmute(e){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#c}set onended(e){this.#c&&this.removeEventListener("ended",this.#c),this.#c=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#d}set onenabledchange(e){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#l}set onstopped(e){this.#l&&this.removeEventListener("stopped",this.#l),this.#l=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new rr.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new n({id:e??(0,Nc.v4)(),kind:this.#u,label:this.#p,contentHint:this.#n,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,es.clone)(this.#h),constraints:(0,es.clone)(this.#s),settings:(0,es.clone)(this.#f),data:t??(0,es.clone)(this.#i)})}getCapabilities(){return this.#h}getConstraints(){return this.#s}async applyConstraints(e={}){return this.#s=e,Promise.resolve()}getSettings(){return this.#f}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new rr.FakeEvent("stopped")),this.dispatchEvent(new rr.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new rr.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new rr.FakeEvent("unmute")))}};ts.FakeMediaStreamTrack=Ni});var Fc=U(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.FakeEventTarget=void 0;var Wi=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof r=="object"&&r.once===!0}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(s=>s.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let r of[...t]){try{r.callback.call(this,e)}catch(s){setTimeout(()=>{throw s},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};rs.FakeEventTarget=Wi});var qc=U(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.FakeHandler=void 0;var tf=Wc(),rf=ge(),nf=ce(),nr=ut(),Fi=Ne(),jc=Se(),sf=Fc(),ne=new nf.Logger("FakeHandler"),$c="FakeHandler",$i=class n extends rf.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${nr.generateRandomNumber()}`;_defaultSendStreamId=`${nr.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:$c,factory:t=>new n(t,e),getNativeRtpCapabilities:async({direction:t})=>(ne.debug("getNativeRtpCapabilities() [direction:%o]",t),n.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(ne.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){let t=e.generateNativeRtpCapabilities();return Fi.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),ne.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return $c}close(){ne.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),ne.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),ne.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:r,codecOptions:s,codec:i}){this.assertNotClosed(),ne.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let o=n.getLocalRtpCapabilities(this._fakeParameters),a=this._getSendExtendedRtpCapabilities(o),c=Fi.getSendingRtpParameters(e.kind,a);c.codecs=Fi.reduceCodecs(c.codecs,i);let l=c.codecs.some(u=>/.+\/rtx$/i.test(u.mimeType));c.mid=`mid-${nr.generateRandomNumber()}`,c.msid=`${t??"-"} ${e.id}`,r||(r=[{}]);for(let u of r)u.ssrc=nr.generateRandomNumber(),l&&(u.rtx={ssrc:nr.generateRandomNumber()});c.encodings=r,c.rtcp={cname:this._cname,reducedSize:!0,mux:!0},c.msid=`${t??this._defaultSendStreamId} ${e.id}`;let d=this._nextLocalId++;return this._tracks.set(d,e),{localId:String(d),rtpParameters:c}}async stopSending(e){if(ne.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?ne.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ne.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),ne.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),ne.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),ne.debug("sendDataChannel()");let t=new ns({id:this._nextSctpStreamId++,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:e.label,protocol:e.protocol}),r={streamId:this._nextSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits};return{dataChannel:t,sctpStreamParameters:r}}async receive(e){this.assertNotClosed();let t=[];for(let r of e){let{trackId:s,kind:i}=r;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),ne.debug("receive() [trackId:%s, kind:%s]",s,i);let o=this._nextLocalId++,a=new tf.FakeMediaStreamTrack({kind:i});this._tracks.set(o,a),t.push({localId:String(o),track:a})}return t}async stopReceiving(e){if(!this._closed)for(let t of e)ne.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),ne.debug("receiveDataChannel()"),{dataChannel:new ns({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:e,localSdpObject:t}){let r=nr.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(r.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((s,i)=>this.emit("@connect",{dtlsParameters:r},s,i)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new jc.InvalidStateError("method called in a closed handler")}};ss.FakeHandler=$i;var ns=class extends sf.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:e,ordered:t=!0,maxPacketLifeTime:r=null,maxRetransmits:s=null,label:i="",protocol:o=""}){super(),ne.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${r}, maxRetransmits:${s}, label:${i}, protocol:${o}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=r,this._maxRetransmits=s,this._label=i,this._protocol=o}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if(this._readyState!=="open")throw new jc.InvalidStateError("not open")}}});var Bc=U(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.generateRouterRtpCapabilities=of;Le.generateNativeRtpCapabilities=af;Le.generateNativeSctpCapabilities=cf;Le.generateLocalDtlsParameters=df;Le.generateTransportRemoteParameters=lf;Le.generateProducerRemoteParameters=uf;Le.generateConsumerRemoteParameters=pf;Le.generateDataProducerRemoteParameters=hf;Le.generateDataConsumerRemoteParameters=ff;var le=ut();function we(){return String(le.generateRandomNumber())}function of(){return le.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})}function af(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}}function cf(){return le.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function df(){return le.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})}function lf(){return{id:we(),iceParameters:le.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:le.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:le.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:le.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function uf(){return le.deepFreeze({id:we()})}function pf({id:n,codecMimeType:e}={}){switch(e){case"audio/opus":return{id:n??we(),producerId:we(),kind:"audio",rtpParameters:le.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:n??we(),producerId:we(),kind:"audio",rtpParameters:le.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:n??we(),producerId:we(),kind:"video",rtpParameters:le.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:n??we(),producerId:we(),kind:"video",rtpParameters:le.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${e}'`)}}function hf(){return le.deepFreeze({id:we()})}function ff({id:n}={}){return{id:n??we(),dataProducerId:we(),sctpStreamParameters:le.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var bi=U(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.debug=K.testFakeParameters=K.FakeHandler=K.enhancedEvents=K.ortc=K.parseScalabilityMode=K.detectDeviceAsync=K.detectDevice=K.Device=K.version=K.types=void 0;var mf=Ur();K.debug=mf.default;K.types=fa();K.version="3.20.0";var ji=Ac();Object.defineProperty(K,"Device",{enumerable:!0,get:function(){return ji.Device}});Object.defineProperty(K,"detectDevice",{enumerable:!0,get:function(){return ji.detectDevice}});Object.defineProperty(K,"detectDeviceAsync",{enumerable:!0,get:function(){return ji.detectDeviceAsync}});var gf=mt();Object.defineProperty(K,"parseScalabilityMode",{enumerable:!0,get:function(){return gf.parse}});K.ortc=Ne();K.enhancedEvents=ge();var _f=qc();Object.defineProperty(K,"FakeHandler",{enumerable:!0,get:function(){return _f.FakeHandler}});K.testFakeParameters=Bc()});var Vc=U((v_,qi)=>{"use strict";var vf=Object.prototype.hasOwnProperty,ue="~";function Xr(){}Object.create&&(Xr.prototype=Object.create(null),new Xr().__proto__||(ue=!1));function wf(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function Hc(n,e,t,r,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new wf(t,r||n,s),o=ue?ue+e:e;return n._events[o]?n._events[o].fn?n._events[o]=[n._events[o],i]:n._events[o].push(i):(n._events[o]=i,n._eventsCount++),n}function is(n,e){--n._eventsCount===0?n._events=new Xr:delete n._events[e]}function ie(){this._events=new Xr,this._eventsCount=0}ie.prototype.eventNames=function(){var e=[],t,r;if(this._eventsCount===0)return e;for(r in t=this._events)vf.call(t,r)&&e.push(ue?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};ie.prototype.listeners=function(e){var t=ue?ue+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,i=r.length,o=new Array(i);s<i;s++)o[s]=r[s].fn;return o};ie.prototype.listenerCount=function(e){var t=ue?ue+e:e,r=this._events[t];return r?r.fn?1:r.length:0};ie.prototype.emit=function(e,t,r,s,i,o){var a=ue?ue+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,d,u;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,s),!0;case 5:return c.fn.call(c.context,t,r,s,i),!0;case 6:return c.fn.call(c.context,t,r,s,i,o),!0}for(u=1,d=new Array(l-1);u<l;u++)d[u-1]=arguments[u];c.fn.apply(c.context,d)}else{var p=c.length,f;for(u=0;u<p;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,r);break;case 4:c[u].fn.call(c[u].context,t,r,s);break;default:if(!d)for(f=1,d=new Array(l-1);f<l;f++)d[f-1]=arguments[f];c[u].fn.apply(c[u].context,d)}}return!0};ie.prototype.on=function(e,t,r){return Hc(this,e,t,r,!1)};ie.prototype.once=function(e,t,r){return Hc(this,e,t,r,!0)};ie.prototype.removeListener=function(e,t,r,s){var i=ue?ue+e:e;if(!this._events[i])return this;if(!t)return is(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!s||o.once)&&(!r||o.context===r)&&is(this,i);else{for(var a=0,c=[],l=o.length;a<l;a++)(o[a].fn!==t||s&&!o[a].once||r&&o[a].context!==r)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:is(this,i)}return this};ie.prototype.removeAllListeners=function(e){var t;return e?(t=ue?ue+e:e,this._events[t]&&is(this,t)):(this._events=new Xr,this._eventsCount=0),this};ie.prototype.off=ie.prototype.removeListener;ie.prototype.addListener=ie.prototype.on;ie.prefixed=ue;ie.EventEmitter=ie;typeof qi<"u"&&(qi.exports=ie)});var lg={};Dl(lg,{ACTIVATION_COLD_BOOT_AFTER_MS:()=>Uo,ACTIVATION_DEGRADED_AFTER_MS:()=>No,ACTIVATION_HINT_PATH:()=>mn,ACTIVATION_STILL_AFTER_MS:()=>Oo,ACTIVITY_DOM_EVENTS:()=>vs,ACTIVITY_FIELD:()=>Ji,ACTIVITY_STAMP_MIN_INTERVAL_MS:()=>Ed,ActivationMonitor:()=>xt,App:()=>el,BACKOFF_BASE_MS:()=>kr,BACKOFF_MAX_ATTEMPTS:()=>it,BACKOFF_MAX_MS:()=>At,COLD_BOOT_WHEN_LIVE_TIMEOUT_MS:()=>hn,CaptureController:()=>un,CaptureUnavailableError:()=>ln,ClientTokenError:()=>rt,CreditsClient:()=>dn,CreditsError:()=>wt,CreditsUnauthorizedError:()=>wr,DATA_CHANNEL_MESSAGE_CEILING:()=>gl,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>vo,DEFAULT_GATEWAY_URL:()=>So,DEFAULT_PRODUCE_ACK_TIMEOUT_MS:()=>Pt,DEFAULT_REFERENCE_JPEG_QUALITY:()=>ml,DEFAULT_REFERENCE_MAX_SIZE:()=>fl,DEFAULT_WHEN_LIVE_TIMEOUT_MS:()=>Ws,DERIVED_LEG_SEP:()=>ar,DGRAM_HEADER_BYTES:()=>pe,DOC_LIVE_GATE_TIMEOUT_MS:()=>Ls,ENVELOPE_KIND:()=>se,FOCUS_FIELD:()=>eo,FOREGROUND_COALESCE_MS:()=>Dd,FrameReassembler:()=>pr,GENERATION_TICK_EMIT_INTERVAL_MS:()=>Rd,GENERATION_TICK_MAX_EXTRAPOLATION_MS:()=>Cd,INPUT_PRESENCE_DEFAULT_HZ:()=>ll,INPUT_PRESENCE_FIELD:()=>Co,InvalidDurationError:()=>ct,LEGACY_ACTIVATION_HINT_PATH:()=>gn,PLATFORM_DOC_NAME:()=>Sr,PermanentLockedError:()=>Or,PinRequiresActiveTempError:()=>Mr,PresenceTracker:()=>dr,ProduceAckTimeoutError:()=>Ct,RecordingNotFoundError:()=>Ir,RecordingsClient:()=>dt,RecordingsError:()=>be,RecordingsUnauthorizedError:()=>Mt,RequestAbortError:()=>nt,RequestCancelledError:()=>Et,RequestDocSyncError:()=>Tt,RequestError:()=>Ce,RequestTimeoutError:()=>kt,RetainNotTempError:()=>Lr,RuntimeArtifactNotFoundError:()=>Dr,RuntimeArtifactsClient:()=>Xe,RuntimeArtifactsError:()=>ae,RuntimeArtifactsUnauthorizedError:()=>xr,SIGNALING_PROTOCOL_VERSION:()=>Vi,STREAM_END:()=>vt,Session:()=>_r,SessionAllocationError:()=>q,SessionDirectory:()=>vr,SessionDirectoryError:()=>_e,SessionEndError:()=>oe,SessionEndUnavailableError:()=>Oe,SessionFailedError:()=>Ue,StreamDirectionConflict:()=>Rt,StreamFragmentReassembler:()=>or,TransportNegotiator:()=>fr,TransportSessionMismatchError:()=>st,TransportSessionSignaling:()=>mr,URUN_DEV_ENV:()=>ko,USER_ACTIVITY_FIELD:()=>Zi,USER_ACTIVITY_MIN_INTERVAL_MS:()=>xd,VISIBILITY_FIELD:()=>Xi,WIRE_MESSAGE_BUDGET:()=>_l,WT_CONTROL_FRAME_MAX:()=>ro,WT_DATA_STREAM_VERSION:()=>so,WebRtcSession:()=>gr,WebTransportSession:()=>hr,WtControlDecoder:()=>lr,WtDataStreamParser:()=>on,activationHintFrom:()=>Fs,cameraCaptureAvailable:()=>bl,captureStillFromVideo:()=>Sl,computeBackoffDelay:()=>It,consumeWtDataStreams:()=>Ps,createActivityTracker:()=>ws,createCameraWarp:()=>kl,createClientToken:()=>tl,createCreditsClient:()=>al,createInputPresencePublisher:()=>ul,createRecordingsClient:()=>ca,createRuntimeArtifactsClient:()=>oa,createStore:()=>sl,decodeStreamEnvelope:()=>ds,derivedLegName:()=>_d,derivedLegRole:()=>ps,describeSessionFailure:()=>br,describeSessionPhase:()=>Mo,encodeStreamEnvelope:()=>Zr,encodeStreamFragments:()=>cs,encodeWtControlFrame:()=>Rs,fitWithin:()=>Us,isDurationString:()=>Sn,isPausedPhase:()=>Lo,isPendingRecording:()=>ol,isRetryableSessionError:()=>Tr,isWakingPhase:()=>Be,mediaRecorderChunkSource:()=>ks,normalizeReferenceImage:()=>wl,normalizeRetention:()=>aa,observeLeaveConfirm:()=>Ss,observePageLifecycle:()=>ys,observePageTeardown:()=>bs,parseDgramHeader:()=>ur,prewake:()=>ra,referenceImageErrorMessage:()=>yl,releaseSessionBeacon:()=>Pr,sessionDirectory:()=>Zd,sessionFailureFromMediaError:()=>Io,sharedCaptureController:()=>dl,videoStream:()=>il,watchGenerationTick:()=>_s,whenLive:()=>fn,writeDgramHeader:()=>Es});module.exports=Al(lg);var bt=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let r;try{r=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!r.channel)return;let s=this._handlers.get(r.channel);if(s)for(let i of s)i(r)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r.delete(t),r.size===0&&this._handlers.delete(e)}}emit(e,t){if(this._disposed)return;let r=JSON.stringify({channel:e,...t});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(r);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(r),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},St=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[r,s]of this._handlers)for(let i of s)this._targetUnsubscribes.push(e.on(r,i));let t=this._pendingSends;this._pendingSends=[];for(let r of t)e.emit(r.channel,r.data)}rewriteSessionChannels(e,t){if(e===t)return;let r=`session:${e}:`,s=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(r)?s+o.slice(r.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(r)?s+o.channel.slice(r.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let r=this._handlers.get(e);r||(r=new Set,this._handlers.set(e,r)),r.add(t);let s=this._target?.on(e,t);return s&&this._targetUnsubscribes.push(s),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e),s?.(),s&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==s))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}};var Oe=class extends Error{code="session_end_unavailable";constructor(e="[urun] this session handle cannot terminally end the session; disconnect the viewer instead",t){super(e),this.name="SessionEndUnavailableError",t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends Error{code;httpStatus;requestId;sessionId;constructor(e,t){super(e),this.name="SessionEndError",this.code=t.code??"session_end_failed",this.httpStatus=t.httpStatus,this.requestId=t.requestId,this.sessionId=t.sessionId,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},_e=class extends Error{code;httpStatus;constructor(e,t){super(e),this.name="SessionDirectoryError",this.code=t?.code??"session_directory_failed",this.httpStatus=t?.httpStatus,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},Ce=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},kt=class extends Ce{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},Tt=class extends Ce{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},Rt=class extends Error{stream;owner;attempted;constructor(e,t,r){super(`[urun] stream "${e}" is already produced by the ${t}; this (${r}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=r,Object.setPrototypeOf(this,new.target.prototype)}},Pt=15e3,Ct=class extends Error{kind;stream;timeoutMs;constructor(e,t){let r=t?.timeoutMs??Pt,s=t?.stream??e,i=s!==e?` "${s}"`:"";super(`[urun] SFU did not ack producer ${e}${i} within ${Math.round(r/1e3)}s \u2014 the server never replied to 'produce'. The runtime's inbound port for this stream is likely unadvertised (a cold or capacity-queued runtime), so the SFU has nothing to forward the track to; the published track never reached the runtime.`),this.name="ProduceAckTimeout",this.kind=e,this.stream=s,this.timeoutMs=r,Object.setPrototypeOf(this,new.target.prototype)}},nt=class extends Ce{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},Et=class extends Ce{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}},Il=/^\[urun\] (?:timed out waiting for session allocation at|session allocation wait expired at|session allocation poll failed at|session allocation failed at|session allocation at|session create at) \S+(?::[ \t]+|[ \t]+|$)/;function Ll(n){return n.replace(/\bhttps?:\/\/[^\s)]+/g,"the session gateway")}function Do(n){let e=n.replace(Il,"");return Ll(e||n.replace(/^\[urun\] /,""))}function Ao(n){let e=n.error?.httpStatus;if(e===401||e===403)return"The backend rejected this client \u2014 sign in again or check the auth token / org access.";if(n.error?.code==="session_archived")return"This session is archived \u2014 call directory.unarchive(sessionId) (the session directory's un-archive verb), then reconnect with the same id.";let t=n.error?.retryAfterSeconds,r=t!==void 0?` It asked for ${Math.round(t)}s.`:"";return e===429?`The backend is shedding load \u2014 its admission queue is full, so this is capacity, not your request.${r} The SDK already retried with backoff; try again in a moment.`:e===408?`The request timed out before the backend answered \u2014 that is a timeout, not a verdict on your request.${r} The SDK already retried with backoff; try again in a moment.`:e!==void 0&&e>=500?"The backend is having an outage (nothing is wrong with your request) \u2014 the SDK already retried with backoff, so try again shortly and report the status above if it persists.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."}function br(n,e){let t=e.error?.reason,r=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(n){case"create-failed":{let s=e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:"",i=e.error?.code;return i==="queue_ttl_expired"||i==="stale_poll_expired"?{message:`[urun] the queued session REQUEST timed out while waiting${s} (${i}) \u2014 the session itself is untouched`,hint:"Nothing was lost and nothing needs replacing: connect again with the same session and the control plane re-admits the request (a poll that arrives in time re-drives it on its own)."}:i==="session_archived"?{message:`[urun] this session is archived${s} \u2014 un-archive it before resuming`+(t?`: ${Do(t)}`:""),hint:Ao(e)}:i==="client_release"?{message:`[urun] the session's admission request was closed (client_release)${s} \u2014 this dial cannot attach through it`,hint:"The request row is terminal; retrying the same dial only repeats the 410. Create a fresh session (a new dial). The SDK itself never closes a request \u2014 a whenLive timeout only rejects."}:{message:`[urun] session create failed${s}${t?`: ${Do(t)}`:""}`,hint:Ao(e)}}case"never-live":{let s=r!==void 0?` after ${r}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`,o=e.lastServerStatus!==void 0&&["requested","queued","pending","allocating","provisioning","waking","waiting_for_capacity","unavailable","allocated","starting"].includes(e.lastServerStatus);return e.error?.code==="expired"?o?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before a runtime picked it up${s}${i} \u2014 the backend never dispatched the session (no runtime pulled it), so no media transport could ever connect`,hint:"Not a network problem \u2014 the session was still waiting for a runtime. Retry in a moment; if it persists, the backend dispatch lane is stuck."}:{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${s} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?o?{message:`[urun] session ${e.sessionId} was created but no runtime ever picked it up${s}${i} \u2014 the backend has not dispatched the session yet (a runtime pulls the demand, then the session server exists)`,hint:"Waiting for a runtime \u2014 not a network, VPN, or firewall problem. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] session ${e.sessionId} was created but never went live${s}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${s} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${t?`: ${t}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${t?`: ${t}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"runtime-failed":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} failed at runtime${t?`: ${t}`:""}`,hint:"The session function crashed on the backend \u2014 check the app logs. The session itself is parked, not gone: attach to it again once the app is fixed."};case"produce-timeout":return{message:`[urun] publishing a track timed out${t?`: ${t}`:""} \u2014 the SFU never acked the produce (the runtime\u2019s inbound port for the stream was not advertised in time)`,hint:"The runtime was still cold or the backend was at capacity when the track was published. Retry in a moment; if it persists, the backend never opened the stream to receive it."};case"insufficient-credits":return{message:`[urun] session create refused${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""} \u2014 the org has insufficient credits${t?`: ${t}`:""}`,hint:"Out of credits \u2014 add credits to keep running sessions."}}}var Ue=class extends Error{kind;status;hint;constructor(e,t,r){let{message:s,hint:i}=br(e,t);super(s),this.name="SessionFailedError",this.kind=e,this.status=t,this.hint=i,r?.cause!==void 0&&(this.cause=r.cause),Object.setPrototypeOf(this,new.target.prototype)}};function Io(n,e){if(n instanceof Ue)return n;let t=n instanceof Error?n:new Error(String(n)),r={phase:e?.phase??"idle",transportState:e?.transportState??"disconnected",...e,error:{reason:t.message,code:t.name,kind:"media-permission"}};return new Ue("media-permission",r,{cause:n})}var st=class extends Error{code="transport_session_mismatch";connectedSessionId;requestedSessionId;constructor(e,t){super(`[urun] cannot retarget a connected transport to a different session: this leg is live on ${e??"(unknown)"} but setConnection() asked for ${t} \u2014 disconnect() this leg first (or use a fresh session handle)`),this.name="TransportSessionMismatchError",this.connectedSessionId=e,this.requestedSessionId=t,Object.setPrototypeOf(this,new.target.prototype)}},q=class extends Error{httpStatus;code;balanceCredits;platformStatus;retryAfterSeconds;constructor(e,t){super(e),this.name="SessionAllocationError",this.httpStatus=t?.httpStatus,this.code=t?.code,this.balanceCredits=t?.balanceCredits,this.platformStatus=t?.platformStatus,this.retryAfterSeconds=t?.retryAfterSeconds,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}};function Be(n){if(!n)return!1;let e=typeof n=="string"?n:n.name;return e==="queued"||e==="unavailable"||e==="provisioning"||e==="waiting_for_capacity"}function Lo(n){return n?(typeof n=="string"?n:n.name)==="paused":!1}var Ws=45e3,hn=6e5;function fn(n,e={}){let{signal:t}=e;return new Promise((r,s)=>{if(t?.aborted){s(t.reason instanceof Error?t.reason:new Error("whenLive aborted"));return}if(n.phase?.name==="live"){r();return}if(n.phase?.name==="error"){let w=n.phase,b=n.status??{phase:w.name,transportState:"disconnected",sessionId:w.sessionId,requestId:w.requestId,queue:w.queue,error:w.error,region:w.region};s(new Ue(w.error?.kind??"transport-failed",b));return}let o,a,c=!1,l=w=>{c||(c=!0,a!==void 0&&clearTimeout(a),t?.removeEventListener("abort",d),o?.(),w?s(w):r())},d=()=>{l(t?.reason instanceof Error?t.reason:new Error("whenLive aborted"))};t?.addEventListener("abort",d,{once:!0});let u=()=>{let w=n.phase;return n.status??{phase:w?.name??"idle",transportState:"disconnected",sessionId:w?.sessionId,requestId:w?.requestId,queue:w?.queue,error:w?.error,region:w?.region}},p=w=>l(new Ue(w,u())),f=e.timeout!==void 0,g=Date.now(),h=f?e.timeout:Ws,m=()=>{a!==void 0&&(clearTimeout(a),a=void 0)},_=()=>{if(c||h<=0)return;clearTimeout(a);let w=g+h-Date.now();a=setTimeout(()=>{if(!f&&Be(n.phase?.name)){a=void 0;return}let b=u();b.elapsedMs===void 0&&(b.elapsedMs=h),a=void 0,t?.removeEventListener("abort",d),o?.(),o=void 0,l(new Ue("never-live",b))},Math.max(0,w))},v=w=>{!f||c||h<=0||w?.runtime?.wake?.expectedWakePath==="cold-boot"&&(hn<=h||(h=hn,_()))},S=w=>{if(!c){if(!f&&Be(w?.name)){m();return}if(f){v(w),a===void 0&&h>0&&_();return}a===void 0&&(g=Date.now(),_())}};o=n.onPhase(w=>{w?.name==="live"?l():w?.name==="error"?p(w.error?.kind??"transport-failed"):S(w)}),c||S(n.phase),c&&o()})}function Mo(n){switch(n.name){case"idle":return"Initializing\u2026";case"unavailable":return"Starting the app\u2026";case"queued":return n.queue?`Waiting in queue (position ${n.queue.position} of ${n.queue.depth})\u2026`:n.runtime?.state==="busy"?"All runtimes are busy \u2014 waiting for capacity\u2026":"Waiting for capacity\u2026";case"provisioning":return n.runtime?.state==="starting"?"Starting model\u2026":"Provisioning\u2026";case"waiting_for_capacity":return n.queue?`Waiting for GPU capacity (position ${n.queue.position} of ${n.queue.depth})\u2026`:"Waiting for GPU capacity";case"connecting":return n.reason==="docs_connecting"?"Connecting session data\u2026":"Connecting\u2026";case"degraded":return"The runtime stopped responding \u2014 recovering\u2026";case"live":return"Live";case"paused":return Ml(n.reason);case"error":{if(n.error?.kind==="insufficient-credits")return"Out of credits \u2014 add credits to keep running sessions.";let e=n.error?.kind;if(e){let{message:t,hint:r}=br(e,{phase:n.name,transportState:"disconnected",sessionId:n.sessionId,requestId:n.requestId,queue:n.queue,error:n.error});return`${t.replace(/^\[urun\] /,"")} \u2014 ${r}`}return n.error?.reason?`Session failed \u2014 ${n.error.reason}`:"Session failed"}case"unknown":return n.reason?`Session in an unrecognized state ("${n.reason}") \u2014 the client SDK may be out of date`:"Session in an unrecognized state \u2014 the client SDK may be out of date"}}function Ml(n){switch(n){case"client_ended":return"Paused \u2014 you hung up. Resume any time.";case"client_paused":return"Paused \u2014 you paused it. Resume any time.";case"client_detached":return"Paused \u2014 this device let go. Resume any time.";case"client_gone":return"Paused \u2014 every device disconnected. Resume any time.";case"session_ended":case"ended":case"closed":return"Paused \u2014 the compute was released. Resume any time.";case"idle_timeout":return"Paused \u2014 idle. Resume any time.";case"max_session_age":return"Paused \u2014 reached its maximum length. Resume any time.";case"credits_exhausted":return"Paused \u2014 out of credits. Add credits, then resume.";case"capacity_pressure":return"Paused \u2014 the GPU was reclaimed while the platform was under load. Resume any time.";case"control_plane_release":return"Paused \u2014 the platform reclaimed the compute. Resume any time.";case"superseded":return"Paused \u2014 another client attached. Resume any time.";case"superseded_by_redial":return"Paused \u2014 a newer connection from this session took over. Resume any time.";case"connect_deadline":return"Paused \u2014 the runtime never finished connecting in time. Resume to try again.";case"adoption_expired":return"Paused \u2014 the runtime was assigned but never picked the session up. Resume to try again.";case"media_lane_bind_failed":return"Paused \u2014 the audio/video lane could not be set up. Resume to try again.";case"lease_lost":return"Paused \u2014 the runtime stopped renewing its lease. Resume any time.";case"presence_unconfirmed":return"Paused \u2014 the platform could not confirm anyone was still attached. Resume any time.";case"runtime_inert":case"assignment_unconfirmable":return"Paused \u2014 the runtime never acknowledged its assignment. Resume to try again.";case"runtime_unreachable":return"Paused \u2014 the platform could not reach the runtime. Resume to try again.";case"runtime_silent":return"Paused \u2014 the runtime stopped sending audio/video. Resume to try again.";case"assignment_undelivered":return"Paused \u2014 the assignment never reached a runtime. Resume to try again.";case"dispatch_released":return"Paused \u2014 the worker finished and gave its GPU seat back. Resume any time.";case"dispatch_parked":return"Paused \u2014 the worker finished and parked the session. Resume any time.";case"runtime_swap_exhausted":return"Paused \u2014 the platform ran out of runtimes to try. Resume any time.";case"dispatch_failed":return"Paused \u2014 handing the session to a worker did not succeed. Resume to try again.";default:return n?`Paused \u2014 ${n}. Resume any time.`:"Paused \u2014 resume any time."}}var Oo=15e3,Uo=45e3,No=12e4,Sr="platform",mn="activation",gn="desired.activation";function Fs(n){if(typeof n=="string"&&n.length>0)return n;if(n&&typeof n=="object"){let e=n.note;if(typeof e=="string"&&e.length>0)return e}}var Ol=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],xt=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let r of this._watches.values())this._arm(r)}}else(t?.name==="error"||t?.name==="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 r={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,r),this._hookFirstMediaSignals(r),!r.done&&this._liveAt!==null&&this._arm(r)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=r=>{if(!(!r||e.done)){if(r.muted===!0&&typeof r.addEventListener=="function"){let s=()=>this._firstMedia(e);r.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>r.removeEventListener?.("unmute",s));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",r=>t(r))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of Ol){let r=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);r.unref?.(),e.timers.push(r)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,r){let s={state:t,elapsedMs:r,stream:e.name},i=Fs(this._options.hint());i!==void 0&&(s.hint=i),e.lastEvent=s;for(let o of Array.from(this._handlers))o(s)}};function Qe(){return typeof process<"u"&&process.stdout!=null&&typeof process.stdout.write=="function"}function Je(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function Wo(){return Je()?"Chrome111":void 0}function Fo(){return typeof globalThis.RTCPeerConnection<"u"?null:"the WebRTC peer globals (RTCPeerConnection) are not installed in this runtime"}function Dt(){if(!Je())return Promise.resolve();throw new Error("[urun-sh/core] Node WebRTC transport is not available in the browser build. The browser uses native WebRTC/WebSocket globals; import the Node build to use the werift-backed transport.")}var kr=500,At=15e3,it=6;function It(n,e=Math.random){if(!Number.isFinite(n)||n<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${n}`);let t=Math.min(At,kr*2**n);return Math.round(e()*t)}function Tr(n){if(n instanceof q){let e=n.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return n instanceof Error?n.name==="TypeError"||n.name==="TimeoutError"||n.name==="AbortError":!1}var $o=10,Ul=.5,_n=$o;function $s(){return _n<1?!1:(_n-=1,!0)}function js(){_n=Math.min($o,_n+Ul)}var Nl="session-api.prod.cloud.urun.sh",Wl=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Y(n){return n.trim().replace(/\/+$/,"")}function Er(n,e){let t=[],r=s=>{if(!s)return;let i=Y(s);i&&!t.includes(i)&&t.push(i)};r(n);for(let s of e??[])r(s);for(let s of wu(n))r(s);return t}var Fl="/v1";function wn(n){try{return new URL(Y(n)).pathname===Fl}catch{return!1}}function Pr(n){try{if(typeof fetch!="function")return;let e=Y(n.baseUrl),t=n.sessionId?`${e}/api/sessions/${encodeURIComponent(n.sessionId)}/end`:`${e}/api/session-requests/${encodeURIComponent(n.requestId)}/cancel`;fetch(t,{method:"POST",headers:n.reason!==void 0?{...xe(n,n.jwt),"Content-Type":"application/json"}:xe(n,n.jwt),...n.reason!==void 0?{body:JSON.stringify({reason:n.reason})}:{},keepalive:!0}).catch(()=>{})}catch{}}async function qs(n){try{let e=`${Y(n.baseUrl)}/api/session-requests/${encodeURIComponent(n.requestId)}/cancel`,t=await Pe(n);if(n.getAccessToken&&!t)throw new oe("[urun] session request cancel refused: getAccessToken resolved no token (an unauthenticated cancel is never sent)",{requestId:n.requestId,code:"no_access_token"});let r=await fetch(e,{method:"POST",headers:xe(n,t),keepalive:!0});if((r.status===401||r.status===403)&&n.getAccessToken){let o=await Pe(n,{forceRefresh:!0,reason:"unauthorized"});o&&o!==t&&(r=await fetch(e,{method:"POST",headers:xe(n,o),keepalive:!0}))}let s=await Lt(r);if(!r.ok)throw new oe(`[urun] session request cancel failed: ${bn(s,r.status)}`,{requestId:n.requestId,code:s.error_code,httpStatus:r.status});let i=String(s.status??"");if(i==="cancelled"||i==="canceled"||i==="closed")return{status:"canceled",requestId:n.requestId};if(i==="failed"||i==="rejected"||i==="expired")return{status:"canceled",requestId:n.requestId,platformStatus:i};throw new oe(`[urun] session request cancel returned an unrecognized request status ${JSON.stringify(i)} (recognized: cancelled/canceled, closed, failed, rejected, expired)`,{requestId:n.requestId,code:"invalid_release_response",httpStatus:r.status})}catch(e){throw e instanceof oe?e:new oe("[urun] session request cancel failed",{requestId:n.requestId,cause:e})}}async function Bs(n){let e;try{e=await yn(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/end`,{method:"POST",keepalive:!0},"session end")}catch(a){if(a instanceof oe)throw a;let c=a;throw new oe(c?.message??"[urun] session end request failed",{sessionId:n.sessionId,...c?.code!==void 0?{code:c.code}:{},...c?.httpStatus!==void 0?{httpStatus:c.httpStatus}:{},cause:a})}let t=zs(e)?e:{},r=String(t.status??""),s=typeof t.pause_reason=="string"?t.pause_reason:void 0,i=typeof t.terminal_reason=="string"?t.terminal_reason:void 0,o=Cr(s)?s:Cr(i)?i:void 0;if(r==="paused")return{status:"paused",sessionId:String(t.logical_id??t.id??n.sessionId),...o!==void 0?{reason:o}:{}};throw new oe(`[urun] session end returned ${JSON.stringify(r)} for session ${n.sessionId} \u2014 an end PARKS the session, so the only contract-valid answer is "paused" (a terminal word on this route would be a session-plane terminal write, which is forbidden)`,{sessionId:n.sessionId,code:"invalid_end_response"})}function zo(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var $l=120,jl=1e3,ql=20,Bl=5,Hl=5e3;function Hs(n,e=Date.now()){if(!n)return null;let t=n.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),s=r.padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return typeof i.exp!="number"||!Number.isFinite(i.exp)?null:i.exp*1e3-e}catch{return null}}var Vl=500,Go=1e4,zl=new Set([502,503,504]),Gl=2,Kl=50,jo=1e4;async function qo(n,e){let t=Date.now()+jo;for(;;){await ot(Kl);let r=await Pe(n);if(r)return r;if(Date.now()>=t)throw new q(`[urun] session allocation at ${e} never got an access token: the wired getAccessToken resolved nothing within ${Math.round(jo/1e3)}s (no unauthenticated request was sent)`)}}function Yl(n,e){if(!n)return null;try{let t=new URL(n),r=e?new URL(Y(e)):null,s=t.pathname==="/api/sessions/create"||t.pathname==="/api/sessions/create/";return t.protocol!=="https:"||!s||!Zl(t,r)?null:Y(t.origin)}catch{return null}}function Ql(n,e){if(!n||!n.trim())return{outcome:"absent"};if(!Jl(e))return{outcome:"bootstrap-only"};let t=n.includes("://")?n:`https://${n}`,r;try{r=new URL(t)}catch{return{outcome:"rejected",reason:"not a parseable URL or host"}}return r.protocol!=="https:"?{outcome:"rejected",reason:`scheme ${r.protocol} is not https:`}:r.pathname!=="/"&&r.pathname!==""?{outcome:"rejected",reason:`expected a bare origin, got path ${r.pathname}`}:vn(r.hostname)?{outcome:"pinned",base:Y(r.origin)}:{outcome:"rejected",reason:`host ${r.hostname} is outside the urun.sh trust set`}}function Jl(n){if(!n)return!1;try{let e=new URL(Y(n));return e.protocol==="https:"&&vn(e.hostname)}catch{return!1}}function Xl(n){let e=Y(n);try{return Y(new URL(e).origin)}catch{return e}}function Zl(n,e){return vn(n.hostname)&&(!e||vn(e.hostname))}function vn(n){let e=n.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}function eu(n){let e=n instanceof q?n.retryAfterSeconds:void 0;return e===void 0||!Number.isFinite(e)||e<=0?0:Math.min(e*1e3,At)}function Ko(n,e){let t=eu(e);return t>0?Math.max(n,Date.now()+t):n}async function Yo(n){if(wn(n.baseUrl))return ou(n);let e=Er(n.baseUrl,n.fallbackUrls),t=null,r=0,s=e.length>1;for(let i=0;i<it;i++){for(let o of e)try{let a=await au(o,n,{pollAttempts:$l,retryAfterLimitMs:s?jl:void 0});return js(),a}catch(a){if(t=a instanceof Error?a:new Error(String(a)),r=Ko(r,t),t instanceof Ee||t instanceof at||lu(t))throw t}if(!Tr(t))break;if(i+1<it){if(!$s())break;await ot(Math.max(It(i),r-Date.now()))}}throw t??new Error("[urun] session allocation failed")}var tu=500,ru=9e5,nu=6e4,su=6e5,iu={queued:!0,claimed:!0,starting:!0,retry_pending:!0};async function ou(n){let e=Y(n.baseUrl),t=n.jwt??await n.getAccessToken?.({reason:"background"})??void 0;if(!t)throw new q("[urun] hub allocation requires a client token (jwt or getAccessToken)",{httpStatus:401});let r=await fetch(`${e}/sessions`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({...wn(n.baseUrl)?{shape:n.shape??"cpu:1"}:{resource_class:"cpu"},idempotency_key:n.idempotencyKey,metadata:{app:n.app,function:n.functionName,org:n.orgId,...n.sessionKey?{logical_id:n.sessionKey}:{}}})}),s=await r.text();if(!r.ok)throw new q(`[urun] hub create failed (${r.status}): ${s.slice(0,300)}`,{httpStatus:r.status});let i=JSON.parse(s);n.onRequest?.({requestId:i.session_id,baseUrl:e,sessionId:i.session_id});let o=null;for(;iu[i.state];){let c=Date.now();if(i.state==="queued"||i.state==="retry_pending"){o=null;let d=i.queue_deadline_at===null?null:typeof i.queue_deadline_at=="number"&&i.queue_deadline_at>0?i.queue_deadline_at:c+ru;if(d!==null&&c>=d+nu)throw new q(`[urun] hub session ${i.session_id} is still ${i.state} past the hub's queue deadline (${i.last_error??i.pause_reason??"hub reported no reason"})`,{httpStatus:504,platformStatus:i.state})}else if(o??=c+su,c>=o)throw new q(`[urun] hub session ${i.session_id} stuck ${i.state} past the boot patience window (${i.last_error??"hub reported no reason"})`,{httpStatus:504,platformStatus:i.state});n.onAdmission?.({status:i.state,sessionId:i.session_id}),await ot(tu);let l=await fetch(`${e}/sessions/${encodeURIComponent(i.session_id)}`,{headers:{authorization:`Bearer ${t}`}});if(!l.ok){if(l.status===404)throw new q(`[urun] hub session ${i.session_id} disappeared (${l.status})`,{httpStatus:l.status});continue}i=await l.json()}if(i.state==="failed"||i.state==="completed")throw new q(`[urun] hub session ${i.session_id} reached ${i.state} (${i.last_error??i.terminal_reason??"no reason recorded"})`,{httpStatus:503,platformStatus:i.state});if(i.state==="paused")throw new q(`[urun] hub session ${i.session_id} is parked (${i.pause_reason??i.last_error??"no reason recorded"})`,{httpStatus:503,platformStatus:i.state});if(i.state!=="running"||!i.sfu_endpoint)throw new q(`[urun] hub session ${i.session_id} ended in state=${i.state} without an sfu_endpoint (${i.last_error??i.terminal_reason??"no reason recorded"})`,{httpStatus:504,platformStatus:i.state});let a=Qo(i);if(!a)throw new q(`[urun] hub session ${i.session_id} is running but carried no sfu_attach credential (hub deployment predates lane 52, or HUB_GRANT_SECRET is unset)`,{httpStatus:502,platformStatus:i.state});return{baseUrl:e,sessionId:i.session_id,wsUrl:i.sfu_endpoint,endsAt:null,sfuAttach:a,response:i}}function Qo(n){let e=n.sfu_attach;if(!(!e||typeof e.token!="string"||typeof e.gen!="number"||!Number.isInteger(e.gen)||e.gen<0||e.token.length===0))return{url:n.sfu_endpoint??"",token:e.token,gen:e.gen}}async function Jo(n){let e=Y(n.baseUrl),t=await fetch(`${e}/sessions/${encodeURIComponent(n.sessionId)}`,{headers:n.jwt?{authorization:`Bearer ${n.jwt}`}:{}});if(t.status===401||t.status===403)throw new q(`[urun] hub session view refresh refused (${t.status}) for ${n.sessionId}`,{httpStatus:t.status});if(!t.ok)return null;let r=await t.json();if(r.session_id!==n.sessionId||r.state!=="running"||!r.sfu_endpoint)return null;let s=Qo(r);return s?{url:r.sfu_endpoint,sessionId:r.session_id,sfuAttach:s}:null}async function au(n,e,t){let r,s,i,o,a=Xl(n),c=0,l=new Set,d=Date.now(),u=d+t.pollAttempts*Go,p=!1,f=12e4,g=10080*60,h=S=>{if(typeof S!="number"||!Number.isFinite(S)||S<=0||S>g)return;let w=d+S*1e3+f;w>u&&(u=w,p=!0)},m=()=>p?Number.POSITIVE_INFINITY:t.pollAttempts,_=8,v=0;for(let S=0;S<m();S++){if(p&&Date.now()>=u)throw Rr(a,!!r,o);s=i??await Pe(e),i=void 0,e.getAccessToken&&!s&&(s=await qo(e,a));let w=!!r,b=Date.now(),T;if(r){let F=0,$=G=>{let X=Math.min(At,kr*2**F),he=Math.max(Math.ceil(X/2),It(F));return F+=1,Math.min(Math.max(G,he),Math.max(0,u-Date.now()))};for(;;){let G=u-Date.now();if(G<=0)throw Rr(a,!0,o);let X=Math.max(1,Math.min(ql,Math.floor(G/1e3)));{let Z=Hs(s);if(Z!==null&&Z<X*1e3+Hl)try{let Me=await Pe(e,{forceRefresh:!0});Me&&Me!==s&&(s=Me)}catch{}}b=Date.now();try{T=await fetch(`${a}/api/session-requests/${encodeURIComponent(r)}?wait_s=${X}`,{headers:xe(e,s),redirect:"manual",signal:gu((X+Bl)*1e3)})}catch{let Z=$(0);if(Z<=0)throw Rr(a,!0,o);await ot(Z);continue}if(o=`HTTP ${T.status}`,!zl.has(T.status))break;try{await T.body?.cancel()}catch(Z){throw new at(`[urun] session allocation poll response cleanup failed at ${a}`,{cause:Z})}let he=$(Ho(T,{},t.retryAfterLimitMs));if(he<=0)throw Rr(a,!0,o);await ot(he)}}else T=await fetch(`${a}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...xe(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(cu(e))});if(T.type==="opaqueredirect"||T.status>=300&&T.status<400){try{await T.body?.cancel()}catch{}throw new Ee(`[urun] ${w?"session poll":"session create"} at ${a} answered an HTTP redirect (status ${T.status}) \u2014 browsers cannot follow a cross-origin redirect with credentials; the control plane must emit the JSON redirect envelope ({status:"redirect", location})`)}let y=await Lt(T);if(o=typeof y.status=="string"&&y.status?y.status:`HTTP ${T.status}`,T.status!==401&&T.status!==403&&(v=0),!r&&y.status==="redirect"){let F=Yl(y.location,a);if(!F)throw new q(`[urun] session create at ${a} answered a redirect envelope without a usable location (${JSON.stringify(y.location??null)}) \u2014 refusing to re-issue an authenticated create to an untrusted target`);if(F===a)throw new q(`[urun] session create at ${a} redirected to ITSELF \u2014 control-plane region apex map misconfiguration`);if(c>=Gl)throw new q(`[urun] session create followed ${c} region redirects and was redirected AGAIN (${a} -> ${F}) \u2014 region forward loop, giving up loudly`);c+=1,a=F;continue}if(y.request_id)try{e.onRequest?.({requestId:y.request_id,baseUrl:a,...y.session_id?{sessionId:y.session_id}:{}})}catch{}if(T.ok&&(y.status==="allocated"||!y.status&&!!y.session_id)&&!!y.session_id){let F=y.session_id,$=Ql(y.session_api_base,a);if($.outcome==="rejected")throw new Ee(`[urun] gateway allocated session ${y.session_id} with an unusable session_api_base (${JSON.stringify(y.session_api_base)}): ${$.reason} \u2014 refusing to pin the session to a region it may not belong to`);if($.outcome==="pinned"&&$.base!==a&&(a=$.base,y.request_id))try{e.onRequest?.({requestId:y.request_id,baseUrl:a,...y.session_id?{sessionId:y.session_id}:{}})}catch{}let G=na(y.ws_url,a,F,"gateway allocated session");return{baseUrl:a,sessionId:F,wsUrl:G,endsAt:zo(y.ends_at),response:y}}if(T.status===202||y.status==="pending"||y.status==="queued"||y.queued){if(r=y.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(h(y.effective_max_queue_time_s),e.onAdmission)try{e.onAdmission(mu(y,r))}catch{}let F=Date.now()-b<Vl;w&&F&&await ot(Ho(T,y,t.retryAfterLimitMs));continue}if((T.status===401||T.status===403)&&e.getAccessToken&&y.error_code!=="session_name_not_yours"){let F=s??"";if(l.add(F),p&&(v+=1,v>_))throw new at(`[urun] session allocation failed at ${a}: authorization refused ${_} consecutive refreshes while the admission wait was extended (last server status: ${o??"none received"}) \u2014 the token provider keeps minting fresh tokens the control plane rejects`,{httpStatus:T.status,code:y.error_code,platformStatus:y.status});let $=await Pe(e,{forceRefresh:!0,reason:"unauthorized"});if($&&!l.has($)){i=$;continue}if($===void 0){let G=await qo(e,a);if(!l.has(G)){i=G;continue}}}let N=bn(y,T.status),Q=y.error_code??(T.status===402?"insufficient_credits":void 0),te=w?at:q;throw new te(`[urun] session allocation failed at ${a}: ${N}`,{httpStatus:T.status,code:Q,balanceCredits:typeof y.balance_credits=="number"?y.balance_credits:void 0,platformStatus:y.status,retryAfterSeconds:Ks(T,y)})}throw Rr(a,!!r,o)}function Rr(n,e=!1,t){let r=e?at:q;return new r(`[urun] session allocation wait expired at ${n} \u2014 the CLIENT-side wait budget elapsed (last server status: ${t??"none received"}; the gateway reported no failure)`)}function xe(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function Pe(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function cu(n){let e=n.priority==="preempt";return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey,...n.sessionKey&&!e?{logical_id:n.sessionKey}:{},...n.concurrencyKey&&!e?{concurrency_key:n.concurrencyKey}:{},...n.label&&!n.sessionKey?{label:n.label}:{},...e?{priority:"preempt"}:{},...n.sharedApp?{shared_app:!0}:{}}}async function yn(n,e,t,r){let s=await Pe(n);if(n.getAccessToken&&!s)throw new _e(`[urun] ${r} refused: getAccessToken resolved no token (an unauthenticated request is never sent)`,{code:"no_access_token"});let i=Er(n.baseUrl,n.fallbackUrls),o;for(let a of i){let c=`${Y(a)}${e}`,l=p=>fetch(c,{method:t.method,headers:t.body!==void 0?{...xe(n,p),"Content-Type":"application/json"}:xe(n,p),...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...t.keepalive?{keepalive:!0}:{}}),d;try{if(d=await l(s),(d.status===401||d.status===403)&&n.getAccessToken){let p=await Pe(n,{forceRefresh:!0,reason:"unauthorized"});p&&p!==s&&(d=await l(p))}}catch(p){o=p;continue}let u=await Lt(d);if(!d.ok)throw new _e(`[urun] ${r} failed: ${bn(u,d.status)}`,{code:u.error_code,httpStatus:d.status});return u}throw new _e(`[urun] ${r} request failed`,{cause:o})}async function Xo(n){let e=new URLSearchParams;n.app&&e.set("app",n.app),n.functionName&&e.set("function",n.functionName),n.includeArchived&&e.set("include_archived","true"),n.limit!==void 0&&e.set("limit",String(n.limit)),n.cursor&&e.set("cursor",n.cursor);let t=e.toString(),r=await yn(n,`/api/sessions${t?`?${t}`:""}`,{method:"GET"},"session list");if(!Array.isArray(r?.sessions))throw new _e("[urun] session list returned no `sessions` array \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_response"});return{rows:r.sessions,nextCursor:r.next_cursor??null}}async function Vs(n){let e=n.archived?"archive":"unarchive";await yn(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/${e}`,{method:"POST"},`session ${e}`)}async function Zo(n){await Bs(n)}async function ea(n){let e=n.name.trim();if(e.length===0)throw new _e("[urun] session name refused: a name is required (an empty name is not a rename)",{code:"invalid_session_name"});await yn(n,`/api/sessions/${encodeURIComponent(n.sessionId)}/name`,{method:"POST",body:{name:e,...n.source?{source:n.source}:{}}},"session name")}async function ta(n){let e=Er(n.baseUrl,n.fallbackUrls),t=null,r=0;for(let s=0;s<it;s++){for(let i of e)try{let o={baseUrl:i,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},a=`${Y(i)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,c=await Pe(o);if(n.getAccessToken&&!c)throw new q(`[urun] viewer-connect for ${n.sessionId} refused: getAccessToken resolved no token (an unauthenticated viewer-connect is never sent)`);let l=await fetch(a,{headers:xe(o,c)});if((l.status===401||l.status===403)&&n.getAccessToken){let p=await Pe(o,{forceRefresh:!0,reason:"unauthorized"});p&&p!==c&&(l=await fetch(a,{headers:xe(o,p)}))}if(!l.ok){let p=await Lt(l);throw new q(`[urun] viewer-connect for ${n.sessionId} failed: `+bn(p,l.status),{httpStatus:l.status,retryAfterSeconds:Ks(l,p)})}let d=await Lt(l),u=na(d.ws_url,i,n.sessionId,"viewer-connect");return js(),{baseUrl:Y(i),sessionId:n.sessionId,wsUrl:u,endsAt:zo(d.ends_at),response:d}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),r=Ko(r,t),t instanceof Ee)throw t}if(!Tr(t))break;if(s+1<it){if(!$s())break;await ot(Math.max(It(s),r-Date.now()))}}throw t??new Error("[urun] viewer-connect failed")}async function ra(n){try{let e=Y(n.baseUrl),t=await Pe(n);if(n.getAccessToken&&!t)return{status:"unavailable"};let r=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...xe(n,t),"Content-Type":"application/json"},body:JSON.stringify({app:n.app,function:n.functionName})});if(r.status===404)return{status:"unknown-app"};if(!r.ok)return{status:"unavailable"};let s=await Lt(r),i={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(i.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(i.warmCapable=s.warm_capable),i}catch(e){return Qe()?console.warn("[urun] prewake failed (advisory, ignored):",e):console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function Lt(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function bn(n,e){let t=n.error_code,r=n.error_message||n.message||n.error,s=t&&r&&r!==t?`${t}: ${r}`:r||t;return s?`${s} (HTTP ${e})`:`HTTP ${e}`}var du=new Set([400,402,409]);function lu(n){return n instanceof q&&n.httpStatus!==void 0&&du.has(n.httpStatus)}var uu=new Set(["capture-attested","no-portable-golden","portable-golden-release-mismatch","portable-golden-attestation-invalid"]);function zs(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Cr(n){return typeof n=="string"&&n.trim().length>0}function Bo(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}function pu(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0}function hu(n){if(zs(n)&&!(!Cr(n.snapshot_id)||!Cr(n.snapshot_compat_key)||!Bo(n.artifact_size_bytes)||!Bo(n.durable_arena_bytes)||n.volatile_arena_bytes!==0||!pu(n.uncovered_weight_bytes)))return{snapshotId:n.snapshot_id,snapshotCompatKey:n.snapshot_compat_key,artifactSizeBytes:n.artifact_size_bytes,durableArenaBytes:n.durable_arena_bytes,volatileArenaBytes:0,uncoveredWeightBytes:n.uncovered_weight_bytes}}function fu(n){if(!zs(n)||n.schema!=="urun.runtime.wake.v1"||n.portability!=="portable"&&n.portability!=="none"||n.expected_wake_path!=="portable-golden-restore"&&n.expected_wake_path!=="cold-boot"||typeof n.reason_code!="string"||!uu.has(n.reason_code)||n.expectation_basis!=="snapshot-registry"||n.restore_observation!=="not-observed")return;let e=n.reason_code;if(n.portability==="portable"&&n.expected_wake_path==="portable-golden-restore"&&e==="capture-attested"){let t=hu(n.golden);return t?{schema:"urun.runtime.wake.v1",portability:"portable",expectedWakePath:"portable-golden-restore",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed",golden:t}:void 0}if(n.portability==="none"&&n.expected_wake_path==="cold-boot"&&e!=="capture-attested"&&n.golden===void 0)return{schema:"urun.runtime.wake.v1",portability:"none",expectedWakePath:"cold-boot",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed"}}function Gs(n){if("serving_region"in n)return typeof n.serving_region=="string"&&n.serving_region.length>0?n.serving_region:null}function mu(n,e){let r={status:typeof n.status=="string"&&n.status.length>0?n.status:n.queued?"queued":"pending",requestId:e};Cr(n.session_id)&&(r.sessionId=n.session_id);let s=Gs(n);s!==void 0&&(r.region=s),typeof n.runtime_ready=="boolean"&&(r.runtimeReady=n.runtime_ready),(n.runtime_status==="unbound"||n.runtime_status==="starting"||n.runtime_status==="ready")&&(r.runtimeStatus=n.runtime_status),typeof n.reason=="string"&&n.reason.length>0&&(r.reason=n.reason),typeof n.decision_reason=="string"&&n.decision_reason.length>0&&(r.decisionReason=n.decision_reason),typeof n.provisioning_refusal_source=="string"&&n.provisioning_refusal_source.length>0&&(r.refusalSource=n.provisioning_refusal_source),typeof n.provisioning_refusal_message=="string"&&n.provisioning_refusal_message.length>0&&(r.refusalMessage=n.provisioning_refusal_message),typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(r.queue={position:n.queue_position,depth:n.queue_depth});let i=n.runtime_state;if(i==="unavailable"||i==="starting"||i==="busy"){r.runtime={state:i},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(r.runtime.reason=n.runtime_reason);let o=fu(n.runtime_wake);o&&(r.runtime.wake=o)}return r}function Ks(n,e){let t=Number(n.headers.get("Retry-After")||""),r=Number(e.retry_after_seconds??t);return Number.isFinite(r)&&r>0?r:void 0}function Ho(n,e,t){let r=Ks(n,e),s=t??Go;return r!==void 0?Math.min(r*1e3,s):1e3}function ot(n){return new Promise(e=>setTimeout(e,n))}function gu(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var Ee=class extends Error{},at=class extends q{};function na(n,e,t,r){if(!n)throw new Ee(`[urun] ${r} ${t} without ws_url`);let s,i;try{s=new URL(n)}catch{throw new Ee(r==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${t}`:`[urun] ${r} ${t} with non-absolute ws_url`)}try{i=new URL(Y(e))}catch{throw new Ee(`[urun] ${r} ${t} has invalid gateway base URL`)}let o=_u(i.hostname)&&i.protocol==="http:";if(!(o&&s.protocol==="ws:"||s.protocol==="wss:"))throw new Ee(`[urun] ${r} ${t} with insecure ws_url`);if(!vu(s,i,o))throw new Ee(`[urun] ${r} ${t} with cross-origin ws_url`);return s.toString()}function _u(n){return n==="localhost"||n==="127.0.0.1"||n==="::1"||n.endsWith(".localhost")}function vu(n,e,t){return!!(t||n.hostname===e.hostname&&n.port===e.port||Vo(n.hostname)&&Vo(e.hostname))}function Vo(n){return n==="urun.sh"||n.endsWith(".urun.sh")}function wu(n){try{return new URL(n).hostname!==Nl?[]:Wl}catch{return[]}}var ae=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},xr=class extends ae{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Dr=class extends ae{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function Ar(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function oa(n){return new Xe(n)}var Xe=class{_options;constructor(e){this._options=e}async list(e){let r=ia(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new ae("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(sa)}async getDownloadUrl(e,t){let r=ia(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!bu(s))throw new ae("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:sa(r.artifact),downloadUrl:s}}async _request(e,t){let r=Er(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of r)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof ae&&Su(s.status))throw s}throw s??new ae("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${Y(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:c}=await this._readError(o,e);throw ku(o.status,a,c)}try{return await o.json()}catch(a){throw new ae(`[urun] runtime artifacts: invalid JSON response from ${Y(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let r=Y(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function sa(n){if(!n||typeof n!="object")throw new ae("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=He(e,"artifact_id")||He(e,"id"),r=He(e,"filename"),s=He(e,"kind"),i=He(e,"status")||"ready",o=yu(e,"size_bytes"),a=He(e,"sha256");if(!t||!r||!s||o==null||!a)throw new ae("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:He(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:He(e,"created_at"),expiresAt:He(e,"expires_at")}}function He(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function yu(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function bu(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function Su(n){return n===401||n===403}function ku(n,e,t){return n===401?new xr(t,e):n===404?new Dr(t,e):new ae(t,n,e)}function ia(n){if(!n||typeof n!="object"||Array.isArray(n))throw new ae("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var be=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)}},Mt=class extends be{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Ir=class extends be{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Lr=class extends be{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)}},Mr=class extends be{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)}},Or=class extends be{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)}},ct=class extends be{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function Sn(n){return/^(\d+[smhdw])+$/.test(n)}function aa(n){if(n==="pin")return{action:"pin"};if(Sn(n))return{action:"retain",duration:n};throw new ct(`[urun] recordings: "${n}" is not a duration or "pin"`)}function Tu(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new Mt(r,e??"unauthorized");if(n===404)return new Ir(r,e??"not_found");if(n===400)return new ct(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new Lr(r,e);case"pin_requires_active_temp":return new Mr(r,e);case"permanent_locked":return new Or(r,e)}return new be(r,{status:n,code:e??`http_${n}`})}var dt=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!Sn(t))throw new ct(`[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 be("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,r.body))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw Tu(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let i={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new Mt("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function ca(n){return new dt(n)}var gd=Ns(bi());var Bi=Ns(Vc(),1);var zc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function yf(n){let e=globalThis.crypto,t=new Uint8Array(n);if(e?.getRandomValues)return e.getRandomValues(t),t;for(let r=0;r<n;r++)t[r]=Math.floor(Math.random()*256);return t}function sr(n=16){let e=yf(n),t="";for(let r=0;r<n;r++)t+=zc[e[r]%zc.length];return t}function Kc(n){return`stream:${n}`}var Yc="urun-stream-v1";var Hi=1,se={BINARY:0,TEXT:1,JSON:2,END:3,CHUNK:4},ir=2,Gc=253952,bf=[se.BINARY,se.TEXT,se.JSON],vt=Symbol("urun:stream:end");function Zr(n){if(n===vt)return Uint8Array.from([Hi,se.END]);let{kind:e,body:t}=Qc(n);return os(e,t)}function Qc(n){return n instanceof Uint8Array?{kind:se.BINARY,body:n}:n instanceof ArrayBuffer?{kind:se.BINARY,body:new Uint8Array(n)}:typeof n=="string"?{kind:se.TEXT,body:new TextEncoder().encode(n)}:{kind:se.JSON,body:new TextEncoder().encode(JSON.stringify(n))}}function os(n,e){let t=new Uint8Array(ir+e.length);return t[0]=Hi,t[1]=n,t.set(e,ir),t}function cs(n){if(n===vt)return[Zr(n)];let{kind:e,body:t}=Qc(n);if(t.length+ir<=Gc)return[os(e,t)];let r=Gc-ir,s=[],i=0;for(;t.length-i>r;)s.push(os(se.CHUNK,t.subarray(i,i+r))),i+=r;return s.push(os(e,t.subarray(i))),s}function ds(n){let{kind:e,body:t}=Jc(n);if(e===se.CHUNK)throw new Error("[urun] CHUNK envelope requires StreamFragmentReassembler (oversized payload)");return as(e,t)}function Jc(n){let e=n instanceof Uint8Array?n:new Uint8Array(n);if(e.length<ir||e[0]!==Hi)throw new Error(`[urun] bad stream envelope (version=${e[0]}, len=${e.length})`);return{kind:e[1],body:e.subarray(ir)}}function as(n,e){switch(n){case se.BINARY:return e.slice();case se.TEXT:return new TextDecoder().decode(e);case se.JSON:return JSON.parse(new TextDecoder().decode(e));case se.END:return vt;default:throw new Error(`[urun] unknown stream envelope KIND 0x${n.toString(16)}`)}}var or=class{_chunks=[];_bufferedLength=0;feed(e){let{kind:t,body:r}=Jc(e);if(t===se.CHUNK){this._chunks.push(r.slice()),this._bufferedLength+=r.length;return}if(bf.includes(t)){if(this._chunks.length===0)return as(t,r);let s=new Uint8Array(this._bufferedLength+r.length),i=0;for(let o of this._chunks)s.set(o,i),i+=o.length;return s.set(r,i),this._chunks=[],this._bufferedLength=0,as(t,s)}if(this._chunks.length>0)throw this._chunks=[],this._bufferedLength=0,new Error(`[urun] stream envelope KIND 0x${t.toString(16)} arrived mid-fragment-sequence; discarding partial payload`);return as(t,r)}};function Xc(n){return{get consumerId(){return n.consumerId},onData(e,t){return n.onStreamData(e,t)},sendData(e,t,r){return n.sendStreamData(e,t,r)}}}var Zc=[1e3,2e3,4e3,8e3,3e4],ed=5,Sf=15e3,ls=[250,500,1e3,2e3,4e3],kf=3e4,Tf={4401:!0,4403:!0};function td(n){let e=n?.dialCloseCode;return e!==void 0&&Tf[e]===!0}var rd={closed:!0,released:!0,releasing:!0,reaped:!0,expired:!0,superseded:!0,cancelled:!0,canceled:!0,max_session_age:!0},Rf=15e3,nd=15e3,sd=15e3,Cf=2e3,Ef=6e3,Pf=2e3,xf=300,id=4e3,Df=2,Af=750,od=3,us=[1e3,2e3,4e3],If=15e3;var ar="--",Lf=["video","audio"];function ps(n){let e=n.lastIndexOf(ar);if(e<=0)return;let t=n.slice(e+ar.length);return Lf.includes(t)?t:void 0}function _d(n,e){return`${n}${ar}${e}`}var Vi="v1";function Mf(n,e){return n.name!==e.name||n.reason!==e.reason||n.sessionId!==e.sessionId||n.requestId!==e.requestId||n.wakingSince!==e.wakingSince||n.region!==e.region||(n.endsAt?.getTime()??null)!==(e.endsAt?.getTime()??null)||n.queue?.position!==e.queue?.position||n.queue?.depth!==e.queue?.depth||n.runtime?.state!==e.runtime?.state||n.runtime?.reason!==e.runtime?.reason||n.runtime?.wake!==e.runtime?.wake?!1:n.error?.reason===e.error?.reason&&n.error?.code===e.error?.code&&n.error?.kind===e.error?.kind&&n.error?.httpStatus===e.error?.httpStatus&&n.error?.retryAfterSeconds===e.error?.retryAfterSeconds}var ad={requested:"provisioning",queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",waking:"provisioning",waiting_for_capacity:"waiting_for_capacity",allocated:"connecting",connecting:"connecting",establishing:"connecting",live:"live",running:"live",degraded:"degraded","no-runtime":"degraded",paused:"paused",error:"error",failed:"error",rejected:"error",expired:"paused",cancelled:"paused",canceled:"paused",closed:"paused",releasing:"paused",released:"paused",reaped:"paused",superseded:"paused"};function cd(n){return Object.prototype.hasOwnProperty.call(ad,n)?{phase:ad[n],unknown:!1}:{phase:"unknown",unknown:!0}}function Of(n){return n==="queued"||n==="pending"}function dd(n){return n==="credits_exhausted"}var ld=3,ud=4e3,pd=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}];function hd(n){if(!n)return;let e=/\/(?:ws\/)?rtc\/([^/?#]+)/.exec(n);if(e)try{return decodeURIComponent(e[1])}catch{return e[1]}}var cr=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Bi.default;_ws=null;_connectedUrl=null;_device=null;_mediaUnavailableReason=null;_mediaVerdictResolve;_mediaVerdict=new Promise(e=>{this._mediaVerdictResolve=e});_recvTransport=null;_pendingConsumeData=[];_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_publishedAudio=null;_publishedVideo=null;_wtMicUplink=null;_wtCamUplink=null;_wtDataUpSender=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_reconnectExhaustedWarned=!1;_intentionalDisconnect=!1;_reconnectTimer=null;_cancelPendingDial=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_connectionViewRefresher=null;_recvIceRestartAttempts=0;_recvIceRestartTimer=null;_sendIceRestartAttempts=0;_sendIceRestartTimer=null;_phase={name:"idle"};_requestId;_liveReached=!1;_lastServerStatus;_endsAt=null;_forceResolveOnNextConnect=!1;_connectStartedAt;_wakingSince;_mediaProbeTimer=null;_statsTimer=null;_statsSampleInFlight=!1;_joinProbes=new Map;_decodeDeathHandled=!1;_selectedCandidatePair=wd();_reportedCandidatePairKey=null;_candidatePairRefreshSeq=0;_diagnosticSinkFailed=!1;_currentEpoch=0;_selfEpochAdoptUntil=0;_pausedIncarnation=null;_consumerId=null;_streamDataHandlers=new Map;_streamDataLane="sctp";_dataProducers=new Map;_dataProducerPromises=new Map;_dataConsumers=new Map;_pendingDataProduce=new Map;_sendTransportWaiters=[];get consumerId(){return this._consumerId===null&&(this._consumerId=Uf()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get isProducingMedia(){let e=r=>r!==null&&!r.closed&&!r.paused,t=(r,s)=>r!==null&&s!==null&&s.track.readyState!=="ended"&&r.deliveredDatagrams()>0;return e(this._audioProducer)||e(this._videoProducer)||t(this._wtMicUplink,this._publishedAudio)||t(this._wtCamUplink,this._publishedVideo)}get endsAt(){return this._endsAt}setEndsAt(e){this._endsAt=e}seedRegion(e){e!==void 0&&this._setPhase(this._phase.name,{reason:this._phase.reason,queue:this._phase.queue,runtime:this._phase.runtime,error:this._phase.error,region:e})}_pastDeadline(){return this._endsAt!==null&&Date.now()>=this._endsAt.getTime()}get status(){let e={phase:this._phase.name,transportState:this._state};return this._sessionId&&(e.sessionId=this._sessionId),this._requestId&&(e.requestId=this._requestId),this._lastServerStatus!==void 0&&(e.lastServerStatus=this._lastServerStatus),this._connectStartedAt!==void 0&&(e.elapsedMs=Date.now()-this._connectStartedAt),this._endsAt!==null&&(e.endsAt=this._endsAt),this._phase.queue&&(e.queue=this._phase.queue),this._phase.runtime&&(e.runtime=this._phase.runtime),this._phase.wakingSince!==void 0&&(e.wakingSince=this._phase.wakingSince),this._phase.error&&(e.error=this._phase.error),this._phase.region!==void 0&&(e.region=this._phase.region),e}get region(){return this._phase.region}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws!==null&&this._ws.readyState===WebSocket.OPEN}signalingOpen(){return this.isOpen}onWtOnlyLegDeath(e){return this._wtOnlyLegDeath=e,()=>{this._wtOnlyLegDeath===e&&(this._wtOnlyLegDeath=null)}}_wtOnlyLegDeath=null;get connectedUrl(){return this._connectedUrl}get intentionalDisconnect(){return this._intentionalDisconnect}getTrackByName(e){if(ps(e)!==void 0)return;let t=this._tracksByName.get(e);if(t&&t.readyState!=="ended")return t;for(let r of this._tracks.values())if(!(r.kind!==e||r.readyState==="ended")&&this._streamNameOf(r)===void 0)return r;return t}_streamNameOf(e){for(let[t,r]of this._tracksByName)if(r===e)return t}setAuth(e){this._options={...this._options,...e},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(e){this._options=e??{url:""},e?.sessionId&&(this._sessionId=e.sessionId)}setConnection(e){if(this.isOpen){let t=hd(e.url);if(e.sessionId!==void 0&&e.sessionId!==this._sessionId)throw new st(this._sessionId,e.sessionId);if(t!==void 0&&t!==this._sessionId)throw new st(this._sessionId,t);this._options={...this._options,...e};return}this._options={...this._options,...e},e.sessionId&&(this._sessionId=e.sessionId)}setConnectionResolver(e){this._resolveConnection=e}setConnectionViewRefresher(e){this._connectionViewRefresher=e}applyControlDocState(e){let t=e&&typeof e=="object"?e.session:void 0,r=qf(t);if(r!==void 0&&this.setIncarnation(r),!t||typeof t!="object")return;let s=t,i=typeof s.status=="string"?s.status:void 0;if(i&&!this.isStaleClosedMarker(s)){if(i==="error"){let o=s.error_reason??s.errorReason,a=typeof o=="string"&&o?o:"session failed";this._setPhase("error",{error:{reason:a,code:"runtime-failed",kind:"runtime-failed"}})}else if(i==="closed"||i==="ended"||i==="paused"){let o=s.close_reason??s.closeReason??s.pause_reason??s.pauseReason;if(dd(o)){this._setPhase("paused",{reason:"credits_exhausted"});return}if(this._pastDeadline()){this._setPhase("paused",{reason:"max_session_age"});return}this._setPhase("paused",{reason:typeof o=="string"&&o?o:i})}}}setIncarnation(e){if(!Number.isFinite(e)||e<=this._currentEpoch)return;let t=this._currentEpoch>0,r=this._state==="connected";this._currentEpoch=e;let i=this._selfEpochAdoptUntil>0&&Date.now()<=this._selfEpochAdoptUntil;this._selfEpochAdoptUntil=0,!i&&t&&r&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(e){return Number.isFinite(e)?e<this._currentEpoch:!1}isStaleClosedMarker(e){if(!e)return!1;let t=typeof e.status=="string"?e.status:void 0;if(t!=="closed"&&t!=="ended"&&t!=="paused"&&t!=="error")return!1;let r=e.status_epoch??e.statusEpoch,s=typeof r=="number"?r:Number(r);return Number.isFinite(s)?s<this._currentEpoch:!1}_isStaleLivenessEvidence(){return this._phase.name!=="paused"||this._pausedIncarnation===null?!1:this._currentEpoch<=this._pausedIncarnation}async connect(e){if(this.isOpen&&this._state==="connected"&&!this._intentionalDisconnect){e!==void 0&&(this._lastStartOptions=e);return}this._lastStartOptions=e,this._intentionalDisconnect=!1,this._pausedIncarnation=null,this._connectStartedAt??=Date.now(),this._cancelPendingDial?.(new Error("TransportSession: connect superseded by a newer connect()"));let t=++this._generation,r=this._state==="reconnecting"||this._state==="renegotiating";r||this._setState("connecting");let s=null,i=()=>t!==this._generation||this._intentionalDisconnect,o=()=>{if(i())throw new Error("TransportSession: connect cancelled")},a=async()=>{for(let d of this._connectUrls()){o();try{return await this._connectOnce(d,t,e),!0}catch(u){s=u instanceof Error?u:new Error(String(u)),i()||this._cleanupSocket()}}return!1},c=this._forceResolveOnNextConnect&&this._resolveConnection!==null;if(this._forceResolveOnNextConnect=!1,c){let d=this._resolveConnection;for(let u=0;d&&u<od;u++){this._setState("reconnecting"),await en(us[Math.min(u,us.length-1)]),o();try{let p=await d();o(),this.setAuth({jwt:p.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:p.url,sessionId:p.sessionId,iceServers:p.iceServers??this._options.iceServers}),p.endsAt!==void 0&&(this._endsAt=p.endsAt)}catch(p){if(i())throw new Error("TransportSession: connect cancelled");s=p instanceof Error?p:new Error(String(p));continue}if(await a())return;if(s&&td(s))break}}else{let d=Date.now()+kf,u=0,p=0,f=0;for(;;){if(o(),await a())return;if(s&&td(s))break;p++,o();let g=null;if(this._connectionViewRefresher)try{g=await this._connectionViewRefresher(),o()}catch(m){if(i())throw new Error("TransportSession: connect cancelled");s=m instanceof Error?m:new Error(String(m))}if(g){if(Date.now()>=d)break;this.setAuth({jwt:g.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:g.url,sessionId:g.sessionId,iceServers:g.iceServers??this._options.iceServers,...g.sfuAttach?{sfuAttach:g.sfuAttach}:{}}),await en(ls[Math.min(u++,ls.length-1)]);continue}let h=this._resolveConnection?Df:1;if(p<h){await en(Af);continue}if(this._resolveConnection&&f<od){this._setState("reconnecting"),await en(us[Math.min(f,us.length-1)]),o(),f++;try{let m=await this._resolveConnection();o(),this.setAuth({jwt:m.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:m.url,sessionId:m.sessionId,iceServers:m.iceServers??this._options.iceServers}),m.endsAt!==void 0&&(this._endsAt=m.endsAt)}catch(m){if(i())throw new Error("TransportSession: connect cancelled");s=m instanceof Error?m:new Error(String(m));continue}continue}if(this._resolveConnection||Date.now()>=d)break;await en(ls[Math.min(u++,ls.length-1)])}}if(i())throw s??new Error("TransportSession: connect cancelled");this._setState("failed");let l=s??new Error("TransportSession: connect failed");throw r||this._emitError(l),l}leaveLeg(){if(!this.isOpen)return!1;this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null);try{this._send({type:"leave"})}catch{}try{this._ws?.close()}catch{}return!0}disconnect(e="client_detached"){this._generation+=1,this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._cancelPendingDial?.(new Error("TransportSession: connect cancelled by disconnect()")),this._stopMediaProbe(),this._stopStatsSampler(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0;try{this._publishedAudio?.track.stop()}catch{}try{this._publishedVideo?.track.stop()}catch{}if(this._publishedAudio=null,this._publishedVideo=null,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let t of this._consumers.values())try{t.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._settleSendTransportWaiters(null,new Error("[urun] sendStreamData: transport disconnected before the send transport arrived")),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}this._pendingConsumeData=[],this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce.reject(new Error("TransportSession: disconnected")),this._pendingProduce=null),this._device=null,this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null),this._cleanupSocket(),this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("paused",{reason:e}),this._emitter.emit("disconnected")}on(e,t){return this._emitter.on(e,t),()=>{this._emitter.off(e,t)}}_emitDiagnostic(e){let t=this._options.diagnosticSink;if(t)try{t(e)}catch(r){this._diagnosticSinkFailed||(this._diagnosticSinkFailed=!0,console.warn(`[urun] diagnosticSink threw (${String(r instanceof Error?r.message:r)}) \u2014 further diagnostics ride only the structured 'diagnostic' event`))}else e.level==="debug"?Qe()?console.warn(`[urun] ${e.message}`,e.detail??{}):console.debug(`[urun] ${e.message}`,e.detail??{}):e.level==="error"?console.error(`[urun] ${e.message}`,e.detail??{}):console.warn(`[urun] ${e.message}`,e.detail??{});this._emitter.emit("diagnostic",e)}sendInput(e,t){this._send({type:"input",data:e,sequence:t})}sendSignal(e){return this._send(e)}onSignal(e){return this.on("signal",e)}emitDiagnostic(e){this._emitDiagnostic(e)}onStreamData(e,t){let r=this._streamDataHandlers.get(e);return r||(r=new Set,this._streamDataHandlers.set(e,r)),r.add(t),()=>{let s=this._streamDataHandlers.get(e);s?.delete(t),s&&s.size===0&&this._streamDataHandlers.delete(e)}}sendStreamData(e,t,r){try{this._requireMediaSupport("sendStreamData")}catch(s){return Promise.reject(s)}return this._wtDataUpSender?this._wtDataUpSender.send(e,Zr(t)):this._ensureDataProducer(e).then(s=>{for(let i of cs(t))s.send(i)})}get wtDataUplinkSeam(){return{onUplink:e=>{this._wtDataUpSender=e},onUplinkLost:(e,t)=>{if(this._wtDataUpSender&&!(t&&this._wtDataUpSender!==t)){if(this._wtDataUpSender=null,!this._sendTransport){console.warn(`[urun-sh/core] WT data uplink lost (${e}) with NO WebRTC send transport \u2014 there is no SCTP to revert to; failing the WT leg so the re-dial ladder re-establishes it`),this._wtOnlyLegDeath?.(e);return}console.warn(`[urun-sh/core] WT data uplink lost (${e}) \u2014 data-up reverts to SCTP for this leg`)}}}}_awaitSendTransport(){return this._sendTransport?Promise.resolve(this._sendTransport):new Promise((e,t)=>{let r={resolve:i=>{clearTimeout(s),e(i)},reject:i=>{clearTimeout(s),t(i)}},s=setTimeout(()=>{let i=this._sendTransportWaiters.indexOf(r);i>=0&&this._sendTransportWaiters.splice(i,1),t(new Error(`[urun] no send transport after ${nd}ms (the server never offered createSendTransport \u2014 media/data produce is impossible on this leg)`))},nd);this._sendTransportWaiters.push(r)})}_settleSendTransportWaiters(e,t){let r=this._sendTransportWaiters;this._sendTransportWaiters=[];for(let s of r)e?s.resolve(e):s.reject(t??new Error("TransportSession: disconnected"))}_ensureDataProducer(e){let t=this._dataProducers.get(e);if(t&&!t.closed)return Promise.resolve(t);let r=this._dataProducerPromises.get(e);if(r)return r;let s=this._awaitSendTransport().then(i=>i.produceData({label:Kc(e),protocol:Yc,ordered:!0})).then(i=>this._awaitDataChannelOpen(i)).then(i=>(this._dataProducers.set(e,i),this._dataProducerPromises.delete(e),i)).catch(i=>{throw this._dataProducerPromises.delete(e),i});return this._dataProducerPromises.set(e,s),s}_awaitDataChannelOpen(e){if(e.closed)return Promise.reject(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"));let t=e.readyState;return t==="open"?Promise.resolve(e):t==="closing"||t==="closed"?Promise.reject(new Error(`[urun] sendStreamData: DataChannel is ${t} \u2014 cannot deliver data-up payloads`)):new Promise((r,s)=>{let i=()=>{l(),r(e)},o=u=>{d(new Error(`[urun] sendStreamData: DataChannel error before open: ${u.message}`))},a=()=>{l(),s(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"))},c=setTimeout(()=>{d(new Error(`[urun] sendStreamData: DataChannel not open after ${sd}ms (the SCTP handshake never completed \u2014 data-up produce is impossible on this channel)`))},sd),l=()=>{clearTimeout(c),e.off("open",i),e.off("error",o),e.observer.off("close",a)},d=u=>{l();try{e.close()}catch{}s(u)};e.on("open",i),e.on("error",o),e.observer.on("close",a)})}_dispatchStreamData(e,t){for(let r of this._streamDataHandlers.get(e)??[])r(t)}markStreamDataLaneQuic(){this._streamDataLane="quic"}noteQuicMediaFlowing(){this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")}noteMediaLegDeath(){this._intentionalDisconnect||this._phase.name==="live"&&this._setPhase("connecting",{reason:"reconnecting"})}dispatchQuicStreamData(e,t){this._dispatchStreamData(e,t)}raiseQuicStreamDataError(e){console.error(e.message),this._emitter.emit("error",e)}quicStreamDataLaneLost(e){if(this._streamDataLane!=="quic")return;this._streamDataLane="sctp";let t=[...this._streamDataHandlers.keys()];if(t.length===0)return;let r=new Error(`[urun] QUIC data lane lost mid-stream (${e}) \u2014 active named streams [${t.join(", ")}] resume over SCTP on the failover leg from now; envelopes in flight on the dead lane are gone (mid-stream-join semantics)`);console.error(r.message),this._emitter.emit("error",r)}_streamNameFromLabel(e){if(e)return e.startsWith("stream:")?e.slice(7):void 0}mediaUnavailableReason(){return this._mediaUnavailableReason}mediaAvailability(){return this._mediaVerdict}_requireMediaSupport(e){if(this._mediaUnavailableReason)throw new Error(`[urun-sh/core] ${e}: realtime media is unavailable in this process \u2014 ${this._mediaUnavailableReason}. This session joined in doc/KV-only mode (the media device was skipped); install the optional "werift" dependency to enable realtime media.`)}async addTrack(e,t){this._requireMediaSupport("addTrack"),await this._publishTrack(e,t)}async _publishTrack(e,t){let r=e.kind==="video";if(!r&&this._wtMicUplink){this._rememberPublishIntent(!1,e,t),this._wtMicUplink.setSource(e);return}if(r&&this._wtCamUplink){this._rememberPublishIntent(!0,e,t),this._wtCamUplink.setSource(e);return}let s=r?this._videoProducer:this._audioProducer;if(s&&!s.closed){if(s.track===e)return;await s.replaceTrack({track:e}),this._rememberPublishIntent(r,e,t);return}let o=await(await this._awaitSendTransport()).produce({track:e,...r?{}:{codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}},stopTracks:!1,...t?{appData:{name:t}}:{}});r?this._videoProducer=o:this._audioProducer=o,this._rememberPublishIntent(r,e,t)}_rememberPublishIntent(e,t,r){let s={track:t,...r!==void 0?{name:r}:{}};e?this._publishedVideo=s:this._publishedAudio=s}removeTrack(){let e=this._publishedAudio;if(this._publishedAudio=null,this._wtMicUplink){this._wtMicUplink.setSource(null);try{e?.track.stop()}catch{}}if(this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}this._audioProducer.close(),this._audioProducer=null}}async addVideoTrack(e,t){this._requireMediaSupport("addVideoTrack"),await this._publishTrack(e,t)}stopVideo(){let e=this._publishedVideo;if(this._publishedVideo=null,this._wtCamUplink){this._wtCamUplink.setSource(null);try{e?.track.stop()}catch{}}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}this._videoProducer.close(),this._videoProducer=null}}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(e,t){this._send({type:"stream.seek",stream:e,target:t})}async _handleMessage(e){switch(e.type){case"routerRtpCapabilities":await this._onRouterCapabilities(e.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(e);break;case"createSendTransport":await this._onCreateSendTransport(e);break;case"consume":await this._onConsume(e);break;case"consumerClosed":this._closeConsumer(e.consumerId);break;case"producerClosed":this._closeConsumersByProducer(e.producerId);break;case"consumerPaused":this._consumers.get(e.consumerId)?.pause();break;case"consumerResumed":this._consumers.get(e.consumerId)?.resume();break;case"iceRestarted":this._onIceRestarted(e);break;case"produced":if(this._pendingProduce){let t=this._pendingProduce;this._pendingProduce=null,clearTimeout(t.timeoutId),t.resolve(e.id)}break;case"dataProduced":{let t=e.label,r=t?this._pendingDataProduce.get(t):void 0;r&&t&&(this._pendingDataProduce.delete(t),r.resolve(e.id));break}case"consumeData":await this._onConsumeData(e);break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(e);break;case"stream.seeked":this._onStreamSeeked(e);break;case"error":this._onServerError(e);break;default:this._emitter.emit("signal",e);break}}_onServerError(e){let t=typeof e.message=="string"?e.message:"signaling error",r=typeof e.code=="string"?e.code:void 0;if(/connect\(\) already called/i.test(t)){if(this._resolveConnection){this._generation++;let s=this._ws;this._ws=null;try{s?.close()}catch{}this._cleanupMedia(),this._forceResolveOnNextConnect=!0,this._renegotiate();return}this._setPhase("error",{error:{reason:t,code:"transport-consumed",kind:"transport-failed"}}),this._emitter.emit("error",new Error(t));return}if(r==="TRANSPORT_BIND_FAILED"){this._emitError(new Error(t),r);return}if(r==="PROTOCOL_VERSION_UNSUPPORTED"){this._setPhase("error",{error:{reason:t,code:r,kind:"create-failed"},reason:t}),this._emitter.emit("error",new Error(t));return}console.warn("[urun] signaling error from server:",t)}_onStreamSeeked(e){let t=typeof e.stream=="string"?e.stream:void 0;if(!t)return;let r=e.target,s=r==="live"?"live":typeof r=="number"?r:Number(r);this._emitter.emit("seeked",t,s)}_reportUnknownServerStatus(e,t,r="signaling",s){let o=`server reported unrecognized ${r==="admission"?"admission response":"session status"} status ${JSON.stringify(e)}`+(t?` (reason: ${JSON.stringify(t)})`:"")+' \u2014 this @urun-sh/core build does not know this word; refusing to render it as "provisioning". The SDK may be out of date for this server.';this._emitDiagnostic({level:"error",kind:"unknown-server-status",message:o,detail:{status:e,origin:r,...t?{reason:t}:{}}}),!this._liveReached&&(this._lastServerStatus=e,this._setPhase("unknown",{reason:e,region:s}))}_onStatus(e){let t=e.request_id??e.requestId;t&&(this._requestId=t);let r=typeof e.status=="string"?e.status:void 0,s=typeof e.reason=="string"&&e.reason?e.reason:void 0,i="region"in e?typeof e.region=="string"&&e.region.length>0?e.region:null:void 0,o=r!==void 0?cd(r):void 0;if(r!==void 0&&o?.unknown){this._reportUnknownServerStatus(r,s,"signaling",i);return}let a=o?.phase??"provisioning";if(this._liveReached&&a!=="paused"&&a!=="error"&&a!=="degraded"){a==="live"&&i!==void 0&&i!==this._phase.region&&this._setPhase("live",{reason:s,region:i});return}if(a==="degraded"){this._setPhase("degraded",{reason:s,region:i});return}if(this._isStaleLivenessEvidence()&&a!=="live"&&a!=="paused"&&a!=="error")return;r!==void 0&&(this._lastServerStatus=r);let c=e.queue_position??e.queuePosition,l=e.queue_depth??e.queueDepth,d=typeof c=="number"&&typeof l=="number";if(a==="paused"){let u=e.reason??e.close_reason??e.closeReason??e.pause_reason??e.pauseReason,p=typeof u=="string"&&u?u:void 0,f=dd(u)?"credits_exhausted":this._pastDeadline()?"max_session_age":s??p??r??"paused";this._setPhase("paused",{reason:f,region:i??null}),this._stopMediaProbe();return}if(a==="error"){let u=s??r??"admission failed";this._setPhase("error",{error:{reason:u,code:r,kind:r==="error"?"runtime-failed":"create-failed"},reason:u,region:i});return}if(a==="queued"){this._setPhase("queued",{...d?{queue:{position:c,depth:l}}:{},reason:s,region:i});return}if(a==="waiting_for_capacity"){this._setPhase("waiting_for_capacity",{...d?{queue:{position:c,depth:l}}:{},reason:s,region:i});return}if(a==="connecting"){this._setPhase("connecting",{reason:s,region:i});return}if(a==="live"){this._setPhase("live",{reason:s,region:i});return}this._setPhase("provisioning",{reason:s,region:i})}_webRtcDialHeld=!1;_heldRouterCaps=null;holdWebRtcDial(){return this._webRtcDialHeld=!0,{proceed:e=>{if(!this._webRtcDialHeld)return;this._webRtcDialHeld=!1;let t=this._heldRouterCaps;this._heldRouterCaps=null,t&&(Qe()?console.warn(`[urun-sh/core] running the deferred WebRTC dial (${e})`):console.info(`[urun-sh/core] running the deferred WebRTC dial (${e})`),this._onRouterCapabilities(t).catch(r=>{console.error("[urun-sh/core] deferred WebRTC dial failed:",r)}))},skip:e=>{Qe()?console.warn(`[urun-sh/core] WebRTC dial SKIPPED (${e}) \u2014 WT-only leg, no RTCPeerConnection`):console.info(`[urun-sh/core] WebRTC dial SKIPPED (${e}) \u2014 WT-only leg, no RTCPeerConnection`)}}}async _onRouterCapabilities(e){if(this._webRtcDialHeld){this._heldRouterCaps=e;return}Je()&&await Dt();let t=Fo();if(t){this._mediaUnavailableReason=t,this._mediaVerdictResolve(t);return}this._mediaVerdictResolve(null);let r=Wo(),s=new gd.Device(r?{handlerName:r}:void 0);await s.load({routerRtpCapabilities:e}),this._device=s,this._send({type:"rtpCapabilities",rtpCapabilities:s.rtpCapabilities})}async _onCreateRecvTransport(e){this._device&&this._buildRecvTransport(e)}_buildRecvTransport(e){if(!this._device)return;let t=e.iceCandidates,r=this._device.createRecvTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:t,dtlsParameters:e.dtlsParameters,...e.sctpParameters?{sctpParameters:e.sctpParameters}:{},iceServers:this._options.iceServers??pd});this._recvIceRestartAttempts=0,this._clearRecvIceRestart();let s=this._generation;r.on("connect",({dtlsParameters:o},a,c)=>{try{this._send({type:"connectTransport",transportId:r.id,dtlsParameters:o}),a()}catch(l){c(l)}}),r.on("connectionstatechange",o=>{if(s===this._generation){if(o==="connected"){this._clearRecvIceRestart(),this._recvIceRestartAttempts=0,this._reportSelectedCandidatePair(r);return}if(!(this._intentionalDisconnect&&o==="closed")&&(o==="failed"||o==="disconnected")){if(this._tryRestartRecvIce())return;o==="failed"&&this._emitError(new Error(`media transport ${o}`),o),this._renegotiate()}}}),this._recvTransport=r;let i=this._pendingConsumeData.splice(0,this._pendingConsumeData.length);for(let o of i)this._onConsumeData(o).catch(()=>{})}async _reportSelectedCandidatePair(e){let t=++this._candidatePairRefreshSeq,r=null;if(typeof e.getStats=="function")try{r=await e.getStats()}catch{}if(this._recvTransport!==e||t!==this._candidatePairRefreshSeq)return;let s=jf(r);if(s.localType===null&&s.remoteType===null&&s.protocol===null&&s.remoteAddress===null&&s.remotePort===null&&this._reportedCandidatePairKey!==null)return;this._selectedCandidatePair=s;let o=JSON.stringify(s);if(this._reportedCandidatePairKey===o)return;this._reportedCandidatePairKey=o;let a=Object.values(this._selectedCandidatePair).some(c=>c!==null);this._emitDiagnostic({level:a?"info":"debug",kind:"ice-candidate-pair",message:`selected ICE candidate pair: local=${this._selectedCandidatePair.localType??"unknown"} remote=${this._selectedCandidatePair.remoteType??"unknown"} protocol=${this._selectedCandidatePair.protocol??"unknown"} remote=${this._selectedCandidatePair.remoteAddress??"unknown"}:${this._selectedCandidatePair.remotePort??"unknown"}`,detail:{sessionId:this._options.sessionId,...this._selectedCandidatePair}})}_tryRestartRecvIce(){let e=this._recvTransport;return!e||e.closed?!1:this._recvIceRestartTimer?!0:this._recvIceRestartAttempts>=ld?!1:(this._recvIceRestartAttempts++,this._armRecvIceRestartWatchdog(),this._requestIceRestart(e.id),!0)}_trySendIceRestart(){let e=this._sendTransport;return!e||e.closed?!1:this._sendIceRestartTimer?!0:this._sendIceRestartAttempts>=ld?!1:(this._sendIceRestartAttempts++,this._armSendIceRestartWatchdog(),this._requestIceRestart(e.id),!0)}_requestIceRestart(e){this._send({type:"restartIce",transportId:e})}_onIceRestarted(e){let t=e.transportId??e.id,r=e.iceParameters;if(!r)return;let s=!!this._recvTransport&&this._recvTransport.id===t,i=!s&&!!this._sendTransport&&this._sendTransport.id===t,o=s?this._recvTransport:i?this._sendTransport:null;o&&(Promise.resolve(o.restartIce({iceParameters:r})).catch(a=>{this._emitter.emit("error",a instanceof Error?a:new Error(String(a)))}),s&&this._recvIceRestartTimer?this._armRecvIceRestartWatchdog():i&&this._sendIceRestartTimer&&this._armSendIceRestartWatchdog())}_armRecvIceRestartWatchdog(){this._clearRecvIceRestart();let e=this._generation;this._recvIceRestartTimer=setTimeout(()=>{this._recvIceRestartTimer=null,!(e!==this._generation||this._intentionalDisconnect)&&this._recvTransport?.connectionState!=="connected"&&(this._emitError(new Error("media transport failed (ice restart timeout)"),"failed"),this._renegotiate())},ud)}_armSendIceRestartWatchdog(){this._clearSendIceRestart();let e=this._generation;this._sendIceRestartTimer=setTimeout(()=>{this._sendIceRestartTimer=null,!(e!==this._generation||this._intentionalDisconnect)&&this._sendTransport?.connectionState!=="connected"&&this._emitError(new Error("media send transport failed (ice restart timeout)"),"failed")},ud)}_clearRecvIceRestart(){this._recvIceRestartTimer&&(clearTimeout(this._recvIceRestartTimer),this._recvIceRestartTimer=null)}_clearSendIceRestart(){this._sendIceRestartTimer&&(clearTimeout(this._sendIceRestartTimer),this._sendIceRestartTimer=null)}async _onCreateSendTransport(e){if(!this._device)return;let t=this._device.createSendTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:e.iceCandidates,dtlsParameters:e.dtlsParameters,...e.sctpParameters?{sctpParameters:e.sctpParameters}:{},iceServers:this._options.iceServers??pd});this._sendIceRestartAttempts=0,this._clearSendIceRestart();let r=this._generation;t.on("connect",({dtlsParameters:s},i,o)=>{try{this._send({type:"connectSendTransport",transportId:t.id,dtlsParameters:s}),i()}catch(a){o(a)}}),t.on("produce",({kind:s,rtpParameters:i,appData:o},a,c)=>{if(this._pendingProduce){c(new Error("produce already pending"));return}let l=o&&typeof o.name=="string"?o.name:void 0,d=setTimeout(()=>{let u=this._pendingProduce;if(!u||u.timeoutId!==d)return;this._pendingProduce=null;let p=new Ct(s,{stream:l,timeoutMs:Pt});this._setPhase("error",{error:{reason:p.message,code:"produce-ack-timeout",kind:"produce-timeout"}}),this._emitter.emit("error",p),u.reject(p)},Pt);this._pendingProduce={timeoutId:d,resolve:u=>{a({id:u})},reject:c};try{this._send(l?{type:"produce",kind:s,name:l,rtpParameters:i}:{type:"produce",kind:s,rtpParameters:i})}catch(u){this._pendingProduce?.timeoutId===d&&(this._pendingProduce=null,clearTimeout(d)),c(u)}}),t.on("producedata",({sctpStreamParameters:s,label:i,protocol:o},a,c)=>{try{i&&this._pendingDataProduce.set(i,{resolve:l=>a({id:l}),reject:c}),this._send({type:"produceData",sctpStreamParameters:s,label:i,protocol:o})}catch(l){i&&this._pendingDataProduce.delete(i),c(l)}}),t.on("connectionstatechange",s=>{if(r===this._generation){if(s==="connected"){this._clearSendIceRestart(),this._sendIceRestartAttempts=0;return}this._intentionalDisconnect&&s==="closed"||(s==="failed"||s==="disconnected")&&this._trySendIceRestart()||(s==="failed"||s==="closed")&&this._emitError(new Error(`media send transport ${s}`),s)}}),this._sendTransport=t,this._settleSendTransportWaiters(t),this._emitter.emit("audioTransportReady"),this._republishPublishedTracks()}async _republishPublishedTracks(){let e=this._publishedAudio;if(e&&e.track.readyState!=="ended"&&(!this._audioProducer||this._audioProducer.closed))try{await this.addTrack(e.track,e.name)}catch(r){console.warn("[urun] republish: mic re-produce after reconnect failed",r)}else e&&e.track.readyState==="ended"&&console.warn("[urun] republish: published mic track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)");let t=this._publishedVideo;if(t&&t.track.readyState!=="ended"&&(!this._videoProducer||this._videoProducer.closed))try{await this.addVideoTrack(t.track,t.name)}catch(r){console.warn("[urun] republish: camera re-produce after reconnect failed",r)}else t&&t.track.readyState==="ended"&&console.warn("[urun] republish: published camera track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)")}async _onConsumeData(e){if(this._streamDataLane==="quic"){this.raiseQuicStreamDataError(new Error(`[urun] consumeData (label=${String(e.label)}) pushed on a leg whose data lane is QUIC \u2014 refusing (one canonical data path per leg, contract urun-infra#1605)`));return}let t=this._recvTransport;if(!t){this._pendingConsumeData.push(e);return}let r=e.label,s=this._streamNameFromLabel(r);if(!s){console.error(`[urun] consumeData pushed with an unparseable label ${JSON.stringify(r??null)} \u2014 no DataConsumer will be attached and no ack sent; the server egress will strand envelopes for this stream (expected label form: "stream:<name>")`),this._emitter.emit("error",new Error(`[urun] consumeData pushed with unparseable label ${JSON.stringify(r??null)}`));return}let i=this._generation,o;try{o=await t.consumeData({id:e.id,dataProducerId:e.dataProducerId,sctpStreamParameters:e.sctpStreamParameters,label:r,protocol:e.protocol})}catch(u){console.error(`[urun] consumeData for named stream "${s}" failed \u2014 no channel will open and no dataConsumerReady ack will be sent; the server egress will strand envelopes on this lane:`,u),this._emitter.emit("error",u instanceof Error?u:new Error(String(u)));return}if(i!==this._generation||this._recvTransport!==t||t.closed||this._intentionalDisconnect){try{o.close()}catch{}return}this._dataConsumers.set(s,o);let a=new or;o.on("message",u=>{try{let p=typeof u=="string"?new TextEncoder().encode(u):new Uint8Array(u),f=a.feed(p);f!==void 0&&this._dispatchStreamData(s,f)}catch(p){this._emitter.emit("error",p instanceof Error?p:new Error(String(p)))}});let c=!1,l=setTimeout(()=>{if(c||o.closed||o.readyState==="open")return;let u=new Error(`[urun] data channel for named stream "${s}" did not open within 10s (consumeData resolved at creation; the SCTP association never established) \u2014 no dataConsumerReady ack was sent and the server egress will strand envelopes on this lane`);console.error(u.message),this._emitter.emit("error",u)},1e4),d=()=>{c||o.closed||(c=!0,clearTimeout(l),this._send({type:"dataConsumerReady",id:e.id}))};o.readyState==="open"?d():o.on("open",d),o.once?.("close",()=>clearTimeout(l))}async _onConsume(e){let t=this._recvTransport;if(!t)return;let r=this._generation,s=await t.consume({id:e.id,producerId:e.producerId,kind:e.kind,rtpParameters:e.rtpParameters});if(r!==this._generation||this._recvTransport!==t||t.closed||this._intentionalDisconnect){try{s.close()}catch{}return}this._consumers.set(s.id,s),this._tracks.set(s.track.id,s.track),this._capJitterBuffer(s,s.kind==="video"?"video":"audio");let i=e.streamName??e.label;i&&this._tracksByName.set(i,s.track),s.track.addEventListener?.("unmute",()=>{r!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")},{once:!0}),this._emitter.emit("track",s.track);let o=s.id;s.track.addEventListener("ended",()=>{r!==this._generation||this._intentionalDisconnect||this._closeConsumer(o)},{once:!0}),this._send({type:"resumeConsumer",consumerId:s.id}),this._startMediaProbe(),this._startStatsSampler()}get audioPlayoutOptions(){return this._options.audioPlayout}get wtMicUplinkSeam(){return{onUplink:e=>{this._wtMicUplink=e;let t=this._publishedAudio;if(this._audioProducer&&!this._audioProducer.closed){console.warn("[urun-sh/core] WT mic uplink engaged \u2014 moving the mic from WebRTC produce to the QUIC lane"),this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}t&&t.track.readyState!=="ended"&&e.setSource(t.track)},onUplinkLost:(e,t)=>{if(!this._wtMicUplink||t&&this._wtMicUplink!==t)return;this._wtMicUplink=null;let r=this._publishedAudio;if(!(!r||r.track.readyState==="ended")){if(console.warn(`[urun-sh/core] WT mic uplink lost (${e}) \u2014 republishing the mic over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-mic-uplink-dead",message:`WT mic uplink lost (${e}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the mic is now DEAD until the WT uplink re-engages.`,detail:{reason:e}});return}this._publishTrack(r.track,r.name).catch(s=>{console.error("[urun-sh/core] mic republish over WebRTC failed:",s)})}}}}get wtCamUplinkSeam(){return{onUplink:e=>{this._wtCamUplink=e;let t=this._publishedVideo;if(this._videoProducer&&!this._videoProducer.closed){console.warn("[urun-sh/core] WT video uplink engaged \u2014 moving the camera from WebRTC produce to the QUIC lane"),this._send({type:"stopVideo"});try{this._videoProducer.close()}catch{}this._videoProducer=null}t&&t.track.readyState!=="ended"&&e.setSource(t.track)},onUplinkLost:(e,t)=>{if(!this._wtCamUplink||t&&this._wtCamUplink!==t)return;this._wtCamUplink=null;let r=this._publishedVideo;if(!(!r||r.track.readyState==="ended")){if(console.warn(`[urun-sh/core] WT video uplink lost (${e}) \u2014 republishing the camera over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-cam-uplink-dead",message:`WT camera uplink lost (${e}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the camera is now DEAD until the WT uplink re-engages.`,detail:{reason:e}});return}this._publishTrack(r.track,r.name).catch(s=>{console.error("[urun-sh/core] camera republish over WebRTC failed:",s)})}}}}_jitterBufferTargetMs(e){if(e==="audio"){let t=this._options.audioPlayout?.jitterBufferTargetMs;return t===void 0?xf:t}return this._options.videoPlayout?.jitterBufferTargetMs}_capJitterBuffer(e,t){let r=this._jitterBufferTargetMs(t);if(r===void 0)return;let s=t==="video"?"videoPlayout":"audioPlayout",i={mediaKind:t,transportId:this._recvTransport?.id??null};if(!Number.isFinite(r)){this._emitDiagnostic({level:"warning",kind:`${t}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be a finite number of milliseconds; got ${String(r)}. No jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:String(r),...i}});return}if(r<0||r>id){this._emitDiagnostic({level:"warning",kind:`${t}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be within the W3C jitterBufferTarget range 0-${id}ms; got ${r}. No jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:r,...i}});return}let o=e.rtpReceiver;if(!o){this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-unsupported`,message:`${t} consumer exposes no RTCRtpReceiver (node/werift leg); no jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:r,reason:"no-receiver",...i}});return}let a=[];if("jitterBufferTarget"in o&&(o.jitterBufferTarget=r,a.push("jitterBufferTarget")),"playoutDelayHint"in o&&(o.playoutDelayHint=r/1e3,a.push("playoutDelayHint")),a.length===0){this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-unsupported`,message:`${t==="audio"?"Audio":"Video"} receiver exposes neither jitterBufferTarget nor playoutDelayHint; standing ${t} playout delay is unbounded on this engine.`,detail:{consumerId:e.id,targetMs:r,...i}});return}this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-capped`,message:`${t==="audio"?"Audio":"Video"} receiver jitter buffer capped at ${r}ms.`,detail:{consumerId:e.id,targetMs:r,applied:a,...i}})}_closeConsumer(e){let t=this._consumers.get(e);if(!t)return;this._consumers.delete(e);let r=t.track;try{t.close()}catch{}if(r){this._tracks.delete(r.id);for(let[s,i]of this._tracksByName)i===r&&this._tracksByName.delete(s)}}_closeConsumersByProducer(e){for(let[t,r]of this._consumers)r.producerId===e&&this._closeConsumer(t)}_mediaPollMs(){let e=this._options.mediaLiveness?.pollMs;return e===void 0?Cf:e}_firstFrameWindowMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?Ef:e}_startMediaProbe(){let e=this._mediaPollMs();if(e<=0||this._mediaProbeTimer)return;let t=this._generation;this._mediaProbeTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._sampleMediaArrival(t)},e)}_stopMediaProbe(){this._mediaProbeTimer&&(clearInterval(this._mediaProbeTimer),this._mediaProbeTimer=null)}_statsPollMs(){let e=this._options.sessionStats;if(!e)return 0;let t=e.pollMs;return t===void 0?Pf:Number.isFinite(t)&&t>0?t:0}_startStatsSampler(){let e=this._statsPollMs();if(e<=0||this._statsTimer)return;let t=this._generation;this._statsTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._isParkedPhase()||this._statsSampleInFlight||(this._statsSampleInFlight=!0,this._sampleSessionStats(t).catch(r=>{try{this._emitter.emit("error",r instanceof Error?r:new Error(String(r)))}catch{}}).finally(()=>{this._statsSampleInFlight=!1}))},e)}_stopStatsSampler(){this._statsTimer&&(clearInterval(this._statsTimer),this._statsTimer=null),this._statsSampleInFlight=!1}_lanePairKey(e){let t=e.track,r=t?this._streamNameOf(t):void 0;if(r===void 0)return null;let s=ps(r);return s===void 0?r:r.slice(0,r.length-ar.length-s.length)}async _sampleSessionStats(e){if(this._consumers.size===0)return;let t=Array.from(this._consumers.values()),r=await Promise.all(t.map(async p=>({consumerId:p.id,kind:p.kind==="video"?"video":"audio",pairKey:this._lanePairKey(p),sample:await md(p)})));if(e!==this._generation||this._intentionalDisconnect||this._isParkedPhase())return;let s=r.filter(p=>p.pairKey===null),i=r.filter(p=>p.pairKey!==null),o=null,a=r;if(i.length>0){let p=new Map;for(let h of i){let m=h.pairKey,_=p.get(m);_?_.push(h):p.set(m,[h])}let f=-1,g=-1;for(let[h,m]of p){let _=new Set(m.map(S=>S.kind)).size>=2?1:0,v=m.reduce((S,w)=>S+w.sample.total,0);(_>f||_===f&&v>g)&&(f=_,g=v,o=h,a=[...m,...s])}}let c=p=>{let f=null,g=-1;for(let{consumerId:h,kind:m,sample:_}of a)m===p&&_.total>g&&(g=_.total,f={consumerId:h,..._});return f},l=c("audio"),d=c("video"),u=d?.estimatedPlayoutTimestamp!=null&&l?.estimatedPlayoutTimestamp!=null?d.estimatedPlayoutTimestamp-l.estimatedPlayoutTimestamp:null;this._emitter.emit("stats",{timestamp:Date.now(),stream:o,avSyncMs:u,audio:l,video:d})}_resetJoinProbes(){this._joinProbes.clear(),this._decodeDeathHandled=!1}async _sampleMediaArrival(e){if(this._consumers.size===0)return;let t=Array.from(this._consumers.entries()),r=await Promise.all(t.map(async([a,c])=>[a,await md(c)]));if(e!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence())return;for(let a of this._joinProbes.keys())this._consumers.has(a)||this._joinProbes.delete(a);let s=Date.now();!this._liveReached&&r.some(([,a])=>a.total>0)&&this._setPhase("live");let i=null,o=!1;for(let[a,c]of r){if(c.total<=0){o=!0;continue}let l=this._joinProbes.get(a);if(l||(l={firstBytesAt:s,startSample:c,settled:!1},this._joinProbes.set(a,l)),!l.settled){if(c.framesDecoded===null){l.settled=!0;continue}if(c.framesDecoded>0){l.settled=!0;continue}if(s-l.firstBytesAt>=this._firstFrameWindowMs()){i??={id:a,probe:l,sample:c};continue}o=!0}}if(i&&!this._decodeDeathHandled){this._decodeDeathHandled=!0;let a=this._firstFrameWindowMs(),c=$f(i.probe.startSample,i.sample),l=c.lossPct!==null&&c.lossPct>=5?" \u2014 consistent with network packet loss between the SFU and this browser":"";this._emitDiagnostic({level:"warning",kind:"decode-wall",message:`video is arriving but the decoder never produced its first frame within ${a/1e3}s of join (framesDecoded still 0) \u2014 no keyframe to start from${l}; re-consuming the stream`,detail:{sessionId:this._options.sessionId,consumerId:i.id,firstFrameWindowMs:a,inboundTotal:i.sample.total,framesDecoded:i.sample.framesDecoded,...Ff(i.sample),...c,likelyCause:c.lossPct!==null&&c.lossPct>=5?"network-packet-loss":null,...this._selectedCandidatePair}}),this._renegotiate();return}!o&&!i&&this._stopMediaProbe()}_renegotiate(){this._intentionalDisconnect||this._isExplicitEndPhase()||this._reconnectTimer||(this._stopMediaProbe(),this._stopStatsSampler(),this._setState("renegotiating"),this._attemptReconnect())}recover(){if(this._intentionalDisconnect||this._isExplicitEndPhase()||this._connectStartedAt===void 0||this._cancelPendingDial)return;if(!this.isOpen){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this._attemptReconnect(void 0,!0);return}let e=this._recvTransport?.connectionState;(e==="disconnected"||e==="failed")&&(this._recvIceRestartTimer||(this._recvIceRestartAttempts=0),this._tryRestartRecvIce()||this._renegotiate());let t=this._sendTransport?.connectionState;(t==="disconnected"||t==="failed")&&(this._sendIceRestartTimer||(this._sendIceRestartAttempts=0),this._trySendIceRestart())}_attemptReconnect(e,t=!1){if(this._intentionalDisconnect||this._isExplicitEndPhase()||this._reconnectTimer)return;this._reconnectAttempts>=ed&&(this._reconnectExhaustedWarned||(this._reconnectExhaustedWarned=!0,this._emitDiagnostic({level:"warning",kind:"signaling-reconnect-forever",message:`signaling reconnect budget spent (${ed} attempts) \u2014 retrying forever with capped backoff while the session lives`})));let r=t?0:Zc[Math.min(this._reconnectAttempts,Zc.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._replaceCurrentLegForReconnect();try{await this.connect(e??this._lastStartOptions)}catch(s){if(s instanceof Error&&s.message==="TransportSession: connect cancelled")return;this._attemptReconnect(e)}},r)}_connectUrls(){let e=[],t=r=>{if(!r)return;let s=hd(r)!==void 0,i=this._sessionId&&!s?`${r}${r.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:r,o=this._options.sfuAttach;if(o){if(!/[?&]token=/.test(i)){let u=`${i}${i.includes("?")?"&":"?"}token=${encodeURIComponent(o.token)}&gen=${o.gen}`;e.includes(u)||e.push(u);return}e.includes(i)||e.push(i);return}let a=this._options.jwt?.trim(),c=/[?&]token=/.test(i),l=a&&!c?`${i}${i.includes("?")?"&":"?"}token=${encodeURIComponent(a)}`:i;e.includes(l)||e.push(l)};t(this._options.url);for(let r of this._options.fallbackUrls??[])t(r);return e}_connectOnce(e,t,r){return new Promise((s,i)=>{let o=!1,a=!1,c=null,l=null,d,u=new WebSocket(e);this._ws=u;let p=()=>this._ws!==u||t!==this._generation,f=h=>{a||(a=!0,c&&clearTimeout(c),this._cancelPendingDial===g&&(this._cancelPendingDial=null),typeof d=="number"&&(h.dialCloseCode=d),i(h))},g=h=>{try{u.close()}catch{}f(h)};this._cancelPendingDial=g,c=setTimeout(()=>{try{u.close()}catch{}f(new Error("TransportSession: connect timed out"))},Sf),u.onopen=()=>{if(!a){if(p()){try{u.close()}catch{}f(new Error("TransportSession: connect superseded during dial"));return}o=!0,c&&clearTimeout(c),this._connectedUrl=e,this._multiplexer=new bt(u),u.send(JSON.stringify(this._startMessage(r))),this._scheduleReconnectBudgetReset(),this._selfEpochAdoptUntil=Date.now()+Rf,this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),a=!0,this._cancelPendingDial===g&&(this._cancelPendingDial=null),s()}},u.onerror=()=>{o||(l??=new Error("WebSocket connection error"))},u.onclose=h=>{if(!o){let m=h?.code;typeof m=="number"&&m!==1005&&(d=m),f(l??new Error("WebSocket closed before connecting"));return}if(!p()&&(this._clearReconnectBudgetReset(),c&&clearTimeout(c),this._setState("disconnected"),!this._intentionalDisconnect)){if(this._pastDeadline()&&this._phase.name!=="paused"){this._setPhase("paused",{reason:"max_session_age"}),this._emitter.emit("disconnected");return}this._emitter.emit("disconnected"),!this._isExplicitEndPhase()&&this._attemptReconnect(r)}},u.onmessage=h=>{if(!(this._ws!==u||t!==this._generation)&&typeof h.data=="string")try{this._handleMessage(JSON.parse(h.data)).catch(m=>{this._emitter.emit("error",m instanceof Error?m:new Error(String(m)))})}catch(m){this._emitter.emit("error",m instanceof Error?m:new Error(String(m)))}}})}_startMessage(e){let t={type:"start",version:Vi,video:e?.video??{width:854,height:480,frameRate:16}};return e?.prompt&&(t.prompt=e.prompt),e?.cameraControl&&(t.camera_control=e.cameraControl),e?.args&&(t.args=e.args),e?.app&&(t.app=e.app),e?.functionName&&(t.function=e.functionName),e?.role&&(t.role=e.role),this._options.orgId&&(t.orgId=this._options.orgId),this._options.jwt&&(t.jwt=this._options.jwt),this._options.authProvider&&(t.authProvider=this._options.authProvider),t}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let e=this._ws;this._ws=null,e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{e.close()}catch{}}_replaceCurrentLegForReconnect(){this._cleanupSocket(),this._cancelPendingDial?.(new Error("TransportSession: reconnect replacing current dial")),this._cleanupMedia()}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0,this._reconnectExhaustedWarned=!1},If))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupDataChannels(){for(let e of this._dataProducers.values())try{e.close()}catch{}this._dataProducers.clear(),this._dataProducerPromises.clear();for(let e of this._dataConsumers.values())try{e.close()}catch{}this._dataConsumers.clear();for(let e of this._pendingDataProduce.values())try{e.reject(new Error("TransportSession: disconnected"))}catch{}this._pendingDataProduce.clear()}_cleanupMedia(){this._stopMediaProbe(),this._stopStatsSampler(),this._resetJoinProbes();for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){try{this._videoProducer.close()}catch{}this._videoProducer=null}if(this._clearRecvIceRestart(),this._clearSendIceRestart(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._pendingConsumeData=[],this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce=null),this._device=null,this._tracks.clear(),this._tracksByName.clear(),this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null)}_send(e){return!this._ws||this._ws.readyState!==WebSocket.OPEN?!1:(this._ws.send(JSON.stringify(e)),!0)}_setState(e){this._state!==e&&(this._state=e,this._emitter.emit("stateChange",e))}_isParkedPhase(){return this._phase.name==="paused"?!0:this._phase.name!=="error"?!1:this._phase.error?.kind!=="transport-failed"}_isExplicitEndPhase(){if(this._phase.name==="paused"&&!this._isComputeReleasedPark())return!1;if(this._phase.name!=="error")return this._isComputeReleasedPark();let e=this._phase.error?.kind;return e!==void 0&&e!=="transport-failed"}_isComputeReleasedPark(){return this._phase.name!=="paused"?!1:rd[this._phase.reason??""]===!0}_setPhase(e,t){let r=this._liveReached;e==="live"?this._liveReached=!0:e==="paused"||e==="error"||e==="degraded"?(this._liveReached=!1,e==="paused"&&!r&&rd[t?.reason??""]!==!0&&(this._forceResolveOnNextConnect=!0,this._cancelPendingDial||this._attemptReconnect())):e==="connecting"&&r&&(this._liveReached=!1);let s={name:e};t?.queue&&(s.queue=t.queue),t?.runtime&&(s.runtime=t.runtime),t?.reason&&(s.reason=t.reason),s.region=t?.region!==void 0?t.region:this._phase.region,Be(e)?(this._wakingSince??=Date.now(),s.wakingSince=this._wakingSince):this._wakingSince=void 0,this._requestId&&(s.requestId=this._requestId),this._sessionId&&(s.sessionId=this._sessionId),this._endsAt!==null&&(s.endsAt=this._endsAt),t?.error&&(s.error=t.error),!Mf(this._phase,s)&&(this._phase=s,this._pausedIncarnation=e==="paused"?this._currentEpoch:null,this._isParkedPhase()&&(this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart()),this._emitter.emit("phase",s))}reportAdmission(e){e.requestId&&(this._requestId=e.requestId),this._lastServerStatus=e.status;let t=cd(e.status);if(t.unknown){this._reportUnknownServerStatus(e.status,e.reason,"admission",e.region);return}if(this._liveReached)return;e.sessionId&&!this._sessionId&&(this._sessionId=e.sessionId);let{runtime:r,queue:s}=e,i=e.decisionReason==="provisioning_refused"?e.refusalMessage??e.decisionReason:e.reason,o={runtime:r,queue:s,...i?{reason:i}:{},...e.region!==void 0?{region:e.region}:{}};if(Of(e.status)){if(r?.state==="unavailable"){this._setPhase("unavailable",o);return}if(r?.state==="starting"){this._setPhase("provisioning",o);return}if(r?.state==="busy"||e.status==="queued"){this._setPhase("queued",o);return}this._setPhase("provisioning",o);return}let a=e.runtimeReady===!1||e.runtimeStatus==="unbound"||e.runtimeStatus==="starting";if(t.phase==="connecting"&&a){this._setPhase("provisioning",o);return}this._setPhase(t.phase,t.phase==="paused"?{...o,region:o.region??null}:o)}_emitError(e,t){this._setPhase("error",{error:{reason:e.message,code:t,kind:"transport-failed"}}),this._emitter.emit("error",e)}reportAllocationFailure(e,t,r,s){r==="insufficient_credits"?this._setPhase("error",{error:{reason:e.message,code:r,kind:"insufficient-credits",httpStatus:t}}):this._setPhase("error",{error:{reason:e.message,code:r??"allocation-failed",kind:"create-failed",httpStatus:t,retryAfterSeconds:s}}),this._emitter.emit("error",e)}};function en(n){return new Promise(e=>setTimeout(e,n))}function Uf(){return sr()}var vd=["packetsReceived","packetsLost","nackCount","pliCount","firCount","keyFramesDecoded","framesReceived","framesDropped","retransmittedPacketsReceived","retransmittedBytesReceived","jitterBufferDelay","jitterBufferEmittedCount","estimatedPlayoutTimestamp","jitterBufferTargetDelay","jitterBufferMinimumDelay","concealedSamples","insertedSamplesForDeceleration"],Nf=new Set(["estimatedPlayoutTimestamp"]);function Wf(){return{total:0,framesDecoded:null,packetsReceived:null,packetsLost:null,nackCount:null,jitter:null,pliCount:null,firCount:null,keyFramesDecoded:null,framesReceived:null,framesDropped:null,retransmittedPacketsReceived:null,retransmittedBytesReceived:null,jitterBufferDelay:null,jitterBufferEmittedCount:null,estimatedPlayoutTimestamp:null,jitterBufferTargetDelay:null,jitterBufferMinimumDelay:null,concealedSamples:null,insertedSamplesForDeceleration:null}}function Ff(n){return Object.fromEntries(vd.map(e=>[e,n[e]]))}function fd(n,e){return n===null||e===null||e<n?null:e-n}function $f(n,e){let t=n.packetsLost!==null&&e.packetsLost!==null?e.packetsLost-n.packetsLost:null,r=fd(n.packetsReceived,e.packetsReceived),s=fd(n.nackCount,e.nackCount),i=t===null?null:Math.max(0,t),o=i!==null&&r!==null?i+r:0;return{packetsLostWindow:t,packetsReceivedWindow:r,nackCountWindow:s,jitterSec:e.jitter,lossPct:o>0&&i!==null?i/o*100:null}}function wd(){return{localType:null,remoteType:null,protocol:null,remoteAddress:null,remotePort:null}}function jf(n){let e=new Map;yd(n,a=>{let c=typeof a.id=="string"?a.id:null;c&&e.set(c,a)});let t=Array.from(e.values()).find(a=>a.type==="transport"),r=typeof t?.selectedCandidatePairId=="string"?t.selectedCandidatePairId:null,s=(r?e.get(r):void 0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.selected===!0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.nominated===!0);if(!s)return wd();let i=typeof s.localCandidateId=="string"?e.get(s.localCandidateId):void 0,o=typeof s.remoteCandidateId=="string"?e.get(s.remoteCandidateId):void 0;return{localType:typeof i?.candidateType=="string"?i.candidateType:null,remoteType:typeof o?.candidateType=="string"?o.candidateType:null,protocol:typeof i?.protocol=="string"?i.protocol:typeof o?.protocol=="string"?o.protocol:null,remoteAddress:typeof o?.address=="string"?o.address:typeof o?.ip=="string"?o.ip:null,remotePort:typeof o?.port=="number"?o.port:null}}function yd(n,e){let t=r=>{r&&typeof r=="object"&&e(r)};if(n instanceof Map)for(let[r,s]of n.entries()){if(!s||typeof s!="object")continue;let i=s;e(typeof i.id=="string"?i:{...i,id:r})}else(Array.isArray(n)||n&&typeof n.forEach=="function")&&n.forEach(t)}async function md(n){let e=Wf();if(typeof n.getStats!="function")return e;let t;try{t=await n.getStats()}catch{return e}return yd(t,s=>{if(s.type==="inbound-rtp"){let i=typeof s.bytesReceived=="number"?s.bytesReceived:0,o=typeof s.packetsReceived=="number"?s.packetsReceived:0;e.total+=i+o,typeof s.framesDecoded=="number"&&(e.framesDecoded=(e.framesDecoded??0)+s.framesDecoded),typeof s.jitter=="number"&&(e.jitter=e.jitter===null?s.jitter:Math.max(e.jitter,s.jitter));for(let a of vd)typeof s[a]=="number"&&(e[a]=Nf.has(a)?e[a]===null?s[a]:Math.max(e[a],s[a]):(e[a]??0)+s[a])}}),e}function qf(n){if(!n||typeof n!="object")return;let e=n.epoch,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0}var rn=Ns(require("yjs"));var bd=require("y-websocket"),Gi=require("y-protocols/awareness");var Bf=1,Hf=4401;function fs(n){let e=new URL(n);return`${e.protocol}//${e.host}/doc`}function Vf(n){let e=Hs(n);return e===null?void 0:Math.floor((Date.now()+e)/1e3)}var zf=2500,Gf=3e4,Kf=1e4,Yf=3;function Sd(n){let e=n.WebSocketPolyfill??globalThis.WebSocket;if(!e)throw new Error("[urun] no WebSocket implementation available for the yjs doc provider (browser global missing and no WebSocketPolyfill passed)");return(t,r,s)=>{let i=`${n.sessionId}/${t}`,o=typeof n.token=="function"?n.token:null,a=typeof n.token=="string"?n.token:void 0,c=new Set,l=(D,W)=>{let k=Vf(D);if(k===void 0||k*1e3>Date.now())return;let z=`${W}:${D}`;c.has(z)||(c.add(z),console.error(`[urun] doc dial for room ${i} would present an EXPIRED token (${W}; exp ${new Date(k*1e3).toISOString()} is in the past) \u2014 the token refresh lane returned a stale credential; dials will be refused once auth enforcement flips`))};l(a,"static");let d=n.maxBackoffTimeMs??zf,u=n.dialTimeoutMs??Gf,p=new bd.WebsocketProvider(n.serverUrl,i,r,{awareness:s,params:{dsv:String(Bf),...n.attach?{token:n.attach.token,gen:String(n.attach.gen)}:a?{token:a}:{}},WebSocketPolyfill:e,disableBc:!0,maxBackoffTime:d,resyncInterval:Kf,connect:o===null}),f=!1,g,h=!1,m=D=>{h||(h=!0,console.error(`[urun] doc token refresh failed for room ${i} (redialing with previous token):`,D))},_=D=>{if(o&&!n.attach){if(g)return g;try{let W=o({redial:D});if(typeof W=="string"){p.params.token=W,l(W,"minted"),h=!1;return}if(W&&typeof W.then=="function"){let z=W.then(j=>{typeof j=="string"&&(p.params.token=j,l(j,"minted"),h=!1)},j=>{m(j)}).finally(()=>{g===z&&(g=void 0)});return g=z,z}}catch(W){m(W)}}},v=n.resolveServerUrl,S=0,w=!1,b=D=>{if(typeof D!="string"||D==="")return;let W=D.replace(/\/+$/,"");W!==p.serverUrl&&(p.serverUrl=W,w=!1)},T=()=>{if(!v)return;let D=++S,W=k=>{w||(w=!0,console.error(`[urun] doc endpoint re-resolve failed for room ${i} (redialing previous host):`,k))};try{let k=v();if(k&&typeof k.then=="function")return k.then(z=>{D===S&&b(z)},W);b(k)}catch(k){W(k)}},y={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null},E=new Set,N=!1,Q=!1,te=()=>{let D={...y};for(let W of[...E])W(D)},F=null,$=()=>{F!==null&&(clearTimeout(F),F=null)},G=()=>{$(),F=setTimeout(()=>{if(F=null,!f&&p.wsconnecting&&p.ws)try{p.ws.close()}catch{}},u)},X=null,he=()=>{X!==null&&(clearTimeout(X),X=null)},Z=()=>{he(),X=setTimeout(()=>{if(X=null,!f&&p.shouldConnect&&!p.wsconnected&&!p.wsconnecting&&p.ws===null)try{p.connect()}catch(D){N||(N=!0,console.error(`[urun] doc connection redial threw for room ${i} (still retrying):`,D)),Z()}},d+500)},Me=({status:D})=>{if(D==="connecting"){he(),G();return}if(D==="connected"){$(),he(),y={...y,connected:!0},te();return}y.connected&&(y={...y,connected:!1},te())},x=D=>{D&&(N&&(Qe()?console.warn(`[urun] doc connection recovered for room ${i}`):console.info(`[urun] doc connection recovered for room ${i}`),N=!1),Q&&(Q=!1),y.consecutiveFailures!==0&&(y={...y,consecutiveFailures:0},te()))},O=D=>{$();let W=D?D.code:null,k=W===Hf;k&&!Q&&(Q=!0,console.error(`[urun] doc dial REFUSED: auth token expired (close ${W}${D?.reason?`, reason "${D.reason}"`:""}) for room ${i} \u2014 forcing a token refresh; the next dial presents a fresh credential`)),y={connected:!1,consecutiveFailures:y.consecutiveFailures+1,lastCloseCode:W,lastCloseReason:D&&D.reason?D.reason:null,authRefused:k},!N&&y.consecutiveFailures>=Yf&&(N=!0,console.error(`[urun] doc connection failing for room ${i}: ${y.consecutiveFailures} consecutive failures (last close ${y.lastCloseCode===null?"by provider liveness reap":`code ${y.lastCloseCode}`}${y.lastCloseReason?`, reason "${y.lastCloseReason}"`:""}). Still retrying \u2014 the doc provider never gives up.`)),te(),_(!0),T(),Z()};p.on("status",Me),p.on("sync",x),p.on("connection-close",O),p.wsconnecting?G():p.wsconnected&&(y={...y,connected:!0});let B=!1;return o!==null&&_(!1),B||p.connect(),{get awareness(){return p.awareness},get synced(){return p.synced},onSync(D){let W=k=>D(k);return p.on("sync",W),()=>p.off("sync",W)},onConnectionState(D){return E.add(D),D({...y}),()=>E.delete(D)},ensureConnected(){B=!1,p.wsconnected||p.connect()},disconnect(){B=!0,p.disconnect()},destroy(){f=!0,$(),he(),p.off("status",Me),p.off("sync",x),p.off("connection-close",O),E.clear(),p.destroy()}}}}var zi=class{constructor(e,t,r){this._name=e;this._doc=t;this.awareness=r}_name;_doc;awareness;_inner=null;_innerUnsub=null;_innerStateUnsub=null;_syncHandlers=new Set;_stateHandlers=new Set;_lastState={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};_destroyed=!1;_suspended=!1;get synced(){return this._inner?.synced??!1}get destroyed(){return this._destroyed}onSync(e){return this._syncHandlers.add(e),()=>this._syncHandlers.delete(e)}onConnectionState(e){return this._stateHandlers.add(e),e({...this._lastState}),()=>this._stateHandlers.delete(e)}attach(e){if(!this._destroyed){if(this._inner&&(this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner.destroy(),this._inner=null),this._inner=e(this._name,this._doc,this.awareness),this._innerUnsub=this._inner.onSync(t=>{for(let r of[...this._syncHandlers])r(t)}),this._inner.onConnectionState)this._innerStateUnsub=this._inner.onConnectionState(t=>{this._lastState=t;for(let r of[...this._stateHandlers])r(t)});else{this._innerStateUnsub=null,this._lastState={connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};for(let t of[...this._stateHandlers])t({...this._lastState})}if(this._suspended&&this._inner.disconnect?.(),this._inner.synced)for(let t of[...this._syncHandlers])t(!0)}}ensureConnected(){this._suspended=!1,this._inner?.ensureConnected?.()}get disconnect(){return this._inner?.disconnect?()=>{this._suspended=!0,this._inner.disconnect()}:void 0}destroy(){this._destroyed=!0,this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner?.destroy(),this._inner=null,this._syncHandlers.clear(),this._stateHandlers.clear()}},hs=class{_target=null;_bridges=[];connect=(e,t,r)=>{let s=new zi(e,t,r);return this._bridges.push(s),this._target&&s.attach(this._target),s};get connected(){return this._target!==null}setTarget(e){if(this._target!==e){this._target=e,this._bridges=this._bridges.filter(t=>!t.destroyed);for(let t of this._bridges)t.attach(e)}}};function nn(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var ms="$bytes";function Qf(n){return n instanceof Uint8Array||n instanceof ArrayBuffer}function Jf(n){if(!nn(n))return!1;let e=Object.keys(n);return e.length===1&&e[0]===ms&&typeof n[ms]=="string"}function Xf(n){return n instanceof ArrayBuffer?new Uint8Array(n):n}function Zf(n){if(typeof Buffer<"u")return Buffer.from(n).toString("base64");let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return btoa(e)}function em(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Ki(n){if(Qf(n))return{[ms]:Zf(Xf(n))};if(Array.isArray(n))return n.map(Ki);if(nn(n)){let e={};for(let[t,r]of Object.entries(n))e[t]=Ki(r);return e}return n}function tn(n){if(Jf(n))return em(n[ms]);if(Array.isArray(n))return n.map(tn);if(nn(n)){let e={};for(let[t,r]of Object.entries(n))e[t]=tn(r);return e}return n}var kd=Symbol("urun:doc:path-absent");function tm(n,e){let t=e.split("."),r=n;for(let s of t){if(r===null||typeof r!="object"||!(s in r))return kd;r=r[s]}return r}function rm(n,e){return n===e?!0:JSON.stringify(n)===JSON.stringify(e)}function Yi(n,e){for(let[t,r]of Object.entries(e))if(nn(r)){let s=n.get(t);if(!(s instanceof rn.Map)){let i=s;s=new rn.Map,n.set(t,s),nn(i)&&Yi(s,i)}Yi(s,r)}else{if(rm(n.get(t),r))continue;n.set(t,r)}}var nm=Symbol("urun:doc:local"),gs=class{_doc=new rn.Doc;_root=this._doc.getMap("session");_awareness=new Gi.Awareness(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(e,t,r){this._key=e,this._sessionId=t,this._root.observeDeep(this._observer),r?(this._connection=r(e,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(e){this._sessionId=e}get synced(){return this._synced}ensureConnected(){this._connection?.ensureConnected?.()}reconnect(){this.ensureConnected()}disconnect(){let e=this._connection;if(!e?.disconnect)throw new Error(`[urun-sh/core] doc('${this._key}').disconnect(): no disconnect-capable connection to sever (a local-only doc, or a connector with no live socket) \u2014 there is nothing to disconnect`);e.disconnect()}onConnectionState(e){return this._connection?.onConnectionState?this._connection.onConnectionState(e):(e({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){e=Ki(e),this.applyPatch(e)}get(e,t){let r=this.snapshot();if(!e)return tn(r);let s=tm(r,e);return s===kd?t:tn(s)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new Qi(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let e=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let t of e)t()}applyPatch(e){this._doc.transact(()=>{Yi(this._root,e)},nm)}snapshot(){return this._root.toJSON()}notify(){let e=tn(this.snapshot());for(let t of this._listeners)t(e)}},Qi=class{constructor(e){this._ytext=e;this._observer=t=>{for(let r of t.delta)if(typeof r.insert=="string"&&r.insert.length>0){let s=r.insert;for(let i of this._delta)i(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};function Td(n){return{get clientId(){return n.clientID},set(e){n.setLocalState(e)},setField(e,t){n.setLocalStateField(e,t)},getLocal(){return n.getLocalState()??null},getStates(){return n.getStates()},on(e,t){let r=()=>t(n.getStates());return n.on("change",r),r(),()=>n.off("change",r)}}}var Rd=1e3,Cd=12e3;function _s(n,e,t={}){let r=null,s=0,i=0,o=null,a=-1,c=()=>{let m=n.get("desired.billing.generationSeconds");if(typeof m!="number"||!Number.isFinite(m)||m<=0)return null;let _=n.get("desired.billing.epoch"),v=n.get("desired.billing.updatedAtMs");return{seconds:m,epoch:typeof _=="number"&&Number.isFinite(_)?_:0,updatedAtMs:typeof v=="number"&&Number.isFinite(v)?v:null}},l=()=>{if(r===null)return null;let m=Math.min(Math.max(0,Date.now()-s),i);return r+m/1e3},d=()=>{let m=t.creditsPerSecond;if(typeof m=="number"&&Number.isFinite(m)&&m>0)return m;let _=n.get("desired.billing.creditsPerSecond");return typeof _=="number"&&Number.isFinite(_)&&_>0?_:null},u=()=>{let m=l();if(m===null)return;let _=Math.floor(m);if(_<=a)return;a=_;let v={seconds:_},S=d();S!==null&&(v.estimatedCredits=_*S),e(v)},p=m=>{s=Date.now();let _=m===null?0:Math.max(0,s-m);i=Math.max(0,12e3-_)},f=()=>{let m=c();if(m!==null){if(o!==null&&m.epoch!==o){o=m.epoch,r=m.seconds,a=-1,p(m.updatedAtMs),u();return}r!==null&&m.seconds<=r||(o=m.epoch,r=m.seconds,p(m.updatedAtMs),u())}};f();let g=n.on("change",f),h=setInterval(u,1e3);return h.unref?.(),()=>{clearInterval(h),g()}}var Ji="activity",Xi="visibility",Ed=15e3,vs=["pointerdown","pointermove","keydown","wheel","touchstart"];function ws(n){let e=n.now??Date.now,t=n.mode==="explicit",r=t?null:n.windowTarget!==void 0?n.windowTarget:typeof window<"u"?window:null,s=t?null:n.documentTarget!==void 0?n.documentTarget:typeof document<"u"?document:null,i=!1,o,a=()=>{if(i)return;let p=e();if(!(o!==void 0&&p-o<15e3)){o=p;try{n.awareness.setLocalStateField(Ji,{at:p})}catch{}}},c=()=>{if(!(i||!s||s.visibilityState===void 0))try{n.awareness.setLocalStateField(Xi,s.visibilityState)}catch{}},l=()=>a(),d=()=>{c(),(!s||s.visibilityState===void 0||s.visibilityState==="visible")&&a()};if(r)for(let p of vs)r.addEventListener(p,l,{passive:!0,capture:!0});s&&s.addEventListener("visibilitychange",d);let u=null;return!t&&n.isProducing&&(u=setInterval(()=>{if(!i)try{n.isProducing?.()&&a()}catch{}},15e3),u.unref?.()),a(),c(),{touch:a,dispose(){if(!i){if(i=!0,r)for(let p of vs)r.removeEventListener(p,l,{capture:!0});s&&s.removeEventListener("visibilitychange",d),u&&(clearInterval(u),u=null)}}}}var Zi="user_activity",eo="focus",xd=3e4;function Pd(n){switch(n){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var dr=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(Pd(e.state));let t=e.on("stateChange",s=>{this._setState(Pd(s))}),r=()=>{t(),this._transportUnsubs.delete(r)};return this._transportUnsubs.add(r),r}_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(eo,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(Zi,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 Dd=250;function ys(n){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let r=Date.now();r-e<250||(e=r,n())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function bs(n){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=r=>{r.persisted||e||(e=!0,n())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function Ss(n){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{n()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Ad="video/mp4";function ks(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,i=!1,o=(a,c,l)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let u=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(Ad)?Ad:void 0),p=new MediaStream([a]),f=new d(p,u?{mimeType:u}:void 0);r=f;let g=Promise.resolve();f.ondataavailable=h=>{let m=h.data;i||!m||m.size===0||(g=g.then(async()=>{let _=new Uint8Array(await m.arrayBuffer());i||c(_)}))},f.onstop=()=>{g.then(()=>{i||l()})},f.onerror=()=>{g.then(()=>{i||l()})},f.start(t)};return{start(a,c){if(r||i)return;let l=n.track();if(l){o(l,a,c);return}s=n.onTrack(d=>{!d||r||i||(s?.(),s=null,o(d,a,c))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function sm(n){let e=n;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=n.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Id(n,e){let t=null,r=!1,s=!1,i=new ReadableStream({pull(o){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return sm(i)}var Ts=require("@msgpack/msgpack"),ro=65536;function Rs(n){let e=(0,Ts.encode)(n),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var lr=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(r>ro)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+r)break;let s=this.buf.subarray(4,4+r);this.buf=this.buf.subarray(4+r),t.push(Object.assign((0,Ts.decode)(s),{raw:s}))}return t}};function Ld(n,e){let t=new DataView(n.buffer,n.byteOffset,n.byteLength),r=t.getUint8(0),s=(r&240)===128,i=r===222;if(!s&&!i&&!(r===223))throw new Error("[urun] mirrorControlBody: source control frame is not a msgpack map");let a=s?r&15:i?t.getUint16(1,!1):t.getUint32(1,!1),c=s?1:i?3:5,l=[];l.push(n.subarray(0,c));for(let f=0;f<a;f++){let g=c,h=sn(n,t,c);c=h.end;let _=sn(n,t,c).end;if(im(t.getUint8(g))){let v=t.getUint8(g),S=(v&224)===160?1:v===217?2:v===218?3:5;if(new TextDecoder().decode(n.subarray(g+S,h.end))==="t"){l.push(n.subarray(g,h.end));let b=new TextEncoder().encode(e);if(b.byteLength>31)throw new Error("[urun] mirrorControlBody: replacement tag too long");l.push(new Uint8Array([160|b.byteLength]),b)}else l.push(n.subarray(g,_))}else l.push(n.subarray(g,_));c=_}let d=l.reduce((f,g)=>f+g.byteLength,0),u=new Uint8Array(d),p=0;for(let f of l)u.set(f,p),p+=f.byteLength;return u}function im(n){return(n&224)===160?!0:n===217||n===218||n===219}function sn(n,e,t){let r=e.getUint8(t),s=t;if(r<=127||r>=224)return{start:s,end:t+1};if((r&224)===160)return{start:s,end:t+1+(r&31)};if((r&240)===128||(r&240)===144){let o=r&15;t+=1;let a=(r&240)===128?o*2:o;for(let c=0;c<a;c++)t=sn(n,e,t).end;return{start:s,end:t}}let i={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(i[r]!==void 0)return{start:s,end:t+1+i[r]};if(r===217||r===196)return{start:s,end:t+2+e.getUint8(t+1)};if(r===218||r===197)return{start:s,end:t+3+e.getUint16(t+1,!1)};if(r===219||r===198)return{start:s,end:t+5+e.getUint32(t+1,!1)};if(r===220||r===221){let o=r===220?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===220?3:5;for(let a=0;a<o;a++)t=sn(n,e,t).end;return{start:s,end:t}}if(r===222||r===223){let o=r===222?e.getUint16(t+1,!1):e.getUint32(t+1,!1);t+=r===222?3:5;for(let a=0;a<o*2;a++)t=sn(n,e,t).end;return{start:s,end:t}}throw new Error(`[urun] mirrorControlBody: unsupported msgpack prefix 0x${r.toString(16)} at byte ${s}`)}var pe=12,to=1,om=0,Cs=1,Md=2;function ur(n){let e=n.getUint8(8);return{groupId:n.getUint32(0,!0),frameSeq:n.getUint32(4,!0),keyframe:(e&to)===to,fragIndex:n.getUint8(9),fragCount:n.getUint8(10),lane:n.getUint8(11)}}function Es(n){let e=new Uint8Array(pe),t=new DataView(e.buffer);return t.setUint32(0,n.groupId,!0),t.setUint32(4,n.frameSeq,!0),t.setUint8(8,n.keyframe?to:0),t.setUint8(9,n.fragIndex),t.setUint8(10,n.fragCount),t.setUint8(11,n.lane??om),e}var am=100,Od=100,pr=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??am}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<pe)return;let t=ur(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 r=this.pending.get(t.frameSeq);if(r||(r={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r)),!r.chunks[t.fragIndex]){r.chunks[t.fragIndex]=e.subarray(pe),r.received++,r.received===r.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,r));for(let s of this.pending.keys())s<t.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-Od?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Od}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 r=t.chunks.reduce((o,a)=>o+a.byteLength,0),s=new Uint8Array(r),i=0;for(let o of t.chunks)s.set(o,i),i+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:s})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var cm=/^avc[13]\.[0-9a-fA-F]{6}$/;function dm(n){return cm.test(n)?null:`codec ${JSON.stringify(n)} 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 no(n,e){let t=dm(n);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var so=1,on=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let r=new Uint8Array(this.buf.byteLength+e.byteLength);r.set(this.buf),r.set(e,this.buf.byteLength),this.buf=r}if(this.name===null){if(this.buf.byteLength<2)return[];let r=this.buf[0];if(r!==so)throw new Error(`[urun] wt data stream: unknown header version 0x${r.toString(16)} \u2014 rejecting stream`);let s=this.buf[1];if(s===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+s)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+s)),this.buf=this.buf.subarray(2+s)}let t=[];for(;this.buf.byteLength>=4;){let r=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+r)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let s=ds(this.buf.subarray(4,4+r));this.buf=this.buf.subarray(4+r),s===vt&&(this.ended=!0),t.push({name:this.name,payload:s})}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 Ps(n,e){let t=n.getReader();for(;;){let{value:r,done:s}=await t.read();if(s)return;r&&lm(r,e).catch(i=>{e.onLaneError(i instanceof Error?i:new Error(String(i)))})}}async function lm(n,e){let t=n.getReader(),r=new on;try{for(;;){let{value:s,done:i}=await t.read();if(i)break;if(!(!s||s.byteLength===0))for(let{name:o,payload:a}of r.push(s))e.onData(o,a)}r.finish()}catch(s){try{await t.cancel?.(s)}catch{}throw s}}var io="wt-playout",um=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 n=this.port;n&&(n.onmessage=e=>this.onMessage(e.data))}post(n){this.port?.postMessage(n)}ensure(n){if(!(this.rings.length===n&&this.held.length===n&&this.rings[0]?.length===this.cap)){this.rings=[];for(let e=0;e<n;e++)this.rings.push(new Float32Array(this.cap));this.held=new Float32Array(n),this.xfadeFrom=new Float32Array(n)}}onMessage(n){if(n.type==="init"){this.holdN=Math.max(1,Math.round(2*n.rate/1e3)),this.fadeN=Math.max(1,Math.round(4*n.rate/1e3)),this.cap=Math.max(1,Math.round(500*n.rate/1e3)),this.primeSamples=Math.max(0,Math.round(n.primeSamples)),this.primeWall=Math.round(250*n.rate/1e3),this.ensure(1);return}if(n.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(n.type!=="pcm")return;let e=n.bufs.map(s=>new Float32Array(s)),t=n.frames;if(this.ensure(e.length),this.depth+t>this.cap){let s=this.depth+t-this.cap;this.read=(this.read+s)%this.cap,this.depth-=s,this.post({type:"overflow",dropped:s})}let r=(this.read+this.depth)%this.cap;for(let s=0;s<t;s++){for(let i=0;i<e.length;i++)this.rings[i][r]=e[i][s];r=r+1===this.cap?0:r+1}this.depth+=t}process(n,e){let t=e[0];if(!t||t.length===0)return!0;this.ensure(t.length);let r=t[0].length;if(!this.started)if(this.depth>=this.primeSamples||this.primeWall<=0)this.started=!0;else{this.primeWall-=r;for(let o of t)o.fill(0);return!0}let s=t.length,i=this.fadeN;for(let o=0;o<r;o++)if(this.depth>0){if(this.starve>0){this.xfadeFrom.set(this.held);for(let a=0;a<s;a++)this.xfadeFrom[a]*=this.holdGain(this.starve);this.xfadeLeft=i,this.born?this.born=!1:this.post({type:"resume"}),this.starve=0}if(this.xfadeLeft>0){let a=1-this.xfadeLeft/i;for(let c=0;c<s;c++){let l=this.rings[c][this.read];this.held[c]=l,t[c][o]=this.xfadeFrom[c]*(1-a)+l*a}this.xfadeLeft--}else for(let a=0;a<s;a++){let c=this.rings[a][this.read];this.held[a]=c,t[a][o]=c}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 c=0;c<s;c++)t[c][o]=this.held[c]*a}return!0}holdGain(n){return n<=this.holdN?1:n<=this.holdN+this.fadeN?1-(n-this.holdN)/this.fadeN:0}};function pm(){return`registerProcessor(${JSON.stringify(io)}, ${um.toString()})`}function Ud(){let n=globalThis;return typeof n.Blob!="function"||typeof n.URL?.createObjectURL!="function"?null:n.URL.createObjectURL(new Blob([pm()],{type:"text/javascript"}))}var oo=40,Nd=2,qe=48e3,hm=12,fm=64,mm=100,ao=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<pe)return;let t=ur(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-mm)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let r=this.pending.get(t.frameSeq);if(!r)for(r={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,r);this.pending.size>fm;){let a=1/0;for(let c of this.pending.keys())c<a&&(a=c);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=r.fragCount||r.chunks[t.fragIndex]||(r.chunks[t.fragIndex]=e.subarray(pe),r.received++,r.received<r.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let s=r.chunks.reduce((a,c)=>a+(c?.byteLength??0),0),i=new Uint8Array(s),o=0;for(let a of r.chunks)i.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:r.timestamp,data:i})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},xs=class{constructor(e,t){this.config=e;this.seam=t;let r=this.seam.jitterBufferTargetMs??oo;Number.isFinite(r)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${r} is not finite \u2014 using default ${oo}ms`),r=oo),this.targetS=Math.max(0,r)/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 ao(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(s){throw this.ownsCtx&&this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,s}this.trackSurfaced=!0,this.resumeLoudly("start");let r=this.dest.stream.getAudioTracks()[0];if(!r)throw new Error("[urun] playout start produced no bridge track");this.startWorkletLoad(),this.surfaceTrack(r)}startWorkletLoad(){let e=this.ctx;if(!e||!e.audioWorklet)return;let t=globalThis.AudioWorkletNode;if(typeof t!="function")return;let r=Ud();r!==null&&(this.workletState="loading",e.audioWorklet.addModule(r).then(()=>{if(this.stopped||this.ctx!==e||this.workletState!=="loading")return;let s=new t(e,io,{numberOfInputs:0,outputChannelCount:[this.config.channels]});s.connect(this.dest),s.connect(e.destination),s.port.onmessage=i=>this.onWorkletEvent(i.data),this.workletNode=s,this.workletState="ready",s.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(s=>{this.stopped||this.ctx!==e||this.workletState!=="loading"||(this.workletState="legacy",console.warn(`[urun] WT audio worklet module FAILED to load (${s instanceof Error?s.message:String(s)}) \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 r of t)e==="ready"?this.pushWorklet(r.planes,r.frames,r.sampleRate,r.timestamp):this.scheduleLegacy(r.planes,r.frames,r.sampleRate,r.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")},r=e;typeof r.addEventListener=="function"?r.addEventListener("statechange",t):e.onstatechange=t}resumeLoudly(e){let t=this.ctx;if(!t||!t.resume||this.resumeInFlight)return;let s=t.state!=="running"?++this.resumeAttempts:0;this.resumeInFlight=!0,t.resume().catch(i=>{console.warn(`[urun] WT audio playout context ${e}: resume FAILED (state=${t.state}, attempt=${s||"n/a"}): ${i instanceof Error?i.message:String(i)} \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:r=>this.schedule(r,this.pendingTs.shift()),error:r=>this.onDecoderError(r)});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 s=globalThis.AudioDecoder;if(typeof s!="function")return;try{this.initDecoder(s)}catch{return}}let r=this.decoder;r&&(this.lastFrameArrivalAt=performance.now(),this.pendingTs.push(e.timestamp),r.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/qe)),data:e.data})))}schedule(e,t){let r=this.ctx,s=this.dest;if(!r||!s||this.stopped){e.close();return}if(r.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=${r.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 i=e.numberOfFrames,o=Math.max(1,e.numberOfChannels),a=e.sampleRate,c=[];for(let l=0;l<o;l++){let d=new Float32Array(i);e.copyTo(d,{planeIndex:l,format:"f32-planar"}),c.push(d)}if(e.close(),this.workletState==="ready"&&this.workletNode){this.pushWorklet(c,i,a,t);return}if(this.workletState==="loading"){this.stashPendingPcm(c,i,a,t);return}this.scheduleLegacy(c,i,a,t)}pushWorklet(e,t,r,s){let i=this.workletNode,o=this.ctx;if(!i||!o||this.stopped)return;if(r!==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=${r} vs ctx=${o.sampleRate}, channels=${e.length} vs configured=${this.config.channels}) \u2014 dropped for the ring player`);return}let a=this.lastTsS;if(s!==void 0){let d=s/qe;a!==null&&d<a&&(i.port.postMessage({type:"reset"}),this.workletStale=!1,this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout: producer timeline RESTART (${(a-d).toFixed(3)}s backward) \u2014 worklet ring flushed, new content fades in`))),this.lastTsS=d}let c=e.map(d=>d.buffer);i.port.postMessage({type:"pcm",frames:t,bufs:c},c),this.workletStale=!1,this.scheduledCount++;let l=performance.now();if(this.lastScheduledAt===0||l-this.lastScheduledAt>500){let d=this.lastScheduledAt===0?-1:l-this.lastScheduledAt,u=s!==void 0&&a!==null?(s/qe-a)*1e3:null;this.lastReplyStart={at:l,idleMs:d,tsJumpMs:u,anchor:"worklet",leadMs:this.targetS*1e3,arrivalToScheduledMs:l-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start (ring): idle=${d.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,r,s){for(this.pendingPcm.push({planes:e,frames:t,sampleRate:r,timestamp:s});this.pendingPcm.length>hm;)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,r,s){let i=this.ctx,o=this.dest;if(!i||!o||this.stopped)return;let a=e.length,c=i.createBuffer(a,t,r);for(let g=0;g<a;g++)c.copyToChannel(e[g],g);let l=t/r,d=i.createBufferSource();d.buffer=c,d.connect(o),d.connect(i.destination);let u,p="ride";if(s===void 0)u=Math.max(this.playhead,i.currentTime+this.targetS),p="arrival-fallback";else{this.contentBaseS===null&&(this.contentBaseS=s/qe,this.wallBaseS=i.currentTime+this.targetS,p="fresh-anchor"),u=this.wallBaseS+s/qe-this.contentBaseS;let g=null;this.lastTsS!==null&&(s<this.lastTsS?(u=i.currentTime+this.targetS,g=`backward ts step ${(this.lastTsS-s/qe).toFixed(3)}s (producer clock reset)`):u>i.currentTime+this.targetS+Math.max(l,this.targetS)&&(g=`forward jump ${(u-i.currentTime).toFixed(3)}s out (lead + ${l.toFixed(3)}s tolerance exceeded \u2014 barge flush / producer re-anchor)`),g&&(p=g.startsWith("backward")?"backward":"surplus",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored on a content-timeline discontinuity: ${g} \u2014 the gap is honest silence at rate 1.0, never a stretch`)),this.contentBaseS=s/qe,this.wallBaseS=i.currentTime+this.targetS,u=this.wallBaseS)),u<i.currentTime&&(p="deficit",this.reanchorLogged||(this.reanchorLogged=!0,console.warn(`[urun] WT audio playout re-anchored ${(i.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=s/qe,this.wallBaseS=i.currentTime+this.targetS,u=this.wallBaseS)}d.start(u),this.liveSources.add(d),d.onended=()=>{this.liveSources.delete(d)},this.scheduledCount++;let f=performance.now();if(this.lastScheduledAt===0||f-this.lastScheduledAt>500){let g=this.lastScheduledAt===0?-1:f-this.lastScheduledAt,h=s!==void 0&&this.lastTsS!==null?(s/qe-this.lastTsS)*1e3:null;this.lastReplyStart={at:f,idleMs:g,tsJumpMs:h,anchor:p,leadMs:(u-i.currentTime)*1e3,arrivalToScheduledMs:f-this.lastFrameArrivalAt},console.info(`[urun] WT audio reply-start: idle=${g.toFixed(0)}ms tsJump=${h===null?"n/a":h.toFixed(0)+"ms"} anchor=${p} lead=${((u-i.currentTime)*1e3).toFixed(0)}ms arrival\u2192scheduled=${(f-this.lastFrameArrivalAt).toFixed(1)}ms target=${(this.targetS*1e3).toFixed(0)}ms droppedNotRunning=${this.notRunningFrames}`)}this.lastScheduledAt=f,s!==void 0&&(this.lastTsS=s/qe),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(s=>e-s<1e4),this.rebuildTimes.length>=Nd){e-this.rebuildBudgetLoggedAt>1e4&&(this.rebuildBudgetLoggedAt=e,console.error(`[urun] WT audio bridge rebuild budget spent (${Nd} 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 s=globalThis.AudioContext;if(typeof s!="function")throw new Error("[urun] AudioContext unavailable for the playout rebuild");t=new s({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 r=this.dest.stream.getAudioTracks()[0];if(!r)throw new Error("[urun] rebuilt playout produced no bridge track");this.surfaceTrack(r)}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(r=>{if(this.stopped)return;if(r?this.lastRemote=r:this.lastRemote&&this.lastRemote.readyState!=="live"&&(this.lastRemote=null),r){this.deliverSurface(r);return}if(this.lastRemote&&this.lastRemote.readyState==="live"){this.deliverSurface(this.lastRemote);return}let s=this.bridgeTrack&&this.bridgeTrack.readyState==="live"?this.bridgeTrack:null;this.deliverSurface(s)}),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(r){console.error(`[urun] WT audio decoder re-init failed \u2014 lane silent until a later frame re-inits; transport unaffected: ${r instanceof Error?r.message:String(r)}`)}}};var an=1200;function co(n,e,t,r,s){let i=r-pe;if(i<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/i));if(o>255)return null;let a=[];for(let c=0;c<o;c++){let l=t.subarray(c*i,Math.min((c+1)*i,t.byteLength)),d=Es({groupId:e>>>0,frameSeq:n>>>0,keyframe:s?.keyframe??!0,fragIndex:c,fragCount:o,lane:s?.lane??Cs}),u=new Uint8Array(pe+l.byteLength);u.set(d,0),u.set(l,pe),a.push(u)}return a}var gm=`
|
|
4
4
|
self.onrtctransform = (event) => {
|
|
5
5
|
const transformer = event.transformer
|
|
6
6
|
if (transformer.options?.role === 'sender') {
|
|
@@ -28,4 +28,4 @@ self.onrtctransform = (event) => {
|
|
|
28
28
|
}
|
|
29
29
|
`;function Wd(n){let e=n.match(/a=rtpmap:(\d+) opus\/48000\/2/)?.[1];if(!e)return n;let t="usedtx=1;useinbandfec=1;maxaveragebitrate=32000",r=!1,s=n.split(`\r
|
|
30
30
|
`).map(i=>i.startsWith(`a=fmtp:${e} `)&&!i.includes("usedtx=")?(r=!0,`${i};${t}`):i);if(!r){let i=s.findIndex(o=>o===`a=rtpmap:${e} opus/48000/2`);i>=0&&s.splice(i+1,0,`a=fmtp:${e} ${t}`)}return s.join(`\r
|
|
31
|
-
`)}var Ds=class n{constructor(e,t){this.sink=e;this.seqState=t??{seq:0}}sink;stopped=!1;deadCb=null;seqState;static FLOW_WINDOW_MS=5e3;static FLOW_MIN_SENT_PER_WINDOW=25;sentCount=0;flowTimer=null;flowLastSent=0;flowLastDelivered=0;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}sentDatagrams(){return this.sentCount}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=_m(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&(this.engage(t),this.startFlowWatch())}}startFlowWatch(){this.flowTimer||this.stopped||(this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),this.flowTimer=setInterval(()=>{if(this.stopped)return;let e=this.sentCount-this.flowLastSent,t=this.sink.delivered()-this.flowLastDelivered;this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),e>0&&console.log(`[urun] WT mic uplink flow: wrote=${(e/(n.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s accepted=${(t/(n.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s`),!(e<n.FLOW_MIN_SENT_PER_WINDOW)&&(t*2>=e||console.error(`[urun] WT mic uplink flow STARVED: wrote ${e} datagrams in ${n.FLOW_WINDOW_MS/1e3}s but QUIC accepted only ${t}`))},n.FLOW_WINDOW_MS))}stop(){if(!this.stopped){this.stopped=!0,this.flowTimer!==null&&(clearInterval(this.flowTimer),this.flowTimer=null),this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let r;try{r=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let s=this.sendPc.addTrack(e);this.sender=s,this.currentTrack=e,this.wireTrackLiveness(e);let i=t.RTCRtpScriptTransform;if(s.transform=new i(r,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(o=>this.die(`loopback renegotiate: ${o instanceof Error?o.message:String(o)}`));return}this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let s=r.transceiver?.mid??null;s!==null&&s===this.renderMidOf()&&this.renderRemoteCb?.(r.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let r=await e.createOffer();r.sdp=Wd(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let s=await t.createAnswer();s.sdp=Wd(s.sdp??""),await t.setLocalDescription(s),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:s.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let r=t.context.createMediaStreamDestination();t.connect(r);let s=r.stream.getAudioTracks()[0]??null;return s?(this.nodeBridge={node:t,dest:r},s):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([gm],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let r=t.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let r=co(this.seqState.seq,e,t,this.sink.maxDatagramSize()||an);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.seqState.seq=this.seqState.seq+1>>>0;return}for(let s of r)this.sink.send(s),this.sentCount++;this.seqState.seq=this.seqState.seq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function _m(n){let e=n;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var vm=9e4,wm="avc1.42E01F",ym=60,bm=3,Sm=1e4;function km(n){return Math.round(n*(vm/1e6))%2**32>>>0}var As=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let s=++this.generation,i=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,i.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&s===this.generation;){let{value:a,done:c}=await i.read();if(c)break;if(a){if(o||this.stopped||s!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&s===this.generation&&this.die(`capture: ${a instanceof Error?a.message:String(a)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(e){let t={width:e.codedWidth,height:e.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==t.width||this.encoderDims.height!==t.height){let i=globalThis.VideoEncoder;if(typeof i!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new i({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:wm,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(o){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let s=this.keyframeWanted||this.framesSinceKeyframe>=ym;this.keyframeWanted=!1,this.framesSinceKeyframe=s?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:s})}catch(i){this.onEncoderError(i instanceof Error?i:new Error(String(i)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=co(this.frameSeq,km(e.timestamp),t,this.sink.maxDatagramSize()||an,{lane:Md,keyframe:e.type==="key"});if(r===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(r=>t-r<Sm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=bm){this.die(`video encoder: ${e.message}`);return}console.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",e.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(e){this.stopped||(console.warn(`[urun] WT video uplink lane dead (${e}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Tm(n){return n.byteLength>=2&&n[0]===1&&n[1]===3}var Is=class{constructor(e){this.transport=e}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(e){this.deadCb=e}send(e,t){let r=new TextEncoder().encode(e);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let i=this.streams.get(e);if(!i){let a=await this.transport.openUniStream(),c=new Uint8Array(2+r.byteLength);c[0]=1,c[1]=r.byteLength,c.set(r,2),await a.write(c),i={writer:a},this.streams.set(e,i)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await i.writer.write(o),Tm(t)&&(this.streams.delete(e),await i.writer.close().catch(()=>{}))}catch(i){throw this.die(i instanceof Error?i.message:String(i)),i}});return this.chain=s.catch(()=>{}),s}stop(e="stopped"){if(this.dead===null){this.dead=e;for(let t of this.streams.values())t.writer.close().catch(()=>{});this.streams.clear()}}die(e){this.dead===null&&(console.warn(`[urun] WT data uplink lane dead (${e})`),this.stop(e),this.deadCb?.(e))}};var Fd=250,Rm=25,Cm=2e3,Em=15e3,Pm=1e3,xm=45e3,Dm=5e3,Am={llm:!0},Im=500,$d=10,Lm=2,Mm=2,lo=2,hr=class n{constructor(e,t,r,s,i,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=s;this.audioUplink=i;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((c,l)=>{this.firstFrameResolve=c,this.firstFrameReject=l}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new pr({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,r=t!==void 0&&t!=="";this.hasVideoLane=r,r&&no(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(d=>({algorithm:"sha-256",value:Uint8Array.from(atob(d),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let s=await this.wt.createBidirectionalStream();this.writer=s.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=s.readable.getReader(),o=new lr,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let l=c;if(this.lastInboundControlAt=performance.now(),typeof l.pingIntervalMs=="number"&&l.pingIntervalMs>0?this.advertisedPingIntervalMs=l.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,console.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),r&&(no(l.codec,"hello-ack"),this.initDecoder(l.codec,l.width,l.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let d={setSource:p=>{this.renderSource=p,this.audioUplinkLane?.setRenderSource?.(p)},onRemote:p=>{this.renderRemoteCb=p}},u=new xs(this.offer.audio,{...this.audioLane,renderHop:d});try{u.start(),this.audioPlayout=u}catch(p){console.warn(`[urun] WT audio lane failed to start (${p instanceof Error?p.message:String(p)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),u.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let d=this.wt.createUnidirectionalStream?.bind(this.wt);if(!d)throw new Error("WebTransport uni streams are not creatable in this environment");let u=new Is({openUniStream:async()=>(await d()).getWriter()});u.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p,u)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(d){let u=d instanceof Error?d.message:String(d);console.warn(`[urun] WT data uplink failed to engage (${u}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(u)}this.controlLoop(i,o,a).catch(d=>this.die(`control loop: ${d}`)),this.datagramLoop().catch(d=>this.die(`datagram loop: ${d}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),Im)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(d=>{this.closedReason=`connection error: ${d}`,this.die(`connection error: ${d}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${Fd}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Em},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Pm))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,r=typeof e.ur=="number"?e.ur:null;if(t===null&&r===null)return;this.gatewayExposesCounters=!0;let s=this.audioDgramsReceived,i=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:r,recvDownlink:s,sentUplink:i},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,c=r!==null&&o.ur!==null?r-o.ur:null,l=s-o.recvDownlink,d=i-o.sentUplink,u="none";if(a!==null&&a>=$d&&l<=0?u="downlink":c!==null&&d>=$d&&c<=0&&(u="uplink"),u==="none"){this.severedStreak="none",this.observePlayoutProgress(l,t);return}if(this.severedStreak!==u){this.severedStreak=u;return}this.severedStreak="none";let p=u==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${d} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+p+` (gateway flow counters ds=${t} ur=${r}, client received=${s} accepted=${i}, confirmed on ${Lm} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let r=this.audioPlayout;if(!r){this.playoutScheduledSeen=null;return}let s=r.playoutProgress(),i=s.surfaced;if(this.playoutScheduledSeen!==null&&s.scheduled>this.playoutScheduledSeen&&i){this.playoutScheduledSeen=s.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=s.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Mm)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,console.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${s.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{r.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=lo}return}this.playoutStallStreak<lo||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${s.scheduled} on ${lo} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let r=performance.now(),s=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,i=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=s===null&&i===null?!0:(s===null||s>=e.stallMs)&&(i===null||i>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&i!==null&&i>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(i/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let c=!!(this.offer.audio&&this.audioLane),l=this.lastInboundDataAt===null?null:r-this.lastInboundDataAt,d=s!==null?s:this.firstInboundDataAt===null?null:r-this.firstInboundDataAt,u=d!==null&&d>=e.stallMs;if(c&&u&&l!==null&&l<=Dm&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((d??0)/1e3)}s while the data lane delivered a frame ${Math.round((l??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${t.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&i!==null&&i>=xm&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(i/1e3)}s while the path reports alive (${t.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e,t))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let s=this.audioUplinkLane;s?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,s??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let s=this.videoUplinkLane;s?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,s??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let t={onData:(r,s)=>{if(Am[r]===!0){let i=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=i),this.lastInboundDataAt=i}e.onData(r,s)},onLaneError:r=>e.onLaneError(r)};this.dataLaneSink=t,Ps(this.wt.incomingUnidirectionalStreams,t).catch(r=>{this.die(`data lane: ${r instanceof Error?r.message:String(r)}`)})}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r};let o=new s({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,i.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=this.decoderConfig;if(!t){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(t.codec,t.width,t.height),this.decoderErrorLogged=!1}catch(r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${r instanceof Error?r.message:String(r)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,s=>this.onUplinkSendError(s))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let r=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(s=>r-s<Cm),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<Rm)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSeqState={seq:0};uplinkSink(e){this.datagramWriter();let t=0;return{send:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??an}}engageAudioUplink(){let e=new Ds(this.uplinkSink("audio"),this.uplinkSeqState);e.onDead(t=>this.onUplinkLaneDead("audio",t,e)),e.onRenderTrack?.(t=>this.renderRemoteCb?.(t)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new As(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let t=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(r){let s=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${s}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,s)}}freshLaneBuilt(e){let t={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),t}onUplinkLaneDead(e,t,r){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let s=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,a=i?.builtAt!=null&&Date.now()-i.builtAt>=n.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(a>n.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${s} uplink lane dead (${t}) \u2014 ${n.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${n.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`,r);return}console.warn(`[urun] WT ${s} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${a}/${n.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let c={count:a,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=c:this.videoUplinkRetry=c,c.timer=setTimeout(()=>{c.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},n.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t,r){e==="audio"?this.audioUplink.onUplinkLost(t,r):this.videoUplink.onUplinkLost(t,r)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;if(t.byteLength>=pe&&t[11]===Cs){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;if(typeof s=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new s({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(Rs(e)),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async sendControlRaw(e){try{let t=new Uint8Array(4+e.byteLength);new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),await this.writer.write(t),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&r.push(...t.push(i))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;let i=s;if(this.lastInboundControlAt=performance.now(),i.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(Ld(s.raw,"pong"))}catch{}}(i.t==="ping"||i.t==="pong")&&this.observeFlowCounters(i),i.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:i>0?100*s.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Fd)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var jd=2500,qd=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Om=1e4,fr=class n{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let t=this.session;!t||t.kind!=="webtransport"||t.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&r&&s,webcodecs:r,codecs:qd,wtData:t&&r&&s&&this.opts.dataLane!==void 0,wtAudio:t&&r&&s&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&s&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&r&&s&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&s&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i}),this.noteOfferedWtHost();let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let l=null;try{return l=this.createWebTransportSession(),await po(l.start(),this.opts.quicDeadlineMs??jd,"quic connect deadline"),this.wtDialedHost=uo(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(l,i.wtData===!0),this.session=l,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(d){if(console.warn(`[urun] WT dial failed (${cn(d)}) \u2014 dialed ${Bd(this.offer.webtransport?.url)}`),l?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let u=String(d instanceof Error?d.message:d);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${u}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(u),d}console.warn("[urun] webtransport failed, falling back to webrtc:",d),this.proceedWebRtcDial(`wt failed: ${String(d instanceof Error?d.message:d)}`),this.notifyEstablished("webrtc",String(d instanceof Error?d.message:d))}}if(this.opts.allowWebRtcFallback===!1){let l=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${l} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(l),new Error(`[urun] WT required but unavailable: ${l}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}noteOfferedWtHost(){let e=uo(this.offer?.webtransport?.url);e===void 0||this.wtDialedHost===void 0||e===this.wtDialedHost||(this.wtHostMismatchCount+=1,console.error(`[urun] re-dial offered host ${e} != original host ${this.wtDialedHost}`+(Um(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,s=this.opts.dataLane!==void 0,i=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:qd,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let l=this.createWebTransportSession();try{await po(l.start(),this.opts.quicDeadlineMs??jd,"quic connect deadline")}catch(d){throw console.warn(`[urun] WT dial failed (${cn(d)}) \u2014 dialed ${Bd(this.offer.webtransport?.url)}`),l.stop().catch(()=>{}),d}if(this.wtDialedHost=uo(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==r)return l.stop().catch(()=>{}),null;try{this.engageQuicDataLane(l,s)}catch(d){throw l.stop().catch(()=>{}),d}if(this.disconnected)return l.stop().catch(()=>{}),null;this.session=l;{let d=this.offer.webtransport;d&&(this.opts.audioLane===void 0||d.audio!==void 0)&&(this.opts.audioUplink===void 0||d.audioUp===!0)&&(this.opts.videoUplink===void 0||d.videoUp===!0)&&(this.opts.dataLane===void 0||d.data===!0)&&(this.opts.dataUplink===void 0||d.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),l}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(s,i)=>r.onData(s,i),onLaneError:s=>r.onLaneError(s)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new hr(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.onWtLegDeath?.(t),this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t,!0);return}let r=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),r){this.session=null,this.wtOnlyLeg=!1,console.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",t),this.redialWtAfterDeath(t,!0);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,r)})}redialWtAfterDeath(e,t=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=n.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${n.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}console.error(`[urun] WT re-dial failed ${n.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let r=this.wtRedialFailures+1,s=ho(n.WT_REDIAL_BASE_MS,r,n.WT_REDIAL_CAP_MS,r===1&&t?0:void 0);console.warn(`[urun] WT re-dial attempt ${r} scheduled in ${Math.round(s)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},s)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){console.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let r=cn(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX} failed (${r}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${r}`)}}}lateWebRtcFailover(e,t,r){this.disconnected||(async()=>{let s=this.createWebRtc();try{let i=await po(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??Om,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(i){if(s.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=r?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function cn(n){if(n instanceof Error)return n.message;if(typeof n=="string")return n;if(n&&typeof n=="object"){try{let e=JSON.stringify(n);if(e!==void 0&&e!=="{}")return e}catch{}return n.constructor?.name??Object.prototype.toString.call(n).slice(8,-1)}return String(n)}function uo(n){if(n)try{return new URL(n).host}catch{return}}function Bd(n){if(!n)return"(no offer url)";try{let e=new URL(n);return e.searchParams.delete("token"),e.toString()}catch{return n.replace(/[?&]token=[^&\s]*/g,"")}}function Um(n){if(!n)return!1;let e=n.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function ho(n,e,t,r){if(r!==void 0)return r;let s=Math.min(n*2**Math.max(0,e-2),t);return Math.round(s*(.75+Math.random()*.5))}function po(n,e,t){return new Promise((r,s)=>{let i=setTimeout(()=>s(new Error(t)),e);n.then(o=>{clearTimeout(i),r(o)},o=>{clearTimeout(i),s(o)})})}var Nm=1e4,mr=class{constructor(e,t=Nm){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=sr();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:l,requestId:d,...u}=c;s(u)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(o),a(),i(new Error(`[urun] signaling request not sent: ${e} \u2014 the signaling socket is not open`)))})}notify(e,t){this.carrier.sendSignal({type:e,...t})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${e} \u2014 the signaling socket is not open`,detail:{method:e}})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};var Wm="video",gr=class{constructor(e,t=Wm){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};function Hd(n){let e=n;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Fm="video";var $m=45e3;async function jm(n,e,t){let s=e?.current()?.name??null;if(s==="live")return"live";if(s==="error")return"gone";if(s==="idle"||s==="connecting")return"live";if(!e)return"unconfirmed";let i=e,o=t.runtimeWaitCapMs??$m;return new Promise(a=>{let c=!1,l,d=null,u=null,p=!1,f=_=>{c||(c=!0,m(),u!==null&&(clearTimeout(u),u=null),l?.(),a(_))};u=setTimeout(()=>{if(p||c||t.isDisposed())return;p=!0;let _=i.current();n.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${t.sessionId} (server status: ${_?.reason??_?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let h=()=>{d===null&&!c&&(d=setTimeout(()=>f("unconfirmed"),o))},m=()=>{d!==null&&(clearTimeout(d),d=null)};l=e.subscribe(_=>{let v=_?.name;if(v==="live")return f("live");if(v==="error")return f("gone");m(),Be(v)||h()}),Be(s)||h()})}function Vd(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=n.holdWebRtcDial?.(),a=s.createElement("canvas"),c=!1,l=null,d=!1,u=()=>{if(l){for(let E of l.getVideoTracks())try{E.stop()}catch{}l=null}d&&(d=!1,t.onOverrideTrack(null))},p=new fr(new mr(n),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new gr(n,t.streamName??Fm)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(E,N)=>n.dispatchQuicStreamData(E,N),onQuicLane:()=>n.markStreamDataLaneQuic(),onQuicLaneLost:E=>n.quicStreamDataLaneLost(E),onLaneError:E=>n.raiseQuicStreamDataError(E)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:E=>{c||(E&&n.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(E))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>w(),onMediaTransportLost:E=>{c||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(E),w())},onWtLegDeath:()=>{n.noteMediaLegDeath?.()},onTransportChange:(E,N)=>{c||(E==="webrtc"&&(u(),w()),t.onTransportChange?.(E,N))}}),f=n.onWtOnlyLegDeath?.(E=>p.failCurrentWtLeg(E)),g=null,h=()=>{g!==null&&(clearInterval(g),g=null)},m=t.wtRetryBaseMs??2e3,_=t.wtRetryCapMs??3e4,v=null,S=0,w=()=>{if(c||v!==null||p.activeTransport==="webtransport")return;let E=ho(m,S+2,_);v=setTimeout(()=>{v=null,S+=1,p.retryWebTransport().then(N=>{if(c){N&&p.disconnect().catch(()=>{});return}if(N)return console.debug(`[urun] webtransport upgraded in background (retry ${S})`),S=0,T(N);w()}).catch(N=>{c||(console.debug(`[urun] webtransport background retry ${S} failed: `+cn(N)),w())})},E)},b=()=>{v!==null&&(clearTimeout(v),v=null)},T=async E=>{if(c||E.kind!=="webtransport")return;let N=t.pathHealthProbeMs??1e4;h();let Q=!1;g=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let F=Hd(E);if(!F){console.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),h();return}let $=F.pathLiveness();if(!$.alive){let G=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${$.evidence}`+(G?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),h(),F.fail(`path health: ${$.evidence}`);return}if(!Q){if(Q=!0,p.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${N}ms \u2014 the QUIC PATH IS HEALTHY (${$.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${N}ms \u2014 no media datagrams reached this client (path healthy: ${$.evidence}); webrtc track remains authoritative`)}},N);try{await E.firstMedia}catch(F){h(),console.debug("[urun] webtransport ended before any media flowed:",F);return}if(h(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;l=a.captureStream();let te=l.getVideoTracks()[0];te&&(d=!0,t.onOverrideTrack(te))},y=!1;return(async()=>{let E=await jm(n,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>c});if(c)return;if(E==="gone"){console.debug(`[urun] session ${e} ended while waiting for a runtime to pick it up \u2014 no media negotiation`),o?.proceed("session ended before a runtime was pulled \u2014 releasing the held WebRTC dial");return}y=!0;let N=await p.connect();if(c){p.disconnect().catch(()=>{});return}await T(N)})().catch(E=>{if(h(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",E);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",E),w();return}o?.proceed(`negotiation unavailable: ${E instanceof Error?E.message:String(E)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",E),w()}),{activeTransport:()=>p.activeTransport,mediaTransportAttempted:()=>y,watchDownlinkStall(E){p.watchDownlinkStall(E)},dispose(){c=!0,f?.(),h(),b(),u(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var qm=new Set;function _o(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var Bm="rpc",Hm="$presence",fo=["control",Sr],Ls=2e4,vo=3e4,zd=3e4,Vm="rpc-resp";function zm(n){return`${Vm}:${n}`}function mo(){return sr()}function Gm(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function Km(n,e,t,r,s,i,o,a,c,l){let d=[],u=null,p=!1,f=null,g=!1,h,m,_=new Promise((k,z)=>{h=k,m=z});_.catch(()=>{});let v=o(),S=null,w=null,b=null,T=null,y=null,E=null,N=!0,Q=()=>{b&&(clearTimeout(b),b=null),T&&(T(),T=null)},te=()=>{y&&(clearTimeout(y),y=null),E&&(E(),E=null)},F=!1,$=()=>{F||!g||(F=!0,n.set({rpc:{[e]:null}}))},G=()=>{N=!1,Q(),te(),S?.(),S=null,w?.(),w=null,a?.removeEventListener("abort",x),v.dispose(),$()},X=()=>{if(u){if(d.length>0){let k=u;u=null,k.resolve({value:d.shift(),done:!1})}else if(f!==null){let k=u;u=null,k.reject(f)}else if(p){let k=u;u=null,k.resolve({value:void 0,done:!0})}}},he=k=>{p||(d.push(k),X())},Z=k=>{p||(f=k,p=!0,m(k),G(),X())},Me=k=>{p||(p=!0,h(k),G(),X())},x=()=>{let k=a?.reason;Z(k instanceof Ce?k:new nt(e))},O=k=>{if(!(p||!k||typeof k!="object"))switch(te(),$(),k.t){case"delta":typeof k.delta=="string"&&he(k.delta);break;case"response":Me(k.body);break;case"error":{let{message:z,code:j}=Gm(k.body);Z(new Ce(z,{requestId:e,code:k.code??j}));break}}},B=()=>{let k=v.messages()[Symbol.asyncIterator]();S=()=>{k.return?.(void 0)};let z=()=>{N&&k.next().then(j=>{if(N){if(j.done){p||Me(void 0);return}O(j.value),z()}},j=>{N&&Z(j)})};z()},D=()=>{if(!g){if(g=!0,a){if(a.aborted){Z(new nt(e));return}a.addEventListener("abort",x,{once:!0})}w=c?.(k=>Z(k))??null,B(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),l&&l>0&&!n.synced&&(b=setTimeout(()=>{b=null,!p&&!n.synced&&Z(new Tt(l,e))},l),T=n.onSynced(()=>Q())),E=n.onSynced(()=>{E=null,!(p||F||y)&&(y=setTimeout(()=>{y=null,!(p||F)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(zd/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},zd))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(D(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(f!==null){let k=f;return f=null,Promise.reject(k)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((k,z)=>{u={resolve:k,reject:z}})},return(){return p||(p=!0,h(void 0),G()),Promise.resolve({value:void 0,done:!0})},throw(k){return p||(p=!0,m(k),G()),Promise.reject(k)}}}},body:_,start:D}}function Gd(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Ym(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=Gd(i);c&&(a.rt=c);let l=Gd(o);return l&&(a.br=l),a}var go=class{constructor(e,t,r,s,i){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=i;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_directOut=!1;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,i=null,o={push(c){if(!s)if(r){let l=r;r=null,l.resolve({value:c,done:!1})}else t.push(c)},end(){if(s=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{s=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||s)&&(i=e._streamConsumeUnavailableError(c),a(),r)){let l=r;r=null,l.reject(i)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):i?Promise.reject(i):s?Promise.resolve({value:void 0,done:!0}):new Promise((c,l)=>{r={resolve:c,reject:l}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}get directOut(){return this._directOut}_setOverrideTrack(e,t){if(this._overrideTrack===e&&this._directOut===(t?.directOut??!1))return;this._overrideTrack=e,this._directOut=e?t?.directOut??!1:!1,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let r=e??this._transport.getTrackByName(this._name)??this._track,s=this._handlers.get("track");if(s)for(let i of s)i(r)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Ym(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Rt(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??ks;return Id(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},_r=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new hs;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_gateDocUp={};_gate="open";_gateTimer=null;_gateDocUnsubs=[];_gateOff=!1;_gatedFrom;_gatedWith;_publicPhase;_phaseHandlers=new Set;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,s,i,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=Xc(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=ys(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=ws({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new dr({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(Hm).awareness.setLocalState({role:"client"}),this._activation=new xt({onPhase:a=>this.onPhase(a),hint:()=>this.doc(Sr).get(mn)??this.doc("control").get(gn),onData:(a,c)=>this._streamData.onData(a,c)}),this._transport.on("phase",()=>this._applyLiveGate());for(let a of fo)this._gateDocUnsubs.push(this.doc(a).onConnectionState(c=>{this._gateDocUp[a]=c.connected,this._applyLiveGate()}))}_applyLiveGate(){let e=this._transport.phase;if(!e)return;let t=this._gateOff||!this._docConnector.connected||fo.every(i=>this._gateDocUp[i]);if(e.name!=="live"||t?(clearTimeout(this._gateTimer??void 0),this._gateTimer=null,this._gate="open"):this._gate==="open"&&(this._gate="connecting",this._gateTimer=setTimeout(()=>{this._gateTimer=null,this._gate="failed",this._applyLiveGate()},Ls)),e===this._gatedFrom&&this._gate===this._gatedWith)return;this._gatedFrom=e,this._gatedWith=this._gate;let r=fo.filter(i=>!this._gateDocUp[i]).join("/"),s=this._gate==="open"?e:this._gate==="connecting"?{...e,name:"connecting",reason:"docs_connecting"}:{...e,name:"error",reason:"doc_plane_unreachable",error:{kind:"transport-failed",code:"doc_plane_unreachable",reason:`the session's ${r} doc connection did not open within ${Ls/1e3}s (still retrying)`}};if(s!==this._publicPhase){this._publicPhase=s;for(let i of[...this._phaseHandlers])i(s)}}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await ta({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new St,o=new cr({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,_o(t),Ar({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),Je()&&await Dt();let c=t.getAccessToken,l=c?d=>!d?.redial&&s?s:Promise.resolve(c()).then(u=>u??s):s;return a.setDocTransport({wsUrl:r.wsUrl,token:l}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase!==this._gatedFrom&&this._applyLiveGate(),this._publicPhase??this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){let e=this._transport.status,t=this.phase;return!e||!t||t===this._transport.phase?e:{...e,phase:t.name,...t.error?{error:t.error}:{}}}get region(){return this._transport.region}onPhase(e){return e(this.phase),this._phaseHandlers.add(e),()=>{this._phaseHandlers.delete(e)}}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return fn(this,e)}on(e,t){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(t),this._generationTickStop||(this._generationTickStop=_s(this.doc("control"),r=>{for(let s of Array.from(this._generationTickHandlers))try{s(r)}catch(i){console.warn("[urun] generationTick handler failed:",i)}})),()=>{this._generationTickHandlers.delete(t),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new dt(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new Xe(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new Xe(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new go(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new gs(e,this._sessionId,qm.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Td(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=fs(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",s=e.attach?`${e.attach.gen}:${e.attach.token}`:"",i=`${t}${r}${s}${this._sessionId}`;i!==this._docEndpointKey&&(this._docEndpointKey=i,this.connectDocs(Sd({serverUrl:t,sessionId:this._sessionId,token:e.token,attach:e.attach,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=mo(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;i=setTimeout(()=>s.abort(new kt(c,r)),c)}let o=this._consumeResponse(r,e,!1,s.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,t,r,s,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(Bm),a=zm(e);return Km(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??vo)}requestStream(e,t={}){let r=mo();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=mo(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Vd(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,runtimePhase:{current:()=>this._transport.phase??null,subscribe:t=>this._transport.on("phase",t)},onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t,{directOut:!0}),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}get mediaTransportAttempted(){return this._dialNegotiation?.mediaTransportAttempted()??!1}watchDownlinkStall(e={}){return this._downlinkStallWatch=e,this._dialNegotiation?.watchDownlinkStall(e),()=>{this._downlinkStallWatch=null}}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new Oe)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Oe);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let s of t)try{s()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let r=Array.from(this._activeRequests);this._activeRequests.clear();for(let s of r)try{s(new Et)}catch{}this._gateOff=!0,clearTimeout(this._gateTimer??void 0),this._gateTimer=null;for(let s of this._gateDocUnsubs.splice(0))s();for(let s of this._docs.values())s.dispose();this._docs.clear();for(let s of this._streams.values())s.dispose();this._streams.clear(),this._transport.disconnect(e)}};function Kd(n){return`urun:session:v2:${n.orgId}:${n.app}:${n.functionName}`}function wo(){try{return globalThis.sessionStorage??null}catch{return null}}var yo=new Map;function Ms(n){if(!n)return;let e=n.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof r?.sub=="string"&&r.sub.length>0?r.sub:void 0}catch{return}}function Qm(n,e){return n!==void 0&&e!==void 0&&n!==e}function bo(n,e){let t=wo(),r=null;if(t)try{let i=t.getItem(n);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(r={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{r=null}let s=yo.get(n)??r??null;return!s||Qm(s.actor,e)?null:s}function Yd(n,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};yo.set(n,t);let r=wo();if(r)try{r.setItem(n,JSON.stringify(t))}catch{}}function Os(n){yo.delete(n);let e=wo();if(e)try{e.removeItem(n)}catch{}}var Qd=new Set(["paused","acquiring","live"]),Jm=new Set(["24h","keep"]);function Jd(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function Xm(n){if(typeof n?.id!="string"||n.id.length===0)throw new _e("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof n.state!="string"||!Qd.has(n.state))throw new _e(`[urun] session ${n.id} reported an unrecognized state ${JSON.stringify(n.state)} \u2014 this @urun-sh/core build knows only ${[...Qd].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof n.recordings_expired=="boolean"?e=n.recordings_expired:console.warn(`[urun] session ${n.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:n.id,label:typeof n.label=="string"&&n.label.length>0?n.label:null,state:n.state,app:typeof n.app=="string"?n.app:"",functionName:typeof n.function=="string"?n.function:"",createdAt:Jd(n.created_at),lastActiveAt:Jd(n.last_active_at),archived:n.archived===!0,preview:typeof n.preview=="string"&&n.preview.length>0?n.preview:null,recordingsExpired:e,retention:Jm.has(n.retention)?n.retention:(n.retention!==void 0&&console.warn(`[urun] session ${n.id} reported an unrecognized retention ${JSON.stringify(n.retention)} \u2014 defaulting to '24h'`),"24h")}}var vr=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await Xo({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(Xm),nextCursor:r}}async end(e){await Zo({...this._request,sessionId:e})}async archive(e){await Vs({...this._request,sessionId:e,archived:!0})}async unarchive(e){await Vs({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await ea({...this._request,sessionId:e,name:t,source:r.source})}};function Xd(n,e,t){let r=Ms(t);Yd(n,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var Zm=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Zd(n,e){return new vr(n,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function el(n,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,r){if(!(Zm.has(r)||typeof r!="string"))return(s,i)=>{let o=s??{},a=Kd({orgId:e.orgId,app:n,functionName:r}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,l,d=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,u=d(),p=e.jwt,f=e.getAccessToken?async x=>{let O=await e.getAccessToken(x);return O&&(p=O),O}:void 0,g={...e,getAccessToken:f},h=new St,m=new cr({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:u,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),_=new _r(u,h,m,_o(g),Ar(g),{activity:i?.activity}),v,S=!1,w=!1,b,T,y=new Promise(x=>{T=x}),E,N=x=>{x.sessionId||b||(b="teardown",E="ticket",Pr({baseUrl:x.baseUrl,requestId:x.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},Q=x=>{b||x.sessionId||(b="abandon",Pr({baseUrl:x.baseUrl,requestId:x.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider,reason:"client_abandoned"}))},te=x=>{let O=x.sessionId||!l?x:{...x,sessionId:l};v=O,T({status:"ready",handle:O}),(w||b==="teardown")&&N(O)};_.setEndHandler(async()=>{let x=v?{status:"ready",handle:v}:await y;if(x.status==="unavailable")throw new Oe("[urun] session allocation failed before a releasable request was created",{cause:x.cause});let O=v??x.handle;return Os(a),b==="teardown"?O.sessionId?{status:"paused",sessionId:O.sessionId,reason:"client_ended"}:{status:"canceled",requestId:O.requestId}:(b="end",O.sessionId?Bs({baseUrl:O.baseUrl,sessionId:O.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):qs({baseUrl:O.baseUrl,requestId:O.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let x=v?{status:"ready",handle:v}:await y;if(x.status==="unavailable")throw new Oe("[urun] session allocation failed before a cancellable request was created",{cause:x.cause});let O=v??x.handle;if(O.sessionId)throw new oe(`[urun] cancel() is for a queued admission request, but this call already has session ${O.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:O.sessionId,code:"cancel_on_live_session"});b="end";try{let B=await qs({baseUrl:O.baseUrl,requestId:O.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return Os(a),B}catch(B){throw b==="end"&&(b=void 0),B}});let F=async x=>{let O,B=i?.sessionId??e.sessionKey??l,D,W;if(B===void 0&&!c){let fe=bo(a);if(fe?.sessionId){if(W=Ms(p),fe.actor!==void 0&&W===void 0&&f){let yt=await Promise.resolve(f()).catch(()=>{});W=Ms(yt??e.jwt)}D=fe.actor!==void 0&&W!==void 0&&fe.actor!==W?void 0:fe.sessionId}}let k=B??D,z=(fe,yt)=>Yo({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,...e.shape?{shape:e.shape}:{},idempotencyKey:fe,sessionKey:yt,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:ye=>{m.reportAdmission(ye),ye.sessionId&&!l&&(l=ye.sessionId,O=ye.sessionId,v&&v.sessionId!==ye.sessionId&&te({...v,sessionId:ye.sessionId}),S||(e.sessionKey||Xd(a,ye.sessionId,p),_.setSessionId(ye.sessionId)))},onRequest:te}),j;try{j=await z(x,k)}catch(fe){let yt=fe instanceof q&&fe.code==="session_name_not_yours"&&k!==void 0&&k===l&&i?.sessionId===void 0&&e.sessionKey===void 0;if(D===void 0&&!yt||!(fe instanceof q)||fe.code!=="session_name_not_yours")throw fe;let ye=D??k;if(ye===void 0)throw fe;console.warn(`[urun] session_name_not_yours: the control plane refused session ${ye} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),yt&&(l=void 0),bo(a,W)?.sessionId===ye&&Os(a),j=await z(d(),void 0)}let Tl=f?await f()??void 0:e.jwt;if(O&&O!==j.sessionId)throw v&&v.sessionId!==j.sessionId&&te({...v,sessionId:j.sessionId}),new q(`Gateway contract violation: admission minted session ${O} but allocation completed as ${j.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return l=j.sessionId,v&&v.sessionId!==j.sessionId&&te({...v,sessionId:j.sessionId}),S||(e.sessionKey||Xd(a,j.sessionId,p),_.setSessionId(j.sessionId),X=wn(j.baseUrl)?{baseUrl:j.baseUrl,sessionId:j.sessionId}:null,_.setArtifactsAuth(Ar({...g,baseUrl:j.baseUrl})),m.setEndsAt(j.endsAt),m.seedRegion(Gs(j.response))),{url:j.wsUrl,sessionId:j.sessionId,jwt:Tl,iceServers:j.response.ice_servers,endsAt:j.endsAt,sfuAttach:j.sfuAttach}},$,G,X=null,he=f?x=>!x?.redial&&$?$:Promise.resolve(f(x?.redial?{forceRefresh:!0,reason:"background"}:void 0)).then(O=>$=O??$):()=>$,Z=()=>{let x=m.connectedUrl;return x?fs(x):void 0};if(m.setConnectionResolver(async()=>{let x=await F(d());return $=x.jwt,G=x.sfuAttach,x}),m.setConnectionViewRefresher(async()=>X?Jo({baseUrl:X.baseUrl,sessionId:X.sessionId,jwt:p}):null),m.on("connected",()=>{m.multiplexer&&h.setTarget(m.multiplexer);let x=m.connectedUrl;x&&_.setDocTransport({wsUrl:x,token:he,attach:G,resolveServerUrl:Z})}),(async x=>{let O;try{O=await F(x)}catch(B){if(S){T({status:"unavailable",cause:B});return}console.error(`[urun] Failed to create session for ${r}:`,B),v&&Q(v);let D=B instanceof Error?B:new Error(String(B)),W=B instanceof q?B.httpStatus:void 0,k=B instanceof q?B.code:void 0,z=B instanceof q?B.retryAfterSeconds:void 0;m.reportAllocationFailure(D,W,k,z),T({status:"unavailable",cause:B});return}S||(m.setAuth({jwt:O.jwt,authProvider:e.authProvider,orgId:e.orgId}),m.setConnection({url:O.url,sessionId:O.sessionId,iceServers:O.iceServers,sfuAttach:O.sfuAttach}),Je()&&await Dt(),$=O.jwt,G=O.sfuAttach,_.setDocTransport({wsUrl:O.url,token:he,attach:G,resolveServerUrl:Z}),await m.connect({app:n,functionName:r,args:o}),_.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(u).catch(x=>{console.error(`[urun] Failed to connect session for ${r}:`,x)}),e.releaseOnLeave!==!1){let x=bs(()=>{if(S=!0,m.leaveLeg())return;if(m.connectedUrl!==null){m.disconnect();return}m.disconnect();let k=v;k?N(k):w=!0});_.onDisconnect(x);let O,B,D=!1,W=()=>{D||(D=!0,O?.(),B?.())};y.then(k=>{k.status!=="ready"||D||(O=Ss(()=>v!==void 0))}),B=_.onPhase(k=>{let z=k?.name;(z==="paused"||z==="error")&&W()}),D&&B(),_.onDisconnect(W)}return _}}})}var So="https://api.urun.sh",ko="URUN_DEV";function eg(){if(typeof process>"u")return!1;let n=process.env?.[ko];if(typeof n!="string")return!1;let e=n.trim().toLowerCase();return e==="1"||e==="true"}var rt=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function tl(n,e={}){if(!n)throw new rt("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=Y(e.baseUrl??So),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata),e.sharedApp&&(s.shared_app=!0),e.bindPrincipal&&(s.bind_principal=!0),(e.dev??eg())&&(s.dev=!0);let i;try{i=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s)})}catch(h){throw new rt(`[urun] client token mint request failed: ${h instanceof Error?h.message:String(h)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let h=typeof o.message=="string"?o.message:`HTTP ${i.status}`;throw new rt(`[urun] client token mint failed: ${h}`,i.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",l=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,d=typeof o.expires_in=="number"?o.expires_in:void 0,u=typeof o.billing_audience=="string"?o.billing_audience:void 0,p=typeof o.credits_admission_ok=="boolean"?o.credits_admission_ok:void 0,f=typeof o.credits_refusal_reason=="string"?o.credits_refusal_reason:void 0;if(!a)throw new rt("[urun] client token mint returned no token (control-plane contract violation)",i.status);let g=Number.isFinite(l)?new Date(l):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:g,orgId:c,...u!==void 0?{billingAudience:u}:{},...p!==void 0?{creditsAdmissionOk:p}:{},...f!==void 0?{creditsRefusalReason:f}:{}}}var rl=3e4,nl="stream:",To=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${nl}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${nl}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${rl}ms`)))},rl);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function sl(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let i=new bt(s);return new To(s,i)}var tg='video/mp4; codecs="avc1.42E01E"';function il(n,e){let t=e?.codec??tg,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);r.src=i,s.addEventListener("sourceopen",()=>{let p;try{p=s.addSourceBuffer(t)}catch(m){throw m instanceof DOMException&&m.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):m}let f=n.getReader();function g(){return p.updating?new Promise(m=>{p.addEventListener("updateend",()=>m(),{once:!0})}):Promise.resolve()}async function h(){try{for(;;){let{done:m,value:_}=await f.read();if(m){await g(),s.readyState==="open"&&s.endOfStream();return}await g();try{p.appendBuffer(_)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let S=p.buffered;if(S.length>0){let w=S.start(S.length-1);p.remove(0,w),await g(),p.appendBuffer(_)}else throw v}else throw v}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}h()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),l=c.getTracks(),d=0,u=l.length;if(u===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let p of l)p.addEventListener("ended",()=>{d++,d>=u&&URL.revokeObjectURL(i)});return c}function ol(n){return n.status.startsWith("pending_")}var wt=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},wr=class extends wt{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function rg(n,e,t){let r=t||e||`HTTP ${n}`;return n===401?new wr(r,e??"unauthorized"):new wt(r,{status:n,code:e??`http_${n}`})}var dn=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new wt("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let r=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(r)?r:[]}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw rg(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:s})}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 wr("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function al(n){return new dn(n)}var ln=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function cl(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function ng(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function sg(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function Ro(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var un=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,Ro(r,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new ln;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(r)}catch(o){let a=`one-capture getUserMedia(${cl(r)}) failed`,c=o instanceof Error?o.message:String(o);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==e){let d=new Error(`${a} \u2014 ${l.kind} capture lost: ${c||o}`);d.cause=o,Ro(l,d)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=ng(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${cl(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw c;Ro(o,c);continue}if(o.track=a,o.stream=sg(s,a),o!==e)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(e,t){let r=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await r.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(e)===s&&r.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},ig=null;function dl(){return ig??=new un}var Co="input",ll=30;function ul(n){let e=n.now??Date.now,t=n.field??Co,r=1e3/Math.max(n.hz??30,.001),s=new Set,i=0,o=0,a=0,c=0,l,d=null,u=!1,p=()=>{if(u)return;l=e(),c+=1;let g={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:c,at:l};try{n.awareness.setLocalStateField(t,g)}catch{}},f=()=>{if(u)return;let g=e();if(l===void 0||g-l>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let h=Math.max(r-(g-l),0);d=setTimeout(()=>{d=null,p()},h),d.unref?.()};return{keyDown(g){let h=String(g).toLowerCase();s.has(h)||(s.add(h),f())},keyUp(g){let h=String(g).toLowerCase();s.delete(h)&&f()},setButtons(g){let h=Number.isFinite(g)?Number(g):0;h!==i&&(i=h,f())},movePointer(g,h){let m=Number.isFinite(g)?Number(g):0,_=Number.isFinite(h)?Number(h):0;m===0&&_===0||(o+=m,a+=_,f())},heldKeys(){return[...s]},clear(){u||(s.clear(),i=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(u)return;let g=s.size>0||i!==0;s.clear(),i=0,d&&(clearTimeout(d),d=null),g&&p(),u=!0}}}var fl=1024,ml=.92,gl=262144,_l=256e3,Eo=[.9,.8,.7,.6,.5],pl=.8,og=8;function Us(n,e,t){if(!(n>0)||!(e>0))throw new Error(`reference image has no pixels (${n}x${e})`);let r=Math.min(1,t/Math.max(n,e));return{width:Math.max(1,Math.round(n*r)),height:Math.max(1,Math.round(e*r))}}async function ag(n){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(n,{imageOrientation:"from-image"})}async function vl(n,e,t){let r=await new Promise(s=>{n.toBlob(s,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function hl(n,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${n} -> ${e} bytes`)}async function Po(n,e,t,r,s){let i=document.createElement("canvas");i.width=e,i.height=t;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(n,0,0,e,t),await vl(i,r,s)}async function cg(n,e,t,r){let{width:s,height:i}=e,o=await Po(n,s,i,t,r);if(o.size<=256e3)return{blob:o,width:s,height:i};if(t==="image/jpeg"){for(let c of Eo)if(!(c>=r)&&(o=await Po(n,s,i,t,c),o.size<=256e3))return hl(`quality ${r} -> ${c}`,o.size),{blob:o,width:s,height:i}}let a=t==="image/jpeg"?Eo[Eo.length-1]:r;for(let c=0;c<og;c++)if(s=Math.max(16,Math.round(s*pl)),i=Math.max(16,Math.round(i*pl)),o=await Po(n,s,i,t,a),o.size<=256e3)return hl(`downscaled to ${s}x${i} @ q${a}`,o.size),{blob:o,width:s,height:i};throw new Error(`this image cannot be sent: even at ${s}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function wl(n,e){let{maxSize:t=1024,type:r="image/jpeg",quality:s=.92,source:i}=e,o=await ag(n);try{let a=Us(o.width,o.height,t),c=await cg(o,a,r,s);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:i}}finally{o.close()}}function yl(n){let e=n instanceof Error?n.name:"",t=n instanceof Error?n.message:String(n);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function bl(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Sl(n,e){let t=n.videoWidth,r=n.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:s=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=Us(t,r,s),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let l=c.getContext("2d");if(!l)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(l.fillStyle="#fff",l.fillRect(0,0,a.width,a.height)),l.drawImage(n,0,0,a.width,a.height);let d=await vl(c,i,o);return{bytes:new Uint8Array(await d.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var dg=new Set(["w","a","s","d"]),yr=(n,e)=>Math.min(e,Math.max(-e,n));function kl(n={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:s=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=n,c=0,l=0,d=0,u=null,p=new Set;return{pointerDelta(f,g){c=yr(c-f*e,o),l=yr(l-g*e,o)},keyDown(f){let g=f.toLowerCase();dg.has(g)&&p.add(g)},keyUp(f){p.delete(f.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let f=1-i;c*=f,l*=f,d*=f},tick(f){if(u===null){u=f;return}let g=Math.max(0,Math.min(100,f-u))/1e3;u=f,p.has("w")&&(d=yr(d+t*g,a)),p.has("s")&&(d=yr(d-t*g,a)),p.has("a")&&(c=yr(c+r*g,o)),p.has("d")&&(c=yr(c-r*g,o));let h=Math.exp(-g*1e3/s);c*=h,l*=h,d*=h},transform(){return{translateX:c,translateY:l,scale:Math.exp(d)}},isIdentity(f=5e-4){return Math.abs(c)<f&&Math.abs(l)<f&&Math.abs(d)<f},reset(){c=0,l=0,d=0,p.clear()}}}
|
|
31
|
+
`)}var Ds=class n{constructor(e,t){this.sink=e;this.seqState=t??{seq:0}}sink;stopped=!1;deadCb=null;seqState;static FLOW_WINDOW_MS=5e3;static FLOW_MIN_SENT_PER_WINDOW=25;sentCount=0;flowTimer=null;flowLastSent=0;flowLastDelivered=0;sendPc=null;recvPc=null;sender=null;currentTrack=null;renderSender=null;renderRemoteCb=null;renderEndedListener=null;worker=null;workerUrl=null;nodeBridge=null;endedListener=null;candQueue=null;negotiatedOnce=!1;negotiating=!1;renegotiateQueued=!1;deliveredDatagrams(){return this.sink.delivered()}sentDatagrams(){return this.sentCount}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.currentTrack&&e.readyState==="live")return;let t=null;if(!(e!==null&&(t=_m(e)?this.bridgedTrack(e):e,!t))){if(this.sender){this.unwireCurrentSource();try{this.sender.replaceTrack(t)}catch(r){this.die(`replaceTrack: ${r instanceof Error?r.message:String(r)}`);return}this.currentTrack=t,t&&this.wireTrackLiveness(t);return}t!==null&&(this.engage(t),this.startFlowWatch())}}startFlowWatch(){this.flowTimer||this.stopped||(this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),this.flowTimer=setInterval(()=>{if(this.stopped)return;let e=this.sentCount-this.flowLastSent,t=this.sink.delivered()-this.flowLastDelivered;this.flowLastSent=this.sentCount,this.flowLastDelivered=this.sink.delivered(),e>0&&console.log(`[urun] WT mic uplink flow: wrote=${(e/(n.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s accepted=${(t/(n.FLOW_WINDOW_MS/1e3)).toFixed(0)}/s`),!(e<n.FLOW_MIN_SENT_PER_WINDOW)&&(t*2>=e||console.error(`[urun] WT mic uplink flow STARVED: wrote ${e} datagrams in ${n.FLOW_WINDOW_MS/1e3}s but QUIC accepted only ${t}`))},n.FLOW_WINDOW_MS))}stop(){if(!this.stopped){this.stopped=!0,this.flowTimer!==null&&(clearInterval(this.flowTimer),this.flowTimer=null),this.unwireCurrentSource(),this.worker&&(this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.worker=null),this.workerUrl&&URL.revokeObjectURL(this.workerUrl),this.workerUrl=null;try{this.sendPc?.close()}catch{}try{this.recvPc?.close()}catch{}this.sendPc=this.recvPc=null,this.sender=null,this.currentTrack=null,this.unwireRenderRemote(),this.renderSender=null,this.renderRemoteCb=null}}engage(e){let t=globalThis;if(typeof t.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}if(typeof t.RTCRtpScriptTransform!="function"){this.die("RTCRtpScriptTransform is not available");return}let r;try{r=this.ensureTransformWorker()}catch(o){this.die(`transform worker: ${o instanceof Error?o.message:String(o)}`);return}if(this.ensurePair(),!this.sendPc)return;let s=this.sendPc.addTrack(e);this.sender=s,this.currentTrack=e,this.wireTrackLiveness(e);let i=t.RTCRtpScriptTransform;if(s.transform=new i(r,{role:"sender"}),this.negotiatedOnce){this.negotiate().catch(o=>this.die(`loopback renegotiate: ${o instanceof Error?o.message:String(o)}`));return}this.negotiate().catch(o=>this.die(`loopback negotiate: ${o instanceof Error?o.message:String(o)}`))}ensurePair(){if(this.sendPc||this.stopped)return;let e=globalThis;if(typeof e.RTCPeerConnection!="function"){this.die("RTCPeerConnection is not available");return}let t=e.RTCPeerConnection;this.sendPc=new t({iceServers:[]}),this.recvPc=new t({iceServers:[]}),this.candQueue={toSend:[],toRecv:[]},this.sendPc.oniceconnectionstatechange=()=>{this.sendPc?.iceConnectionState==="failed"&&this.die("loopback ICE failed")},this.sendPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toRecv.push(r.candidate),this.flushCandidates())},this.recvPc.onicecandidate=r=>{if(!r.candidate)return;let s=this.candQueue;s!==null&&(s.toSend.push(r.candidate),this.flushCandidates())},this.sendPc.onnegotiationneeded=()=>{this.negotiatedOnce&&this.negotiate().catch(r=>this.die(`loopback renegotiate: ${r instanceof Error?r.message:String(r)}`))},this.recvPc.ontrack=r=>{let s=r.transceiver?.mid??null;s!==null&&s===this.renderMidOf()&&this.renderRemoteCb?.(r.track)}}setRenderSource(e){if(!this.stopped){if(e===null){if(this.renderSender){this.unwireRenderRemote();try{this.renderSender.replaceTrack(null)}catch{}}return}if(!(!this.sendPc&&(this.ensurePair(),!this.sendPc))){if(!this.renderSender)this.renderSender=this.sendPc.addTrack(e);else try{this.renderSender.replaceTrack(e)}catch(t){this.die(`render replaceTrack: ${t instanceof Error?t.message:String(t)}`);return}this.wireRenderRemote(e),!this.negotiatedOnce&&this.sender&&this.negotiate().catch(t=>this.die(`loopback negotiate: ${t instanceof Error?t.message:String(t)}`))}}}onRenderTrack(e){this.renderRemoteCb=e}renderMidOf(){if(!this.renderSender)return null;let e=this.sendPc;try{return e.getTransceivers?.().find(t=>t.sender===this.renderSender)?.mid??null}catch{return null}}wireRenderRemote(e){this.unwireRenderRemote(),this.renderEndedListener=()=>{this.renderRemoteCb&&this.renderRemoteCb(null)},e.addEventListener("ended",this.renderEndedListener)}unwireRenderRemote(){this.renderEndedListener&&this.renderSender?.track&&this.renderSender.track.removeEventListener("ended",this.renderEndedListener),this.renderEndedListener=null}async negotiate(){let e=this.sendPc,t=this.recvPc;if(!(!e||!t||this.stopped)){if(this.negotiating){this.renegotiateQueued=!0;return}this.negotiating=!0,this.negotiatedOnce=!0;try{do{this.renegotiateQueued=!1;let r=await e.createOffer();r.sdp=Wd(r.sdp??""),await e.setLocalDescription(r),await t.setRemoteDescription(e.localDescription??{type:"offer",sdp:r.sdp});let s=await t.createAnswer();s.sdp=Wd(s.sdp??""),await t.setLocalDescription(s),await e.setRemoteDescription(t.localDescription??{type:"answer",sdp:s.sdp}),this.flushCandidates()}while(this.renegotiateQueued)}finally{this.negotiating=!1}}}flushCandidates(){let e=this.candQueue;if(e){for(;e.toSend.length&&this.sendPc;)Promise.resolve(this.sendPc.addIceCandidate(e.toSend.shift())).catch(()=>{});for(;e.toRecv.length&&this.recvPc;)Promise.resolve(this.recvPc.addIceCandidate(e.toRecv.shift())).catch(()=>{})}}bridgedTrack(e){let t=e;try{let r=t.context.createMediaStreamDestination();t.connect(r);let s=r.stream.getAudioTracks()[0]??null;return s?(this.nodeBridge={node:t,dest:r},s):(this.die("AudioNode bridge produced no audio track"),null)}catch(r){return this.die(`AudioNode bridge: ${r instanceof Error?r.message:String(r)}`),null}}wireTrackLiveness(e){this.endedListener=()=>this.die("mic track ended"),e.addEventListener("ended",this.endedListener)}unwireCurrentSource(){if(this.endedListener&&this.currentTrack&&this.currentTrack.removeEventListener("ended",this.endedListener),this.endedListener=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}}ensureTransformWorker(){if(this.worker)return this.worker;this.workerUrl=URL.createObjectURL(new Blob([gm],{type:"text/javascript"}));let e=new Worker(this.workerUrl);return e.onmessage=t=>{let r=t.data;r?.type==="enc"&&r.payload instanceof ArrayBuffer?this.onEncodedFrame(r.rtpTimestamp??0,new Uint8Array(r.payload)):r?.type==="err"&&this.die(`transform: ${r.detail??"unknown"}`)},e.onerror=t=>this.die(`transform worker: ${t.message||"error"}`),this.worker=e,e}onEncodedFrame(e,t){if(this.stopped)return;let r=co(this.seqState.seq,e,t,this.sink.maxDatagramSize()||an);if(r===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.seqState.seq=this.seqState.seq+1>>>0;return}for(let s of r)this.sink.send(s),this.sentCount++;this.seqState.seq=this.seqState.seq+1>>>0}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function _m(n){let e=n;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var vm=9e4,wm="avc1.42E01F",ym=60,bm=3,Sm=1e4;function km(n){return Math.round(n*(vm/1e6))%2**32>>>0}var As=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let r=globalThis.MediaStreamTrackProcessor;if(typeof r!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let s=++this.generation,i=new r({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,i.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&s===this.generation;){let{value:a,done:c}=await i.read();if(c)break;if(a){if(o||this.stopped||s!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&s===this.generation&&this.die(`capture: ${a instanceof Error?a.message:String(a)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(e){let t={width:e.codedWidth,height:e.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==t.width||this.encoderDims.height!==t.height){let i=globalThis.VideoEncoder;if(typeof i!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new i({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:wm,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(o){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let s=this.keyframeWanted||this.framesSinceKeyframe>=ym;this.keyframeWanted=!1,this.framesSinceKeyframe=s?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:s})}catch(i){this.onEncoderError(i instanceof Error?i:new Error(String(i)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let r=co(this.frameSeq,km(e.timestamp),t,this.sink.maxDatagramSize()||an,{lane:Md,keyframe:e.type==="key"});if(r===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let s of r)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(r=>t-r<Sm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=bm){this.die(`video encoder: ${e.message}`);return}console.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",e.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(e){this.stopped||(console.warn(`[urun] WT video uplink lane dead (${e}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function Tm(n){return n.byteLength>=2&&n[0]===1&&n[1]===3}var Is=class{constructor(e){this.transport=e}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(e){this.deadCb=e}send(e,t){let r=new TextEncoder().encode(e);if(r.byteLength===0||r.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${r.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let i=this.streams.get(e);if(!i){let a=await this.transport.openUniStream(),c=new Uint8Array(2+r.byteLength);c[0]=1,c[1]=r.byteLength,c.set(r,2),await a.write(c),i={writer:a},this.streams.set(e,i)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await i.writer.write(o),Tm(t)&&(this.streams.delete(e),await i.writer.close().catch(()=>{}))}catch(i){throw this.die(i instanceof Error?i.message:String(i)),i}});return this.chain=s.catch(()=>{}),s}stop(e="stopped"){if(this.dead===null){this.dead=e;for(let t of this.streams.values())t.writer.close().catch(()=>{});this.streams.clear()}}die(e){this.dead===null&&(console.warn(`[urun] WT data uplink lane dead (${e})`),this.stop(e),this.deadCb?.(e))}};var Fd=250,Rm=25,Cm=2e3,Em=15e3,Pm=1e3,xm=45e3,Dm=5e3,Am={llm:!0},Im=500,$d=10,Lm=2,Mm=2,lo=2,hr=class n{constructor(e,t,r,s,i,o,a){this.offer=e;this.sessionId=t;this.canvas=r;this.audioLane=s;this.audioUplink=i;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((c,l)=>{this.firstFrameResolve=c,this.firstFrameReject=l}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorLogged=!1;writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;stallWatch=null;stallTimer=null;audioLaneLastArrivalAt=null;lastInboundControlAt=null;lastInboundDataAt=null;firstInboundDataAt=null;advertisedPingIntervalMs=null;noCadenceLogged=!1;reassembler=new pr({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});mediaDeadTimer=null;audioDgramsReceived=0;mediaDeadBaseline=null;severedStreak="none";playoutScheduledSeen=null;playoutStallStreak=0;playoutStallRebuilt=!1;gatewayExposesCounters=!1;lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;renderSource=null;renderRemoteCb=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,r=t!==void 0&&t!=="";this.hasVideoLane=r,r&&no(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(d=>({algorithm:"sha-256",value:Uint8Array.from(atob(d),u=>u.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let s=await this.wt.createBidirectionalStream();this.writer=s.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=s.readable.getReader(),o=new lr,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");let l=c;if(this.lastInboundControlAt=performance.now(),typeof l.pingIntervalMs=="number"&&l.pingIntervalMs>0?this.advertisedPingIntervalMs=l.pingIntervalMs:this.noCadenceLogged||(this.noCadenceLogged=!0,console.warn("[urun] gateway advertises no liveness cadence (pre-#2826 or mid-roll gateway) \u2014 the downlink-stall watch will never judge this leg dead on silence alone")),r&&(no(l.codec,"hello-ack"),this.initDecoder(l.codec,l.width,l.height)),this.offer.audio&&this.audioLane){this.renderSource=null,this.renderRemoteCb=null;let d={setSource:p=>{this.renderSource=p,this.audioUplinkLane?.setRenderSource?.(p)},onRemote:p=>{this.renderRemoteCb=p}},u=new xs(this.offer.audio,{...this.audioLane,renderHop:d});try{u.start(),this.audioPlayout=u}catch(p){console.warn(`[urun] WT audio lane failed to start (${p instanceof Error?p.message:String(p)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),u.stop()}}if(this.offer.audioUp===!0&&this.audioUplink&&this.engageUplinkLane("audio"),this.offer.videoUp===!0&&this.videoUplink&&this.engageUplinkLane("video"),this.offer.dataUp===!0&&this.dataUplink)try{let d=this.wt.createUnidirectionalStream?.bind(this.wt);if(!d)throw new Error("WebTransport uni streams are not creatable in this environment");let u=new Is({openUniStream:async()=>(await d()).getWriter()});u.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p,u)}),this.dataUplinkSender=u,this.dataUplink.onUplink(u)}catch(d){let u=d instanceof Error?d.message:String(d);console.warn(`[urun] WT data uplink failed to engage (${u}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(u)}this.controlLoop(i,o,a).catch(d=>this.die(`control loop: ${d}`)),this.datagramLoop().catch(d=>this.die(`datagram loop: ${d}`)),this.feedbackLoop(),(this.offer.audio!==void 0||this.offer.audioUp===!0)&&(this.mediaDeadTimer=setInterval(()=>this.mediaDeadTick(),Im)),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(d=>{this.closedReason=`connection error: ${d}`,this.die(`connection error: ${d}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${Fd}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}watchDownlinkStall(e={}){this.stallWatch={stallMs:e.stallMs??Em},this.stallTimer===null&&(this.stallTimer=setInterval(()=>this.downlinkStallTick(),Pm))}clearStallWatch(){this.stallTimer!==null&&(clearInterval(this.stallTimer),this.stallTimer=null),this.stallWatch=null}clearMediaDeadWatch(){this.mediaDeadTimer!==null&&(clearInterval(this.mediaDeadTimer),this.mediaDeadTimer=null),this.mediaDeadBaseline=null,this.severedStreak="none",this.playoutScheduledSeen=null,this.playoutStallStreak=0,this.playoutStallRebuilt=!1}mediaDeadTick(){this.stopped||this.deadFired||this.sendControl({t:"ping",ts:performance.now(),id:0}).catch(()=>{})}observeFlowCounters(e){if(this.stopped||this.deadFired)return;let t=typeof e.ds=="number"?e.ds:null,r=typeof e.ur=="number"?e.ur:null;if(t===null&&r===null)return;this.gatewayExposesCounters=!0;let s=this.audioDgramsReceived,i=this.audioUplinkLane?.deliveredDatagrams()??0,o=this.mediaDeadBaseline;if(this.mediaDeadBaseline={ds:t,ur:r,recvDownlink:s,sentUplink:i},!o)return;let a=t!==null&&o.ds!==null?t-o.ds:null,c=r!==null&&o.ur!==null?r-o.ur:null,l=s-o.recvDownlink,d=i-o.sentUplink,u="none";if(a!==null&&a>=$d&&l<=0?u="downlink":c!==null&&d>=$d&&c<=0&&(u="uplink"),u==="none"){this.severedStreak="none",this.observePlayoutProgress(l,t);return}if(this.severedStreak!==u){this.severedStreak=u;return}this.severedStreak="none";let p=u==="downlink"?`the gateway has SENT ${a} new downlink datagrams since the last sample while this client RECEIVED none`:`this client ACCEPTED ${d} new mic datagrams since the last sample while the gateway RECEIVED none`;this.die("media dead on a live leg: "+p+` (gateway flow counters ds=${t} ur=${r}, client received=${s} accepted=${i}, confirmed on ${Lm} consecutive samples) \u2014 the QUIC session is established but its datagram lanes are severed; re-dialing (owner direction 2026-09-26)`)}observePlayoutProgress(e,t){let r=this.audioPlayout;if(!r){this.playoutScheduledSeen=null;return}let s=r.playoutProgress(),i=s.surfaced;if(this.playoutScheduledSeen!==null&&s.scheduled>this.playoutScheduledSeen&&i){this.playoutScheduledSeen=s.scheduled,this.playoutStallStreak=0,this.playoutStallRebuilt=!1;return}if(this.playoutScheduledSeen=s.scheduled,e<=0){this.playoutStallStreak=0;return}if(this.playoutStallStreak++,!(this.playoutStallStreak<Mm)){if(!this.playoutStallRebuilt){this.playoutStallRebuilt=!0,this.playoutStallStreak=0,console.warn(`[urun] WT playout stalled while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${s.scheduled}) \u2014 rebuilding the reply surface in place (no leg death; a re-dial follows only if the rebuild does not restore progress)`);try{r.rebuildSurface()}catch(o){console.error(`[urun] WT playout surface rebuild failed \u2014 escalating to a re-dial: ${o instanceof Error?o.message:String(o)}`),this.playoutStallStreak=lo}return}this.playoutStallStreak<lo||(this.playoutStallStreak=0,this.playoutStallRebuilt=!1,this.die(`playout stalled past its in-place surface rebuild while datagrams still flow (gateway ds=${t}, client received=${this.audioDgramsReceived}, scheduled=${s.scheduled} on ${lo} consecutive samples) \u2014 the reply surface is dead and no rebuild heals it; re-dialing`))}}downlinkStallTick(){if(this.stopped||this.deadFired)return;let e=this.stallWatch;if(!e)return;let t=this.pathLiveness();if(!t.alive)return;let r=performance.now(),s=this.audioLaneLastArrivalAt===null?null:r-this.audioLaneLastArrivalAt,i=this.lastInboundControlAt===null?null:r-this.lastInboundControlAt,o=s===null&&i===null?!0:(s===null||s>=e.stallMs)&&(i===null||i>=e.stallMs),a=this.advertisedPingIntervalMs;if(a!==null&&o&&i!==null&&i>=2*a){this.die(`downlink stall: the gateway advertised a ${Math.round(a/1e3)}s liveness cadence but delivered no inbound frame of any kind for ${Math.round(i/1e3)}s while the path reports alive (${t.evidence}) \u2014 the promised liveness evidence stopped; re-dialing (owner ruling 2026-09-26)`);return}let c=!!(this.offer.audio&&this.audioLane),l=this.lastInboundDataAt===null?null:r-this.lastInboundDataAt,d=s!==null?s:this.firstInboundDataAt===null?null:r-this.firstInboundDataAt,u=d!==null&&d>=e.stallMs;if(c&&u&&l!==null&&l<=Dm&&this.gatewayPings>0){this.die(`media-starved leg: no audio datagram for ${Math.round((d??0)/1e3)}s while the data lane delivered a frame ${Math.round((l??0)/1e3)}s ago (${this.gatewayPings} gateway pings; ${t.evidence}) \u2014 the reliable lanes are alive so the application is mid-conversation, and a dark audio lane under it is severed media fanout, never an idle application; re-dialing`);return}o&&i!==null&&i>=xm&&this.gatewayPings>0&&this.die(`one-way downlink stall: the gateway pinged this leg before (its downlink pipe demonstrably worked) but NOTHING has arrived \u2014 no audio datagram, no inbound control frame \u2014 for ${Math.round(i/1e3)}s while the path reports alive (${t.evidence}) and client control writes keep resolving \u2014 the downlink is severed in one direction; re-dialing (owner ruling 2026-09-26)`)}async stop(){this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e,t))}dropDatagramUplinks(e){if(this.clearUplinkRetryTimers(),this.audioUplinkLane!==null||this.audioUplinkRetry!==null){let s=this.audioUplinkLane;s?.stop(),this.audioUplinkLane=null,this.audioUplinkRetry=null,this.audioUplink?.onUplinkLost(e,s??void 0)}if(this.videoUplinkLane!==null||this.videoUplinkRetry!==null){let s=this.videoUplinkLane;s?.stop(),this.videoUplinkLane=null,this.videoUplinkRetry=null,this.videoUplink?.onUplinkLost(e,s??void 0)}}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");let t={onData:(r,s)=>{if(Am[r]===!0){let i=performance.now();this.firstInboundDataAt===null&&(this.firstInboundDataAt=i),this.lastInboundDataAt=i}e.onData(r,s)},onLaneError:r=>e.onLaneError(r)};this.dataLaneSink=t,Ps(this.wt.incomingUnidirectionalStreams,t).catch(r=>{this.die(`data lane: ${r instanceof Error?r.message:String(r)}`)})}initDecoder(e,t,r){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:r};let o=new s({output:a=>{this.canvas.width=a.displayWidth,this.canvas.height=a.displayHeight,i.drawImage(a,0,0),a.close()},error:a=>this.onDecoderError(a)});o.configure({codec:e,...t>0&&r>0?{codedWidth:t,codedHeight:r}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"}),this.decoder=o}onDecoderError(e){if(this.stopped||this.deadFired)return;console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let t=this.decoderConfig;if(!t){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder error with no retained config to re-init from \u2014 video stays down: ${e.message}`));return}try{this.initDecoder(t.codec,t.width,t.height),this.decoderErrorLogged=!1}catch(r){this.decoderErrorLogged||(this.decoderErrorLogged=!0,console.error(`[urun] webtransport decoder re-init failed (video stays down; transport unaffected): ${r instanceof Error?r.message:String(r)}`));return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,s=>this.onUplinkSendError(s))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let r=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(s=>r-s<Cm),this.uplinkSendErrorsAt.push(r),!(this.uplinkSendErrorsAt.length<Rm)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}static UPLINK_LANE_RETRY_MAX=3;static UPLINK_LANE_RETRY_BACKOFF_MS=1e3;static UPLINK_LANE_HEALTHY_MS=3e4;audioUplinkRetry=null;videoUplinkRetry=null;uplinkSeqState={seq:0};uplinkSink(e){this.datagramWriter();let t=0;return{send:r=>this.uplinkSend(r,()=>{t++}),delivered:()=>t,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??an}}engageAudioUplink(){let e=new Ds(this.uplinkSink("audio"),this.uplinkSeqState);e.onDead(t=>this.onUplinkLaneDead("audio",t,e)),e.onRenderTrack?.(t=>this.renderRemoteCb?.(t)),this.renderSource&&e.setRenderSource?.(this.renderSource),this.audioUplinkLane=e,this.audioUplinkRetry=this.freshLaneBuilt(this.audioUplinkRetry),this.audioUplink.onUplink(e)}engageVideoUplink(){let e=new As(this.uplinkSink("video"));e.onDead(t=>this.onUplinkLaneDead("video",t,e)),this.videoUplinkLane=e,this.videoUplinkRetry=this.freshLaneBuilt(this.videoUplinkRetry),this.videoUplink.onUplink(e)}engageUplinkLane(e){let t=e==="audio"?"mic":"video";try{e==="audio"?this.engageAudioUplink():this.engageVideoUplink()}catch(r){let s=r instanceof Error?r.message:String(r);console.warn(`[urun] WT ${t} uplink failed to engage (${s}) \u2014 keeping the WT session; the ${t} stays on the WebRTC produce path`),this.seamUplinkLost(e,s)}}freshLaneBuilt(e){let t={count:e?.count??0,builtAt:Date.now(),timer:void 0};return e&&(clearTimeout(e.timer),e.timer=void 0),t}onUplinkLaneDead(e,t,r){if(e==="audio"?(this.audioUplinkLane=null,this.renderRemoteCb?.(null)):this.videoUplinkLane=null,this.stopped||this.deadFired)return;let s=e==="audio"?"mic":"video",i=e==="audio"?this.audioUplinkRetry:this.videoUplinkRetry,a=i?.builtAt!=null&&Date.now()-i.builtAt>=n.UPLINK_LANE_HEALTHY_MS?1:(i?.count??0)+1;if(a>n.UPLINK_LANE_RETRY_MAX){console.error(`[urun] WT ${s} uplink lane dead (${t}) \u2014 ${n.UPLINK_LANE_RETRY_MAX} recovery attempts exhausted; the lane is down until the transport's own revert runs (onUplinkLost)`),e==="audio"?this.audioUplinkRetry=null:this.videoUplinkRetry=null,this.seamUplinkLost(e,`lane dead after ${n.UPLINK_LANE_RETRY_MAX} recovery attempts: ${t}`,r);return}console.warn(`[urun] WT ${s} uplink lane dead (${t}) \u2014 re-engaging the lane on the live WT session (recovery ${a}/${n.UPLINK_LANE_RETRY_MAX}); the session and its other lanes stay up`);let c={count:a,builtAt:null,timer:void 0};e==="audio"?this.audioUplinkRetry=c:this.videoUplinkRetry=c,c.timer=setTimeout(()=>{c.timer=void 0,!(this.stopped||this.deadFired)&&this.engageUplinkLane(e)},n.UPLINK_LANE_RETRY_BACKOFF_MS)}seamUplinkLost(e,t,r){e==="audio"?this.audioUplink.onUplinkLost(t,r):this.videoUplink.onUplinkLost(t,r)}clearUplinkRetryTimers(){for(let e of[this.audioUplinkRetry,this.videoUplinkRetry])e&&(clearTimeout(e.timer),e.timer=void 0)}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:r}=await e.read();if(r)break;if(!t)continue;if(t.byteLength>=pe&&t[11]===Cs){this.audioLaneLastArrivalAt=performance.now(),this.audioDgramsReceived++,this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,r){let s=globalThis.EncodedVideoChunk;if(typeof s=="function"){if(!this.decoder&&this.decoderConfig)try{this.initDecoder(this.decoderConfig.codec,this.decoderConfig.width,this.decoderConfig.height),this.decoderErrorLogged=!1}catch{return}this.decoder&&(this.decoder.decode(new s({type:t?"key":"delta",timestamp:e*(1e6/24),data:r})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}}async sendControl(e){try{await this.writer.write(Rs(e)),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async sendControlRaw(e){try{let t=new Uint8Array(4+e.byteLength);new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),await this.writer.write(t),this.controlWritesAccepted++}catch(t){let r=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=r),this.die(`control stream write refused: ${r}`),t}}async readControl(e,t,r=[]){for(;;){let s=r.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&r.push(...t.push(i))}}async controlLoop(e,t,r){for(;!this.stopped;){let s=await this.readControl(e,t,r);if(!s)break;let i=s;if(this.lastInboundControlAt=performance.now(),i.t==="ping"){this.gatewayPings++;try{await this.sendControlRaw(Ld(s.raw,"pong"))}catch{}}(i.t==="ping"||i.t==="pong")&&this.observeFlowCounters(i),i.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),r=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=s.delivered+s.abandoned;this.lastStats={recvBps:r>0?s.bytes*8/r:0,lossPct:i>0?100*s.abandoned/i:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},Fd)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.clearStallWatch(),this.clearMediaDeadWatch(),this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var jd=2500,qd=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Om=1e4,fr=class n{constructor(e,t,r){this.signaling=e;this.sessionId=t;this.opts=r}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;static WT_REDIAL_BASE_MS=2e3;static WT_REDIAL_MAX=3;static WT_REDIAL_CAP_MS=3e4;wtRedialFailures=0;wtRedialTimer=null;wtDialedHost;wtHostMismatchCount=0;disconnected=!1;downlinkStallWatch=null;watchDownlinkStall(e={}){this.downlinkStallWatch={stallMs:e.stallMs??15e3},this.applyStallWatch()}applyStallWatch(){let e=this.session;!e||e.kind!=="webtransport"||!this.downlinkStallWatch||e.watchDownlinkStall?.(this.downlinkStallWatch)}failCurrentWtLeg(e){if(this.disconnected)return;let t=this.session;!t||t.kind!=="webtransport"||t.fail?.(e)}get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis;this.disconnected=!1;let t=typeof e.WebTransport=="function",r=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&r&&s,webcodecs:r,codecs:qd,wtData:t&&r&&s&&this.opts.dataLane!==void 0,wtAudio:t&&r&&s&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&s&&this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",wtVideoUp:t&&r&&s&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&r&&s&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i}),this.noteOfferedWtHost();let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let l=null;try{return l=this.createWebTransportSession(),await po(l.start(),this.opts.quicDeadlineMs??jd,"quic connect deadline"),this.wtDialedHost=uo(this.offer.webtransport?.url)??this.wtDialedHost,this.engageQuicDataLane(l,i.wtData===!0),this.session=l,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(d){if(console.warn(`[urun] WT dial failed (${cn(d)}) \u2014 dialed ${Bd(this.offer.webtransport?.url)}`),l?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let u=String(d instanceof Error?d.message:d);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${u}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(u),d}console.warn("[urun] webtransport failed, falling back to webrtc:",d),this.proceedWebRtcDial(`wt failed: ${String(d instanceof Error?d.message:d)}`),this.notifyEstablished("webrtc",String(d instanceof Error?d.message:d))}}if(this.opts.allowWebRtcFallback===!1){let l=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${l} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(l),new Error(`[urun] WT required but unavailable: ${l}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.disconnected=!0,this.wtRedialTimer!==null&&(clearTimeout(this.wtRedialTimer),this.wtRedialTimer=null),this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}noteOfferedWtHost(){let e=uo(this.offer?.webtransport?.url);e===void 0||this.wtDialedHost===void 0||e===this.wtDialedHost||(this.wtHostMismatchCount+=1,console.error(`[urun] re-dial offered host ${e} != original host ${this.wtDialedHost}`+(Um(e)?" \u2014 the offered host looks INTERNAL (RFC1918/.internal): an external browser cannot dial it":"")+` (mismatch #${this.wtHostMismatchCount}) \u2014 evidence only, no policy change`))}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let r=this.session,s=this.opts.dataLane!==void 0,i=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.RTCPeerConnection=="function"&&typeof e.RTCRtpScriptTransform=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:qd,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;this.noteOfferedWtHost();let l=this.createWebTransportSession();try{await po(l.start(),this.opts.quicDeadlineMs??jd,"quic connect deadline")}catch(d){throw console.warn(`[urun] WT dial failed (${cn(d)}) \u2014 dialed ${Bd(this.offer.webtransport?.url)}`),l.stop().catch(()=>{}),d}if(this.wtDialedHost=uo(this.offer.webtransport?.url)??this.wtDialedHost,this.session!==r)return l.stop().catch(()=>{}),null;try{this.engageQuicDataLane(l,s)}catch(d){throw l.stop().catch(()=>{}),d}if(this.disconnected)return l.stop().catch(()=>{}),null;this.session=l;{let d=this.offer.webtransport;d&&(this.opts.audioLane===void 0||d.audio!==void 0)&&(this.opts.audioUplink===void 0||d.audioUp===!0)&&(this.opts.videoUplink===void 0||d.videoUp===!0)&&(this.opts.dataLane===void 0||d.data===!0)&&(this.opts.dataUplink===void 0||d.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),r?.stop().catch(()=>{}),l}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let r=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(s,i)=>r.onData(s,i),onLaneError:s=>r.onLaneError(s)}),r.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e,this.opts.audioLane);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new hr(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;this.wtRedialFailures=0,this.applyStallWatch(),e.onDead(t=>{if(this.opts.onWtLegDeath?.(t),this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; re-dialing WT (attempt 1 immediate, then the bounded ladder)`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.redialWtAfterDeath(t,!0);return}let r=this.wtOnlyLeg;if(this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),r){this.session=null,this.wtOnlyLeg=!1,console.warn("[urun] quic died mid-session on a WT-only leg \u2014 RE-DIALING WebTransport first (same session id; the late WebRTC dial is the fallback):",t),this.redialWtAfterDeath(t,!0);return}console.warn("[urun] quic died mid-session, failing over to webrtc:",t),this.lateWebRtcFailover(e,t,r)})}redialWtAfterDeath(e,t=!1){if(this.wtRedialTimer!==null)return;if(this.wtRedialFailures>=n.WT_REDIAL_MAX){if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT re-dial failed ${n.WT_REDIAL_MAX} times (${e}) \u2014 WT-REQUIRED policy: no WebRTC floor exists to escalate to; the forever-retry continues in the background`),this.opts.onWtRequiredOutage?.(e);return}console.error(`[urun] WT re-dial failed ${n.WT_REDIAL_MAX} times (${e}) \u2014 standing up the deferred WebRTC dial as the floor; WT keeps retrying in the background`),this.proceedWebRtcDial(`wt re-dial spent: ${e}`),this.lateWebRtcFailover(null,e,!0);return}let r=this.wtRedialFailures+1,s=ho(n.WT_REDIAL_BASE_MS,r,n.WT_REDIAL_CAP_MS,r===1&&t?0:void 0);console.warn(`[urun] WT re-dial attempt ${r} scheduled in ${Math.round(s)}ms (${e}) \u2014 the session stays attached`),this.wtRedialTimer=setTimeout(()=>{this.wtRedialTimer=null,!this.disconnected&&this.attemptWtRedial(e)},s)}async attemptWtRedial(e){if(!(this.disconnected||this.session!==null)){if(this.signaling.isOpen?.()===!1){this.redialWtAfterDeath(`${e}; signaling socket closed \u2014 waiting for the reconnect`);return}this.wtRedialFailures+=1;try{if(await this.retryWebTransport()!==null){console.warn(`[urun] WT leg re-established on the live session (re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX})`);return}this.redialWtAfterDeath(`${e}; no WT offer on re-dial`)}catch(t){let r=cn(t);console.warn(`[urun] WT re-dial attempt ${this.wtRedialFailures}/${n.WT_REDIAL_MAX} failed (${r}) \u2014 the session stays attached; retrying`),this.redialWtAfterDeath(`${e}; re-dial failed: ${r}`)}}}lateWebRtcFailover(e,t,r){this.disconnected||(async()=>{let s=this.createWebRtc();try{let i=await po(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??Om,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(i){if(s.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=r?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function cn(n){if(n instanceof Error)return n.message;if(typeof n=="string")return n;if(n&&typeof n=="object"){try{let e=JSON.stringify(n);if(e!==void 0&&e!=="{}")return e}catch{}return n.constructor?.name??Object.prototype.toString.call(n).slice(8,-1)}return String(n)}function uo(n){if(n)try{return new URL(n).host}catch{return}}function Bd(n){if(!n)return"(no offer url)";try{let e=new URL(n);return e.searchParams.delete("token"),e.toString()}catch{return n.replace(/[?&]token=[^&\s]*/g,"")}}function Um(n){if(!n)return!1;let e=n.replace(/^\[/,"").split("]")[0]?.split(":")[0]??"";return/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(e)?!0:e.endsWith(".internal")||e.endsWith(".svc.cluster.local")||/^ip-\d+(-\d+)+/.test(e)}function ho(n,e,t,r){if(r!==void 0)return r;let s=Math.min(n*2**Math.max(0,e-2),t);return Math.round(s*(.75+Math.random()*.5))}function po(n,e,t){return new Promise((r,s)=>{let i=setTimeout(()=>s(new Error(t)),e);n.then(o=>{clearTimeout(i),r(o)},o=>{clearTimeout(i),s(o)})})}var Nm=1e4,mr=class{constructor(e,t=Nm){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;isOpen(){return this.carrier.signalingOpen()}request(e,t){let r=sr();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==r)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:l,requestId:d,...u}=c;s(u)});this.carrier.sendSignal({type:e,requestId:r,...t})||(clearTimeout(o),a(),i(new Error(`[urun] signaling request not sent: ${e} \u2014 the signaling socket is not open`)))})}notify(e,t){this.carrier.sendSignal({type:e,...t})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${e} \u2014 the signaling socket is not open`,detail:{method:e}})}on(e,t){return this.carrier.onSignal(r=>{r.type===e&&t(r)})}};var Wm="video",gr=class{constructor(e,t=Wm){this.transport=e;this.streamName=t;this.firstMedia=new Promise((r,s)=>{this.firstMediaResolve=r,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let r=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(r(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(r)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};function Hd(n){let e=n;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Fm="video";var $m=45e3;async function jm(n,e,t){let s=e?.current()?.name??null;if(s==="live")return"live";if(s==="error")return"gone";if(s==="idle"||s==="connecting")return"live";if(!e)return"unconfirmed";let i=e,o=t.runtimeWaitCapMs??$m;return new Promise(a=>{let c=!1,l,d=null,u=null,p=!1,f=_=>{c||(c=!0,m(),u!==null&&(clearTimeout(u),u=null),l?.(),a(_))};u=setTimeout(()=>{if(p||c||t.isDisposed())return;p=!0;let _=i.current();n.emitDiagnostic({level:"info",kind:"runtime-pending",message:`waiting for a runtime to pick up session ${t.sessionId} (server status: ${_?.reason??_?.name??"unknown"}) \u2014 media negotiation starts once the runtime is live; this is not a transport failure`})},2e3);let h=()=>{d===null&&!c&&(d=setTimeout(()=>f("unconfirmed"),o))},m=()=>{d!==null&&(clearTimeout(d),d=null)};l=e.subscribe(_=>{let v=_?.name;if(v==="live")return f("live");if(v==="error")return f("gone");m(),Be(v)||h()}),Be(s)||h()})}function Vd(n,e,t){let r=globalThis,s=r.document;if(!(typeof s?.createElement=="function"&&typeof r.WebTransport=="function"&&typeof r.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=n.holdWebRtcDial?.(),a=s.createElement("canvas"),c=!1,l=null,d=!1,u=()=>{if(l){for(let E of l.getVideoTracks())try{E.stop()}catch{}l=null}d&&(d=!1,t.onOverrideTrack(null))},p=new fr(new mr(n),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new gr(n,t.streamName??Fm)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(E,N)=>n.dispatchQuicStreamData(E,N),onQuicLane:()=>n.markStreamDataLaneQuic(),onQuicLaneLost:E=>n.quicStreamDataLaneLost(E),onLaneError:E=>n.raiseQuicStreamDataError(E)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,ctx:t.audioPlayout?.audioContext,onTrack:E=>{c||(E&&n.noteQuicMediaFlowing?.(),t.onOverrideAudioTrack(E))}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>w(),onMediaTransportLost:E=>{c||(u(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(E),w())},onWtLegDeath:()=>{n.noteMediaLegDeath?.()},onTransportChange:(E,N)=>{c||(E==="webrtc"&&(u(),w()),t.onTransportChange?.(E,N))}}),f=n.onWtOnlyLegDeath?.(E=>p.failCurrentWtLeg(E)),g=null,h=()=>{g!==null&&(clearInterval(g),g=null)},m=t.wtRetryBaseMs??2e3,_=t.wtRetryCapMs??3e4,v=null,S=0,w=()=>{if(c||v!==null||p.activeTransport==="webtransport")return;let E=ho(m,S+2,_);v=setTimeout(()=>{v=null,S+=1,p.retryWebTransport().then(N=>{if(c){N&&p.disconnect().catch(()=>{});return}if(N)return console.debug(`[urun] webtransport upgraded in background (retry ${S})`),S=0,T(N);w()}).catch(N=>{c||(console.debug(`[urun] webtransport background retry ${S} failed: `+cn(N)),w())})},E)},b=()=>{v!==null&&(clearTimeout(v),v=null)},T=async E=>{if(c||E.kind!=="webtransport")return;let N=t.pathHealthProbeMs??1e4;h();let Q=!1;g=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let F=Hd(E);if(!F){console.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),h();return}let $=F.pathLiveness();if(!$.alive){let G=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${$.evidence}`+(G?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),h(),F.fail(`path health: ${$.evidence}`);return}if(!Q){if(Q=!0,p.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${N}ms \u2014 the QUIC PATH IS HEALTHY (${$.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${N}ms \u2014 no media datagrams reached this client (path healthy: ${$.evidence}); webrtc track remains authoritative`)}},N);try{await E.firstMedia}catch(F){h(),console.debug("[urun] webtransport ended before any media flowed:",F);return}if(h(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;l=a.captureStream();let te=l.getVideoTracks()[0];te&&(d=!0,t.onOverrideTrack(te))},y=!1;return(async()=>{let E=await jm(n,t.runtimePhase,{sessionId:e,runtimeWaitCapMs:t.runtimeWaitCapMs,isDisposed:()=>c});if(c)return;if(E==="gone"){console.debug(`[urun] session ${e} ended while waiting for a runtime to pick it up \u2014 no media negotiation`),o?.proceed("session ended before a runtime was pulled \u2014 releasing the held WebRTC dial");return}y=!0;let N=await p.connect();if(c){p.disconnect().catch(()=>{});return}await T(N)})().catch(E=>{if(h(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",E);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",E),w();return}o?.proceed(`negotiation unavailable: ${E instanceof Error?E.message:String(E)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",E),w()}),{activeTransport:()=>p.activeTransport,mediaTransportAttempted:()=>y,watchDownlinkStall(E){p.watchDownlinkStall(E)},dispose(){c=!0,f?.(),h(),b(),u(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var qm=new Set;function _o(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var Bm="rpc",Hm="$presence",fo=["control",Sr],Ls=2e4,vo=3e4,zd=3e4,Vm="rpc-resp";function zm(n){return`${Vm}:${n}`}function mo(){return sr()}function Gm(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function Km(n,e,t,r,s,i,o,a,c,l){let d=[],u=null,p=!1,f=null,g=!1,h,m,_=new Promise((k,z)=>{h=k,m=z});_.catch(()=>{});let v=o(),S=null,w=null,b=null,T=null,y=null,E=null,N=!0,Q=()=>{b&&(clearTimeout(b),b=null),T&&(T(),T=null)},te=()=>{y&&(clearTimeout(y),y=null),E&&(E(),E=null)},F=!1,$=()=>{F||!g||(F=!0,n.set({rpc:{[e]:null}}))},G=()=>{N=!1,Q(),te(),S?.(),S=null,w?.(),w=null,a?.removeEventListener("abort",x),v.dispose(),$()},X=()=>{if(u){if(d.length>0){let k=u;u=null,k.resolve({value:d.shift(),done:!1})}else if(f!==null){let k=u;u=null,k.reject(f)}else if(p){let k=u;u=null,k.resolve({value:void 0,done:!0})}}},he=k=>{p||(d.push(k),X())},Z=k=>{p||(f=k,p=!0,m(k),G(),X())},Me=k=>{p||(p=!0,h(k),G(),X())},x=()=>{let k=a?.reason;Z(k instanceof Ce?k:new nt(e))},O=k=>{if(!(p||!k||typeof k!="object"))switch(te(),$(),k.t){case"delta":typeof k.delta=="string"&&he(k.delta);break;case"response":Me(k.body);break;case"error":{let{message:z,code:j}=Gm(k.body);Z(new Ce(z,{requestId:e,code:k.code??j}));break}}},B=()=>{let k=v.messages()[Symbol.asyncIterator]();S=()=>{k.return?.(void 0)};let z=()=>{N&&k.next().then(j=>{if(N){if(j.done){p||Me(void 0);return}O(j.value),z()}},j=>{N&&Z(j)})};z()},D=()=>{if(!g){if(g=!0,a){if(a.aborted){Z(new nt(e));return}a.addEventListener("abort",x,{once:!0})}w=c?.(k=>Z(k))??null,B(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),l&&l>0&&!n.synced&&(b=setTimeout(()=>{b=null,!p&&!n.synced&&Z(new Tt(l,e))},l),T=n.onSynced(()=>Q())),E=n.onSynced(()=>{E=null,!(p||F||y)&&(y=setTimeout(()=>{y=null,!(p||F)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(zd/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},zd))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(D(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(f!==null){let k=f;return f=null,Promise.reject(k)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((k,z)=>{u={resolve:k,reject:z}})},return(){return p||(p=!0,h(void 0),G()),Promise.resolve({value:void 0,done:!0})},throw(k){return p||(p=!0,m(k),G()),Promise.reject(k)}}}},body:_,start:D}}function Gd(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Ym(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=Gd(i);c&&(a.rt=c);let l=Gd(o);return l&&(a.br=l),a}var go=class{constructor(e,t,r,s,i){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._onActivity=i;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_directOut=!1;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],r=null,s=!1,i=null,o={push(c){if(!s)if(r){let l=r;r=null,l.resolve({value:c,done:!1})}else t.push(c)},end(){if(s=!0,r){let c=r;r=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{s=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||s)&&(i=e._streamConsumeUnavailableError(c),a(),r)){let l=r;r=null,l.reject(i)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):i?Promise.reject(i):s?Promise.resolve({value:void 0,done:!0}):new Promise((c,l)=>{r={resolve:c,reject:l}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}get directOut(){return this._directOut}_setOverrideTrack(e,t){if(this._overrideTrack===e&&this._directOut===(t?.directOut??!1))return;this._overrideTrack=e,this._directOut=e?t?.directOut??!1:!1,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let r=e??this._transport.getTrackByName(this._name)??this._track,s=this._handlers.get("track");if(s)for(let i of s)i(r)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),r=Ym(t,this._name),s=r?.br;if(s?.by==="runtime")throw new Rt(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??ks;return Id(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}on(e,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let r of t)r(e)}},_r=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new hs;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_gateDocUp={};_gate="open";_gateTimer=null;_gateDocUnsubs=[];_gateOff=!1;_gatedFrom;_gatedWith;_publicPhase;_phaseHandlers=new Set;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_namedSessionIdProbe;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_downlinkStallWatch=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,r,s,i,o){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=Xc(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=ys(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=ws({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new dr({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this.doc(Hm).awareness.setLocalState({role:"client"}),this._activation=new xt({onPhase:a=>this.onPhase(a),hint:()=>this.doc(Sr).get(mn)??this.doc("control").get(gn),onData:(a,c)=>this._streamData.onData(a,c)}),this._transport.on("phase",()=>this._applyLiveGate());for(let a of fo)this._gateDocUnsubs.push(this.doc(a).onConnectionState(c=>{this._gateDocUp[a]=c.connected,this._applyLiveGate()}))}_applyLiveGate(){let e=this._transport.phase;if(!e)return;let t=this._gateOff||!this._docConnector.connected||fo.every(i=>this._gateDocUp[i]);if(e.name!=="live"||t?(clearTimeout(this._gateTimer??void 0),this._gateTimer=null,this._gate="open"):this._gate==="open"&&(this._gate="connecting",this._gateTimer=setTimeout(()=>{this._gateTimer=null,this._gate="failed",this._applyLiveGate()},Ls)),e===this._gatedFrom&&this._gate===this._gatedWith)return;this._gatedFrom=e,this._gatedWith=this._gate;let r=fo.filter(i=>!this._gateDocUp[i]).join("/"),s=this._gate==="open"?e:this._gate==="connecting"?{...e,name:"connecting",reason:"docs_connecting"}:{...e,name:"error",reason:"doc_plane_unreachable",error:{kind:"transport-failed",code:"doc_plane_unreachable",reason:`the session's ${r} doc connection did not open within ${Ls/1e3}s (still retrying)`}};if(s!==this._publicPhase){this._publicPhase=s;for(let i of[...this._phaseHandlers])i(s)}}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let r=await ta({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new St,o=new cr({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,_o(t),Ar({...t,baseUrl:r.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),Je()&&await Dt();let c=t.getAccessToken,l=c?d=>!d?.redial&&s?s:Promise.resolve(c()).then(u=>u??s):s;return a.setDocTransport({wsUrl:r.wsUrl,token:l}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase!==this._gatedFrom&&this._applyLiveGate(),this._publicPhase??this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){let e=this._transport.status,t=this.phase;return!e||!t||t===this._transport.phase?e:{...e,phase:t.name,...t.error?{error:t.error}:{}}}get region(){return this._transport.region}onPhase(e){return e(this.phase),this._phaseHandlers.add(e),()=>{this._phaseHandlers.delete(e)}}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return fn(this,e)}on(e,t){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(t),this._generationTickStop||(this._generationTickStop=_s(this.doc("control"),r=>{for(let s of Array.from(this._generationTickHandlers))try{s(r)}catch(i){console.warn("[urun] generationTick handler failed:",i)}})),()=>{this._generationTickHandlers.delete(t),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new dt(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new Xe(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new Xe(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let r of this._docs.values())r.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}setNamedSessionIdProbe(e){this._namedSessionIdProbe=e}namedSessionId(){return this._namedSessionIdProbe?.()}stream(e){let t=this._streams.get(e);return t||(t=new go(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new gs(e,this._sessionId,qm.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Td(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=fs(e.wsUrl),r=typeof e.token=="function"?"<token-supplier>":e.token??"",s=e.attach?`${e.attach.gen}:${e.attach.token}`:"",i=`${t}${r}${s}${this._sessionId}`;i!==this._docEndpointKey&&(this._docEndpointKey=i,this.connectDocs(Sd({serverUrl:t,sessionId:this._sessionId,token:e.token,attach:e.attach,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let r=mo(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;i=setTimeout(()=>s.abort(new kt(c,r)),c)}let o=this._consumeResponse(r,e,!1,s.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,t,r,s,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(Bm),a=zm(e);return Km(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??vo)}requestStream(e,t={}){let r=mo();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=mo(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}connect(){return this._transport.connect()}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Vd(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,runtimePhase:{current:()=>this._transport.phase??null,subscribe:t=>this._transport.on("phase",t)},onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t,{directOut:!0}),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}),this._downlinkStallWatch&&this._dialNegotiation?.watchDownlinkStall(this._downlinkStallWatch))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}get mediaTransportAttempted(){return this._dialNegotiation?.mediaTransportAttempted()??!1}watchDownlinkStall(e={}){return this._downlinkStallWatch=e,this._dialNegotiation?.watchDownlinkStall(e),()=>{this._downlinkStallWatch=null}}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new Oe)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Oe);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let s of t)try{s()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let r=Array.from(this._activeRequests);this._activeRequests.clear();for(let s of r)try{s(new Et)}catch{}this._gateOff=!0,clearTimeout(this._gateTimer??void 0),this._gateTimer=null;for(let s of this._gateDocUnsubs.splice(0))s();for(let s of this._docs.values())s.dispose();this._docs.clear();for(let s of this._streams.values())s.dispose();this._streams.clear(),this._transport.disconnect(e)}};function Kd(n){return`urun:session:v2:${n.orgId}:${n.app}:${n.functionName}`}function wo(){try{return globalThis.sessionStorage??null}catch{return null}}var yo=new Map;function Ms(n){if(!n)return;let e=n.split(".");if(!(e.length<2))try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=JSON.parse(atob(t+"=".repeat((4-t.length%4)%4)));return typeof r?.sub=="string"&&r.sub.length>0?r.sub:void 0}catch{return}}function Qm(n,e){return n!==void 0&&e!==void 0&&n!==e}function bo(n,e){let t=wo(),r=null;if(t)try{let i=t.getItem(n);if(i){let o=JSON.parse(i);typeof o?.sessionId=="string"&&o.sessionId.length>0&&(r={sessionId:o.sessionId,...typeof o.actor=="string"&&o.actor.length>0?{actor:o.actor}:{}})}}catch{r=null}let s=yo.get(n)??r??null;return!s||Qm(s.actor,e)?null:s}function Yd(n,e){let t={sessionId:e.sessionId,...e.actor!==void 0?{actor:e.actor}:{}};yo.set(n,t);let r=wo();if(r)try{r.setItem(n,JSON.stringify(t))}catch{}}function Os(n){yo.delete(n);let e=wo();if(e)try{e.removeItem(n)}catch{}}var Qd=new Set(["paused","acquiring","live"]),Jm=new Set(["24h","keep"]);function Jd(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}function Xm(n){if(typeof n?.id!="string"||n.id.length===0)throw new _e("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof n.state!="string"||!Qd.has(n.state))throw new _e(`[urun] session ${n.id} reported an unrecognized state ${JSON.stringify(n.state)} \u2014 this @urun-sh/core build knows only ${[...Qd].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof n.recordings_expired=="boolean"?e=n.recordings_expired:console.warn(`[urun] session ${n.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:n.id,label:typeof n.label=="string"&&n.label.length>0?n.label:null,state:n.state,app:typeof n.app=="string"?n.app:"",functionName:typeof n.function=="string"?n.function:"",createdAt:Jd(n.created_at),lastActiveAt:Jd(n.last_active_at),archived:n.archived===!0,preview:typeof n.preview=="string"&&n.preview.length>0?n.preview:null,recordingsExpired:e,retention:Jm.has(n.retention)?n.retention:(n.retention!==void 0&&console.warn(`[urun] session ${n.id} reported an unrecognized retention ${JSON.stringify(n.retention)} \u2014 defaulting to '24h'`),"24h")}}var vr=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:r}=await Xo({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(Xm),nextCursor:r}}async end(e){await Zo({...this._request,sessionId:e})}async archive(e){await Vs({...this._request,sessionId:e,archived:!0})}async unarchive(e){await Vs({...this._request,sessionId:e,archived:!1})}async setName(e,t,r={}){await ea({...this._request,sessionId:e,name:t,source:r.source})}};function Xd(n,e,t){let r=Ms(t);Yd(n,r!==void 0?{sessionId:e,actor:r}:{sessionId:e})}var Zm=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Zd(n,e){return new vr(n,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function el(n,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,r){if(!(Zm.has(r)||typeof r!="string"))return(s,i)=>{let o=s??{},a=Kd({orgId:e.orgId,app:n,functionName:r}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,l,d=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,u=d(),p=e.jwt,f=e.getAccessToken?async x=>{let O=await e.getAccessToken(x);return O&&(p=O),O}:void 0,g={...e,getAccessToken:f},h=new St,m=new cr({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:u,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),_=new _r(u,h,m,_o(g),Ar(g),{activity:i?.activity}),v,S=!1,w=!1,b,T,y=new Promise(x=>{T=x}),E,N=x=>{x.sessionId||b||(b="teardown",E="ticket",Pr({baseUrl:x.baseUrl,requestId:x.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},Q=x=>{b||x.sessionId||(b="abandon",Pr({baseUrl:x.baseUrl,requestId:x.requestId,orgId:e.orgId,jwt:p,authProvider:e.authProvider,reason:"client_abandoned"}))},te=x=>{let O=x.sessionId||!l?x:{...x,sessionId:l};v=O,T({status:"ready",handle:O}),(w||b==="teardown")&&N(O)};_.setNamedSessionIdProbe(()=>v?.sessionId),_.setEndHandler(async()=>{let x=v?{status:"ready",handle:v}:await y;if(x.status==="unavailable")throw new Oe("[urun] session allocation failed before a releasable request was created",{cause:x.cause});let O=v??x.handle;return Os(a),b==="teardown"?O.sessionId?{status:"paused",sessionId:O.sessionId,reason:"client_ended"}:{status:"canceled",requestId:O.requestId}:(b="end",O.sessionId?Bs({baseUrl:O.baseUrl,sessionId:O.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):qs({baseUrl:O.baseUrl,requestId:O.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let x=v?{status:"ready",handle:v}:await y;if(x.status==="unavailable")throw new Oe("[urun] session allocation failed before a cancellable request was created",{cause:x.cause});let O=v??x.handle;if(O.sessionId)throw new oe(`[urun] cancel() is for a queued admission request, but this call already has session ${O.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:O.sessionId,code:"cancel_on_live_session"});b="end";try{let B=await qs({baseUrl:O.baseUrl,requestId:O.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return Os(a),B}catch(B){throw b==="end"&&(b=void 0),B}});let F=async x=>{let O,B=i?.sessionId??e.sessionKey??l,D,W;if(B===void 0&&!c){let fe=bo(a);if(fe?.sessionId){if(W=Ms(p),fe.actor!==void 0&&W===void 0&&f){let yt=await Promise.resolve(f()).catch(()=>{});W=Ms(yt??e.jwt)}D=fe.actor!==void 0&&W!==void 0&&fe.actor!==W?void 0:fe.sessionId}}let k=B??D,z=(fe,yt)=>Yo({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,...e.shape?{shape:e.shape}:{},idempotencyKey:fe,sessionKey:yt,label:i?.label,...i?.sharedApp?{sharedApp:!0}:{},concurrencyKey:i?.concurrencyKey,priority:e.priority,onAdmission:ye=>{m.reportAdmission(ye),ye.sessionId&&!l&&(l=ye.sessionId,O=ye.sessionId,v&&v.sessionId!==ye.sessionId&&te({...v,sessionId:ye.sessionId}),S||(e.sessionKey||Xd(a,ye.sessionId,p),_.setSessionId(ye.sessionId)))},onRequest:te}),j;try{j=await z(x,k)}catch(fe){let yt=fe instanceof q&&fe.code==="session_name_not_yours"&&k!==void 0&&k===l&&i?.sessionId===void 0&&e.sessionKey===void 0;if(D===void 0&&!yt||!(fe instanceof q)||fe.code!=="session_name_not_yours")throw fe;let ye=D??k;if(ye===void 0)throw fe;console.warn(`[urun] session_name_not_yours: the control plane refused session ${ye} for this actor \u2014 dropping the tab bookmark for that name and minting a fresh session`),yt&&(l=void 0),bo(a,W)?.sessionId===ye&&Os(a),j=await z(d(),void 0)}let Tl=f?await f()??void 0:e.jwt;if(O&&O!==j.sessionId)throw v&&v.sessionId!==j.sessionId&&te({...v,sessionId:j.sessionId}),new q(`Gateway contract violation: admission minted session ${O} but allocation completed as ${j.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return l=j.sessionId,v&&v.sessionId!==j.sessionId&&te({...v,sessionId:j.sessionId}),S||(e.sessionKey||Xd(a,j.sessionId,p),_.setSessionId(j.sessionId),X=wn(j.baseUrl)?{baseUrl:j.baseUrl,sessionId:j.sessionId}:null,_.setArtifactsAuth(Ar({...g,baseUrl:j.baseUrl})),m.setEndsAt(j.endsAt),m.seedRegion(Gs(j.response))),{url:j.wsUrl,sessionId:j.sessionId,jwt:Tl,iceServers:j.response.ice_servers,endsAt:j.endsAt,sfuAttach:j.sfuAttach}},$,G,X=null,he=f?x=>!x?.redial&&$?$:Promise.resolve(f(x?.redial?{forceRefresh:!0,reason:"background"}:void 0)).then(O=>$=O??$):()=>$,Z=()=>{let x=m.connectedUrl;return x?fs(x):void 0};if(m.setConnectionResolver(async()=>{let x=await F(d());return $=x.jwt,G=x.sfuAttach,x}),m.setConnectionViewRefresher(async()=>X?Jo({baseUrl:X.baseUrl,sessionId:X.sessionId,jwt:p}):null),m.on("connected",()=>{m.multiplexer&&h.setTarget(m.multiplexer);let x=m.connectedUrl;x&&_.setDocTransport({wsUrl:x,token:he,attach:G,resolveServerUrl:Z})}),(async x=>{let O;try{O=await F(x)}catch(B){if(S){T({status:"unavailable",cause:B});return}console.error(`[urun] Failed to create session for ${r}:`,B),v&&Q(v);let D=B instanceof Error?B:new Error(String(B)),W=B instanceof q?B.httpStatus:void 0,k=B instanceof q?B.code:void 0,z=B instanceof q?B.retryAfterSeconds:void 0;m.reportAllocationFailure(D,W,k,z),T({status:"unavailable",cause:B});return}S||(m.setAuth({jwt:O.jwt,authProvider:e.authProvider,orgId:e.orgId}),m.setConnection({url:O.url,sessionId:O.sessionId,iceServers:O.iceServers,sfuAttach:O.sfuAttach}),Je()&&await Dt(),$=O.jwt,G=O.sfuAttach,_.setDocTransport({wsUrl:O.url,token:he,attach:G,resolveServerUrl:Z}),await m.connect({app:n,functionName:r,args:o}),_.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(u).catch(x=>{console.error(`[urun] Failed to connect session for ${r}:`,x)}),e.releaseOnLeave!==!1){let x=bs(()=>{if(S=!0,m.leaveLeg())return;if(m.connectedUrl!==null){m.disconnect();return}m.disconnect();let k=v;k?N(k):w=!0});_.onDisconnect(x);let O,B,D=!1,W=()=>{D||(D=!0,O?.(),B?.())};y.then(k=>{k.status!=="ready"||D||(O=Ss(()=>v!==void 0))}),B=_.onPhase(k=>{let z=k?.name;(z==="paused"||z==="error")&&W()}),D&&B(),_.onDisconnect(W)}return _}}})}var So="https://api.urun.sh",ko="URUN_DEV";function eg(){if(typeof process>"u")return!1;let n=process.env?.[ko];if(typeof n!="string")return!1;let e=n.trim().toLowerCase();return e==="1"||e==="true"}var rt=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function tl(n,e={}){if(!n)throw new rt("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,r=Y(e.baseUrl??So),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata),e.sharedApp&&(s.shared_app=!0),e.bindPrincipal&&(s.bind_principal=!0),(e.dev??eg())&&(s.dev=!0);let i;try{i=await t(`${r}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(s)})}catch(h){throw new rt(`[urun] client token mint request failed: ${h instanceof Error?h.message:String(h)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let h=typeof o.message=="string"?o.message:`HTTP ${i.status}`;throw new rt(`[urun] client token mint failed: ${h}`,i.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",l=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,d=typeof o.expires_in=="number"?o.expires_in:void 0,u=typeof o.billing_audience=="string"?o.billing_audience:void 0,p=typeof o.credits_admission_ok=="boolean"?o.credits_admission_ok:void 0,f=typeof o.credits_refusal_reason=="string"?o.credits_refusal_reason:void 0;if(!a)throw new rt("[urun] client token mint returned no token (control-plane contract violation)",i.status);let g=Number.isFinite(l)?new Date(l):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:g,orgId:c,...u!==void 0?{billingAudience:u}:{},...p!==void 0?{creditsAdmissionOk:p}:{},...f!==void 0?{creditsRefusalReason:f}:{}}}var rl=3e4,nl="stream:",To=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let r=`${nl}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${nl}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${rl}ms`)))},rl);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function sl(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let i=new bt(s);return new To(s,i)}var tg='video/mp4; codecs="avc1.42E01E"';function il(n,e){let t=e?.codec??tg,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);r.src=i,s.addEventListener("sourceopen",()=>{let p;try{p=s.addSourceBuffer(t)}catch(m){throw m instanceof DOMException&&m.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):m}let f=n.getReader();function g(){return p.updating?new Promise(m=>{p.addEventListener("updateend",()=>m(),{once:!0})}):Promise.resolve()}async function h(){try{for(;;){let{done:m,value:_}=await f.read();if(m){await g(),s.readyState==="open"&&s.endOfStream();return}await g();try{p.appendBuffer(_)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let S=p.buffered;if(S.length>0){let w=S.start(S.length-1);p.remove(0,w),await g(),p.appendBuffer(_)}else throw v}else throw v}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}h()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(r),l=c.getTracks(),d=0,u=l.length;if(u===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let p of l)p.addEventListener("ended",()=>{d++,d>=u&&URL.revokeObjectURL(i)});return c}function ol(n){return n.status.startsWith("pending_")}var wt=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},wr=class extends wt{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function rg(n,e,t){let r=t||e||`HTTP ${n}`;return n===401?new wr(r,e??"unauthorized"):new wt(r,{status:n,code:e??`http_${n}`})}var dn=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new wt("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let r=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(r)?r:[]}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw rg(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r){let s={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:s})}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 wr("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function al(n){return new dn(n)}var ln=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function cl(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function ng(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function sg(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function Ro(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var un=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,Ro(r,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new ln;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(r)}catch(o){let a=`one-capture getUserMedia(${cl(r)}) failed`,c=o instanceof Error?o.message:String(o);for(let l of[...this.claims.values()])if(this.claims.delete(l.kind),l.released=!0,l!==e){let d=new Error(`${a} \u2014 ${l.kind} capture lost: ${c||o}`);d.cause=o,Ro(l,d)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=ng(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${cl(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw c;Ro(o,c);continue}if(o.track=a,o.stream=sg(s,a),o!==e)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(e,t){let r=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await r.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(e)===s&&r.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},ig=null;function dl(){return ig??=new un}var Co="input",ll=30;function ul(n){let e=n.now??Date.now,t=n.field??Co,r=1e3/Math.max(n.hz??30,.001),s=new Set,i=0,o=0,a=0,c=0,l,d=null,u=!1,p=()=>{if(u)return;l=e(),c+=1;let g={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:c,at:l};try{n.awareness.setLocalStateField(t,g)}catch{}},f=()=>{if(u)return;let g=e();if(l===void 0||g-l>=r){d&&(clearTimeout(d),d=null),p();return}if(d)return;let h=Math.max(r-(g-l),0);d=setTimeout(()=>{d=null,p()},h),d.unref?.()};return{keyDown(g){let h=String(g).toLowerCase();s.has(h)||(s.add(h),f())},keyUp(g){let h=String(g).toLowerCase();s.delete(h)&&f()},setButtons(g){let h=Number.isFinite(g)?Number(g):0;h!==i&&(i=h,f())},movePointer(g,h){let m=Number.isFinite(g)?Number(g):0,_=Number.isFinite(h)?Number(h):0;m===0&&_===0||(o+=m,a+=_,f())},heldKeys(){return[...s]},clear(){u||(s.clear(),i=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(u)return;let g=s.size>0||i!==0;s.clear(),i=0,d&&(clearTimeout(d),d=null),g&&p(),u=!0}}}var fl=1024,ml=.92,gl=262144,_l=256e3,Eo=[.9,.8,.7,.6,.5],pl=.8,og=8;function Us(n,e,t){if(!(n>0)||!(e>0))throw new Error(`reference image has no pixels (${n}x${e})`);let r=Math.min(1,t/Math.max(n,e));return{width:Math.max(1,Math.round(n*r)),height:Math.max(1,Math.round(e*r))}}async function ag(n){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(n,{imageOrientation:"from-image"})}async function vl(n,e,t){let r=await new Promise(s=>{n.toBlob(s,e,e==="image/jpeg"?t:void 0)});if(!r)throw new Error(`could not encode the reference image as ${e}`);return r}function hl(n,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${n} -> ${e} bytes`)}async function Po(n,e,t,r,s){let i=document.createElement("canvas");i.width=e,i.height=t;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return r==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(n,0,0,e,t),await vl(i,r,s)}async function cg(n,e,t,r){let{width:s,height:i}=e,o=await Po(n,s,i,t,r);if(o.size<=256e3)return{blob:o,width:s,height:i};if(t==="image/jpeg"){for(let c of Eo)if(!(c>=r)&&(o=await Po(n,s,i,t,c),o.size<=256e3))return hl(`quality ${r} -> ${c}`,o.size),{blob:o,width:s,height:i}}let a=t==="image/jpeg"?Eo[Eo.length-1]:r;for(let c=0;c<og;c++)if(s=Math.max(16,Math.round(s*pl)),i=Math.max(16,Math.round(i*pl)),o=await Po(n,s,i,t,a),o.size<=256e3)return hl(`downscaled to ${s}x${i} @ q${a}`,o.size),{blob:o,width:s,height:i};throw new Error(`this image cannot be sent: even at ${s}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function wl(n,e){let{maxSize:t=1024,type:r="image/jpeg",quality:s=.92,source:i}=e,o=await ag(n);try{let a=Us(o.width,o.height,t),c=await cg(o,a,r,s);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:r,width:c.width,height:c.height,source:i}}finally{o.close()}}function yl(n){let e=n instanceof Error?n.name:"",t=n instanceof Error?n.message:String(n);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function bl(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function Sl(n,e){let t=n.videoWidth,r=n.videoHeight;if(!(t>0)||!(r>0))throw new Error("the camera has not shown a frame yet");let{maxSize:s=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=Us(t,r,s),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let l=c.getContext("2d");if(!l)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(l.fillStyle="#fff",l.fillRect(0,0,a.width,a.height)),l.drawImage(n,0,0,a.width,a.height);let d=await vl(c,i,o);return{bytes:new Uint8Array(await d.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var dg=new Set(["w","a","s","d"]),yr=(n,e)=>Math.min(e,Math.max(-e,n));function kl(n={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:r=.18,decayTauMs:s=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=n,c=0,l=0,d=0,u=null,p=new Set;return{pointerDelta(f,g){c=yr(c-f*e,o),l=yr(l-g*e,o)},keyDown(f){let g=f.toLowerCase();dg.has(g)&&p.add(g)},keyUp(f){p.delete(f.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let f=1-i;c*=f,l*=f,d*=f},tick(f){if(u===null){u=f;return}let g=Math.max(0,Math.min(100,f-u))/1e3;u=f,p.has("w")&&(d=yr(d+t*g,a)),p.has("s")&&(d=yr(d-t*g,a)),p.has("a")&&(c=yr(c+r*g,o)),p.has("d")&&(c=yr(c-r*g,o));let h=Math.exp(-g*1e3/s);c*=h,l*=h,d*=h},transform(){return{translateX:c,translateY:l,scale:Math.exp(d)}},isIdentity(f=5e-4){return Math.abs(c)<f&&Math.abs(l)<f&&Math.abs(d)<f},reset(){c=0,l=0,d=0,p.clear()}}}
|