@whereby.com/browser-sdk 3.14.10 → 3.14.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- this.whereby=this.whereby||{},this.whereby.react=function(e,t,r){"use strict";function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}function i(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(r){if("default"!==r&&!(r in e)){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}})}),Object.freeze(e)}var s=n(t),o=n(r),a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var d={exports:{}};d.exports=function(e){return(e instanceof Buffer?e:Buffer.from(e.toString(),"binary")).toString("base64")};var l,u,p=c(d.exports),h={},f={exports:{}};function m(){if(u)return l;u=1;var e=1e3,t=60*e,r=60*t,n=24*r,i=7*n,s=365.25*n;function o(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return l=function(a,c){c=c||{};var d=typeof a;if("string"===d&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*i;case"days":case"day":case"d":return c*n;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===d&&isFinite(a))return c.long?function(i){var s=Math.abs(i);if(s>=n)return o(i,s,n,"day");if(s>=r)return o(i,s,r,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=n)return Math.round(i/n)+"d";if(s>=r)return Math.round(i/r)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},l}var g=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n}),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,i=-1,s=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(i=n,s=r,n++):(r++,n++);else{if(-1===i)return!1;n=i+1,s++,r=s}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=m(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))}),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!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`."))}})(),t.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"],t.log=console.debug||console.log||(()=>{}),e.exports=g(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(f,f.exports);var v=f.exports,b={};Object.defineProperty(b,"__esModule",{value:!0});var y={},_=Object.defineProperty,w=Object.getOwnPropertyDescriptor,S=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,k={};((e,t)=>{for(var r in t)_(e,r,{get:t[r],enumerable:!0})})(k,{BrowserDetector:()=>I,KnownBrowsers:()=>R,KnownPlatforms:()=>E,default:()=>D});var T,P=(T=k,((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of S(t))!C.call(e,i)&&i!==r&&_(e,i,{get:()=>t[i],enumerable:!(n=w(t,i))||n.enumerable});return e})(_({},"__esModule",{value:!0}),T)),R={chrome:"Google Chrome",brave:"Brave",crios:"Google Chrome",edge:"Microsoft Edge",edg:"Microsoft Edge",edgios:"Microsoft Edge",fennec:"Mozilla Firefox",jsdom:"JsDOM",mozilla:"Mozilla Firefox",fxios:"Mozilla Firefox",msie:"Microsoft Internet Explorer",opera:"Opera",opios:"Opera",opr:"Opera",opt:"Opera",rv:"Microsoft Internet Explorer",safari:"Safari",samsungbrowser:"Samsung Browser",electron:"Electron"},E={android:"Android",androidTablet:"Android Tablet",cros:"Chrome OS",fennec:"Android Tablet",ipad:"IPad",ipod:"IPod",iphone:"IPhone",jsdom:"JsDOM",linux:"Linux",mac:"Macintosh",tablet:"Android Tablet",win:"Windows","windows phone":"Windows Phone",xbox:"Microsoft Xbox"},O=(e,t=-1)=>{let r=new RegExp(`^-?\\d+(?:.\\d{0,${t}})?`),n=Number(e).toString().match(r);return n?n[0]:null},x=()=>typeof window<"u"?window.navigator:null,I=class{userAgent;constructor(e){this.userAgent=e||x()?.userAgent||null}static get VERSION(){return"4.1.0"}parseUserAgent(e){let t={},r=e||this.userAgent||"",n=r.toLowerCase().replace(/\s\s+/g," "),i=/(edge)\/([\w.]+)/.exec(n)||/(edg)[/]([\w.]+)/.exec(n)||/(opr)[/]([\w.]+)/.exec(n)||/(opt)[/]([\w.]+)/.exec(n)||/(fxios)[/]([\w.]+)/.exec(n)||/(edgios)[/]([\w.]+)/.exec(n)||/(jsdom)[/]([\w.]+)/.exec(n)||/(samsungbrowser)[/]([\w.]+)/.exec(n)||/(electron)[/]([\w.]+)/.exec(n)||/(chrome)[/]([\w.]+)/.exec(n)||/(crios)[/]([\w.]+)/.exec(n)||/(opios)[/]([\w.]+)/.exec(n)||/(version)(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(webkit)[/]([\w.]+).*(version)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(webkit)[/]([\w.]+)/.exec(n)||/(opera)(?:.*version|)[/]([\w.]+)/.exec(n)||/(msie) ([\w.]+)/.exec(n)||/(fennec)[/]([\w.]+)/.exec(n)||n.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(n)||n.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(n)||[],s=/(ipad)/.exec(n)||/(ipod)/.exec(n)||/(iphone)/.exec(n)||/(jsdom)/.exec(n)||/(windows phone)/.exec(n)||/(xbox)/.exec(n)||/(win)/.exec(n)||/(tablet)/.exec(n)||/(android)/.test(n)&&!1===/(mobile)/.test(n)&&["androidTablet"]||/(android)/.exec(n)||/(mac)/.exec(n)||/(linux)/.exec(n)||/(cros)/.exec(n)||[],o=i[5]||i[3]||i[1]||null,a=s[0]||null,c=i[4]||i[2]||null,d=x();"chrome"===o&&"function"==typeof d?.brave?.isBrave&&(o="brave"),o&&(t[o]=!0),a&&(t[a]=!0);let l=!!(t.tablet||t.android||t.androidTablet),u=!!(t.ipad||t.tablet||t.androidTablet),p=!!(t.android||t.androidTablet||t.tablet||t.ipad||t.ipod||t.iphone||t["windows phone"]),h=!!(t.cros||t.mac||t.linux||t.win),f=!!(t.brave||t.chrome||t.crios||t.opr||t.safari||t.edg||t.electron),m=!(!t.msie&&!t.rv),g=!(!t.chrome&&!t.crios),v=!!(t.fxios||t.fennec||t.mozilla),b=!!t.safari,y=!!(t.opera||t.opios||t.opr||t.opt),_=!!(t.edg||t.edge||t.edgios);return{name:R[o]??null,platform:E[a]??null,userAgent:r,version:c,shortVersion:c?O(parseFloat(c),2):null,isAndroid:l,isTablet:u,isMobile:p,isDesktop:h,isWebkit:f,isIE:m,isChrome:g,isFireFox:v,isSafari:b,isOpera:y,isEdge:_}}getBrowserInfo(){let e=this.parseUserAgent();return{name:e.name,platform:e.platform,userAgent:e.userAgent,version:e.version,shortVersion:e.shortVersion}}},D=I,M={};Object.defineProperty(M,"__esModule",{value:!0}),M.Logger=void 0;const j=v,A="mediasoup-client";M.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,j.default)(`${A}:${e}`),this._warn=(0,j.default)(`${A}:WARN:${e}`),this._error=(0,j.default)(`${A}:ERROR:${e}`)):(this._debug=(0,j.default)(A),this._warn=(0,j.default)(`${A}:WARN`),this._error=(0,j.default)(`${A}: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}};var L,N={},F={exports:{}},B="object"==typeof Reflect?Reflect:null,z=B&&"function"==typeof B.apply?B.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};L=B&&"function"==typeof B.ownKeys?B.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var U=Number.isNaN||function(e){return e!=e};function V(){V.init.call(this)}F.exports=V,F.exports.once=function(e,t){return new Promise(function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}X(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&X(e,"error",t,r)}(e,i,{once:!0})})},V.EventEmitter=V,V.prototype._events=void 0,V.prototype._eventsCount=0,V.prototype._maxListeners=void 0;var $=10;function G(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function q(e){return void 0===e._maxListeners?V.defaultMaxListeners:e._maxListeners}function H(e,t,r,n){var i,s,o;if(G(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=q(e))>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,function(e){console&&console.warn&&console.warn(e)}(a)}return e}function W(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function J(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=W.bind(n);return i.listener=r,n.wrapFn=i,i}function K(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):Y(i,i.length)}function Q(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function Y(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function X(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){n.once&&e.removeEventListener(t,i),r(s)})}}Object.defineProperty(V,"defaultMaxListeners",{enumerable:!0,get:function(){return $},set:function(e){if("number"!=typeof e||e<0||U(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");$=e}}),V.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},V.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||U(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},V.prototype.getMaxListeners=function(){return q(this)},V.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n="error"===e,i=this._events;if(void 0!==i)n=n&&void 0===i.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)z(a,this,t);else{var c=a.length,d=Y(a,c);for(r=0;r<c;++r)z(d[r],this,t)}return!0},V.prototype.addListener=function(e,t){return H(this,e,t,!1)},V.prototype.on=V.prototype.addListener,V.prototype.prependListener=function(e,t){return H(this,e,t,!0)},V.prototype.once=function(e,t){return G(t),this.on(e,J(this,e,t)),this},V.prototype.prependOnceListener=function(e,t){return G(t),this.prependListener(e,J(this,e,t)),this},V.prototype.removeListener=function(e,t){var r,n,i,s,o;if(G(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},V.prototype.off=V.prototype.removeListener,V.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},V.prototype.listeners=function(e){return K(this,e,!0)},V.prototype.rawListeners=function(e){return K(this,e,!1)},V.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Q.call(e,t)},V.prototype.listenerCount=Q,V.prototype.eventNames=function(){return this._eventsCount>0?L(this._events):[]};var Z=F.exports;Object.defineProperty(N,"__esModule",{value:!0}),N.EnhancedEventEmitter=void 0;const ee=Z,te=new M.Logger("EnhancedEventEmitter");class re extends ee.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(t){te.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,t);try{super.emit("listenererror",e,t)}catch(e){}return Boolean(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)}}N.EnhancedEventEmitter=re;var ne={};Object.defineProperty(ne,"__esModule",{value:!0}),ne.InvalidStateError=ne.UnsupportedError=void 0;class ie extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ie):this.stack=new Error(e).stack}}ne.UnsupportedError=ie;class se extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,se):this.stack=new Error(e).stack}}ne.InvalidStateError=se;var oe={};Object.defineProperty(oe,"__esModule",{value:!0}),oe.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},oe.generateRandomNumber=function(){return Math.round(1e7*Math.random())},oe.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const n of r){const r=t[n];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var ae={},ce={},de={},le=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(de,"__esModule",{value:!0}),de.Logger=void 0;const ue=le(v),pe="h264-profile-level-id";de.Logger=class{constructor(e){e?(this._debug=(0,ue.default)(`${pe}:${e}`),this._warn=(0,ue.default)(`${pe}:WARN:${e}`),this._error=(0,ue.default)(`${pe}:ERROR:${e}`)):(this._debug=(0,ue.default)(pe),this._warn=(0,ue.default)(`${pe}:WARN`),this._error=(0,ue.default)(`${pe}: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}},Object.defineProperty(ce,"__esModule",{value:!0}),ce.ProfileLevelId=ce.Level=ce.Profile=void 0,ce.parseProfileLevelId=Se,ce.profileLevelIdToString=Ce,ce.profileToString=function(e){switch(e){case fe.ConstrainedBaseline:return"ConstrainedBaseline";case fe.Baseline:return"Baseline";case fe.Main:return"Main";case fe.ConstrainedHigh:return"ConstrainedHigh";case fe.High:return"High";case fe.PredictiveHigh444:return"PredictiveHigh444";default:return void he.warn(`profileToString() | unrecognized profile ${e}`)}},ce.levelToString=function(e){switch(e){case me.L1_b:return"1b";case me.L1:return"1";case me.L1_1:return"1.1";case me.L1_2:return"1.2";case me.L1_3:return"1.3";case me.L2:return"2";case me.L2_1:return"2.1";case me.L2_2:return"2.2";case me.L3:return"3";case me.L3_1:return"3.1";case me.L3_2:return"3.2";case me.L4:return"4";case me.L4_1:return"4.1";case me.L4_2:return"4.2";case me.L5:return"5";case me.L5_1:return"5.1";case me.L5_2:return"5.2";default:return void he.warn(`levelToString() | unrecognized level ${e}`)}},ce.parseSdpProfileLevelId=ke,ce.isSameProfile=function(e={},t={}){const r=ke(e),n=ke(t);return Boolean(r&&n&&r.profile===n.profile)},ce.isSameProfileAndLevel=function(e={},t={}){const r=ke(e),n=ke(t);return Boolean(r&&n&&r.profile===n.profile&&r.level==n.level)},ce.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void he.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=ke(e),n=ke(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!n)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==n.profile)throw new TypeError("H264 Profile mismatch");const i=Pe(e)&&Pe(t),s=r.level,o=n.level,a=function(e,t){return function(e,t){if(e===me.L1_b)return t!==me.L1&&t!==me.L1_b;if(t===me.L1_b)return e!==me.L1;return e<t}(e,t)?e:t}(s,o),c=i?s:a;return he.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),Ce(new ge(r.profile,c))},ce.supportedLevel=function(e,t){for(let r=we.length-1;r>=0;--r){const n=we[r];if(256*n.max_macroblock_frame_size<=e&&n.max_macroblocks_per_second<=t*n.max_macroblock_frame_size)return he.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${n.level}]`),n.level}return void he.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const he=new de.Logger;var fe,me;!function(e){e[e.ConstrainedBaseline=1]="ConstrainedBaseline",e[e.Baseline=2]="Baseline",e[e.Main=3]="Main",e[e.ConstrainedHigh=4]="ConstrainedHigh",e[e.High=5]="High",e[e.PredictiveHigh444=6]="PredictiveHigh444"}(fe||(ce.Profile=fe={})),function(e){e[e.L1_b=0]="L1_b",e[e.L1=10]="L1",e[e.L1_1=11]="L1_1",e[e.L1_2=12]="L1_2",e[e.L1_3=13]="L1_3",e[e.L2=20]="L2",e[e.L2_1=21]="L2_1",e[e.L2_2=22]="L2_2",e[e.L3=30]="L3",e[e.L3_1=31]="L3_1",e[e.L3_2=32]="L3_2",e[e.L4=40]="L4",e[e.L4_1=41]="L4_1",e[e.L4_2=42]="L4_2",e[e.L5=50]="L5",e[e.L5_1=51]="L5_1",e[e.L5_2=52]="L5_2"}(me||(ce.Level=me={}));class ge{constructor(e,t){this.profile=e,this.level=t}}ce.ProfileLevelId=ge;const ve=new ge(fe.ConstrainedBaseline,me.L3_1);class be{constructor(e){this.mask=~Te("x",e),this.masked_value=Te("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class ye{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const _e=[new ye(66,new be("x1xx0000"),fe.ConstrainedBaseline),new ye(77,new be("1xxx0000"),fe.ConstrainedBaseline),new ye(88,new be("11xx0000"),fe.ConstrainedBaseline),new ye(66,new be("x0xx0000"),fe.Baseline),new ye(88,new be("10xx0000"),fe.Baseline),new ye(77,new be("0x0x0000"),fe.Main),new ye(100,new be("00000000"),fe.High),new ye(100,new be("00001100"),fe.ConstrainedHigh),new ye(244,new be("00000000"),fe.PredictiveHigh444)],we=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:me.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:me.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:me.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:me.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:me.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:me.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:me.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:me.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:me.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:me.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:me.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:me.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:me.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:me.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:me.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:me.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:me.L5_2}];function Se(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,n=t>>8&255,i=t>>16&255;let s;switch(r){case me.L1_1:s=16&n?me.L1_b:me.L1_1;break;case me.L1:case me.L1_2:case me.L1_3:case me.L2:case me.L2_1:case me.L2_2:case me.L3:case me.L3_1:case me.L3_2:case me.L4:case me.L4_1:case me.L4_2:case me.L5:case me.L5_1:case me.L5_2:s=r;break;default:return void he.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of _e)if(i===t.profile_idc&&t.profile_iop.isMatch(n))return he.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new ge(t.profile,s);he.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function Ce(e){if(e.level==me.L1_b)switch(e.profile){case fe.ConstrainedBaseline:return"42f00b";case fe.Baseline:return"42100b";case fe.Main:return"4d100b";default:return void he.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case fe.ConstrainedBaseline:t="42e0";break;case fe.Baseline:t="4200";break;case fe.Main:t="4d00";break;case fe.ConstrainedHigh:t="640c";break;case fe.High:t="6400";break;case fe.PredictiveHigh444:t="f400";break;default:return void he.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function ke(e={}){const t=e["profile-level-id"];return t?Se(t):ve}function Te(e,t){return Number(t[0]===e)<<7|Number(t[1]===e)<<6|Number(t[2]===e)<<5|Number(t[3]===e)<<4|Number(t[4]===e)<<3|Number(t[5]===e)<<2|Number(t[6]===e)<<1|Number(t[7]===e)}function Pe(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}Object.defineProperty(ae,"__esModule",{value:!0}),ae.validateAndNormalizeRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)Me(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)Ae(t)},ae.validateAndNormalizeRtpParameters=De,ae.validateAndNormalizeSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},ae.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},ae.getExtendedRtpCapabilities=function(e,t,r){const n={codecs:[],headerExtensions:[]};if(r)for(const r of e.codecs??[]){if(Be(r))continue;const e=(t.codecs??[]).find(e=>ze(e,r,{strict:!0,modify:!0}));if(!e)continue;const i={kind:r.kind,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,localPayloadType:r.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:e.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:r.parameters??{},remoteParameters:e.parameters??{},rtcpFeedback:Ve(r,e)};n.codecs.push(i)}else for(const r of t.codecs??[]){if(Be(r))continue;const t=(e.codecs??[]).find(e=>ze(e,r,{strict:!0,modify:!0}));if(!t)continue;const i={kind:t.kind,mimeType:t.mimeType,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:r.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters??{},remoteParameters:r.parameters??{},rtcpFeedback:Ve(t,r)};n.codecs.push(i)}for(const r of n.codecs){const n=e.codecs.find(e=>Be(e)&&e.parameters?.apt===r.localPayloadType),i=t.codecs.find(e=>Be(e)&&e.parameters?.apt===r.remotePayloadType);n&&i&&(r.localRtxPayloadType=n.preferredPayloadType,r.remoteRtxPayloadType=i.preferredPayloadType)}for(const r of t.headerExtensions){const t=e.headerExtensions.find(e=>Ue(e,r));if(!t)continue;const i={kind:r.kind,uri:r.uri,sendId:t.preferredId,recvId:r.preferredId,encrypt:t.preferredEncrypt??!1,direction:"sendrecv"};switch(r.direction){case"sendrecv":i.direction="sendrecv";break;case"recvonly":i.direction="sendonly";break;case"sendonly":i.direction="recvonly";break;case"inactive":i.direction="inactive"}n.headerExtensions.push(i)}return n},ae.getRecvRtpCapabilities=function(e){const t={codecs:[],headerExtensions:[]};for(const r of e.codecs){const e={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(e),!r.remoteRtxPayloadType)continue;const n={kind:r.kind,mimeType:`${r.kind}/rtx`,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(n)}for(const r of e.headerExtensions){if("sendrecv"!==r.direction&&"recvonly"!==r.direction)continue;const e={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt??!1,direction:r.direction};t.headerExtensions.push(e)}return t},ae.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},ae.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"goog-remb"!==e.type);else if(r.headerExtensions.some(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"transport-cc"!==e.type);else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"transport-cc"!==e.type&&"goog-remb"!==e.type);return r},ae.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(ze(e[n],t,{strict:!0})){r.push(e[n]),Be(e[n+1])&&r.push(e[n+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),Be(e[1])&&r.push(e[1]);return r},ae.generateProbatorRtpParameters=function(e){De(e=Ee.clone(e));const t={mid:Oe,codecs:[],headerExtensions:[],encodings:[{ssrc:xe}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=Ie,t.headerExtensions=e.headerExtensions,t},ae.canSend=function(e,t){return(t.codecs??[]).some(t=>t.kind===e)},ae.canReceive=function(e,t){if(De(e),0===e.codecs.length)return!1;const r=e.codecs[0];return(t.codecs??[]).some(e=>e.preferredPayloadType===r.payloadType)};const Re=ce,Ee=oe,Oe="probator",xe=1234,Ie=127;function De(e){if("object"!=typeof e)throw new TypeError("params is not an object");if(e.mid&&"string"!=typeof e.mid)throw new TypeError("params.mid is not a string");if(!Array.isArray(e.codecs))throw new TypeError("missing params.codecs");for(const t of e.codecs)Le(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("params.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)Ne(t);if(e.encodings&&!Array.isArray(e.encodings))throw new TypeError("params.encodings is not an array");e.encodings||(e.encodings=[]);for(const t of e.encodings)Fe(t);if(e.rtcp&&"object"!=typeof e.rtcp)throw new TypeError("params.rtcp is not an object");e.rtcp||(e.rtcp={}),function(e){if("object"!=typeof e)throw new TypeError("rtcp is not an object");if(e.cname&&"string"!=typeof e.cname)throw new TypeError("invalid rtcp.cname");e.reducedSize&&"boolean"==typeof e.reducedSize||(e.reducedSize=!0)}(e.rtcp)}function Me(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if(e.kind=r[1].toLowerCase(),"number"!=typeof e.preferredPayloadType)throw new TypeError("missing codec.preferredPayloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===e.kind?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)je(t)}function je(e){if("object"!=typeof e)throw new TypeError("fb is not an object");if(!e.type||"string"!=typeof e.type)throw new TypeError("missing fb.type");e.parameter&&"string"==typeof e.parameter||(e.parameter="")}function Ae(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if("audio"!==e.kind&&"video"!==e.kind)throw new TypeError("invalid ext.kind");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.preferredId)throw new TypeError("missing ext.preferredId");if(e.preferredEncrypt&&"boolean"!=typeof e.preferredEncrypt)throw new TypeError("invalid ext.preferredEncrypt");if(e.preferredEncrypt||(e.preferredEncrypt=!1),e.direction&&"string"!=typeof e.direction)throw new TypeError("invalid ext.direction");e.direction||(e.direction="sendrecv")}function Le(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if("number"!=typeof e.payloadType)throw new TypeError("missing codec.payloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===r[1].toLowerCase()?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)je(t)}function Ne(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.id)throw new TypeError("missing ext.id");if(e.encrypt&&"boolean"!=typeof e.encrypt)throw new TypeError("invalid ext.encrypt");e.encrypt||(e.encrypt=!1),e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError("invalid header extension parameter")}}function Fe(e){if("object"!=typeof e)throw new TypeError("encoding is not an object");if(e.ssrc&&"number"!=typeof e.ssrc)throw new TypeError("invalid encoding.ssrc");if(e.rid&&"string"!=typeof e.rid)throw new TypeError("invalid encoding.rid");if(e.rtx&&"object"!=typeof e.rtx)throw new TypeError("invalid encoding.rtx");if(e.rtx&&"number"!=typeof e.rtx.ssrc)throw new TypeError("missing encoding.rtx.ssrc");if(e.dtx&&"boolean"==typeof e.dtx||(e.dtx=!1),e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("invalid encoding.scalabilityMode")}function Be(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function ze(e,t,{strict:r=!1,modify:n=!1}={}){const i=e.mimeType.toLowerCase();if(i!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(i){case"video/h264":if(r){if((e.parameters["packetization-mode"]??0)!==(t.parameters["packetization-mode"]??0))return!1;if(!Re.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=Re.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}n&&(r?(e.parameters["profile-level-id"]=r,t.parameters["profile-level-id"]=r):(delete e.parameters["profile-level-id"],delete t.parameters["profile-level-id"]))}break;case"video/vp9":if(r){if((e.parameters["profile-id"]??0)!==(t.parameters["profile-id"]??0))return!1}}return!0}function Ue(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function Ve(e,t){const r=[];for(const n of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find(e=>e.type===n.type&&(e.parameter===n.parameter||!e.parameter&&!n.parameter));e&&r.push(e)}return r}var $e={},Ge={},qe={},He={};Object.defineProperty(He,"__esModule",{value:!0}),He.Logger=void 0;const We=v,Je="awaitqueue";He.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=We(`${Je}:${e}`),this._warn=We(`${Je}:WARN:${e}`),this._error=We(`${Je}:ERROR:${e}`)):(this._debug=We(Je),this._warn=We(`${Je}:WARN`),this._error=We(`${Je}: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}};var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.AwaitQueueRemovedTaskError=Ke.AwaitQueueStoppedError=void 0;class Qe extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Qe)}}Ke.AwaitQueueStoppedError=Qe;class Ye extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Ye)}}Ke.AwaitQueueRemovedTaskError=Ye,Object.defineProperty(qe,"__esModule",{value:!0}),qe.AwaitQueue=void 0;const Xe=Ke,Ze=new He.Logger("AwaitQueue");qe.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;stopping=!1;constructor(){Ze.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,Ze.debug(`push() [name:${t}]`),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise((r,n)=>{const i={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(i.completed)return;i.completed=!0,this.pendingTasks.delete(i.id),Ze.debug(`resolving task [name:${i.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!i.completed&&(i.completed=!0,this.pendingTasks.delete(i.id),Ze.debug(`rejecting task [name:${i.name}]: %s`,String(e)),n(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(i.id,i),1===this.pendingTasks.size&&this.execute(i)})}stop(){Ze.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Ze.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Xe.AwaitQueueStoppedError);this.stopping=!1}remove(e){Ze.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Xe.AwaitQueueRemovedTaskError):Ze.debug(`stop() | no task with given idx [taskIdx:${e}]`)}dump(){const e=Date.now();let 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(Ze.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=qe;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Ke;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(Ge);var et={};Object.defineProperty(et,"__esModule",{value:!0}),et.Producer=void 0;const tt=N,rt=ne,nt=new M.Logger("Producer");class it extends tt.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new tt.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),nt.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=n,this._kind=n.kind,this._rtpParameters=i,this._paused=!!o&&!n.enabled,this._maxSpatialLayer=void 0,this._stopTracks=s,this._disableTrackOnPause=o,this._zeroRtpOnPause=a,this._appData=c??{},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||(nt.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(nt.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new rt.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){nt.debug("pause()"),this._closed?nt.error("pause() | Producer closed"):(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(){nt.debug("resume()"),this._closed?nt.error("resume() | Producer closed"):(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(nt.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new rt.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new rt.InvalidStateError("track ended");e!==this._track?(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()):nt.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new rt.InvalidStateError("closed");if("video"!==this._kind)throw new rt.UnsupportedError("not a video Producer");if("number"!=typeof e)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 rt.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)})}onTrackEnded(){nt.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(e){}}}et.Producer=it;var st={};Object.defineProperty(st,"__esModule",{value:!0}),st.Consumer=void 0;const ot=N,at=ne,ct=new M.Logger("Consumer");class dt extends ot.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new ot.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:s,appData:o}){super(),ct.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=n,this._track=i,this._rtpParameters=s,this._paused=!i.enabled,this._appData=o??{},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||(ct.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(ct.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new at.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){ct.debug("pause()"),this._closed?ct.error("pause() | Consumer closed"):this._paused?ct.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){ct.debug("resume()"),this._closed?ct.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):ct.debug("resume() | Consumer is already resumed")}onTrackEnded(){ct.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(e){}}}st.Consumer=dt;var lt={};Object.defineProperty(lt,"__esModule",{value:!0}),lt.DataProducer=void 0;const ut=N,pt=ne,ht=new M.Logger("DataProducer");class ft extends ut.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new ut.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),ht.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=n??{},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||(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"))}send(e){if(ht.debug("send()"),this._closed)throw new pt.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(ht.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;const t=e.error??new Error("unknown DataChannel error");"sctp-failure"===e.error?.errorDetail?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",()=>{this._closed||ht.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}}lt.DataProducer=ft;var mt={};Object.defineProperty(mt,"__esModule",{value:!0}),mt.DataConsumer=void 0;const gt=N,vt=new M.Logger("DataConsumer");class bt extends gt.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new gt.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),vt.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=n,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||(vt.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(vt.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(vt.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;const t=e.error??new Error("unknown DataChannel error");"sctp-failure"===e.error?.errorDetail?vt.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):vt.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(vt.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)})}}mt.DataConsumer=bt,Object.defineProperty($e,"__esModule",{value:!0}),$e.Transport=void 0;const yt=Ge,_t=N,wt=ne,St=oe,Ct=ae,kt=et,Tt=st,Pt=lt,Rt=mt,Et=new M.Logger("Transport");class Ot{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}let xt=class extends _t.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 yt.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new _t.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d,handlerFactory:l,getSendExtendedRtpCapabilities:u,recvRtpCapabilities:p,canProduceByKind:h}){super(),Et.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=u,this._recvRtpCapabilities=p,this._canProduceByKind=h,this._maxSctpMessageSize=s?s.maxMessageSize:null;const f=St.clone(c)??{};delete f.iceServers,delete f.iceTransportPolicy,delete f.bundlePolicy,delete f.rtcpMuxPolicy,this._handler=l.factory({direction:e,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:f,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){Et.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(const e of this._producers.values())e.transportClosed();this._producers.clear();for(const e of this._consumers.values())e.transportClosed();this._consumers.clear();for(const e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(const 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 wt.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(Et.debug("restartIce()"),this._closed)throw new wt.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(Et.debug("updateIceServers()"),this._closed)throw new wt.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,encodings:t,codecOptions:r,codec:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,onRtpSender:a,appData:c={}}={}){if(Et.debug("produce() [track:%o]",e),this._closed)throw new wt.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new wt.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new wt.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new wt.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(c&&"object"!=typeof c)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push(async()=>{let d;if(t&&!Array.isArray(t))throw TypeError("encodings must be an array");t&&0===t.length?d=void 0:t&&(d=t.map(e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t}));const{localId:l,rtpParameters:u,rtpSender:p}=await this._handler.send({track:e,encodings:d,codecOptions:r,codec:n,onRtpSender:a});try{Ct.validateAndNormalizeRtpParameters(u);const{id:t}=await new Promise((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:u,appData:c},t,r)}),r=new kt.Producer({id:t,localId:l,rtpSender:p,track:e,rtpParameters:u,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,appData:c});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(l).catch(()=>{}),e}},"transport.produce()").catch(t=>{if(i)try{e.stop()}catch(e){}throw t})}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:s,appData:o={}}){if(Et.debug("consume()"),this._closed)throw new wt.InvalidStateError("closed");if("recv"!==this._direction)throw new wt.UnsupportedError("not a receiving Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing producerId");if("audio"!==r&&"video"!==r)throw new TypeError(`invalid kind '${r}'`);if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");const a=St.clone(n);if(!Ct.canReceive(a,this._recvRtpCapabilities))throw new wt.UnsupportedError("cannot consume this Producer");const c=new Ot({id:e,producerId:t,kind:r,rtpParameters:a,streamId:i,onRtpReceiver:s,appData:o});return this._pendingConsumerTasks.push(c),queueMicrotask(()=>{this._closed||!1===this._consumerCreationInProgress&&this.createPendingConsumers()}),c.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:n="",protocol:i="",appData:s={}}={}){if(Et.debug("produceData()"),this._closed)throw new wt.InvalidStateError("closed");if("send"!==this._direction)throw new wt.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new wt.UnsupportedError("SCTP not enabled by remote Transport");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("producedata"))throw new TypeError('no "producedata" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");return(t||r)&&(e=!1),this._awaitQueue.push(async()=>{const{dataChannel:o,sctpStreamParameters:a}=await this._handler.sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i});Ct.validateAndNormalizeSctpStreamParameters(a);const{id:c}=await new Promise((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:n,protocol:i,appData:s},e,t)}),d=new Pt.DataProducer({id:c,dataChannel:o,sctpStreamParameters:a,appData:s});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:n="",protocol:i="",appData:s={}}){if(Et.debug("consumeData()"),this._closed)throw new wt.InvalidStateError("closed");if("recv"!==this._direction)throw new wt.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new wt.UnsupportedError("SCTP not enabled by remote Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing dataProducerId");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");const o=St.clone(r);return Ct.validateAndNormalizeSctpStreamParameters(o),this._awaitQueue.push(async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:n,protocol:i}),a=new Rt.DataConsumer({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:o,appData:s});return this._dataConsumers.set(a.id,a),this.handleDataConsumer(a),this._observer.safeEmit("newdataconsumer",a),a},"transport.consumeData()")}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingConsumerTasks.length)return void Et.debug("createPendingConsumers() | there is no Consumer to be created");const e=[...this._pendingConsumerTasks];let t;this._pendingConsumerTasks=[];const r=[];for(const t of e){const{id:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o})}try{const n=await this._handler.receive(r);for(let r=0;r<n.length;++r){const i=e[r],s=n[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:l}=i.consumerOptions,{localId:u,rtpReceiver:p,track:h}=s,f=new Tt.Consumer({id:o,localId:u,producerId:a,rtpReceiver:p,track:h,rtpParameters:d,appData:l});this._consumers.set(f.id,f),this.handleConsumer(f),this._probatorConsumerCreated||t||"video"!==c||(t=f),this._observer.safeEmit("newconsumer",f),i.resolve(f)}}catch(t){for(const r of e)r.reject(t)}if(t)try{const e=Ct.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),Et.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){Et.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",e)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingPauseConsumers.size)return void Et.debug("pausePendingConsumers() | there is no Consumer to be paused");const e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{const t=e.map(e=>e.localId);await this._handler.pauseReceiving(t)}catch(e){Et.error("pausePendingConsumers() | failed to pause Consumers:",e)}},"transport.pausePendingConsumers").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingResumeConsumers.size)return void Et.debug("resumePendingConsumers() | there is no Consumer to be resumed");const e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{const t=e.map(e=>e.localId);await this._handler.resumeReceiving(t)}catch(e){Et.error("resumePendingConsumers() | failed to resume Consumers:",e)}},"transport.resumePendingConsumers").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingCloseConsumers.size)return void Et.debug("closePendingConsumers() | there is no Consumer to be closed");const e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(e=>e.localId))}catch(e){Et.error("closePendingConsumers() | failed to close Consumers:",e)}},"transport.closePendingConsumers").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){const e=this._handler;e.on("@connect",({dtlsParameters:e},t,r)=>{this._closed?r(new wt.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)}),e.on("@icegatheringstatechange",e=>{e!==this._iceGatheringState&&(Et.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))}),e.on("@icecandidateerror",e=>{Et.warn(`ICE candidate error [url:${e.url}, localAddress:${e.address}, localPort:${e.port}]: ${e.errorCode} "${e.errorText}"`),this.safeEmit("icecandidateerror",e)}),e.on("@connectionstatechange",e=>{e!==this._connectionState&&(Et.debug("connection state changed to %s",e),this._connectionState=e,this._closed||this.safeEmit("connectionstatechange",e))})}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(e=>Et.warn("producer.close() failed:%o",e))}),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,n)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(r).catch(n)}),e.on("@setmaxspatiallayer",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(r).catch(n)}),e.on("@setrtpencodingparameters",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(r).catch(n)}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new wt.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),!1===this._consumerCloseInProgress&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||!1===this._consumerPauseInProgress&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()})}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new wt.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)})}};$e.Transport=xt;var It={},Dt={},Mt={},jt={exports:{}},At=jt.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"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(e){return null!=e.subtype?"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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"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"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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(e){return null!=e.maxMessageSize?"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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{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(At).forEach(function(e){At[e].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})});var Lt=jt.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=Lt,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach(function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(i))return r(c,o,i)}}),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}})})}}(Mt);var Nt=Lt,Ft=/%[sdv%]/g,Bt=function(e){var t=1,r=arguments,n=r.length;return e.replace(Ft,function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},zt=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return Bt.apply(null,n)},Ut=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Vt=["i","c","b","a"],$t=Mt,Gt=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var r=t.outerOrder||Ut,n=t.innerOrder||Vt,i=[];return r.forEach(function(t){Nt[t].forEach(function(r){r.name in e&&null!=e[r.name]?i.push(zt(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){i.push(zt(t,r,e))})})}),e.media.forEach(function(e){i.push(zt("m",Nt.m[0],e)),n.forEach(function(t){Nt[t].forEach(function(r){r.name in e&&null!=e[r.name]?i.push(zt(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){i.push(zt(t,r,e))})})})}),i.join("\r\n")+"\r\n"},qt=Lt;Dt.grammar=qt;var Ht=Dt.write=Gt,Wt=Dt.parse=$t.parse;Dt.parseParams=$t.parseParams,Dt.parseFmtpConfig=$t.parseFmtpConfig,Dt.parsePayloads=$t.parsePayloads,Dt.parseRemoteCandidates=$t.parseRemoteCandidates,Dt.parseImageAttributes=$t.parseImageAttributes,Dt.parseSimulcastStreamList=$t.parseSimulcastStreamList;var Jt={};Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.parse=function(e){const t=Kt.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const Kt=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var Qt={};Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=new Map;for(const n of e.media){const e=n.type;switch(e){case"audio":case"video":break;default:continue}for(const r of n.rtp){const n={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(n.preferredPayloadType,n)}for(const e of n.fmtp??[]){const r=Yt.parseParams(e.config),n=t.get(e.payload);n&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),n.parameters=r)}for(const r of n.rtcpFb??[]){const n={type:r.type,parameter:r.subtype};if(n.parameter||delete n.parameter,"*"!==r.payload){const e=t.get(Number(r.payload));if(!e)continue;e.rtcpFeedback.push(n)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(n)}for(const t of n.ext??[]){if(t["encrypt-uri"])continue;const n={kind:e,uri:t.uri,preferredId:t.value};r.set(n.preferredId,n)}}return{codecs:Array.from(t.values()),headerExtensions:Array.from(r.values())}},Qt.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,n=e.fingerprint;if(!r||!n){const t=(e.media??[]).find(e=>0!==e.port);t&&(r??=t.setup,n??=t.fingerprint)}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!n)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:n.type,value:n.hash}]}},Qt.getCname=function({offerMediaObject:e}){const t=(e.ssrcs??[]).find(e=>"cname"===e.attribute);if(!t)return"";return t.value},Qt.applyCodecParameters=function({offerRtpParameters:e,answerMediaObject:t}){for(const r of e.codecs){const e=r.mimeType.toLowerCase();if("audio/opus"!==e)continue;if(!(t.rtp??[]).find(e=>e.payload===r.payloadType))continue;t.fmtp=t.fmtp??[];let n=t.fmtp.find(e=>e.payload===r.payloadType);n||(n={payload:r.payloadType,config:""},t.fmtp.push(n));const i=Yt.parseParams(n.config);switch(e){case"audio/opus":{const e=r.parameters?.["sprop-stereo"];void 0!==e&&(i.stereo=Number(e)?1:0);break}}n.config="";for(const e of Object.keys(i))n.config&&(n.config+=";"),n.config+=`${e}=${i[e]}`}};const Yt=Dt;var Xt={};Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.getRtpEncodings=function({offerMediaObject:e}){const t=new Set;for(const r of e.ssrcs??[]){const e=r.id;e&&t.add(e)}if(0===t.size)throw new Error("no a=ssrc lines found");const r=new Map;for(const n of e.ssrcGroups??[]){if("FID"!==n.semantics)continue;const e=n.ssrcs.split(/\s+/),i=Number(e[0]),s=Number(e[1]);t.has(i)&&(t.delete(i),t.delete(s),r.set(i,s))}for(const e of t)r.set(e,void 0);const n=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},Xt.addLegacySimulcast=function({offerMediaObject:e,numStreams:t}){if(t<=1)throw new TypeError("numStreams must be greater than 1");const r=(e.ssrcs??[]).find(e=>"msid"===e.attribute);if(!r)throw new Error("a=ssrc line with msid information not found");const[n,i]=r.value.split(" "),s=Number(r.id);let o;(e.ssrcGroups??[]).some(e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===s&&(o=Number(t[1]),!0)});const a=(e.ssrcs??[]).find(e=>"cname"===e.attribute);if(!a)throw new Error("a=ssrc line with cname information not found");const c=a.value,d=[],l=[];for(let e=0;e<t;++e)d.push(s+e),o&&l.push(o+e);e.ssrcGroups=[],e.ssrcs=[],e.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(const t of d)e.ssrcs.push({id:t,attribute:"cname",value:c}),e.ssrcs.push({id:t,attribute:"msid",value:`${n} ${i}`});for(let t=0;t<l.length;++t){const r=d[t],s=l[t];e.ssrcs.push({id:s,attribute:"cname",value:c}),e.ssrcs.push({id:s,attribute:"msid",value:`${n} ${i}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var Zt={};Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.addNackSupportForOpus=function(e){for(const t of e.codecs??[])"audio/opus"!==t.mimeType.toLowerCase()&&"audio/multiopus"!==t.mimeType.toLowerCase()||t.rtcpFeedback?.some(e=>"nack"===e.type&&!e.parameter)||(t.rtcpFeedback||(t.rtcpFeedback=[]),t.rtcpFeedback.push({type:"nack"}))};var er={},tr={};Object.defineProperty(tr,"__esModule",{value:!0}),tr.OfferMediaSection=tr.AnswerMediaSection=tr.MediaSection=void 0;const rr=Dt,nr=oe;class ir{_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(const e of t){const t={foundation:e.foundation,component:1,ip:e.address??e.ip,port:e.port,priority:e.priority,transport:e.protocol,type:e.type};e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}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 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause(),delete this._mediaObject.ext,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}close(){this.disable(),this._mediaObject.port=0}}tr.MediaSection=ir;tr.AnswerMediaSection=class extends ir{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,offerMediaObject:s,offerRtpParameters:o,answerRtpParameters:a,codecOptions:c}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s.mid),this._mediaObject.type=s.type,this._mediaObject.protocol=s.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),s.type){case"audio":case"video":this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(const e of a.codecs){const t={payload:e.payloadType,codec:sr(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=nr.clone(e.parameters)??{};let n=nr.clone(e.rtcpFeedback)??[];if(c){const{opusStereo:t,opusFec:i,opusDtx:s,opusMaxPlaybackRate:a,opusMaxAverageBitrate:d,opusPtime:l,opusNack:u,videoGoogleStartBitrate:p,videoGoogleMaxBitrate:h,videoGoogleMinBitrate:f}=c,m=o.codecs.find(t=>t.payloadType===e.payloadType);switch(e.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":void 0!==t&&(m.parameters["sprop-stereo"]=t?1:0,r.stereo=t?1:0),void 0!==i&&(m.parameters.useinbandfec=i?1:0,r.useinbandfec=i?1:0),void 0!==s&&(m.parameters.usedtx=s?1:0,r.usedtx=s?1:0),void 0!==a&&(r.maxplaybackrate=a),void 0!==d&&(r.maxaveragebitrate=d),void 0!==l&&(m.parameters.ptime=l,r.ptime=l),u||(m.rtcpFeedback=m.rtcpFeedback.filter(e=>"nack"!==e.type||e.parameter),n=n.filter(e=>"nack"!==e.type||e.parameter));break;case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":void 0!==p&&(r["x-google-start-bitrate"]=p),void 0!==h&&(r["x-google-max-bitrate"]=h),void 0!==f&&(r["x-google-min-bitrate"]=f)}}const i={payload:e.payloadType,config:""};for(const e of Object.keys(r))i.config&&(i.config+=";"),i.config+=`${e}=${r[e]}`;i.config&&this._mediaObject.fmtp.push(i);for(const t of n)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=a.codecs.map(e=>e.payloadType).join(" "),this._mediaObject.ext=[];for(const e of a.headerExtensions){(s.ext??[]).some(t=>t.uri===e.uri)&&this._mediaObject.ext.push({uri:e.uri,value:e.id})}if("extmap-allow-mixed"===s.extmapAllowMixed&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),s.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:s.simulcast.list1},this._mediaObject.rids=[];for(const e of s.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}else if(s.simulcast_03){this._mediaObject.simulcast_03={value:s.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(const e of s.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break;case"application":"number"==typeof s.sctpPort?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):s.sctpmap&&(this._mediaObject.payloads=String(n.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize})}}setDtlsRole(e){switch(e){case"client":this._mediaObject.setup="active";break;case"server":this._mediaObject.setup="passive";break;case"auto":this._mediaObject.setup="actpass"}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;const t={};for(const r of e)r.rid&&(t[r.rid]=r);const r=this._mediaObject.simulcast.list1,n=rr.parseSimulcastStreamList(r);for(const e of n)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=n.map(e=>e.map(e=>`${e.paused?"~":""}${e.scid}`).join(",")).join(";")}};function sr(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}tr.OfferMediaSection=class extends ir{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,mid:s,kind:o,offerRtpParameters:a,streamId:c,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s),this._mediaObject.type=o,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},this._mediaObject.protocol=n?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",o){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=`${c??"-"} ${d}`;for(const e of a.codecs){const t={payload:e.payloadType,codec:sr(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r={payload:e.payloadType,config:""};for(const t of Object.keys(e.parameters??{}))r.config&&(r.config+=";"),r.config+=`${t}=${e.parameters[t]}`;r.config&&this._mediaObject.fmtp.push(r);for(const t of e.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=a.codecs.map(e=>e.payloadType).join(" "),this._mediaObject.ext=[];for(const e of a.headerExtensions)this._mediaObject.ext.push({uri:e.uri,value:e.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";const e=a.encodings[0],t=e.ssrc,r=e.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],t&&a.rtcp.cname&&this._mediaObject.ssrcs.push({id:t,attribute:"cname",value:a.rtcp.cname}),r&&(a.rtcp.cname&&this._mediaObject.ssrcs.push({id:r,attribute:"cname",value:a.rtcp.cname}),t&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${t} ${r}`}));break}case"application":this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}},Object.defineProperty(er,"__esModule",{value:!0}),er.RemoteSdp=void 0;const or=Dt,ar=tr,cr=["av1","h264"],dr=new M.Logger("RemoteSdp");er.RemoteSdp=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:"mediasoup-client"},name:"-",timing:{start:0,stop:0},media:[]},e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){dr.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(const t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){dr.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){dr.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){const 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:n,codecOptions:i}){const s=new ar.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}),o=s.getObject();o.rtp.find(e=>cr.includes(e.codec.toLowerCase()))||(o.ext=o.ext?.filter(e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"!==e.uri)),t?this._replaceMediaSection(s,t):this._midToIndex.has(s.mid)?this._replaceMediaSection(s):this._addMediaSection(s)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}){this.setSessionExtmapAllowMixed();const s=new ar.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}),o=this._mediaSections.find(e=>e.closed);o?this._replaceMediaSection(s,o.mid):this._addMediaSection(s)}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){const t=this._findMediaSection(e);return e===this._firstMid?(dr.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){const r=this._findMediaSection(e);r.muxSimulcastStreams(t),this._replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){const t=new ar.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this._addMediaSection(t)}receiveSctpAssociation(){const e=new ar.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++,or.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("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this._regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}_findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)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(" "))}},Object.defineProperty(It,"__esModule",{value:!0}),It.Chrome111=void 0;const lr=Dt,ur=N,pr=ae,hr=ne,fr=Jt,mr=Qt,gr=Xt,vr=Zt,br=er,yr=new M.Logger("Chrome111"),_r="Chrome111",wr={OS:1024,MIS:1024};class Sr extends ur.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:_r,factory:e=>new Sr(e),getNativeRtpCapabilities:async()=>{yr.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video",{sendEncodings:[{scalabilityMode:"L3T3"}]});const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=lr.parse(t.sdp);return Sr.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(yr.debug("getNativeSctpCapabilities()"),{numStreams:wr})}}static getLocalRtpCapabilities(e){const t=mr.extractRtpCapabilities({sdpObject:e});return pr.validateAndNormalizeRtpCapabilities(t),vr.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),yr.debug("constructor()"),this._direction=e,this._remoteSdp=new br.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(yr.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return _r}close(){if(yr.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}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(),yr.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),yr.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});yr.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();yr.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){if(this.assertNotClosed(),this.assertSendDirection(),yr.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1){let e=1;for(const r of t){const t=r.scalabilityMode?(0,fr.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`})}const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(o.sender);const a=await this._pc.createOffer();let c=lr.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=Sr.getLocalRtpCapabilities(c),l=this._getSendExtendedRtpCapabilities(d),u=pr.getSendingRtpParameters(e.kind,l);u.codecs=pr.reduceCodecs(u.codecs,n);const p=pr.getSendingRemoteRtpParameters(e.kind,l);p.codecs=pr.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c}),yr.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const h=o.mid;u.mid=h,c=lr.parse(this._pc.localDescription.sdp);const f=c.media[s.idx];if(u.rtcp.cname=mr.getCname({offerMediaObject:f}),t)if(1===t.length){const e=gr.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),u.encodings=e}else u.encodings=t;else u.encodings=gr.getRtpEncodings({offerMediaObject:f});this._remoteSdp.send({offerMediaObject:f,reuseMid:s.reuseMid,offerRtpParameters:u,answerRtpParameters:p,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return yr.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(h,o),{localId:h,rtpParameters:u,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),yr.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();yr.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),yr.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();yr.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),yr.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();yr.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?yr.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):yr.debug("replaceTrack() [localId:%s, no track]",e);const 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(),yr.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();yr.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),yr.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();yr.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};yr.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%wr.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=lr.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),yr.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;yr.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=lr.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find(e=>String(e.mid)===i);mr.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:lr.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),yr.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){yr.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();yr.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){yr.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();yr.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){yr.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();yr.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};yr.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=lr.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}yr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=lr.parse(this._pc.localDescription.sdp));const r=mr.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new hr.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}It.Chrome111=Sr;var Cr={};Object.defineProperty(Cr,"__esModule",{value:!0}),Cr.Chrome74=void 0;const kr=Dt,Tr=N,Pr=ae,Rr=ne,Er=Jt,Or=Qt,xr=Xt,Ir=Zt,Dr=er,Mr=new M.Logger("Chrome74"),jr="Chrome74",Ar={OS:1024,MIS:1024};class Lr extends Tr.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:jr,factory:e=>new Lr(e),getNativeRtpCapabilities:async()=>{Mr.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=kr.parse(t.sdp);return Lr.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(Mr.debug("getNativeSctpCapabilities()"),{numStreams:Ar})}}static getLocalRtpCapabilities(e){const t=Or.extractRtpCapabilities({sdpObject:e});return Pr.validateAndNormalizeRtpCapabilities(t),Ir.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Mr.debug("constructor()"),this._direction=e,this._remoteSdp=new Dr.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Mr.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return jr}close(){if(Mr.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}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(),Mr.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Mr.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Mr.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Mr.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n}){this.assertNotClosed(),this.assertSendDirection(),Mr.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const i=this._remoteSdp.getNextMediaSectionIdx(),s=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let o=await this._pc.createOffer(),a=kr.parse(o.sdp);a.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const c=Lr.getLocalRtpCapabilities(a),d=this._getSendExtendedRtpCapabilities(c),l=Pr.getSendingRtpParameters(e.kind,d);l.codecs=Pr.reduceCodecs(l.codecs,n);const u=Pr.getSendingRemoteRtpParameters(e.kind,d);u.codecs=Pr.reduceCodecs(u.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:a});let p=!1;const h=(0,Er.parse)((t??[{}])[0].scalabilityMode);let f;t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===l.codecs[0].mimeType.toLowerCase()&&(Mr.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,a=kr.parse(o.sdp),f=a.media[i.idx],xr.addLegacySimulcast({offerMediaObject:f,numStreams:h.spatialLayers}),o={type:"offer",sdp:kr.write(a)}),Mr.debug("send() | calling pc.setLocalDescription() [offer:%o]",o),await this._pc.setLocalDescription(o);const m=s.mid;if(l.mid=m,a=kr.parse(this._pc.localDescription.sdp),f=a.media[i.idx],l.rtcp.cname=Or.getCname({offerMediaObject:f}),t)if(1===t.length){let e=xr.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),p&&(e=[e[0]]),l.encodings=e}else l.encodings=t;else l.encodings=xr.getRtpEncodings({offerMediaObject:f});if(l.encodings.length>1&&("video/vp8"===l.codecs[0].mimeType.toLowerCase()||"video/h264"===l.codecs[0].mimeType.toLowerCase()))for(const e of l.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,reuseMid:i.reuseMid,offerRtpParameters:l,answerRtpParameters:u,codecOptions:r});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return Mr.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(m,s),{localId:m,rtpParameters:l,rtpSender:s.sender}}async stopSending(e){if(this.assertSendDirection(),Mr.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Mr.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Mr.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Mr.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Mr.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Mr.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Mr.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Mr.debug("replaceTrack() [localId:%s, no track]",e);const 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(),Mr.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Mr.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Mr.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Mr.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Mr.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ar.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=kr.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Mr.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;Mr.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=kr.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find(e=>String(e.mid)===i);Or.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:kr.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Mr.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Mr.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mr.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Mr.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mr.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Mr.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mr.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Mr.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=kr.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Mr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=kr.parse(this._pc.localDescription.sdp));const r=Or.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new Rr.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Cr.Chrome74=Lr;var Nr={};Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.Firefox120=void 0;const Fr=Dt,Br=N,zr=ne,Ur=ae,Vr=Jt,$r=Qt,Gr=Xt,qr=er,Hr=new M.Logger("Firefox120"),Wr="Firefox120",Jr={OS:16,MIS:2048};class Kr extends Br.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Wr,factory:e=>new Kr(e),getNativeRtpCapabilities:async()=>{Hr.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});const t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"}),e.addTransceiver(r,{direction:"sendrecv",sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const n=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}e=void 0;const i=Fr.parse(n.sdp);return Kr.getLocalRtpCapabilities(i)}catch(n){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e?.close()}catch(e){}throw e=void 0,n}},getNativeSctpCapabilities:async()=>(Hr.debug("getNativeSctpCapabilities()"),{numStreams:Jr})}}static getLocalRtpCapabilities(e){const t=$r.extractRtpCapabilities({sdpObject:e});return Ur.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Hr.debug("constructor()"),this._direction=e,this._remoteSdp=new qr.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Hr.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Wr}close(){if(Hr.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}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 zr.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Hr.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Hr.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Hr.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),Hr.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const s=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(s.sender);const o=await this._pc.createOffer();let a=Fr.parse(o.sdp);a.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const c=Kr.getLocalRtpCapabilities(a),d=this._getSendExtendedRtpCapabilities(c),l=Ur.getSendingRtpParameters(e.kind,d);l.codecs=Ur.reduceCodecs(l.codecs,n);const u=Ur.getSendingRemoteRtpParameters(e.kind,d);u.codecs=Ur.reduceCodecs(u.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:a});const p=(0,Vr.parse)((t??[{}])[0].scalabilityMode);Hr.debug("send() | calling pc.setLocalDescription() [offer:%o]",o),await this._pc.setLocalDescription(o);const h=s.mid;l.mid=h,a=Fr.parse(this._pc.localDescription.sdp);const f=a.media[a.media.length-1];if(l.rtcp.cname=$r.getCname({offerMediaObject:f}),t)if(1===t.length){const e=Gr.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),l.encodings=e}else l.encodings=t;else l.encodings=Gr.getRtpEncodings({offerMediaObject:f});if(l.encodings.length>1&&("video/vp8"===l.codecs[0].mimeType.toLowerCase()||"video/h264"===l.codecs[0].mimeType.toLowerCase()))for(const e of l.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,offerRtpParameters:l,answerRtpParameters:u,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Hr.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(h,s),{localId:h,rtpParameters:l,rtpSender:s.sender}}async stopSending(e){if(this.assertSendDirection(),Hr.debug("stopSending() [localId:%s]",e),this._closed)return;const 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);const r=await this._pc.createOffer();Hr.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Hr.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Hr.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Hr.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Hr.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Hr.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Hr.debug("replaceTrack() [localId:%s, no track]",e);const 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(),Hr.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Hr.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Hr.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Hr.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Hr.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Jr.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Fr.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Hr.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;Hr.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Fr.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,o=r.get(e),a=s.media.find(e=>String(e.mid)===o);$r.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:Fr.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Hr.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Hr.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hr.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hr.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hr.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hr.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hr.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Hr.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Fr.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Hr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Fr.parse(this._pc.localDescription.sdp));const r=$r.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new zr.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Nr.Firefox120=Kr;var Qr={};Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.Safari12=void 0;const Yr=Dt,Xr=N,Zr=ae,en=ne,tn=Jt,rn=er,nn=Qt,sn=Xt,on=Zt,an=new M.Logger("Safari12"),cn="Safari12",dn={OS:1024,MIS:1024};class ln extends Xr.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:cn,factory:e=>new ln(e),getNativeRtpCapabilities:async()=>{an.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=Yr.parse(t.sdp);return ln.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(an.debug("getNativeSctpCapabilities()"),{numStreams:dn})}}static getLocalRtpCapabilities(e){const t=nn.extractRtpCapabilities({sdpObject:e});return Zr.validateAndNormalizeRtpCapabilities(t),on.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),an.debug("constructor()"),this._direction=e,this._remoteSdp=new rn.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",e=>{this.emit("@icecandidateerror",e)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(an.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return cn}close(){if(an.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}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(),an.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),an.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});an.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();an.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),an.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});i&&i(o.sender);let a=await this._pc.createOffer(),c=Yr.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=ln.getLocalRtpCapabilities(c),l=this._getSendExtendedRtpCapabilities(d),u=Zr.getSendingRtpParameters(e.kind,l);u.codecs=Zr.reduceCodecs(u.codecs,n);const p=Zr.getSendingRemoteRtpParameters(e.kind,l);let h;p.codecs=Zr.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c});const f=(0,tn.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(an.debug("send() | enabling legacy simulcast"),c=Yr.parse(a.sdp),h=c.media[s.idx],sn.addLegacySimulcast({offerMediaObject:h,numStreams:t.length}),a={type:"offer",sdp:Yr.write(c)}),an.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const m=o.mid;if(u.mid=m,c=Yr.parse(this._pc.localDescription.sdp),h=c.media[s.idx],u.rtcp.cname=nn.getCname({offerMediaObject:h}),u.encodings=sn.getRtpEncodings({offerMediaObject:h}),t)for(let e=0;e<u.encodings.length;++e)t[e]&&Object.assign(u.encodings[e],t[e]);if(u.encodings.length>1&&("video/vp8"===u.codecs[0].mimeType.toLowerCase()||"video/h264"===u.codecs[0].mimeType.toLowerCase()))for(const e of u.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${f.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:h,reuseMid:s.reuseMid,offerRtpParameters:u,answerRtpParameters:p,codecOptions:r});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return an.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(m,o),{localId:m,rtpParameters:u,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;an.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();an.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),an.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();an.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),an.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();an.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?an.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):an.debug("replaceTrack() [localId:%s, no track]",e);const 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(),an.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();an.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),an.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();an.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};an.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%dn.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Yr.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),an.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;an.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Yr.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find(e=>String(e.mid)===i);nn.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Yr.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),an.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){an.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();an.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){an.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();an.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){an.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();an.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};an.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Yr.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}an.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Yr.parse(this._pc.localDescription.sdp));const r=nn.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new en.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Qr.Safari12=ln;var un={};Object.defineProperty(un,"__esModule",{value:!0}),un.ReactNative106=void 0;const pn=Dt,hn=N,fn=ae,mn=ne,gn=Jt,vn=er,bn=Qt,yn=Xt,_n=Zt,wn=new M.Logger("ReactNative106"),Sn="ReactNative106",Cn={OS:1024,MIS:1024};class kn extends hn.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Sn,factory:e=>new kn(e),getNativeRtpCapabilities:async()=>{wn.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=pn.parse(t.sdp);return kn.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(wn.debug("getNativeSctpCapabilities()"),{numStreams:Cn})}}static getLocalRtpCapabilities(e){const t=bn.extractRtpCapabilities({sdpObject:e});return fn.validateAndNormalizeRtpCapabilities(t),_n.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),wn.debug("constructor()"),this._direction=e,this._remoteSdp=new vn.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(wn.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Sn}close(){if(wn.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch(e){}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(),wn.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),wn.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});wn.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();wn.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),wn.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(o.sender);let a=await this._pc.createOffer(),c=pn.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=kn.getLocalRtpCapabilities(c),l=this._getSendExtendedRtpCapabilities(d),u=fn.getSendingRtpParameters(e.kind,l);u.codecs=fn.reduceCodecs(u.codecs,n);const p=fn.getSendingRemoteRtpParameters(e.kind,l);p.codecs=fn.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c});let h=!1;const f=(0,gn.parse)((t??[{}])[0].scalabilityMode);let m;t&&1===t.length&&f.spatialLayers>1&&"video/vp9"===u.codecs[0].mimeType.toLowerCase()&&(wn.debug("send() | enabling legacy simulcast for VP9 SVC"),h=!0,c=pn.parse(a.sdp),m=c.media[s.idx],yn.addLegacySimulcast({offerMediaObject:m,numStreams:f.spatialLayers}),a={type:"offer",sdp:pn.write(c)}),wn.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);let g=o.mid??void 0;if(g||wn.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),u.mid=g,c=pn.parse(this._pc.localDescription.sdp),m=c.media[s.idx],u.rtcp.cname=bn.getCname({offerMediaObject:m}),t)if(1===t.length){let e=yn.getRtpEncodings({offerMediaObject:m});Object.assign(e[0],t[0]),h&&(e=[e[0]]),u.encodings=e}else u.encodings=t;else u.encodings=yn.getRtpEncodings({offerMediaObject:m});if(u.encodings.length>1&&("video/vp8"===u.codecs[0].mimeType.toLowerCase()||"video/h264"===u.codecs[0].mimeType.toLowerCase()))for(const e of u.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${f.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,reuseMid:s.reuseMid,offerRtpParameters:u,answerRtpParameters:p,codecOptions:r});const v={type:"answer",sdp:this._remoteSdp.getSdp()};return wn.debug("send() | calling pc.setRemoteDescription() [answer:%o]",v),await this._pc.setRemoteDescription(v),g||(g=o.mid,u.mid=g),this._mapMidTransceiver.set(g,o),{localId:g,rtpParameters:u,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;wn.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();wn.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),wn.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();wn.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),wn.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();wn.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?wn.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):wn.debug("replaceTrack() [localId:%s, no track]",e);const 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(),wn.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();wn.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),wn.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();wn.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};wn.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Cn.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=pn.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),wn.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;wn.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=pn.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find(e=>String(e.mid)===i);bn.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:pn.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),wn.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){wn.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wn.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){wn.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wn.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){wn.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wn.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};wn.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=pn.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}wn.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=pn.parse(this._pc.localDescription.sdp));const r=bn.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new mn.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}un.ReactNative106=kn,Object.defineProperty(y,"__esModule",{value:!0}),y.Device=void 0,y.detectDevice=Nn,y.detectDeviceAsync=Fn;const Tn=P,Pn=N,Rn=ne,En=oe,On=ae,xn=$e,In=It,Dn=Cr,Mn=Nr,jn=Qr,An=un,Ln=new M.Logger("Device");function Nn(e){Ln.debug("detectDevice() [userAgent:%s]",e),e||"object"!=typeof navigator||(e=navigator.userAgent);return zn(new Tn.default(e))}async function Fn(e){Ln.debug("detectDeviceAsync() [userAgent:%s]",e),e||"object"!=typeof navigator||(e=navigator.userAgent);return zn(new Tn.default(e))}class Bn{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new Pn.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(Ln.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&!(e=await Fn()))throw new Rn.UnsupportedError("device not supported");return new Bn({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(Ln.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)Ln.debug("constructor() | handler given: %s",e);else{if(!(e=Nn()))throw new Rn.UnsupportedError("device not supported");Ln.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=In.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=Dn.Chrome74.createFactory();break;case"Firefox120":this._handlerFactory=Mn.Firefox120.createFactory();break;case"Safari12":this._handlerFactory=jn.Safari12.createFactory();break;case"ReactNative106":this._handlerFactory=An.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(){if(!this._loaded)throw new Rn.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Rn.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(Ln.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new Rn.InvalidStateError("already loaded");const r=En.clone(e);On.validateAndNormalizeRtpCapabilities(r);const{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,s=En.clone(await n());On.validateAndNormalizeRtpCapabilities(s),Ln.debug("load() | got native RTP capabilities:%o",s),this._getSendExtendedRtpCapabilities=e=>En.clone(On.getExtendedRtpCapabilities(e,r,t));const o=On.getExtendedRtpCapabilities(s,r,!1);this._recvRtpCapabilities=On.getRecvRtpCapabilities(o),On.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities),Ln.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._canProduceByKind.audio=On.canSend("audio",this._recvRtpCapabilities),this._canProduceByKind.video=On.canSend("video",this._recvRtpCapabilities),this._sctpCapabilities=await i(),On.validateSctpCapabilities(this._sctpCapabilities),Ln.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),Ln.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(!this._loaded)throw new Rn.InvalidStateError("not loaded");if("audio"!==e&&"video"!==e)throw new TypeError(`invalid kind "${e}"`);return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c}){return Ln.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c}){return Ln.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){if(!this._loaded)throw new Rn.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(n))throw new TypeError("missing iceCandidates");if("object"!=typeof i)throw new TypeError("missing dtlsParameters");if(s&&"object"!=typeof s)throw new TypeError("wrong sctpParameters");if(d&&"object"!=typeof d)throw new TypeError("if given, appData must be an object");const l=new xn.Transport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",l),l}}function zn(e){if("object"==typeof navigator&&"ReactNative"===navigator.product)return Ln.debug("detectDeviceImpl() | React-Native detected"),"undefined"==typeof RTCPeerConnection||"undefined"==typeof RTCRtpTransceiver?void Ln.warn("detectDeviceImpl() | unsupported react-native-webrtc without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?"):"ReactNative106";{const t=e.parseUserAgent(),r=/^\d+/.exec(t?.shortVersion??"0"),n=parseInt(r?.[0]??"0",10),i=t.platform===Tn.KnownPlatforms.iphone||t.platform===Tn.KnownPlatforms.ipad||t.platform===Tn.KnownPlatforms.mac&&(t.isMobile||t.isTablet||"object"==typeof navigator&&navigator?.maxTouchPoints>=2),s=t.isChrome,o=t.isFireFox,a=t.isSafari,c=t.isEdge,d=t.isDesktop&&t.name===Tn.KnownBrowsers.electron,l={browserMajorVersion:n,isIOS:i,isChrome:s,isFirefox:o,isSafari:a,isElectron:d};if(Ln.debug("detectDeviceImpl() | detected browser [userAgent:%s, parsed:%o, result:%o]",t.userAgent,t,l),(s||c)&&!i&&n>=111)return"Chrome111";if(s&&!i&&n>=74||c&&!i&&n>=88)return"Chrome74";if(d)return"Chrome111";if(o&&!i&&n>=120)return"Firefox120";if(a&&n>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(i&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";{const r=e.userAgent?.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(r){return Number(r[1])>=111?"Chrome111":"Chrome74"}return void Ln.warn("detectDeviceImpl() | browser not supported [userAgent:%s, parsed:%o, result:%o]",t.userAgent,t,l)}}}y.Device=Bn;var Un={},Vn={},$n={},Gn={};Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.default="ffffffff-ffff-ffff-ffff-ffffffffffff";var qn={};Object.defineProperty(qn,"__esModule",{value:!0}),qn.default="00000000-0000-0000-0000-000000000000";var Hn={},Wn={},Jn={};Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,Object.defineProperty(Wn,"__esModule",{value:!0});const Kn=Jn;Wn.default=function(e){return"string"==typeof e&&Kn.default.test(e)},Object.defineProperty(Hn,"__esModule",{value:!0});const Qn=Wn;Hn.default=function(e){if(!(0,Qn.default)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)};var Yn={};Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.unsafeStringify=void 0;const Xn=Wn,Zn=[];for(let BE=0;BE<256;++BE)Zn.push((BE+256).toString(16).slice(1));function ei(e,t=0){return(Zn[e[t+0]]+Zn[e[t+1]]+Zn[e[t+2]]+Zn[e[t+3]]+"-"+Zn[e[t+4]]+Zn[e[t+5]]+"-"+Zn[e[t+6]]+Zn[e[t+7]]+"-"+Zn[e[t+8]]+Zn[e[t+9]]+"-"+Zn[e[t+10]]+Zn[e[t+11]]+Zn[e[t+12]]+Zn[e[t+13]]+Zn[e[t+14]]+Zn[e[t+15]]).toLowerCase()}Yn.unsafeStringify=ei,Yn.default=function(e,t=0){const r=ei(e,t);if(!(0,Xn.default)(r))throw TypeError("Stringified UUID is invalid");return r};var ti={},ri={};let ni;Object.defineProperty(ri,"__esModule",{value:!0});const ii=new Uint8Array(16);ri.default=function(){if(!ni){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ni=crypto.getRandomValues.bind(crypto)}return ni(ii)},Object.defineProperty(ti,"__esModule",{value:!0}),ti.updateV1State=void 0;const si=ri,oi=Yn,ai={};function ci(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=16383&(r[8]<<8|r[9])),e.msecs=t,e}function di(e,t,r,n,i,s,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(s){if(o<0||o+16>s.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`)}else s=new Uint8Array(16),o=0;t??=Date.now(),r??=0,n??=16383&(e[8]<<8|e[9]),i??=e.slice(10,16);const a=(1e4*(268435455&(t+=122192928e5))+r)%4294967296;s[o++]=a>>>24&255,s[o++]=a>>>16&255,s[o++]=a>>>8&255,s[o++]=255&a;const c=t/4294967296*1e4&268435455;s[o++]=c>>>8&255,s[o++]=255&c,s[o++]=c>>>24&15|16,s[o++]=c>>>16&255,s[o++]=n>>>8|128,s[o++]=255&n;for(let e=0;e<6;++e)s[o++]=i[e];return s}ti.updateV1State=ci,ti.default=function(e,t,r){let n;const i=e?._v6??!1;if(e){const t=Object.keys(e);1===t.length&&"_v6"===t[0]&&(e=void 0)}if(e)n=di(e.random??e.rng?.()??(0,si.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{const e=Date.now(),s=(0,si.default)();ci(ai,e,s),n=di(s,ai.msecs,ai.nsecs,i?void 0:ai.clockseq,i?void 0:ai.node,t,r)}return t??(0,oi.unsafeStringify)(n)};var li={};Object.defineProperty(li,"__esModule",{value:!0});const ui=Hn,pi=Yn;li.default=function(e){const t=function(e){return Uint8Array.of((15&e[6])<<4|e[7]>>4&15,(15&e[7])<<4|(240&e[4])>>4,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,(15&e[1])<<4|(240&e[2])>>4,96|15&e[2],e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,ui.default)(e):e);return"string"==typeof e?(0,pi.unsafeStringify)(t):t};var hi={},fi={};function mi(e){return 14+(e+64>>>9<<4)+1}function gi(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function vi(e,t,r,n,i,s){return gi((o=gi(gi(t,e),gi(n,s)))<<(a=i)|o>>>32-a,r);var o,a}function bi(e,t,r,n,i,s,o){return vi(t&r|~t&n,e,t,i,s,o)}function yi(e,t,r,n,i,s,o){return vi(t&n|r&~n,e,t,i,s,o)}function _i(e,t,r,n,i,s,o){return vi(t^r^n,e,t,i,s,o)}function wi(e,t,r,n,i,s,o){return vi(r^(t|~n),e,t,i,s,o)}Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=function(e){const t=function(e){if(0===e.length)return new Uint32Array;const t=new Uint32Array(mi(8*e.length)).fill(0);for(let r=0;r<e.length;r++)t[r>>2]|=(255&e[r])<<r%4*8;return t}(e),r=function(e,t){const r=new Uint32Array(mi(t)).fill(0);r.set(e),r[t>>5]|=128<<t%32,r[r.length-1]=t,e=r;let n=1732584193,i=-271733879,s=-1732584194,o=271733878;for(let t=0;t<e.length;t+=16){const r=n,a=i,c=s,d=o;n=bi(n,i,s,o,e[t],7,-680876936),o=bi(o,n,i,s,e[t+1],12,-389564586),s=bi(s,o,n,i,e[t+2],17,606105819),i=bi(i,s,o,n,e[t+3],22,-1044525330),n=bi(n,i,s,o,e[t+4],7,-176418897),o=bi(o,n,i,s,e[t+5],12,1200080426),s=bi(s,o,n,i,e[t+6],17,-1473231341),i=bi(i,s,o,n,e[t+7],22,-45705983),n=bi(n,i,s,o,e[t+8],7,1770035416),o=bi(o,n,i,s,e[t+9],12,-1958414417),s=bi(s,o,n,i,e[t+10],17,-42063),i=bi(i,s,o,n,e[t+11],22,-1990404162),n=bi(n,i,s,o,e[t+12],7,1804603682),o=bi(o,n,i,s,e[t+13],12,-40341101),s=bi(s,o,n,i,e[t+14],17,-1502002290),i=bi(i,s,o,n,e[t+15],22,1236535329),n=yi(n,i,s,o,e[t+1],5,-165796510),o=yi(o,n,i,s,e[t+6],9,-1069501632),s=yi(s,o,n,i,e[t+11],14,643717713),i=yi(i,s,o,n,e[t],20,-373897302),n=yi(n,i,s,o,e[t+5],5,-701558691),o=yi(o,n,i,s,e[t+10],9,38016083),s=yi(s,o,n,i,e[t+15],14,-660478335),i=yi(i,s,o,n,e[t+4],20,-405537848),n=yi(n,i,s,o,e[t+9],5,568446438),o=yi(o,n,i,s,e[t+14],9,-1019803690),s=yi(s,o,n,i,e[t+3],14,-187363961),i=yi(i,s,o,n,e[t+8],20,1163531501),n=yi(n,i,s,o,e[t+13],5,-1444681467),o=yi(o,n,i,s,e[t+2],9,-51403784),s=yi(s,o,n,i,e[t+7],14,1735328473),i=yi(i,s,o,n,e[t+12],20,-1926607734),n=_i(n,i,s,o,e[t+5],4,-378558),o=_i(o,n,i,s,e[t+8],11,-2022574463),s=_i(s,o,n,i,e[t+11],16,1839030562),i=_i(i,s,o,n,e[t+14],23,-35309556),n=_i(n,i,s,o,e[t+1],4,-1530992060),o=_i(o,n,i,s,e[t+4],11,1272893353),s=_i(s,o,n,i,e[t+7],16,-155497632),i=_i(i,s,o,n,e[t+10],23,-1094730640),n=_i(n,i,s,o,e[t+13],4,681279174),o=_i(o,n,i,s,e[t],11,-358537222),s=_i(s,o,n,i,e[t+3],16,-722521979),i=_i(i,s,o,n,e[t+6],23,76029189),n=_i(n,i,s,o,e[t+9],4,-640364487),o=_i(o,n,i,s,e[t+12],11,-421815835),s=_i(s,o,n,i,e[t+15],16,530742520),i=_i(i,s,o,n,e[t+2],23,-995338651),n=wi(n,i,s,o,e[t],6,-198630844),o=wi(o,n,i,s,e[t+7],10,1126891415),s=wi(s,o,n,i,e[t+14],15,-1416354905),i=wi(i,s,o,n,e[t+5],21,-57434055),n=wi(n,i,s,o,e[t+12],6,1700485571),o=wi(o,n,i,s,e[t+3],10,-1894986606),s=wi(s,o,n,i,e[t+10],15,-1051523),i=wi(i,s,o,n,e[t+1],21,-2054922799),n=wi(n,i,s,o,e[t+8],6,1873313359),o=wi(o,n,i,s,e[t+15],10,-30611744),s=wi(s,o,n,i,e[t+6],15,-1560198380),i=wi(i,s,o,n,e[t+13],21,1309151649),n=wi(n,i,s,o,e[t+4],6,-145523070),o=wi(o,n,i,s,e[t+11],10,-1120210379),s=wi(s,o,n,i,e[t+2],15,718787259),i=wi(i,s,o,n,e[t+9],21,-343485551),n=gi(n,r),i=gi(i,a),s=gi(s,c),o=gi(o,d)}return Uint32Array.of(n,i,s,o)}(t,8*e.length);return function(e){const t=new Uint8Array(4*e.length);for(let r=0;r<4*e.length;r++)t[r]=e[r>>2]>>>r%4*8&255;return t}(r)};var Si={};Object.defineProperty(Si,"__esModule",{value:!0}),Si.URL=Si.DNS=Si.stringToBytes=void 0;const Ci=Hn,ki=Yn;function Ti(e){e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}Si.stringToBytes=Ti,Si.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Si.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",Si.default=function(e,t,r,n,i,s){const o="string"==typeof r?Ti(r):r,a="string"==typeof n?(0,Ci.default)(n):n;if("string"==typeof n&&(n=(0,Ci.default)(n)),16!==n?.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(a),c.set(o,a.length),c=t(c),c[6]=15&c[6]|e,c[8]=63&c[8]|128,i){s=s||0;for(let e=0;e<16;++e)i[s+e]=c[e];return i}return(0,ki.unsafeStringify)(c)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=fi,r=Si;var n=Si;function i(e,n,i,s){return(0,r.default)(48,t.default,e,n,i,s)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=r.DNS,i.URL=r.URL,e.default=i}(hi);var Pi={},Ri={};Object.defineProperty(Ri,"__esModule",{value:!0});const Ei="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);Ri.default={randomUUID:Ei},Object.defineProperty(Pi,"__esModule",{value:!0});const Oi=Ri,xi=ri,Ii=Yn;Pi.default=function(e,t,r){if(Oi.default.randomUUID&&!t&&!e)return Oi.default.randomUUID();const n=(e=e||{}).random??e.rng?.()??(0,xi.default)();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=n[e];return t}return(0,Ii.unsafeStringify)(n)};var Di={},Mi={};function ji(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function Ai(e,t){return e<<t|e>>>32-t}Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128;const i=(e=n).length/4+2,s=Math.ceil(i/16),o=new Array(s);for(let t=0;t<s;++t){const r=new Uint32Array(16);for(let n=0;n<16;++n)r[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];o[t]=r}o[s-1][14]=8*(e.length-1)/Math.pow(2,32),o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<s;++e){const n=new Uint32Array(80);for(let t=0;t<16;++t)n[t]=o[e][t];for(let e=16;e<80;++e)n[e]=Ai(n[e-3]^n[e-8]^n[e-14]^n[e-16],1);let i=r[0],s=r[1],a=r[2],c=r[3],d=r[4];for(let e=0;e<80;++e){const r=Math.floor(e/20),o=Ai(i,5)+ji(r,s,a,c)+d+t[r]+n[e]>>>0;d=c,c=a,a=Ai(s,30)>>>0,s=i,i=o}r[0]=r[0]+i>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+a>>>0,r[3]=r[3]+c>>>0,r[4]=r[4]+d>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=Mi,r=Si;var n=Si;function i(e,n,i,s){return(0,r.default)(80,t.default,e,n,i,s)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=r.DNS,i.URL=r.URL,e.default=i}(Di);var Li={};Object.defineProperty(Li,"__esModule",{value:!0});const Ni=Yn,Fi=ti,Bi=li;Li.default=function(e,t,r){e??={},r??=0;let n=(0,Fi.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,Bi.default)(n),t){for(let e=0;e<16;e++)t[r+e]=n[e];return t}return(0,Ni.unsafeStringify)(n)};var zi={};Object.defineProperty(zi,"__esModule",{value:!0});const Ui=Hn,Vi=Yn;zi.default=function(e){const t=function(e){return Uint8Array.of((15&e[3])<<4|e[4]>>4&15,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|15&e[6],e[7],(15&e[1])<<4|(240&e[2])>>4,(15&e[2])<<4|(240&e[3])>>4,16|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,Ui.default)(e):e);return"string"==typeof e?(0,Vi.unsafeStringify)(t):t};var $i={};Object.defineProperty($i,"__esModule",{value:!0}),$i.updateV7State=void 0;const Gi=ri,qi=Yn,Hi={};function Wi(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++),e}function Ji(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(n){if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else n=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=255&t,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|3&e[10],n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}$i.updateV7State=Wi,$i.default=function(e,t,r){let n;if(e)n=Ji(e.random??e.rng?.()??(0,Gi.default)(),e.msecs,e.seq,t,r);else{const e=Date.now(),i=(0,Gi.default)();Wi(Hi,e,i),n=Ji(i,Hi.msecs,Hi.seq,t,r)}return t??(0,qi.unsafeStringify)(n)};var Ki={};Object.defineProperty(Ki,"__esModule",{value:!0});const Qi=Wn;Ki.default=function(e){if(!(0,Qi.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.version=e.validate=e.v7=e.v6ToV1=e.v6=e.v5=e.v4=e.v3=e.v1ToV6=e.v1=e.stringify=e.parse=e.NIL=e.MAX=void 0;var t=Gn;Object.defineProperty(e,"MAX",{enumerable:!0,get:function(){return t.default}});var r=qn;Object.defineProperty(e,"NIL",{enumerable:!0,get:function(){return r.default}});var n=Hn;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return n.default}});var i=Yn;Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.default}});var s=ti;Object.defineProperty(e,"v1",{enumerable:!0,get:function(){return s.default}});var o=li;Object.defineProperty(e,"v1ToV6",{enumerable:!0,get:function(){return o.default}});var a=hi;Object.defineProperty(e,"v3",{enumerable:!0,get:function(){return a.default}});var c=Pi;Object.defineProperty(e,"v4",{enumerable:!0,get:function(){return c.default}});var d=Di;Object.defineProperty(e,"v5",{enumerable:!0,get:function(){return d.default}});var l=Li;Object.defineProperty(e,"v6",{enumerable:!0,get:function(){return l.default}});var u=zi;Object.defineProperty(e,"v6ToV1",{enumerable:!0,get:function(){return u.default}});var p=$i;Object.defineProperty(e,"v7",{enumerable:!0,get:function(){return p.default}});var h=Wn;Object.defineProperty(e,"validate",{enumerable:!0,get:function(){return h.default}});var f=Ki;Object.defineProperty(e,"version",{enumerable:!0,get:function(){return f.default}})}($n);var Yi={};Object.defineProperty(Yi,"__esModule",{value:!0}),Yi.FakeEventTarget=void 0;Yi.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]??=[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(e=>e.callback!==("function"==typeof t?t:t.handleEvent)))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout(()=>{throw e},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};var Xi={};Object.defineProperty(Xi,"__esModule",{value:!0}),Xi.FakeEvent=void 0;Xi.FakeEvent=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){}};var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.FakeMediaStreamTrack=void 0;const es=$n,ts=Yi,rs=Xi,ns=Zi;class is extends ts.FakeEventTarget{#e;#t;#r;#n;#i;#s;#o;#a;#c;#d;#l;#u=null;#p=null;#h=null;#f=null;#m=null;constructor({kind:e,id:t,label:r,contentHint:n,enabled:i,muted:s,readyState:o,capabilities:a,constraints:c,settings:d,data:l}){super(),this.#e=t??(0,es.v4)(),this.#t=e,this.#r=r??"",this.#o=n??"",this.#i=i??!0,this.#s=s??!1,this.#n=o??"live",this.#a=a??{},this.#c=c??{},this.#d=d??{},this.#l=l??{}}get id(){return this.#e}get kind(){return this.#t}get label(){return this.#r}get contentHint(){return this.#o}set contentHint(e){this.#o=e}get enabled(){return this.#i}set enabled(e){const t=this.#i!==e;this.#i=e,t&&this.dispatchEvent(new rs.FakeEvent("enabledchange"))}get muted(){return this.#s}get readyState(){return this.#n}get data(){return this.#l}set data(e){this.#l=e}get onmute(){return this.#u}set onmute(e){this.#u&&this.removeEventListener("mute",this.#u),this.#u=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#p}set onunmute(e){this.#p&&this.removeEventListener("unmute",this.#p),this.#p=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#h}set onended(e){this.#h&&this.removeEventListener("ended",this.#h),this.#h=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#f}set onenabledchange(e){this.#f&&this.removeEventListener("enabledchange",this.#f),this.#f=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#m}set onstopped(e){this.#m&&this.removeEventListener("stopped",this.#m),this.#m=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(){"ended"!==this.#n&&(this.#n="ended",this.dispatchEvent(new rs.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new is({id:e??(0,es.v4)(),kind:this.#t,label:this.#r,contentHint:this.#o,enabled:this.#i,muted:this.#s,readyState:this.#n,capabilities:(0,ns.clone)(this.#a),constraints:(0,ns.clone)(this.#c),settings:(0,ns.clone)(this.#d),data:t??(0,ns.clone)(this.#l)})}getCapabilities(){return this.#a}getConstraints(){return this.#c}async applyConstraints(e={}){return this.#c=e,Promise.resolve()}getSettings(){return this.#d}remoteStop(){"ended"!==this.#n&&(this.#n="ended",this.dispatchEvent(new rs.FakeEvent("stopped")),this.dispatchEvent(new rs.FakeEvent("ended")))}remoteMute(){this.#s||(this.#s=!0,this.dispatchEvent(new rs.FakeEvent("mute")))}remoteUnmute(){this.#s&&(this.#s=!1,this.dispatchEvent(new rs.FakeEvent("unmute")))}}Vn.FakeMediaStreamTrack=is;var ss={};Object.defineProperty(ss,"__esModule",{value:!0}),ss.FakeEventTarget=void 0;ss.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]??=[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(e=>e.callback!==("function"==typeof t?t:t.handleEvent)))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout(()=>{throw e},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}},Object.defineProperty(Un,"__esModule",{value:!0}),Un.FakeHandler=void 0;const os=Vn,as=N,cs=oe,ds=ae,ls=ne,us=ss,ps=new M.Logger("FakeHandler"),hs="FakeHandler";class fs extends as.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${cs.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:hs,factory:t=>new fs(t,e),getNativeRtpCapabilities:async()=>(ps.debug("getNativeRtpCapabilities()"),fs.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(ps.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){const t=e.generateNativeRtpCapabilities();return ds.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),ps.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return hs}close(){ps.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(),ps.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),ps.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,encodings:t,codecOptions:r,codec:n}){this.assertNotClosed(),ps.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});const i=fs.getLocalRtpCapabilities(this._fakeParameters),s=this._getSendExtendedRtpCapabilities(i),o=ds.getSendingRtpParameters(e.kind,s);o.codecs=ds.reduceCodecs(o.codecs,n);const a=o.codecs.some(e=>/.+\/rtx$/i.test(e.mimeType));o.mid=`mid-${cs.generateRandomNumber()}`,t||(t=[{}]);for(const e of t)e.ssrc=cs.generateRandomNumber(),a&&(e.rtx={ssrc:cs.generateRandomNumber()});o.encodings=t,o.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const c=this._nextLocalId++;return this._tracks.set(c,e),{localId:String(c),rtpParameters:o}}async stopSending(e){if(ps.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?ps.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ps.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),ps.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),ps.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),ps.debug("sendDataChannel()");return{dataChannel:new ms({id:this._nextSctpStreamId++,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}),sctpStreamParameters:{streamId:this._nextSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r}}}async receive(e){this.assertNotClosed();const t=[];for(const r of e){const{trackId:e,kind:n}=r;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),ps.debug("receive() [trackId:%s, kind:%s]",e,n);const i=this._nextLocalId++,s=new os.FakeMediaStreamTrack({kind:n});this._tracks.set(i,s),t.push({localId:String(i),track:s})}return t}async stopReceiving(e){if(!this._closed)for(const t of e)ps.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}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),ps.debug("receiveDataChannel()");return{dataChannel:new ms({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}async setupTransport({localDtlsRole:e,localSdpObject:t}){const r=cs.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(r.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((e,t)=>this.emit("@connect",{dtlsParameters:r},e,t)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new ls.InvalidStateError("method called in a closed handler")}}Un.FakeHandler=fs;class ms extends us.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:n=null,label:i="",protocol:s=""}){super(),ps.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${r}, maxRetransmits:${n}, label:${i}, protocol:${s}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=r,this._maxRetransmits=n,this._label=i,this._protocol=s}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("open"!==this._readyState)throw new ls.InvalidStateError("not open")}}var gs={};Object.defineProperty(gs,"__esModule",{value:!0}),gs.generateRouterRtpCapabilities=function(){return vs.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"}]})},gs.generateNativeRtpCapabilities=function(){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}]}},gs.generateNativeSctpCapabilities=function(){return vs.deepFreeze({numStreams:{OS:2048,MIS:2048}})},gs.generateLocalDtlsParameters=function(){return vs.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"})},gs.generateTransportRemoteParameters=function(){return{id:bs(),iceParameters:vs.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:vs.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:vs.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:vs.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}},gs.generateProducerRemoteParameters=function(){return vs.deepFreeze({id:bs()})},gs.generateConsumerRemoteParameters=function({id:e,codecMimeType:t}={}){switch(t){case"audio/opus":return{id:e??bs(),producerId:bs(),kind:"audio",rtpParameters:vs.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:e??bs(),producerId:bs(),kind:"audio",rtpParameters:vs.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:e??bs(),producerId:bs(),kind:"video",rtpParameters:vs.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:e??bs(),producerId:bs(),kind:"video",rtpParameters:vs.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 '${t}'`)}},gs.generateDataProducerRemoteParameters=function(){return vs.deepFreeze({id:bs()})},gs.generateDataConsumerRemoteParameters=function({id:e}={}){return{id:e??bs(),dataProducerId:bs(),sctpStreamParameters:vs.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}};const vs=oe;function bs(){return String(vs.generateRandomNumber())}!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.debug=e.testFakeParameters=e.FakeHandler=e.enhancedEvents=e.ortc=e.parseScalabilityMode=e.detectDeviceAsync=e.detectDevice=e.Device=e.version=e.types=void 0;const t=v;e.debug=t.default,e.types=b,e.version="3.15.7";var r=y;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return r.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return r.detectDevice}}),Object.defineProperty(e,"detectDeviceAsync",{enumerable:!0,get:function(){return r.detectDeviceAsync}});var n=Jt;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return n.parse}}),e.ortc=ae,e.enhancedEvents=N;var i=Un;Object.defineProperty(e,"FakeHandler",{enumerable:!0,get:function(){return i.FakeHandler}}),e.testFakeParameters=gs}(h);let ys=!0,_s=!0;function ws(e,t,r){const n=e.match(t);return n&&n.length>=r&&parseFloat(n[r],10)}function Ss(e,t,r){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),i.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const n=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Cs(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ys=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ks(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(_s=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Ts(){if("object"==typeof window){if(ys)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ps(e,t){_s&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Rs(e){return"[object Object]"===Object.prototype.toString.call(e)}function Es(e){return Rs(e)?Object.keys(e).reduce(function(t,r){const n=Rs(e[r]),i=n?Es(e[r]):e[r],s=n&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})},{}):e}function Os(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?Os(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach(t=>{Os(e,e.get(t),r)})}))}function xs(e,t,r){const n=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}),s.forEach(t=>{e.forEach(r=>{r.type===n&&r.trackId===t.id&&Os(e,r,i)})}),i}const Is=Ts;function Ds(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const n="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[i("min",r)]=n.ideal,t.optional.push(e),e={},e[i("max",r)]=n.ideal,t.optional.push(e)):(e[i("",r)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then(r=>{let o=(r=r.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),Is("chrome: "+JSON.stringify(e)),i(e)})}e.video=n(e.video)}return Is("chrome: "+JSON.stringify(e)),i(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,n){i(e,e=>{r.webkitGetUserMedia(e,t,e=>{n&&n(s(e))})})}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(s(e))))}}}function Ms(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function js(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.track.id):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.id):{track:r};const i=new Event("track");i.track=r,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Ss(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function As(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Ls(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>xs(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),Ss(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>xs(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,n;return this.getSenders().forEach(r=>{r.track===e&&(t?n=!0:t=r)}),this.getReceivers().forEach(t=>(t.track===e&&(r?n=!0:r=t),t.track===e)),n||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Ns(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(n)&&this._shimmedLocalStreams[r.id].push(n):this._shimmedLocalStreams[r.id]=[r,n],n};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{const t=this.getSenders().find(t=>t.track===e);if(t)throw new DOMException("Track already exists.","InvalidAccessError")});const t=this.getSenders();r.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function Fs(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Ns(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{const t=this.getSenders().find(t=>t.track===e);if(t)throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}n.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(i.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const i=this.getSenders().find(e=>e.track===t);if(i)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const n=new e.MediaStream([t]);this._streams[r.id]=n,this._reverseStreams[n.id]=r,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then(e=>s(this,e))}};e.RTCPeerConnection.prototype[t]=n[t]});const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(n.id,"g"),i.id)}),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(r=>{this._streams[r].getTracks().find(t=>e.track===t)&&(t=this._streams[r])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Bs(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]})}function zs(e,t){Ss(e,"negotiationneeded",e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e})}var Us=Object.freeze({__proto__:null,fixNegotiationNeeded:zs,shimAddTrackRemoveTrack:Fs,shimAddTrackRemoveTrackWithNative:Ns,shimGetSendersWithDtmf:As,shimGetUserMedia:Ds,shimMediaStream:Ms,shimOnTrack:js,shimPeerConnection:Bs,shimSenderReceiverGetStats:Ls});function Vs(e,t){const r=e&&e.navigator,n=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,n){Ps("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function $s(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Gs(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]});const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,s]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!i)try{e.forEach(e=>{e.type=r[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:r[t.type]||t.type}))})}return e}).then(i,s)}}function qs(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Hs(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),Ss(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ws(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ps("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Js(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ks(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const r=e.length>0;r&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=t.apply(this,arguments);if(r){const{sender:t}=n,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(r).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function Qs(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Ys(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Xs(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Zs=Object.freeze({__proto__:null,shimAddTransceiver:Ks,shimCreateAnswer:Xs,shimCreateOffer:Ys,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})},shimGetParameters:Qs,shimGetUserMedia:Vs,shimOnTrack:$s,shimPeerConnection:Gs,shimRTCDataChannel:Js,shimReceiverGetStats:Hs,shimRemoveStream:Ws,shimSenderGetStats:qs});function eo(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(r=>t.call(this,r,e)),e.getVideoTracks().forEach(r=>t.call(this,r,e))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach(e=>{r.includes(e.track)&&this.removeTrack(e)})})}}function to(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)})}),t.apply(e,arguments)}}}function ro(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const n=i.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,r){const n=s.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,r){const n=o.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.addIceCandidate=a}function no(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(io(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,n){t.mediaDevices.getUserMedia(e).then(r,n)}.bind(t))}function io(e){return e&&void 0!==e.video?Object.assign({},e,{video:Es(e.video)}):e}function so(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let n=e.iceServers[r];void 0===n.urls&&n.url?(Ps("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function oo(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ao(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function co(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var lo=Object.freeze({__proto__:null,shimAudioContext:co,shimCallbacksAPI:ro,shimConstraints:io,shimCreateOfferLegacy:ao,shimGetUserMedia:no,shimLocalStreamsAPI:eo,shimRTCIceServerUrls:so,shimRemoteStreamsAPI:to,shimTrackEventTransceiver:oo}),uo={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter(e=>0===e.indexOf(r))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)r=n[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+r+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(r.attribute=e.substring(t+1,n),r.value=e.substring(n+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const n=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return n&&i?{usernameFragment:n.substring(12),password:i.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");r.profile=n[2];for(let i=3;i<n.length;i++){const s=n[i],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),i=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=i.length?t.parseFmtp(i[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{r.headerExtensions.push(t.parseExtmap(e))});const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach(e=>{i.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),r},t.writeRtpDescription=function(e,r){let n="";n+="m="+e+" ",n+=r.codecs.length>0?"9":"0",n+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=r.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)});let i=0;return r.codecs.forEach(e=>{e.maxptime>i&&(i=e.maxptime)}),i>0&&(n+="a=maxptime:"+i+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){const r=[],n=t.parseRtpParameters(e),i=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),i&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},r.push(t))}}),0===r.length&&a&&r.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,r.forEach(e=>{e.maxBitrate=l})),r},t.parseRtcpParameters=function(e){const r={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(r.cname=n.value,r.ssrc=n.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.length;const s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return r=n[0].substring(7).split(" "),{stream:r[0],track:r[1]};const i=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return i.length>0?(r=i[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let i;n.length>0&&(i=parseInt(n[0].substring(19),10)),isNaN(i)&&(i=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:r.fmt,maxMessageSize:i};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,n){let i;const s=void 0!==r?r:2;i=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+i+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(uo);var po=uo.exports,ho=c(po),fo=i({__proto__:null,default:ho},[po]);function mo(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const r=new t(e),n=ho.parseCandidate(e.candidate);for(const e in n)e in r||Object.defineProperty(r,e,{value:n[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Ss(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function go(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Ss(e,"icecandidate",e=>{if(e.candidate){const t=ho.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function vo(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=ho.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=ho.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),n=function(e,r){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const i=ho.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?n=parseInt(i[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(n=2147483637),n}(arguments[0],e);let i;i=0===r&&0===n?Number.POSITIVE_INFINITY:0===r||0===n?Math.max(r,n):Math.min(r,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>i}),this._sctp=s}return r.apply(this,arguments)}}function bo(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const n=arguments[0],i=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&i>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},Ss(e,"datachannel",e=>(t(e.channel,e.target),e))}function yo(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function _o(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function wo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function So(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>r.apply(this,[e]))})}var Co=Object.freeze({__proto__:null,removeExtmapAllowMixed:_o,shimAddIceCandidateNullOrEmpty:wo,shimConnectionState:yo,shimMaxMessageSize:vo,shimParameterlessSetLocalDescription:So,shimRTCIceCandidate:mo,shimRTCIceCandidateRelayProtocol:go,shimSendThrowTypeError:bo});const ko=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=Ts,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.userAgentData&&r.userAgentData.brands){const e=r.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(r.mozGetUserMedia)t.browser="firefox",t.version=parseInt(ws(r.userAgent,/Firefox\/(\d+)\./,1));else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(ws(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(ws(r.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=ws(r.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),i={browserDetails:n,commonShim:Co,extractVersion:ws,disableLog:Cs,disableWarnings:ks,sdp:fo};switch(n.browser){case"chrome":if(!Us||!Bs||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===n.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=Us,wo(e,n),So(e),Ds(e,n),Ms(e),Bs(e,n),js(e),Fs(e,n),As(e),Ls(e),zs(e,n),mo(e),go(e),yo(e),vo(e,n),bo(e),_o(e,n);break;case"firefox":if(!Zs||!Gs||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=Zs,wo(e,n),So(e),Vs(e,n),Gs(e,n),$s(e),Ws(e),qs(e),Hs(e),Js(e),Ks(e),Qs(e),Ys(e),Xs(e),mo(e),yo(e),vo(e,n),bo(e);break;case"safari":if(!lo||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=lo,wo(e,n),So(e),so(e),ao(e),ro(e),eo(e),to(e),oo(e),no(e),co(e),mo(e),go(e),vo(e,n),bo(e),_o(e,n);break;default:r("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});var To;function Po(){}function Ro(){Ro.init.call(this)}function Eo(e){return void 0===e._maxListeners?Ro.defaultMaxListeners:e._maxListeners}function Oo(e,t,r,n){var i,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new Po,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=Eo(e))&&i>0&&o.length>i){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function xo(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function Io(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Do(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}function Mo(e){return{id:e.id,tracks:e.getTracks().map(function(e){return{id:e.id,kind:e.kind,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}})}}Po.prototype=Object.create(null),Ro.EventEmitter=Ro,Ro.usingDomains=!1,Ro.prototype.domain=void 0,Ro.prototype._events=void 0,Ro.prototype._maxListeners=void 0,Ro.defaultMaxListeners=10,Ro.init=function(){this.domain=null,Ro.usingDomains&&(!To.active||this instanceof To.Domain||(this.domain=To.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Po,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Ro.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Ro.prototype.getMaxListeners=function(){return Eo(this)},Ro.prototype.emit=function(e){var t,r,n,i,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Do(e,n),s=0;s<n;++s)i[s].call(r)}(r,l,this);break;case 2:!function(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=Do(e,i),o=0;o<i;++o)s[o].call(r,n)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=Do(e,s),a=0;a<s;++a)o[a].call(r,n,i)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=Do(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];!function(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=Do(e,i),o=0;o<i;++o)s[o].apply(r,n)}(r,l,this,i)}return!0},Ro.prototype.addListener=function(e,t){return Oo(this,e,t,!1)},Ro.prototype.on=Ro.prototype.addListener,Ro.prototype.prependListener=function(e,t){return Oo(this,e,t,!0)},Ro.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,xo(this,e,t)),this},Ro.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,xo(this,e,t)),this},Ro.prototype.removeListener=function(e,t){var r,n,i,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0===--this._eventsCount?this._events=new Po:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new Po,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,o||t)}return this},Ro.prototype.off=function(e,t){return this.removeListener(e,t)},Ro.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Po,this._eventsCount=0):r[e]&&(0===--this._eventsCount?this._events=new Po:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new Po,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Ro.prototype.listeners=function(e){var t,r,n=this._events;return r=n&&(t=n[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[],r},Ro.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Io.call(e,t)},Ro.prototype.listenerCount=Io,Ro.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var jo=function(e,t,r){var n=0,i=!!window.mozRTCPeerConnection,s=!!window.RTCIceGatherer,o={};if(r.forEach(function(r){if(window[r+"RTCPeerConnection"]&&("webkit"!==r||!s)){var a=window[r+"RTCPeerConnection"],c=function(r,c){var d=new a(r,c),l="PC_"+n++;d.__rtcStatsId=l,r||(r={nullConfig:!0}),((r=JSON.parse(JSON.stringify(r)))&&r.iceServers||[]).forEach(function(e){delete e.credential}),r.browserType=i?"moz":s?"edge":"webkit",e("create",l,r),c&&e("constraints",l,c),d.addEventListener("icecandidate",function(t){e("onicecandidate",l,t.candidate)}),d.addEventListener("addstream",function(t){e("onaddstream",l,t.stream.id+" "+t.stream.getTracks().map(function(e){return e.kind+":"+e.id}))}),d.addEventListener("track",function(t){e("ontrack",l,t.track.kind+":"+t.track.id+" "+t.streams.map(function(e){return"stream:"+e.id}))}),d.addEventListener("removestream",function(t){e("onremovestream",l,t.stream.id+" "+t.stream.getTracks().map(function(e){return e.kind+":"+e.id}))}),d.addEventListener("signalingstatechange",function(){e("onsignalingstatechange",l,d.signalingState)}),d.addEventListener("iceconnectionstatechange",function(){e("oniceconnectionstatechange",l,d.iceConnectionState)}),d.addEventListener("icegatheringstatechange",function(){e("onicegatheringstatechange",l,d.iceGatheringState)}),d.addEventListener("connectionstatechange",function(){e("onconnectionstatechange",l,d.connectionState)}),d.addEventListener("negotiationneeded",function(){e("onnegotiationneeded",l,void 0)}),d.addEventListener("datachannel",function(t){e("ondatachannel",l,[t.channel.id,t.channel.label])});var u=function(){d.getStats(null).then(function(t){var r=function(e){if(!e.entries)return e;var t={};return e.forEach(function(e,r){t[r]=e}),t}(t),n=JSON.parse(JSON.stringify(r));e("getstats",l,function(e,t){t=JSON.parse(JSON.stringify(t)),Object.keys(t).forEach(function(r){var n=t[r];delete n.id,e[r]&&Object.keys(n).forEach(function(i){n[i]===e[r][i]&&delete t[r][i],(0===Object.keys(n).length||1===Object.keys(n).length&&n.timestamp)&&delete t[r]})});var r=-1/0;return Object.keys(t).forEach(function(e){var n=t[e];n.timestamp>r&&(r=n.timestamp)}),Object.keys(t).forEach(function(e){var n=t[e];n.timestamp===r&&(n.timestamp=0)}),t.timestamp=r,t}(o[l]||{},r)),o[l]=n})};if(!s&&t)var p=window.setInterval(function(){"closed"!==d.signalingState?u():window.clearInterval(p)},t);return s||d.addEventListener("connectionstatechange",function(){"connected"!==d.connectionState&&"failed"!==d.connectionState||u()}),d};["createDataChannel","close"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){return e(t,this.__rtcStatsId,arguments),r.apply(this,arguments)})}),["addStream","removeStream"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=arguments[0],i=n.getTracks().map(function(e){return e.kind+":"+e.id}).join(",");return e(t,this.__rtcStatsId,n.id+" "+i),r.apply(this,arguments)})}),["addTrack"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=arguments[0],i=[].slice.call(arguments,1);return e(t,this.__rtcStatsId,n.kind+":"+n.id+" "+(i.map(function(e){return"stream:"+e.id}).join(";")||"-")),r.apply(this,arguments)})}),["removeTrack"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=arguments[0].track;return e(t,this.__rtcStatsId,n?n.kind+":"+n.id:"null"),r.apply(this,arguments)})}),["createOffer","createAnswer"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n,i=this.__rtcStatsId,s=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?n=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(n=arguments[2]),e(t,this.__rtcStatsId,n),r.apply(this,n?[n]:void 0).then(function(r){if(e(t+"OnSuccess",i,r),!(s.length>0&&"function"==typeof s[0]))return r;s[0].apply(null,[r])},function(r){if(e(t+"OnFailure",i,r.toString()),!(s.length>1&&"function"==typeof s[1]))throw r;s[1].apply(null,[r])})})}),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=this.__rtcStatsId,i=arguments;return e(t,this.__rtcStatsId,i[0]),r.apply(this,[i[0]]).then(function(){e(t+"OnSuccess",n,void 0),i.length>=2&&"function"==typeof i[1]&&i[1].apply(null,[])},function(r){if(e(t+"OnFailure",n,r.toString()),!(i.length>=3&&"function"==typeof i[2]))throw r;i[2].apply(null,[r])})})}),a.generateCertificate&&Object.defineProperty(c,"generateCertificate",{get:function(){return arguments.length?a.generateCertificate.apply(null,arguments):a.generateCertificate}}),window[r+"RTCPeerConnection"]=c,window[r+"RTCPeerConnection"].prototype=a.prototype}}),r.forEach(function(t){var r=t+(t.length?"GetUserMedia":"getUserMedia");if(navigator[r]){var n=navigator[r].bind(navigator);navigator[r]=function(){e("getUserMedia",null,arguments[0]);var t=arguments[1],r=arguments[2];n(arguments[0],function(r){e("getUserMediaOnSuccess",null,Mo(r)),t&&t(r)},function(t){e("getUserMediaOnFailure",null,t.name),r&&r(t)})}.bind(navigator)}}),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var a=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(){return e("navigator.mediaDevices.getUserMedia",null,arguments[0]),a.apply(navigator.mediaDevices,arguments).then(function(t){return e("navigator.mediaDevices.getUserMediaOnSuccess",null,Mo(t)),t},function(t){return e("navigator.mediaDevices.getUserMediaOnFailure",null,t.name),Promise.reject(t)})}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var c=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getDisplayMedia=function(){return e("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),c.apply(navigator.mediaDevices,arguments).then(function(t){return e("navigator.mediaDevices.getDisplayMediaOnSuccess",null,Mo(t)),t},function(t){return e("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)})}.bind(navigator.mediaDevices)}return{resetDelta(){o={}}}},Ao=c(jo);let Lo;const No=new Uint8Array(16);function Fo(){if(!Lo&&(Lo="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Lo))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lo(No)}const Bo=[];for(let zE=0;zE<256;++zE)Bo.push((zE+256).toString(16).slice(1));var zo={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Uo(e,t,r){if(zo.randomUUID&&!e)return zo.randomUUID();const n=(e=e||{}).random||(e.rng||Fo)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(e,t=0){return Bo[e[t+0]]+Bo[e[t+1]]+Bo[e[t+2]]+Bo[e[t+3]]+"-"+Bo[e[t+4]]+Bo[e[t+5]]+"-"+Bo[e[t+6]]+Bo[e[t+7]]+"-"+Bo[e[t+8]]+Bo[e[t+9]]+"-"+Bo[e[t+10]]+Bo[e[t+11]]+Bo[e[t+12]]+Bo[e[t+13]]+Bo[e[t+14]]+Bo[e[t+15]]}(n)}const Vo=Object.create(null);Vo.open="0",Vo.close="1",Vo.ping="2",Vo.pong="3",Vo.message="4",Vo.upgrade="5",Vo.noop="6";const $o=Object.create(null);Object.keys(Vo).forEach(e=>{$o[Vo[e]]=e});const Go={type:"error",data:"parser error"},qo="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Ho="function"==typeof ArrayBuffer,Wo=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Jo=({type:e,data:t},r,n)=>qo&&t instanceof Blob?r?n(t):Ko(t,n):Ho&&(t instanceof ArrayBuffer||Wo(t))?r?n(t):Ko(new Blob([t]),n):n(Vo[e]+(t||"")),Ko=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Qo(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Yo;const Xo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Zo="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let UE=0;UE<64;UE++)Zo[Xo.charCodeAt(UE)]=UE;const ea="function"==typeof ArrayBuffer,ta=(e,t)=>{if("string"!=typeof e)return{type:"message",data:na(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:ra(e.substring(1),t)};return $o[r]?e.length>1?{type:$o[r],data:e.substring(1)}:{type:$o[r]}:Go},ra=(e,t)=>{if(ea){const r=(e=>{let t,r,n,i,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=Zo[e.charCodeAt(t)],n=Zo[e.charCodeAt(t+1)],i=Zo[e.charCodeAt(t+2)],s=Zo[e.charCodeAt(t+3)],l[c++]=r<<2|n>>4,l[c++]=(15&n)<<4|i>>2,l[c++]=(3&i)<<6|63&s;return d})(e);return na(r,t)}return{base64:!0,data:e}},na=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,ia=String.fromCharCode(30);function sa(){return new TransformStream({transform(e,t){!function(e,t){qo&&e.data instanceof Blob?e.data.arrayBuffer().then(Qo).then(t):Ho&&(e.data instanceof ArrayBuffer||Wo(e.data))?t(Qo(e.data)):Jo(e,!1,e=>{Yo||(Yo=new TextEncoder),t(Yo.encode(e))})}(e,r=>{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(r)})}})}let oa;function aa(e){return e.reduce((e,t)=>e+t.length,0)}function ca(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function da(e){if(e)return function(e){for(var t in da.prototype)e[t]=da.prototype[t];return e}(e)}da.prototype.on=da.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},da.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},da.prototype.off=da.prototype.removeListener=da.prototype.removeAllListeners=da.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},da.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},da.prototype.emitReserved=da.prototype.emit,da.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},da.prototype.hasListeners=function(e){return!!this.listeners(e).length};const la="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function ua(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const pa=la.setTimeout,ha=la.clearTimeout;function fa(e,t){t.useNativeTimers?(e.setTimeoutFn=pa.bind(la),e.clearTimeoutFn=ha.bind(la)):(e.setTimeoutFn=la.setTimeout.bind(la),e.clearTimeoutFn=la.clearTimeout.bind(la))}function ma(e){return"string"==typeof e?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(e):Math.ceil(1.33*(e.byteLength||e.size))}class ga extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class va extends da{constructor(e){super(),this.writable=!1,fa(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new ga(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=ta(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const ba="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),ya={};let _a,wa=0,Sa=0;function Ca(e){let t="";do{t=ba[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function ka(){const e=Ca(+new Date);return e!==_a?(wa=0,_a=e):e+"."+Ca(wa++)}for(;Sa<64;Sa++)ya[ba[Sa]]=Sa;let Ta=!1;try{Ta="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(VE){}const Pa=Ta;function Ra(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Pa))return new XMLHttpRequest}catch(e){}if(!t)try{return new(la[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Ea(){}const Oa=null!=new Ra({xdomain:!1}).responseType;let xa=class e extends da{constructor(e,t){super(),fa(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var t;const r=ua(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this.opts.xd;const n=this.xhr=new Ra(r);try{n.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(t=this.opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(n)),4===n.readyState&&(200===n.status||1223===n.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof n.status?n.status:0)},0))},n.send(this.data)}catch(e){return void this.setTimeoutFn(()=>{this.onError(e)},0)}"undefined"!=typeof document&&(this.index=e.requestsCount++,e.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Ea,t)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete e.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}};if(xa.requestsCount=0,xa.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Ia);else if("function"==typeof addEventListener){addEventListener("onpagehide"in la?"pagehide":"unload",Ia,!1)}function Ia(){for(let e in xa.requests)xa.requests.hasOwnProperty(e)&&xa.requests[e].abort()}const Da="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Ma=la.WebSocket||la.MozWebSocket,ja="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const Aa={websocket:class extends va{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=ja?{}:ua(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=ja?new Ma(e,t,r):t?new Ma(e,t):new Ma(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;Jo(r,this.supportsBinary,e=>{try{this.ws.send(e)}catch(e){}n&&Da(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ka()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Ma}},webtransport:class extends va{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const t=function(e,t){oa||(oa=new TextDecoder);const r=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===n){if(aa(r)<1)break;const e=ca(r,1);s=!(128&~e[0]),i=127&e[0],n=i<126?3:126===i?1:2}else if(1===n){if(aa(r)<2)break;const e=ca(r,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(aa(r)<8)break;const e=ca(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(Go);break}i=s*Math.pow(2,32)+t.getUint32(4),n=3}else{if(aa(r)<i)break;const e=ca(r,i);a.enqueue(ta(s?e:oa.decode(e),t)),n=0}if(0===i||i>e){a.enqueue(Go);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=sa();n.readable.pipeTo(e.writable),this.writer=n.writable.getWriter();const i=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;this.writer.write(r).then(()=>{n&&Da(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends va{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=Oa&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(ia),n=[];for(let e=0;e<r.length;e++){const i=ta(r[e],t);if(n.push(i),"error"===i.type)break}return n})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach((e,s)=>{Jo(e,!1,e=>{n[s]=e,++i===r&&t(n.join(ia))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=ka()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new xa(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}},La=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Na=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Fa(e){if(e.length>2e3)throw"URI too long";const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=La.exec(e||""),s={},o=14;for(;o--;)s[Na[o]]=i[o]||"";return-1!=r&&-1!=n&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(r[t]=n)}),r}(0,s.query),s}let Ba=class e extends da{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Fa(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Fa(t.host).host),fa(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new Aa[e](r)}open(){let t;if(this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(e){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",e=>this.onClose("transport close",e))}probe(t){let r=this.createTransport(t),n=!1;e.priorWebsocketSuccess=!1;const i=()=>{n||(r.send([{type:"ping",data:"probe"}]),r.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;e.priorWebsocketSuccess="websocket"===r.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(l(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=r.name,this.emitReserved("upgradeError",e)}}))};function s(){n||(n=!0,l(),r.close(),r=null)}const o=e=>{const t=new Error("probe error: "+e);t.transport=r.name,s(),this.emitReserved("upgradeError",t)};function a(){o("transport closed")}function c(){o("socket closed")}function d(e){r&&e.name!==r.name&&s()}const l=()=>{r.removeListener("open",i),r.removeListener("error",o),r.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};r.once("open",i),r.once("error",o),r.once("close",a),this.once("close",c),this.once("upgrading",d),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||r.open()},200):r.open()}onOpen(){if(this.readyState="open",e.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const r=this.writeBuffer[t].data;if(r&&(e+=ma(r)),t>0&&e>this.maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}onError(t){e.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}};Ba.protocol=4;const za="function"==typeof ArrayBuffer,Ua=Object.prototype.toString,Va="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Ua.call(Blob),$a="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Ua.call(File);function Ga(e){return za&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Va&&e instanceof Blob||$a&&e instanceof File}function qa(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(qa(e[t]))return!0;return!1}if(Ga(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return qa(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&qa(e[t]))return!0;return!1}function Ha(e){const t=[],r=e.data,n=e;return n.data=Wa(r,t),n.attachments=t.length,{packet:n,buffers:t}}function Wa(e,t){if(!e)return e;if(Ga(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=Wa(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=Wa(e[n],t));return r}return e}function Ja(e,t){return e.data=Ka(e.data,t),delete e.attachments,e}function Ka(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Ka(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Ka(e[r],t));return e}const Qa=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Ya;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Ya||(Ya={}));function Xa(e){return"[object Object]"===Object.prototype.toString.call(e)}class Za extends da{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Ya.BINARY_EVENT;r||t.type===Ya.BINARY_ACK?(t.type=r?Ya.EVENT:Ya.ACK,this.reconstructor=new ec(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Ga(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Ya[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Ya.BINARY_EVENT||r.type===Ya.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Za.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Ya.CONNECT:return Xa(t);case Ya.DISCONNECT:return void 0===t;case Ya.CONNECT_ERROR:return"string"==typeof t||Xa(t);case Ya.EVENT:case Ya.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Qa.indexOf(t[0]));case Ya.ACK:case Ya.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ec{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Ja(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var tc=Object.freeze({__proto__:null,Decoder:Za,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Ya.EVENT&&e.type!==Ya.ACK||!qa(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Ya.EVENT?Ya.BINARY_EVENT:Ya.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Ya.BINARY_EVENT&&e.type!==Ya.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Ha(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}},get PacketType(){return Ya},protocol:5});function rc(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const nc=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ic extends da{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[rc(e,"open",this.onopen.bind(this)),rc(e,"packet",this.onpacket.bind(this)),rc(e,"error",this.onerror.bind(this)),rc(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(nc.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Ya.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise((n,i)=>{t.push((e,t)=>r?e?i(e):n(t):n(e)),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ya.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ya.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ya.EVENT:case Ya.BINARY_EVENT:this.onevent(e);break;case Ya.ACK:case Ya.BINARY_ACK:this.onack(e);break;case Ya.DISCONNECT:this.ondisconnect();break;case Ya.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,t.packet({type:Ya.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ya.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function sc(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}sc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+r:e-r}return 0|Math.min(e,this.max)},sc.prototype.reset=function(){this.attempts=0},sc.prototype.setMin=function(e){this.ms=e},sc.prototype.setMax=function(e){this.max=e},sc.prototype.setJitter=function(e){this.jitter=e};class oc extends da{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,fa(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new sc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||tc;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Ba(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=rc(t,"open",function(){r.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=rc(t,"error",i);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{n(),i(new Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(n),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(rc(e,"ping",this.onping.bind(this)),rc(e,"data",this.ondata.bind(this)),rc(e,"error",this.onerror.bind(this)),rc(e,"close",this.onclose.bind(this)),rc(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Da(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new ic(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const ac={};function cc(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=Fa(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,s=r.path,o=ac[i]&&s in ac[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new oc(n,t):(ac[i]||(ac[i]=new oc(n,t)),a=ac[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(cc,{Manager:oc,Socket:ic,io:cc,connect:cc});var dc={},lc={},uc={};Object.defineProperty(uc,"__esModule",{value:!0}),uc.isCorrect=uc.isInSubnet=void 0,uc.isInSubnet=function(e){return!(this.subnetMask<e.subnetMask)&&this.mask(e.subnetMask)===e.mask()},uc.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}};var pc={};Object.defineProperty(pc,"__esModule",{value:!0}),pc.RE_SUBNET_STRING=pc.RE_ADDRESS=pc.GROUPS=pc.BITS=void 0,pc.BITS=32,pc.GROUPS=4,pc.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,pc.RE_SUBNET_STRING=/\/\d{1,2}$/;var hc={};Object.defineProperty(hc,"__esModule",{value:!0}),hc.AddressError=void 0;class fc extends Error{constructor(e,t){super(e),this.name="AddressError",null!==t&&(this.parseMessage=t)}}hc.AddressError=fc;var mc,gc={exports:{}};mc=gc,function(){var e;function t(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function r(){return new t(null)}var n="undefined"!=typeof navigator;n&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,r,n,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],d=this[e++]>>15,l=a*c+d*o;i=((c=o*c+((32767&l)<<15)+r[n]+(1073741823&i))>>>30)+(l>>>15)+a*d+(i>>>30),r[n++]=1073741823&c}return i},e=30):n&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this[e++]+r[n]+i;i=Math.floor(o/67108864),r[n++]=67108863&o}return i},e=26):(t.prototype.am=function(e,t,r,n,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],d=this[e++]>>14,l=a*c+d*o;i=((c=o*c+((16383&l)<<14)+r[n]+i)>>28)+(l>>14)+a*d,r[n++]=268435455&c}return i},e=28),t.prototype.DB=e,t.prototype.DM=(1<<e)-1,t.prototype.DV=1<<e,t.prototype.FV=Math.pow(2,52),t.prototype.F1=52-e,t.prototype.F2=2*e-52;var i,s,o=new Array;for(i="0".charCodeAt(0),s=0;s<=9;++s)o[i++]=s;for(i="a".charCodeAt(0),s=10;s<36;++s)o[i++]=s;for(i="A".charCodeAt(0),s=10;s<36;++s)o[i++]=s;function a(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function c(e,t){var r=o[e.charCodeAt(t)];return null==r?-1:r}function d(e){var t=r();return t.fromInt(e),t}function l(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function u(e){this.m=e}function p(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function h(e,t){return e&t}function f(e,t){return e|t}function m(e,t){return e^t}function g(e,t){return e&~t}function v(e){if(0==e)return-1;var t=0;return 65535&e||(e>>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function b(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function y(){}function _(e){return e}function w(e){this.r2=r(),this.q3=r(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}u.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},u.prototype.revert=function(e){return e},u.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},u.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},u.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},p.prototype.convert=function(e){var n=r();return e.abs().dlShiftTo(this.m.t,n),n.divRemTo(this.m,null,n),e.s<0&&n.compareTo(t.ZERO)>0&&this.m.subTo(n,n),n},p.prototype.revert=function(e){var t=r();return e.copyTo(t),this.reduce(t),t},p.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e[t],n=r*this.mpl+((r*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,n,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},p.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},p.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},t.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},t.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},t.prototype.fromString=function(e,r){var n;if(16==r)n=4;else if(8==r)n=3;else if(256==r)n=8;else if(2==r)n=1;else if(32==r)n=5;else{if(4!=r)return void this.fromRadix(e,r);n=2}this.t=0,this.s=0;for(var i=e.length,s=!1,o=0;--i>=0;){var a=8==n?255&e[i]:c(e,i);a<0?"-"==e.charAt(i)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+n>this.DB?(this[this.t-1]|=(a&(1<<this.DB-o)-1)<<o,this[this.t++]=a>>this.DB-o):this[this.t-1]|=a<<o,(o+=n)>=this.DB&&(o-=this.DB))}8==n&&128&e[0]&&(this.s=-1,o>0&&(this[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),s&&t.ZERO.subTo(this,this)},t.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},t.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s},t.prototype.drShiftTo=function(e,t){for(var r=e;r<this.t;++r)t[r-e]=this[r];t.t=Math.max(this.t-e,0),t.s=this.s},t.prototype.lShiftTo=function(e,t){var r,n=e%this.DB,i=this.DB-n,s=(1<<i)-1,o=Math.floor(e/this.DB),a=this.s<<n&this.DM;for(r=this.t-1;r>=0;--r)t[r+o+1]=this[r]>>i|a,a=(this[r]&s)<<n;for(r=o-1;r>=0;--r)t[r]=0;t[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},t.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,s=(1<<n)-1;t[0]=this[r]>>n;for(var o=r+1;o<this.t;++o)t[o-r-1]|=(this[o]&s)<<i,t[o-r]=this[o]>>n;n>0&&(t[this.t-r-1]|=(this.s&s)<<i),t.t=this.t-r,t.clamp()}},t.prototype.subTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]-e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e[r],t[r++]=n&this.DM,n>>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t[r++]=this.DV+n:n>0&&(t[r++]=n),t.t=r,t.clamp()},t.prototype.multiplyTo=function(e,r){var n=this.abs(),i=e.abs(),s=n.t;for(r.t=s+i.t;--s>=0;)r[s]=0;for(s=0;s<i.t;++s)r[s+n.t]=n.am(0,i[s],r,s,0,n.t);r.s=0,r.clamp(),this.s!=e.s&&t.ZERO.subTo(r,r)},t.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e[r]=0;for(r=0;r<t.t-1;++r){var n=t.am(r,t[r],e,2*r,0,1);(e[r+t.t]+=t.am(r+1,2*t[r],e,2*r+1,n,t.t-r-1))>=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()},t.prototype.divRemTo=function(e,n,i){var s=e.abs();if(!(s.t<=0)){var o=this.abs();if(o.t<s.t)return null!=n&&n.fromInt(0),void(null!=i&&this.copyTo(i));null==i&&(i=r());var a=r(),c=this.s,d=e.s,u=this.DB-l(s[s.t-1]);u>0?(s.lShiftTo(u,a),o.lShiftTo(u,i)):(s.copyTo(a),o.copyTo(i));var p=a.t,h=a[p-1];if(0!=h){var f=h*(1<<this.F1)+(p>1?a[p-2]>>this.F2:0),m=this.FV/f,g=(1<<this.F1)/f,v=1<<this.F2,b=i.t,y=b-p,_=null==n?r():n;for(a.dlShiftTo(y,_),i.compareTo(_)>=0&&(i[i.t++]=1,i.subTo(_,i)),t.ONE.dlShiftTo(p,_),_.subTo(a,a);a.t<p;)a[a.t++]=0;for(;--y>=0;){var w=i[--b]==h?this.DM:Math.floor(i[b]*m+(i[b-1]+v)*g);if((i[b]+=a.am(0,w,i,y,0,p))<w)for(a.dlShiftTo(y,_),i.subTo(_,i);i[b]<--w;)i.subTo(_,i)}null!=n&&(i.drShiftTo(p,n),c!=d&&t.ZERO.subTo(n,n)),i.t=p,i.clamp(),u>0&&i.rShiftTo(u,i),c<0&&t.ZERO.subTo(i,i)}}},t.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},t.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},t.prototype.exp=function(e,n){if(e>4294967295||e<1)return t.ONE;var i=r(),s=r(),o=n.convert(this),a=l(e)-1;for(o.copyTo(i);--a>=0;)if(n.sqrTo(i,s),(e&1<<a)>0)n.mulTo(s,o,i);else{var c=i;i=s,s=c}return n.revert(i)},t.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<<t)-1,i=!1,s="",o=this.t,c=this.DB-o*this.DB%t;if(o-- >0)for(c<this.DB&&(r=this[o]>>c)>0&&(i=!0,s=a(r));o>=0;)c<t?(r=(this[o]&(1<<c)-1)<<t-c,r|=this[--o]>>(c+=this.DB-t)):(r=this[o]>>(c-=t)&n,c<=0&&(c+=this.DB,--o)),r>0&&(i=!0),i&&(s+=a(r));return i?s:"0"},t.prototype.negate=function(){var e=r();return t.ZERO.subTo(this,e),e},t.prototype.abs=function(){return this.s<0?this.negate():this},t.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0},t.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+l(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var n=r();return this.abs().divRemTo(e,null,n),this.s<0&&n.compareTo(t.ZERO)>0&&e.subTo(n,n),n},t.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new u(t):new p(t),this.exp(e,r)},t.ZERO=d(0),t.ONE=d(1),y.prototype.convert=_,y.prototype.revert=_,y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},y.prototype.sqrTo=function(e,t){e.squareTo(t)},w.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=r();return e.copyTo(t),this.reduce(t),t},w.prototype.revert=function(e){return e},w.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},w.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},w.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var S,C,k,T=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],P=(1<<26)/T[T.length-1];function R(){var e;e=(new Date).getTime(),C[k++]^=255&e,C[k++]^=e>>8&255,C[k++]^=e>>16&255,C[k++]^=e>>24&255,k>=j&&(k-=j)}if(t.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},t.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),n=Math.pow(e,t),i=d(n),s=r(),o=r(),a="";for(this.divRemTo(i,s,o);s.signum()>0;)a=(n+o.intValue()).toString(e).substr(1)+a,s.divRemTo(i,s,o);return o.intValue().toString(e)+a},t.prototype.fromRadix=function(e,r){this.fromInt(0),null==r&&(r=10);for(var n=this.chunkSize(r),i=Math.pow(r,n),s=!1,o=0,a=0,d=0;d<e.length;++d){var l=c(e,d);l<0?"-"==e.charAt(d)&&0==this.signum()&&(s=!0):(a=r*a+l,++o>=n&&(this.dMultiply(i),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(r,o)),this.dAddOffset(a,0)),s&&t.ZERO.subTo(this,this)},t.prototype.fromNumber=function(e,r,n){if("number"==typeof r)if(e<2)this.fromInt(1);else for(this.fromNumber(e,n),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),f,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(r);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(t.ONE.shiftLeft(e-1),this);else{var i=new Array,s=7&e;i.length=1+(e>>3),r.nextBytes(i),s>0?i[0]&=(1<<s)-1:i[0]=0,this.fromString(i,256)}},t.prototype.bitwiseTo=function(e,t,r){var n,i,s=Math.min(e.t,this.t);for(n=0;n<s;++n)r[n]=t(this[n],e[n]);if(e.t<this.t){for(i=e.s&this.DM,n=s;n<this.t;++n)r[n]=t(this[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=s;n<e.t;++n)r[n]=t(i,e[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},t.prototype.changeBit=function(e,r){var n=t.ONE.shiftLeft(e);return this.bitwiseTo(n,r,n),n},t.prototype.addTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]+e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e[r],t[r++]=n&this.DM,n>>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t[r++]=n:n<-1&&(t[r++]=this.DV+n),t.t=r,t.clamp()},t.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},t.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},t.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i<n;++i)r[i+this.t]=this.am(0,e[i],r,i,0,this.t);for(n=Math.min(e.t,t);i<n;++i)this.am(0,e[i],r,i,0,t-i);r.clamp()},t.prototype.multiplyUpperTo=function(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r[this.t+n-t]=this.am(t-n,e[n],r,0,0,this.t+n-t);r.clamp(),r.drShiftTo(1,r)},t.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this[n])%e;return r},t.prototype.millerRabin=function(e){var n=this.subtract(t.ONE),i=n.getLowestSetBit();if(i<=0)return!1;var s=n.shiftRight(i);(e=e+1>>1)>T.length&&(e=T.length);for(var o=r(),a=0;a<e;++a){o.fromInt(T[Math.floor(Math.random()*T.length)]);var c=o.modPow(s,this);if(0!=c.compareTo(t.ONE)&&0!=c.compareTo(n)){for(var d=1;d++<i&&0!=c.compareTo(n);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(n))return!1}}return!0},t.prototype.clone=function(){var e=r();return this.copyTo(e),e},t.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},t.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},t.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},t.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},t.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n<this.DB&&(r=this[e]>>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<<this.DB-n);e>=0;)n<8?(r=(this[e]&(1<<n)-1)<<8-n,r|=this[--e]>>(n+=this.DB-8)):(r=this[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),128&r&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},t.prototype.equals=function(e){return 0==this.compareTo(e)},t.prototype.min=function(e){return this.compareTo(e)<0?this:e},t.prototype.max=function(e){return this.compareTo(e)>0?this:e},t.prototype.and=function(e){var t=r();return this.bitwiseTo(e,h,t),t},t.prototype.or=function(e){var t=r();return this.bitwiseTo(e,f,t),t},t.prototype.xor=function(e){var t=r();return this.bitwiseTo(e,m,t),t},t.prototype.andNot=function(e){var t=r();return this.bitwiseTo(e,g,t),t},t.prototype.not=function(){for(var e=r(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},t.prototype.shiftLeft=function(e){var t=r();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},t.prototype.shiftRight=function(e){var t=r();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},t.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+v(this[e]);return this.s<0?this.t*this.DB:-1},t.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=b(this[r]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:!!(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,f)},t.prototype.clearBit=function(e){return this.changeBit(e,g)},t.prototype.flipBit=function(e){return this.changeBit(e,m)},t.prototype.add=function(e){var t=r();return this.addTo(e,t),t},t.prototype.subtract=function(e){var t=r();return this.subTo(e,t),t},t.prototype.multiply=function(e){var t=r();return this.multiplyTo(e,t),t},t.prototype.divide=function(e){var t=r();return this.divRemTo(e,t,null),t},t.prototype.remainder=function(e){var t=r();return this.divRemTo(e,null,t),t},t.prototype.divideAndRemainder=function(e){var t=r(),n=r();return this.divRemTo(e,t,n),new Array(t,n)},t.prototype.modPow=function(e,t){var n,i,s=e.bitLength(),o=d(1);if(s<=0)return o;n=s<18?1:s<48?3:s<144?4:s<768?5:6,i=s<8?new u(t):t.isEven()?new w(t):new p(t);var a=new Array,c=3,h=n-1,f=(1<<n)-1;if(a[1]=i.convert(this),n>1){var m=r();for(i.sqrTo(a[1],m);c<=f;)a[c]=r(),i.mulTo(m,a[c-2],a[c]),c+=2}var g,v,b=e.t-1,y=!0,_=r();for(s=l(e[b])-1;b>=0;){for(s>=h?g=e[b]>>s-h&f:(g=(e[b]&(1<<s+1)-1)<<h-s,b>0&&(g|=e[b-1]>>this.DB+s-h)),c=n;!(1&g);)g>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),y)a[g].copyTo(o),y=!1;else{for(;c>1;)i.sqrTo(o,_),i.sqrTo(_,o),c-=2;c>0?i.sqrTo(o,_):(v=o,o=_,_=v),i.mulTo(_,a[g],o)}for(;b>=0&&!(e[b]&1<<s);)i.sqrTo(o,_),v=o,o=_,_=v,--s<0&&(s=this.DB-1,--b)}return i.revert(o)},t.prototype.modInverse=function(e){var r=e.isEven();if(this.isEven()&&r||0==e.signum())return t.ZERO;for(var n=e.clone(),i=this.clone(),s=d(1),o=d(0),a=d(0),c=d(1);0!=n.signum();){for(;n.isEven();)n.rShiftTo(1,n),r?(s.isEven()&&o.isEven()||(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;i.isEven();)i.rShiftTo(1,i),r?(a.isEven()&&c.isEven()||(a.addTo(this,a),c.subTo(e,c)),a.rShiftTo(1,a)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);n.compareTo(i)>=0?(n.subTo(i,n),r&&s.subTo(a,s),o.subTo(c,o)):(i.subTo(n,i),r&&a.subTo(s,a),c.subTo(o,c))}return 0!=i.compareTo(t.ONE)?t.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},t.prototype.pow=function(e){return this.exp(e,new y)},t.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(i<s&&(s=i),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},t.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=T[T.length-1]){for(t=0;t<T.length;++t)if(r[0]==T[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<T.length;){for(var n=T[t],i=t+1;i<T.length&&n<P;)n*=T[i++];for(n=r.modInt(n);t<i;)if(n%T[t++]==0)return!1}return r.millerRabin(e)},t.prototype.square=function(){var e=r();return this.squareTo(e),e},t.prototype.Barrett=w,null==C){var E;if(C=new Array,k=0,"undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var O=new Uint8Array(32);for(window.crypto.getRandomValues(O),E=0;E<32;++E)C[k++]=O[E]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5"){var x=window.crypto.random(32);for(E=0;E<x.length;++E)C[k++]=255&x.charCodeAt(E)}for(;k<j;)E=Math.floor(65536*Math.random()),C[k++]=E>>>8,C[k++]=255&E;k=0,R()}function I(){if(null==S){for(R(),(S=new M).init(C),k=0;k<C.length;++k)C[k]=0;k=0}return S.next()}function D(){}function M(){this.i=0,this.j=0,this.S=new Array}D.prototype.nextBytes=function(e){var t;for(t=0;t<e.length;++t)e[t]=I()},M.prototype.init=function(e){var t,r,n;for(t=0;t<256;++t)this.S[t]=t;for(r=0,t=0;t<256;++t)r=r+this.S[t]+e[t%e.length]&255,n=this.S[t],this.S[t]=this.S[r],this.S[r]=n;this.i=0,this.j=0},M.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]};var j=256;mc.exports={default:t,BigInteger:t,SecureRandom:D}}.call(a);var vc=gc.exports,bc={};!function(e){!function(){var t={not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function r(e){return function(e,n){var i,s,o,a,c,d,l,u,p,h=1,f=e.length,m="";for(s=0;s<f;s++)if("string"==typeof e[s])m+=e[s];else if("object"==typeof e[s]){if((a=e[s]).keys)for(i=n[h],o=0;o<a.keys.length;o++){if(null==i)throw new Error(r('[sprintf] Cannot access property "%s" of undefined value "%s"',a.keys[o],a.keys[o-1]));i=i[a.keys[o]]}else i=a.param_no?n[a.param_no]:n[h++];if(t.not_type.test(a.type)&&t.not_primitive.test(a.type)&&i instanceof Function&&(i=i()),t.numeric_arg.test(a.type)&&"number"!=typeof i&&isNaN(i))throw new TypeError(r("[sprintf] expecting number but found %T",i));switch(t.number.test(a.type)&&(u=i>=0),a.type){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,a.width?parseInt(a.width):0);break;case"e":i=a.precision?parseFloat(i).toExponential(a.precision):parseFloat(i).toExponential();break;case"f":i=a.precision?parseFloat(i).toFixed(a.precision):parseFloat(i);break;case"g":i=a.precision?String(Number(i.toPrecision(a.precision))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=a.precision?i.substring(0,a.precision):i;break;case"t":i=String(!!i),i=a.precision?i.substring(0,a.precision):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=a.precision?i.substring(0,a.precision):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=a.precision?i.substring(0,a.precision):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(a.type)?m+=i:(!t.number.test(a.type)||u&&!a.sign?p="":(p=u?"+":"-",i=i.toString().replace(t.sign,"")),d=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(p+i).length,c=a.width&&l>0?d.repeat(l):"",m+=a.align?p+i+c:"0"===d?p+c+i:c+p+i)}return m}(function(e){if(i[e])return i[e];var r,n=e,s=[],o=0;for(;n;){if(null!==(r=t.text.exec(n)))s.push(r[0]);else if(null!==(r=t.modulo.exec(n)))s.push("%");else{if(null===(r=t.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var a=[],c=r[2],d=[];if(null===(d=t.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a.push(d[1]);""!==(c=c.substring(d[0].length));)if(null!==(d=t.key_access.exec(c)))a.push(d[1]);else{if(null===(d=t.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");a.push(d[1])}r[2]=a}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");s.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}n=n.substring(r[0].length)}return i[e]=s}(e),arguments)}function n(e,t){return r.apply(null,[e].concat(t||[]))}var i=Object.create(null);e.sprintf=r,e.vsprintf=n,"undefined"!=typeof window&&(window.sprintf=r,window.vsprintf=n)}()}(bc);var yc=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),_c=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),wc=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&yc(t,e,r);return _c(t,e),t};Object.defineProperty(lc,"__esModule",{value:!0}),lc.Address4=void 0;const Sc=wc(uc),Cc=wc(pc),kc=hc,Tc=vc,Pc=bc;class Rc{constructor(e){this.groups=Cc.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=Sc.isCorrect(Cc.BITS),this.isInSubnet=Sc.isInSubnet,this.address=e;const t=Cc.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>Cc.BITS)throw new kc.AddressError("Invalid subnet mask.");e=e.replace(Cc.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new Rc(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(Cc.RE_ADDRESS))throw new kc.AddressError("Invalid IPv4 address.");return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromHex(e){const t=e.replace(/:/g,"").padStart(8,"0"),r=[];let n;for(n=0;n<8;n+=2){const e=t.slice(n,n+2);r.push(parseInt(e,16))}return new Rc(r.join("."))}static fromInteger(e){return Rc.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new Rc(t)}toHex(){return this.parsedAddress.map(e=>(0,Pc.sprintf)("%02x",parseInt(e,10))).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){const e=[];let t;for(t=0;t<Cc.GROUPS;t+=2){const r=(0,Pc.sprintf)("%02x%02x",parseInt(this.parsedAddress[t],10),parseInt(this.parsedAddress[t+1],10));e.push((0,Pc.sprintf)("%x",parseInt(r,16)))}return e.join(":")}bigInteger(){return new Tc.BigInteger(this.parsedAddress.map(e=>(0,Pc.sprintf)("%02x",parseInt(e,10))).join(""),16)}_startAddress(){return new Tc.BigInteger(this.mask()+"0".repeat(Cc.BITS-this.subnetMask),2)}startAddress(){return Rc.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Tc.BigInteger("1");return Rc.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Tc.BigInteger(this.mask()+"1".repeat(Cc.BITS-this.subnetMask),2)}endAddress(){return Rc.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Tc.BigInteger("1");return Rc.fromBigInteger(this._endAddress().subtract(e))}static fromBigInteger(e){return Rc.fromInteger(parseInt(e.toString(),10))}mask(e){return void 0===e&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||(e={});const t=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?t:(0,Pc.sprintf)("%s.in-addr.arpa.",t)}isMulticast(){return this.isInSubnet(new Rc("224.0.0.0/4"))}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Cc.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(Cc.RE_ADDRESS,(0,Pc.sprintf)('<span class="hover-group group-v4 group-6">%s</span>.<span class="hover-group group-v4 group-7">%s</span>',e.slice(0,2).join("."),e.slice(2,4).join(".")))}}lc.Address4=Rc;var Ec={},Oc={};Object.defineProperty(Oc,"__esModule",{value:!0}),Oc.RE_URL_WITH_PORT=Oc.RE_URL=Oc.RE_ZONE_STRING=Oc.RE_SUBNET_STRING=Oc.RE_BAD_ADDRESS=Oc.RE_BAD_CHARACTERS=Oc.TYPES=Oc.SCOPES=Oc.GROUPS=Oc.BITS=void 0,Oc.BITS=128,Oc.GROUPS=8,Oc.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},Oc.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"},Oc.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,Oc.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,Oc.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,Oc.RE_ZONE_STRING=/%.*$/,Oc.RE_URL=new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/),Oc.RE_URL_WITH_PORT=new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);var xc={};Object.defineProperty(xc,"__esModule",{value:!0}),xc.simpleGroup=xc.spanLeadingZeroes=xc.spanAll=xc.spanAllZeroes=void 0;const Ic=bc;function Dc(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function Mc(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}xc.spanAllZeroes=Dc,xc.spanAll=function(e,t=0){return e.split("").map((e,r)=>(0,Ic.sprintf)('<span class="digit value-%s position-%d">%s</span>',e,r+t,Dc(e))).join("")},xc.spanLeadingZeroes=function(e){return e.split(":").map(e=>Mc(e)).join(":")},xc.simpleGroup=function(e,t=0){return e.split(":").map((e,r)=>/group-v4/.test(e)?e:(0,Ic.sprintf)('<span class="hover-group group-%d">%s</span>',r+t,Mc(e)))};var jc={},Ac=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Lc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Nc=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&Ac(t,e,r);return Lc(t,e),t};Object.defineProperty(jc,"__esModule",{value:!0}),jc.possibleElisions=jc.simpleRegularExpression=jc.ADDRESS_BOUNDARY=jc.padGroup=jc.groupPossibilities=void 0;const Fc=Nc(Oc),Bc=bc;function zc(e){return(0,Bc.sprintf)("(%s)",e.join("|"))}function Uc(e){return e.length<4?(0,Bc.sprintf)("0{0,%d}%s",4-e.length,e):e}jc.groupPossibilities=zc,jc.padGroup=Uc,jc.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]",jc.simpleRegularExpression=function(e){const t=[];e.forEach((e,r)=>{0===parseInt(e,16)&&t.push(r)});const r=t.map(t=>e.map((e,r)=>{if(r===t){const t=0===r||r===Fc.GROUPS-1?":":"";return zc([Uc(e),t])}return Uc(e)}).join(":"));return r.push(e.map(Uc).join(":")),zc(r)},jc.possibleElisions=function(e,t,r){const n=t?"":":",i=r?"":":",s=[];t||r||s.push("::"),t&&r&&s.push(""),(r&&!t||!r&&t)&&s.push(":"),s.push((0,Bc.sprintf)("%s(:0{1,4}){1,%d}",n,e-1)),s.push((0,Bc.sprintf)("(0{1,4}:){1,%d}%s",e-1,i)),s.push((0,Bc.sprintf)("(0{1,4}:){%d}0{1,4}",e-1));for(let t=1;t<e-1;t++)for(let r=1;r<e-t;r++)s.push((0,Bc.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}",r,e-r-t-1));return zc(s)};var Vc=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),$c=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Gc=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&Vc(t,e,r);return $c(t,e),t};Object.defineProperty(Ec,"__esModule",{value:!0}),Ec.Address6=void 0;const qc=Gc(uc),Hc=Gc(pc),Wc=Gc(Oc),Jc=Gc(xc),Kc=lc,Qc=jc,Yc=hc,Xc=vc,Zc=bc;function ed(e){if(!e)throw new Error("Assertion failed.")}function td(e){return e=(e=e.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2')).replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2')}function rd(e){return(0,Zc.sprintf)("%04x",parseInt(e,16))}function nd(e){return 255&e}class id{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=qc.isInSubnet,this.isCorrect=qc.isCorrect(Wc.BITS),this.groups=void 0===t?Wc.GROUPS:t,this.address=e;const r=Wc.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>Wc.BITS)throw new Yc.AddressError("Invalid subnet mask.");e=e.replace(Wc.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new Yc.AddressError("Invalid subnet mask.");const n=Wc.RE_ZONE_STRING.exec(e);n&&(this.zone=n[0],e=e.replace(Wc.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new id(e),!0}catch(e){return!1}}static fromBigInteger(e){const t=e.toString(16).padStart(32,"0"),r=[];let n;for(n=0;n<Wc.GROUPS;n++)r.push(t.slice(4*n,4*(n+1)));return new id(r.join(":"))}static fromURL(e){let t,r,n=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=Wc.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],n=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=Wc.RE_URL.exec(e),null===r)return{error:"failed to parse address from URL",address:null,port:null};t=r[1]}else t=e;return n?(n=parseInt(n,10),(n<0||n>65536)&&(n=null)):n=null,{address:new id(t),port:n}}static fromAddress4(e){const t=new Kc.Address4(e),r=Wc.BITS-(Hc.BITS-t.subnetMask);return new id(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new Yc.AddressError("Invalid 'ip6.arpa' form.");const r=t.split(".").reverse();for(let e=7;e>0;e--){const t=4*e;r.splice(t,0,":")}return t=r.join(""),new id(t)}microsoftTranscription(){return(0,Zc.sprintf)("%s.ipv6-literal.net",this.correctForm().replace(/:/g,"-"))}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=Wc.BITS-this.subnetMask-Math.abs(e-Wc.BITS);return t<0?"0":function(e){const t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,"$1,$2");return e}(new Xc.BigInteger("2",10).pow(t).toString(10))}_startAddress(){return new Xc.BigInteger(this.mask()+"0".repeat(Wc.BITS-this.subnetMask),2)}startAddress(){return id.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Xc.BigInteger("1");return id.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Xc.BigInteger(this.mask()+"1".repeat(Wc.BITS-this.subnetMask),2)}endAddress(){return id.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Xc.BigInteger("1");return id.fromBigInteger(this._endAddress().subtract(e))}getScope(){let e=Wc.SCOPES[this.getBits(12,16).intValue()];return"Global unicast"===this.getType()&&"Link local"!==e&&(e="Global"),e||"Unknown"}getType(){for(const e of Object.keys(Wc.TYPES))if(this.isInSubnet(new id(e)))return Wc.TYPES[e];return"Global unicast"}getBits(e,t){return new Xc.BigInteger(this.getBitsBase2(e,t),2)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){const r=t-e;if(r%4!=0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,t).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,Wc.BITS)}reverseForm(e){e||(e={});const t=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,t).reverse().join(".");return t>0?e.omitSuffix?r:(0,Zc.sprintf)("%s.ip6.arpa.",r):e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const n=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&n.push([e-r,e-1]),r=0)}r>1&&n.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const i=n.map(e=>e[1]-e[0]+1);if(n.length>0){const e=i.indexOf(Math.max(...i));t=function(e,t){const r=[],n=[];let i;for(i=0;i<e.length;i++)i<t[0]?r.push(e[i]):i>t[1]&&n.push(e[i]);return r.concat(["compact"]).concat(n)}(this.parsedAddress,n[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)"compact"!==t[e]&&(t[e]=parseInt(t[e],16).toString(16));let s=t.join(":");return s=s.replace(/^compact$/,"::"),s=s.replace(/^compact|compact$/,":"),s=s.replace(/compact/,""),s}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Wc.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(Hc.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new Kc.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new Yc.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(Hc.RE_ADDRESS,this.address4.parsedAddress.map(td).join(".")));this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(":")}return e}parse(e){const t=(e=this.parse4in6(e)).match(Wc.RE_BAD_CHARACTERS);if(t)throw new Yc.AddressError((0,Zc.sprintf)("Bad character%s detected in address: %s",t.length>1?"s":"",t.join("")),e.replace(Wc.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(Wc.RE_BAD_ADDRESS);if(r)throw new Yc.AddressError((0,Zc.sprintf)("Address failed regex: %s",r.join("")),e.replace(Wc.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let n=[];const i=e.split("::");if(2===i.length){let e=i[0].split(":"),t=i[1].split(":");1===e.length&&""===e[0]&&(e=[]),1===t.length&&""===t[0]&&(t=[]);const r=this.groups-(e.length+t.length);if(!r)throw new Yc.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,n=n.concat(e);for(let e=0;e<r;e++)n.push("0");n=n.concat(t)}else{if(1!==i.length)throw new Yc.AddressError("Too many :: groups found");n=e.split(":"),this.elidedGroups=0}if(n=n.map(e=>(0,Zc.sprintf)("%x",parseInt(e,16))),n.length!==this.groups)throw new Yc.AddressError("Incorrect number of groups found");return n}canonicalForm(){return this.parsedAddress.map(rd).join(":")}decimal(){return this.parsedAddress.map(e=>(0,Zc.sprintf)("%05d",parseInt(e,16))).join(":")}bigInteger(){return new Xc.BigInteger(this.parsedAddress.map(rd).join(""),16)}to4(){const e=this.binaryZeroPad().split("");return Kc.Address4.fromHex(new Xc.BigInteger(e.slice(96,128).join(""),2).toString(16))}to4in6(){const e=this.to4(),t=new id(this.parsedAddress.slice(0,6).join(":"),6).correctForm();let r="";return/:$/.test(t)||(r=":"),t+r+e.address}inspectTeredo(){const e=this.getBitsBase16(0,32),t=this.getBits(80,96).xor(new Xc.BigInteger("ffff",16)).toString(),r=Kc.Address4.fromHex(this.getBitsBase16(32,64)),n=Kc.Address4.fromHex(this.getBits(96,128).xor(new Xc.BigInteger("ffffffff",16)).toString(16)),i=this.getBits(64,80),s=this.getBitsBase2(64,80),o=i.testBit(15),a=i.testBit(14),c=i.testBit(8),d=i.testBit(9),l=new Xc.BigInteger(s.slice(2,6)+s.slice(8,16),2).toString(10);return{prefix:(0,Zc.sprintf)("%s:%s",e.slice(0,4),e.slice(4,8)),server4:r.address,client4:n.address,flags:s,coneNat:o,microsoft:{reserved:a,universalLocal:d,groupIndividual:c,nonce:l},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=Kc.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:(0,Zc.sprintf)("%s",e.slice(0,4)),gateway:t.address}}to6to4(){if(!this.is4())return null;const e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new id(e)}toByteArray(){const e=this.bigInteger().toByteArray();return 17===e.length&&0===e[0]?e.slice(1):e}toUnsignedByteArray(){return this.toByteArray().map(nd)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(nd))}static fromUnsignedByteArray(e){const t=new Xc.BigInteger("256",10);let r=new Xc.BigInteger("0",10),n=new Xc.BigInteger("1",10);for(let i=e.length-1;i>=0;i--)r=r.add(n.multiply(new Xc.BigInteger(e[i].toString(10),10))),n=n.multiply(t);return id.fromBigInteger(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return"1111111010000000000000000000000000000000000000000000000000000000"===this.getBitsBase2(0,64)}isMulticast(){return"Multicast"===this.getType()}is4(){return this.v4}isTeredo(){return this.isInSubnet(new id("2001::/32"))}is6to4(){return this.isInSubnet(new id("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":(0,Zc.sprintf)(":%s",e),(0,Zc.sprintf)("http://[%s]%s/",this.correctForm(),e)}link(e){e||(e={}),void 0===e.className&&(e.className=""),void 0===e.prefix&&(e.prefix="/#address="),void 0===e.v4&&(e.v4=!1);let t=this.correctForm;return e.v4&&(t=this.to4in6),e.className?(0,Zc.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>',e.prefix,t.call(this),e.className):(0,Zc.sprintf)('<a href="%1$s%2$s">%2$s</a>',e.prefix,t.call(this))}group(){if(0===this.elidedGroups)return Jc.simpleGroup(this.address).join(":");ed("number"==typeof this.elidedGroups),ed("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...Jc.simpleGroup(t)):e.push("");const n=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)n.push((0,Zc.sprintf)("group-%d",e));return e.push((0,Zc.sprintf)('<span class="%s"></span>',n.join(" "))),r.length?e.push(...Jc.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(ed(this.address4 instanceof Kc.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new id(this.correctForm());if(0===r.elidedGroups)t.push((0,Qc.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===Wc.GROUPS)t.push((0,Qc.possibleElisions)(Wc.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,Qc.simpleRegularExpression)(e[0].split(":"))),ed("number"==typeof r.elidedGroups),t.push((0,Qc.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,Qc.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",Qc.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",Qc.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}Ec.Address6=id,function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&t(n,e,i);return r(n,e),n};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;const i=lc;Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});const s=Ec;Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return s.Address6}});const o=hc;Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}});const c=n(xc);e.v6={helpers:c}}(dc);var sd={exports:{}};!function(e){(function(){var t,r,n,i,s,o,a,c;r={},null!==e&&e.exports?e.exports=r:this.ipaddr=r,a=function(e,t,r,n){var i,s;if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;n>0;){if((s=r-n)<0&&(s=0),e[i]>>s!==t[i]>>s)return!1;n-=r,i+=1}return!0},r.subnetMatch=function(e,t,r){var n,i,s,o,a;for(s in null==r&&(r="unicast"),t)for(!(o=t[s])[0]||o[0]instanceof Array||(o=[o]),n=0,i=o.length;n<i;n++)if(a=o[n],e.kind()===a[0].kind()&&e.match.apply(e,a))return s;return r},r.IPv4=function(){function e(e){var t,r,n;if(4!==e.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(t=0,r=e.length;t<r;t++)if(!(0<=(n=e[t])&&n<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=e}return e.prototype.kind=function(){return"ipv4"},e.prototype.toString=function(){return this.octets.join(".")},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv4"!==e.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,e.octets,8,t)},e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.toIPv4MappedAddress=function(){return r.IPv6.parse("::ffff:"+this.toString())},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,n,i,s,o;for(o={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},e=0,i=!1,t=r=3;r>=0;t=r+=-1){if(!((n=this.octets[t])in o))return null;if(s=o[n],i&&0!==s)return null;8!==s&&(i=!0),e+=s}return 32-e},e}(),n="(0?\\d+|0x[a-f0-9]+)",i={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},r.IPv4.parser=function(e){var t,r,n,s,o;if(r=function(e){return"0"===e[0]&&"x"!==e[1]?parseInt(e,8):parseInt(e)},t=e.match(i.fourOctet))return function(){var e,i,s,o;for(o=[],e=0,i=(s=t.slice(1,6)).length;e<i;e++)n=s[e],o.push(r(n));return o}();if(t=e.match(i.longValue)){if((o=r(t[1]))>4294967295||o<0)throw new Error("ipaddr: address outside defined range");return function(){var e,t;for(t=[],s=e=0;e<=24;s=e+=8)t.push(o>>s&255);return t}().reverse()}return null},r.IPv6=function(){function e(e,t){var r,n,i,s,o,a;if(16===e.length)for(this.parts=[],r=n=0;n<=14;r=n+=2)this.parts.push(e[r]<<8|e[r+1]);else{if(8!==e.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=e}for(i=0,s=(a=this.parts).length;i<s;i++)if(!(0<=(o=a[i])&&o<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return e.prototype.kind=function(){return"ipv6"},e.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},e.prototype.toRFC5952String=function(){var e,t,r,n,i;for(n=/((^|:)(0(:|$)){2,})/g,i=this.toNormalizedString(),e=0,t=-1;r=n.exec(i);)r[0].length>t&&(e=r.index,t=r[0].length);return t<0?i:i.substring(0,e)+"::"+i.substring(e+t)},e.prototype.toByteArray=function(){var e,t,r,n,i;for(e=[],t=0,r=(i=this.parts).length;t<r;t++)n=i[t],e.push(n>>8),e.push(255&n);return e},e.prototype.toNormalizedString=function(){var e,t,r;return e=function(){var e,r,n,i;for(i=[],e=0,r=(n=this.parts).length;e<r;e++)t=n[e],i.push(t.toString(16));return i}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.toFixedLengthString=function(){var e,t,r;return e=function(){var e,r,n,i;for(i=[],e=0,r=(n=this.parts).length;e<r;e++)t=n[e],i.push(t.toString(16).padStart(4,"0"));return i}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv6"!==e.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,e.parts,16,t)},e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],reserved:[[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},e.prototype.toIPv4Address=function(){var e,t,n;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=(n=this.parts.slice(-2))[0],t=n[1],new r.IPv4([e>>8,255&e,t>>8,255&t])},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,n,i,s,o;for(o={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},e=0,i=!1,t=r=7;r>=0;t=r+=-1){if(!((n=this.parts[t])in o))return null;if(s=o[n],i&&0!==s)return null;16!==s&&(i=!0),e+=s}return 128-e},e}(),s="(?:[0-9a-f]+::?)+",c="%[0-9a-z]{1,}",o={zoneIndex:new RegExp(c,"i"),native:new RegExp("^(::)?("+s+")?([0-9a-f]+)?(::)?("+c+")?$","i"),transitional:new RegExp("^((?:"+s+")|(?:::)(?:"+s+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"("+c+")?$","i")},t=function(e,t){var r,n,i,s,a,c;if(e.indexOf("::")!==e.lastIndexOf("::"))return null;for((c=(e.match(o.zoneIndex)||[])[0])&&(c=c.substring(1),e=e.replace(/%.+$/,"")),r=0,n=-1;(n=e.indexOf(":",n+1))>=0;)r++;if("::"===e.substr(0,2)&&r--,"::"===e.substr(-2,2)&&r--,r>t)return null;for(a=t-r,s=":";a--;)s+="0:";return":"===(e=e.replace("::",s))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){var t,r,n,s;for(s=[],t=0,r=(n=e.split(":")).length;t<r;t++)i=n[t],s.push(parseInt(i,16));return s}(),zoneId:c}},r.IPv6.parser=function(e){var r,n,i,s,a,c,d;if(o.native.test(e))return t(e,8);if((s=e.match(o.transitional))&&(d=s[6]||"",(r=t(s[1].slice(0,-1)+d,6)).parts)){for(n=0,i=(c=[parseInt(s[2]),parseInt(s[3]),parseInt(s[4]),parseInt(s[5])]).length;n<i;n++)if(!(0<=(a=c[n])&&a<=255))return null;return r.parts.push(c[0]<<8|c[1]),r.parts.push(c[2]<<8|c[3]),{parts:r.parts,zoneId:r.zoneId}}return null},r.IPv4.isIPv4=r.IPv6.isIPv6=function(e){return null!==this.parser(e)},r.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(e){return!1}},r.IPv4.isValidFourPartDecimal=function(e){return!(!r.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},r.IPv6.isValid=function(e){var t;if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{return new this((t=this.parser(e)).parts,t.zoneId),!0}catch(e){return!1}},r.IPv4.parse=function(e){var t;if(null===(t=this.parser(e)))throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},r.IPv6.parse=function(e){var t;if(null===(t=this.parser(e)).parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(t.parts,t.zoneId)},r.IPv4.parseCIDR=function(e){var t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=32)return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},r.IPv4.subnetMaskFromPrefixLength=function(e){var t,r,n;if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(n=[0,0,0,0],r=0,t=Math.floor(e/8);r<t;)n[r]=255,r++;return t<4&&(n[t]=Math.pow(2,e%8)-1<<8-e%8),new this(n)},r.IPv4.broadcastAddressFromCIDR=function(e){var t,r,n,i,s;try{for(n=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)|255^parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv4.networkAddressFromCIDR=function(e){var t,r,n,i,s;try{for(n=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv6.parseCIDR=function(e){var t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=128)return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},r.isValid=function(e){return r.IPv6.isValid(e)||r.IPv4.isValid(e)},r.parse=function(e){if(r.IPv6.isValid(e))return r.IPv6.parse(e);if(r.IPv4.isValid(e))return r.IPv4.parse(e);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},r.parseCIDR=function(e){try{return r.IPv6.parseCIDR(e)}catch(t){try{return r.IPv4.parseCIDR(e)}catch(e){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},r.fromByteArray=function(e){var t;if(4===(t=e.length))return new r.IPv4(e);if(16===t)return new r.IPv6(e);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},r.process=function(e){var t;return"ipv6"===(t=this.parse(e)).kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(a)}(sd);var od=sd.exports,ad=function(e,t){if("string"==typeof t)return cd(e,t);if("object"==typeof t){for(var r=!1,n=0;n<t.length;n++)if(cd(e,t[n])){r=!0;break}return r}};function cd(e,t){try{var r=od.process(e);if(-1===t.indexOf("/")){var n=od.process(t);return"ipv6"===r.kind()&&"ipv6"===n.kind()?r.toNormalizedString()===n.toNormalizedString():r.toString()==n.toString()}var i=od.parseCIDR(t);return r.match(i)}catch(e){return!1}}var dd=ad,ld=/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,ud=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.2.0/24","192.168.0.0/16","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","224.0.0.0/3"],pd=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];for(var hd=function(e){var t=[],r={originalIp:e,boiledIp:!1,isValid:!1,isBogon:!1,isApipa:!1,isMulticast:!1,isRfc1918:!1,isPublicIp:!1};if(ld.test(e)){r.isValid=!0;for(var n=e.split("."),i=0;i<4;i++)t.push(parseInt(n[i],10));r.boiledIp=t.join("."),dd(r.boiledIp,ud)&&(r.isBogon=!0),dd(r.boiledIp,"169.254.0.0/16")&&(r.isApipa=!0),dd(r.boiledIp,"224.0.0.0/4")&&(r.isMulticast=!0),dd(r.boiledIp,pd)?r.isRfc1918=!0:!1===r.isBogon&&(r.isPublicIp=!0)}return r},fd=c(hd),md={exports:{}},gd=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vd=[],bd=0;bd<256;bd++)vd[bd]=(bd+256).toString(16).substr(1);md.exports=function(e,t){var r;if(Buffer.isBuffer(e))r=function(e){var t=0,r=vd;return r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]}(e);else{if("[object String]"!==Object.prototype.toString.call(e))return!1;r=e}if(r=r.toLowerCase(),!gd.test(r))return!1;if(void 0===t)t=yd(r);else if(yd(r)!==t)return!1;switch(t){case 1:case 2:return!0;case 3:case 4:case 5:return-1!==["8","9","a","b"].indexOf(r.charAt(19));default:throw new Error("Invalid version provided.")}};var yd=md.exports.version=function(e){return 0|e.charAt(14)},_d=c(md.exports);class wd extends Error{constructor(e){super(e.message),this.name="AssertionError",this.code="ERR_ASSERTION",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,Error.captureStackTrace&&Error.captureStackTrace(this,e.stackStartFn)}}function Sd(e){if(e.message instanceof Error)throw e.message;throw new wd(e)}function Cd(...e){!function(e,t,r,n){if(!r){let i=!1;if(0===t)i=!0,n="No value argument passed to `assert.ok()`";else if(n instanceof Error)throw n;const s=new wd({actual:r,expected:!0,message:n,operator:"==",stackStartFn:e});throw s.generatedMessage=i,s}}(Cd,e.length,...e)}const kd={fail:e=>{Sd({actual:"fail()",expected:"fail() should not be called",message:e,operator:"fail",stackStartFn:kd.fail})},ok:Cd};function Td(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r(function(t){t(e)})}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())})}kd.notEqual=function e(t,r,n){if(arguments.length<2)throw new Error("'actual' and 'expected' arguments are required");t==r&&Sd({actual:t,expected:r,message:n,operator:"!=",stackStartFn:e})},kd.ok=Cd,"function"==typeof SuppressedError&&SuppressedError;const Pd="[a-fA-F\\d:]",Rd=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${Pd})|(?<=${Pd})(?=\\s|$))`:"",Ed="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Od="[a-fA-F\\d]{1,4}",xd=`\n(?:\n(?:${Od}:){7}(?:${Od}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${Od}:){6}(?:${Ed}|:${Od}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${Od}:){5}(?::${Ed}|(?::${Od}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${Od}:){4}(?:(?::${Od}){0,1}:${Ed}|(?::${Od}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${Od}:){3}(?:(?::${Od}){0,2}:${Ed}|(?::${Od}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${Od}:){2}(?:(?::${Od}){0,3}:${Ed}|(?::${Od}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${Od}:){1}(?:(?::${Od}){0,4}:${Ed}|(?::${Od}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${Od}){0,5}:${Ed}|(?::${Od}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Id=new RegExp(`(?:^${Ed}$)|(?:^${xd}$)`),Dd=new RegExp(`^${Ed}$`),Md=new RegExp(`^${xd}$`),jd=e=>e&&e.exact?Id:new RegExp(`(?:${Rd(e)}${Ed}${Rd(e)})|(?:${Rd(e)}${xd}${Rd(e)})`,"g");jd.v4=e=>e&&e.exact?Dd:new RegExp(`${Rd(e)}${Ed}${Rd(e)}`,"g"),jd.v6=e=>e&&e.exact?Md:new RegExp(`${Rd(e)}${xd}${Rd(e)}`,"g");const Ad=new URLSearchParams(window.location.search).has("debug");class Ld{constructor(){this._isEnabled=!1,this._isEnabled=Ad}isEnabled(){return this._isEnabled}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}info(...e){if(this._isEnabled)return console.info(...e)}warn(...e){if(this._isEnabled)return console.warn(...e)}error(...e){if(this._isEnabled)return console.error(...e)}withDebugLogger(e){return this._debugger=e,this}debug(...e){if(!this._isEnabled||!this._debugger)return;const t=[];e.forEach(e=>{if("function"==typeof e){const r=e();t.push(r)}else t.push(e)}),this._debugger.print(...t)}}const Nd={codecOptions:{opusDtx:!0,opusFec:!0},encodings:[{dtx:!0}]},Fd={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:4,maxBitrate:15e4},{scaleResolutionDownBy:2,maxBitrate:5e5},{scaleResolutionDownBy:1,maxBitrate:1e6}]},Bd={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:2,maxBitrate:15e4},{scaleResolutionDownBy:1,maxBitrate:5e5}]},zd={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2",maxBitrate:1e6}]},Ud={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2",maxBitrate:5e5}]},Vd={encodings:[{}]},$d={encodings:[{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},Gd={encodings:[{scaleResolutionDownBy:4,dtx:!0,maxBitrate:15e4},{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},qd=(e,t,r,n=!1)=>{var i;const{lowDataModeEnabled:s,simulcastScreenshareOn:o,vp9On:a}=r;if("audio"===e)return Nd;const c="chrome"===(null===(i=ko.browserDetails)||void 0===i?void 0:i.browser)&&a;return t?Wd({areTooManyAlreadyPresenting:n,simulcastScreenshareOn:o}):Hd({lowBandwidth:s,isVp9Available:c})},Hd=({lowBandwidth:e,isVp9Available:t})=>e?t?Ud:Bd:t?zd:Fd,Wd=({areTooManyAlreadyPresenting:e,simulcastScreenshareOn:t})=>e?Gd:t?$d:Vd;var Jd;!function(e){e.H264="video/h264",e.VP9="video/vp9"}(Jd||(Jd={}));function Kd(e,t){const r=e.find(({mimeType:e})=>e.toLowerCase()===t);return r?[...e].sort((e,n)=>{var i;return e.mimeType.toLowerCase()===t?-1:"video/rtx"===e.mimeType.toLowerCase()&&(null===(i=e.parameters)||void 0===i?void 0:i.apt)===r.preferredPayloadType?n.mimeType.toLowerCase()===t?1:-1:0}):e}function Qd(e){return Td(this,void 0,void 0,function*(){const t=yield Promise.all(e.map(({mimeType:e})=>function(e){return Td(this,void 0,void 0,function*(){const{powerEfficient:t}=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{width:1280,height:720,bitrate:2580,framerate:24,contentType:e}});return t})}(e).then(t=>[e,t]))),r=Object.fromEntries(t),n=e.sort((e,t)=>{const n=r[e.mimeType];return n===r[t.mimeType]?0:n?-1:1});return n})}function Yd(e,t){return Td(this,void 0,void 0,function*(){let r=function(e,t){const r=e.map(({mimeType:e})=>e).filter((e,t,r)=>r.indexOf(e)===t),n=function(e,{av1On:t}){return e.unshift("video/vp9"),t&&e.unshift("video/av1"),e}(r,t);return e.sort((e,t)=>{const r=n.indexOf(e.mimeType.toLowerCase()),i=n.indexOf(t.mimeType.toLowerCase());return(r>=0?r:Number.MAX_VALUE)-(i>=0?i:Number.MAX_VALUE)})}(e,t);return r=yield Qd(e),r})}ko.default;const Xd={id:Uo(),connectionNumber:0},Zd=()=>{};let el=Zd;const tl=function(e,t=console){const r=[];let n,i,s,o,a,c,d,l,u,p,h,f,m=0,g=!1,v=0;const b={connected:!1,trace:(...e)=>{if(e.push(Date.now()),"customEvent"===e[0]&&"roomSessionId"===e[2].type){const t=c&&c[2].value.roomSessionId,r=e[2].value.roomSessionId;c=e,g&&r&&r!==t&&(null==n||n.close()),r&&(g=!0)}else"customEvent"===e[0]&&"clientId"===e[2].type?s=e:"customEvent"===e[0]&&"organizationId"===e[2].type?i=e:"customEvent"===e[0]&&"displayName"===e[2].type?o=e:"customEvent"===e[0]&&"userRole"===e[2].type?a=e:"customEvent"===e[0]&&"deviceId"===e[2].type?l=e:"customEvent"===e[0]&&"roomProduct"===e[2].type?u=e:"customEvent"===e[0]&&"roomMode"===e[2].type?p=e:"customEvent"===e[0]&&"sfuServer"===e[2].type?h=e:"customEvent"===e[0]&&"featureFlags"===e[2].type&&(f=e);(null==n?void 0:n.readyState)===WebSocket.OPEN?(m=0,n.send(JSON.stringify(e))):"getstats"===e[0]?v<20&&(v++,r.push(e)):"customEvent"===e[0]&&"insightsStats"===e[2].type||r.push(e),(null==n?void 0:n.readyState)===WebSocket.CLOSED&&d&&setTimeout(()=>{n.readyState===WebSocket.CLOSED&&d&&b.connect()},1e3*m)},close:()=>{d=!1,null==n||n.close()},connect:()=>{d=!0,m+=1,null==n||n.close(),b.connected=!0,n=new WebSocket(e+window.location.pathname,"1.0"),n.onerror=e=>{b.connected=!1,t.warn("[RTCSTATS] WebSocket error",e)},n.onclose=e=>{b.connected=!1,t.info(`[RTCSTATS] Closed ${e.code}`),el()},n.onopen=()=>{for(Xd.connectionNumber++,n.send(JSON.stringify(["clientInfo",null,Xd])),i&&n.send(JSON.stringify(i)),s&&n.send(JSON.stringify(s)),c&&n.send(JSON.stringify(c)),o&&n.send(JSON.stringify(o)),a&&n.send(JSON.stringify(a)),l&&n.send(JSON.stringify(l)),p&&n.send(JSON.stringify(p)),u&&n.send(JSON.stringify(u)),h&&n.send(JSON.stringify(h)),f&&n.send(JSON.stringify(f));r.length;)n.send(JSON.stringify(r.shift()));v=0}}};return b}("wss://rtcstats.srv.whereby.com"),rl=Ao(tl.trace,1e4,[""]);el=(null==rl?void 0:rl.resetDelta)||Zd;const nl={sendEvent:(e,t)=>{tl.trace("customEvent",null,{type:e,value:t})},sendAudioMuted:e=>{nl.sendEvent("audio_muted",{muted:e})},sendVideoMuted:e=>{nl.sendEvent("video_muted",{muted:e})},server:tl};let il=[],sl=0;const ol=new WeakMap,al=e=>{il=il.filter(t=>t!==e)};if(window.RTCPeerConnection){const $E=window.RTCPeerConnection;function GE(e){const t=new $E(e);il.push(t),ol.set(t,{index:sl++});const r=()=>{"closed"===t.connectionState&&(al(t),t.removeEventListener("connectionstatechange",r))};return t.addEventListener("connectionstatechange",r),t}GE.prototype=$E.prototype,window.RTCPeerConnection=GE}const cl=new WeakMap;const dl=(e=cl)=>Promise.all(il.map(t=>Td(void 0,void 0,void 0,function*(){let r=e.get(t);r||(r={ssrcToTrackId:{}},e.set(t,r));try{const e=yield t.getStats();let n=null;if(e.forEach(t=>{if(!("inbound-rtp"!==t.type&&"outbound-rtp"!==t.type||t.trackIdentifier||r.ssrcToTrackId[t.ssrc])){if(t.mediaSourceId){const n=e.get(t.mediaSourceId);n&&n.trackIdentifier&&(r.ssrcToTrackId[t.ssrc]=n.trackIdentifier)}if(!r.ssrcToTrackId[t.ssrc]&&t.trackId){const n=e.get(t.trackId);n&&n.trackIdentifier&&(r.ssrcToTrackId[t.ssrc]=n.trackIdentifier)}r.ssrcToTrackId[t.ssrc]||(n||(n=[]),n.push(t.ssrc))}}),n){const e=[...t.getSenders(),...t.getReceivers()];(yield Promise.all(e.map(e=>e.getStats()))).forEach((t,n)=>{t.forEach(t=>{"inbound-rtp"!==t.type&&"outbound-rtp"!==t.type||(r.ssrcToTrackId[t.ssrc]=e[n].track.id)})}),n.forEach(e=>{r.ssrcToTrackId[e]||(r.ssrcToTrackId[e]="?"+e)})}return[t,e,r]}catch(e){return nl.sendEvent("trackSsrcLookupFailed",{name:null==e?void 0:e.name,cause:null==e?void 0:e.cause,message:null==e?void 0:e.message}),[t,[],r]}}))),ll={id:"unknown",clientId:"unknown",audio:{enabled:!1,track:void 0},video:{enabled:!1,track:void 0},isAudioOnlyModeEnabled:!1,isLocalClient:!0,isPresentation:!1};function ul(e,t,r){return Td(this,arguments,void 0,function*(e,{logger:t,interval:r},n){const i=ul.bind(null,e,{interval:r,logger:t});try{const a=e.getClients(),c=a.find(e=>e.isLocalClient&&!e.isPresentation)||ll;let d=e.statsByView[c.id];d||(d={tracks:{},candidatePairs:{},pressure:null},e.statsByView[c.id]=d),d.pressure=e.lastPressureObserverRecord;if(Date.now()-e.lastUpdateTime<400)return n?e.statsByView:(e.subscriptions.forEach(t=>{var r;return null===(r=t.onUpdatedStats)||void 0===r?void 0:r.call(t,e.statsByView,a)}),void(e.nextTimeout=setTimeout(i,r)));if(e.lastUpdateTime=Date.now(),(yield dl()).forEach(([n,i,s])=>{const o=(e=>{var t;return null===(t=ol.get(e))||void 0===t?void 0:t.index})(n);void 0===o&&t.warn("Could not find index for PeerConnection"),"closed"===n.connectionState&&(i=new Map,al(n)),s.previousSSRCs=s.currentSSRCs||{},s.currentSSRCs={},i.forEach(t=>{var n,l;if("candidate-pair"===t.type&&/inprogress|succeeded/.test(t.state)){const a=null===(n=s._oldReport)||void 0===n?void 0:n.get(t.id),c=a?t.timestamp-a.timestamp:r,l=o+":"+t.id;let u=d.candidatePairs[l];u||(u={startTime:e.lastUpdateTime,id:l},d.candidatePairs[l]=u),function(e,t,r,n,i){const s=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0),o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.bitrateIn=8e3*s/n,e.bitrateOut=8e3*o/n,e.state=t.state,e.roundTripTime=t.currentRoundTripTime,e.requestsSent=t.requestsSent,e.responsesReceived=t.responsesReceived,e.requestsReceived=t.requestsReceived,e.responsesSent=t.responsesSent,e.availableOutgoingBitrate=t.availableOutgoingBitrate,e.availableIncomingBitrate=t.availableIncomingBitrate;const a=i.get(t.remoteCandidateId),c=i.get(t.localCandidateId);e.usingTurn=!1,c&&/relay/i.test(c.candidateType||"")&&(e.usingTurn=!0,e.turnProtocol=c.relayProtocol),a&&c&&(e.localEp=`${c.protocol}:${c.address||c.ip}:${c.port} ${c.candidateType} (${c.networkType})`,e.remoteEp=`${a.protocol}:${a.address||a.ip}:${a.port} ${a.candidateType}`)}(u,t,a,c,i),u.lastRtcStatsTime=e.lastUpdateTime}if("inbound-rtp"===t.type||"outbound-rtp"===t.type){const n=t.mediaType||t.kind,d=t.ssrc;let u=t.trackIdentifier||s.ssrcToTrackId[d],p=null===(l=s._oldReport)||void 0===l?void 0:l.get(t.id);if(p&&p.mediaSourceId!==t.mediaSourceId){const e=i.get(t.mediaSourceId);e&&e.trackIdentifier&&(u=e.trackIdentifier,s.ssrcToTrackId[d]=u)}const h=a.find(e=>{var t;return(null===(t=e[n].track)||void 0===t?void 0:t.id)===u})||c,f=h[n].track;if(!t.trackIdentifier&&s.ssrcToTrackId[d]&&(null==f?void 0:f.id)&&f.id!==s.ssrcToTrackId[d]&&(u=f.id,s.ssrcToTrackId[d]=f.id),s.currentSSRCs[d]=h.id,p){const e=i.get(t.transportId),r=s._oldReport.get(p.transportId);(r&&(null==e?void 0:e.selectedCandidatePairId)!==r.selectedCandidatePairId||t.bytesReceived<p.bytesReceived||t.bytesSent<p.bytesSent)&&(p=null)}const m=p?t.timestamp-p.timestamp:r,g=((e,t,r,n,i,s)=>{let o=e[n];o||(o={candidatePairs:{},tracks:{},startTime:t,updated:t},e[n]=o),o.updated=t;let a=o.tracks[i];a||(a={ssrcs:{},startTime:t,updated:t},o.tracks[i]=a),a.updated=t;let c=a.ssrcs[s];return c||(c={startTime:t,updated:t,pcIndex:r},a.ssrcs[s]=c),c.updated=t,c})(e.statsByView,e.lastUpdateTime,o,h.id,u,d);!function(e,t,r,n,i){if(e.codec)return;e.kind=t.kind||t.mediaType,e.ssrc=t.ssrc,e.direction="inbound-rtp"===t.type?"in":"out";const s=t.codecId&&i.get(t.codecId);e.codec=s&&[s.mimeType,s.channels&&`${s.channels}ch`,s.clockRate,s.payloadType,t.encoderImplementation||t.decoderImplementation,s.sdpFmtpLine].filter(Boolean).join(" "),e.mid=t.mid,e.rid=t.rid}(g,t,0,0,i),function(e,t,r,n,i){const s=(t.nackCount||0)-((null==r?void 0:r.nackCount)||0);if(e.nackCount=(e.nackCount||0)+s,e.nackRate=1e3*s/n,"in"===e.direction){const i=t.packetsReceived-((null==r?void 0:r.packetsReceived)||0);e.packetCount=(e.packetCount||0)+i,e.packetRate=1e3*i/n;const s=t.packetsLost-((null==r?void 0:r.packetsLost)||0);e.packetLossCount=(e.packetLossCount||0)+s,e.packetLossRate=1e3*s/n,e.lossRatio=s/(s+i)*1e3/n;const o=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesReceived&&(a=t.headerBytesReceived-((null==r?void 0:r.headerBytesReceived)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;if(e.bitrate=8e3*c/n,e.mediaRatio=o/c,"audio"===t.kind){const n=(t.fecBytesReceived||0)-((null==r?void 0:r.fecBytesReceived)||0);e.fecRatio=n/o}const d=(t.jitterBufferDelay||0)-((null==r?void 0:r.jitterBufferDelay)||0),l=(t.jitterBufferEmittedCount||0)-((null==r?void 0:r.jitterBufferEmittedCount)||0);e.jitter=l?d/l:0}else{const s=t.packetsSent-((null==r?void 0:r.packetsSent)||0);e.packetCount=(e.packetCount||0)+s,e.packetRate=1e3*s/n;const o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesSent&&(a=t.headerBytesSent-((null==r?void 0:r.headerBytesSent)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;e.bitrate=8e3*c/n,e.mediaRatio=o/c;const d=t.totalPacketSendDelay-((null==r?void 0:r.totalPacketSendDelay)||0);e.sendDelay=d/s;const l=t.retransmittedPacketsSent-((null==r?void 0:r.retransmittedPacketsSent)||0);if(e.retransRatio=l/s*1e3/n,t.remoteId){const r=i.get(t.remoteId);r&&(e.roundTripTime=r.roundTripTime||0,e.jitter=r.jitter||0,e.fractionLost=r.fractionLost||0)}}}(g,t,p,m,i),"video"===n&&function(e,t,r,n,i){e.width=t.frameWidth,e.height=t.frameHeight,e.qualityLimitationReason=t.qualityLimitationReason||"";const s=t.pliCount-((null==r?void 0:r.pliCount)||0);e.pliCount=(e.pliCount||0)+s,e.pliRate=1e3*s/n;const o=t.firCount-((null==r?void 0:r.firCount)||0);if(e.firCount=(e.firCount||0)+o,e.firRate=1e3*o/n,"in"===e.direction){const i=t.keyFramesDecoded-((null==r?void 0:r.keyFramesDecoded)||0);e.kfCount=(e.kfCount||0)+i,e.kfRate=1e3*i/n;const s=t.framesDecoded-((null==r?void 0:r.framesDecoded)||0);e.frameCount=(e.frameCount||0)+s;const o=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=o/s,e.fps=1e3*s/n}else{const s=t.keyFramesEncoded-((null==r?void 0:r.keyFramesEncoded)||0);e.kfCount=(e.kfCount||0)+s,e.kfRate=1e3*s/n;const o=t.framesEncoded-((null==r?void 0:r.framesEncoded)||0);e.frameCount=(e.frameCount||0)+o;const a=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=a/o,e.fps=1e3*o/n;const c=t.totalEncodeTime-((null==r?void 0:r.totalEncodeTime)||0);if(e.encodeTime=c/o,t.mediaSourceId){const r=i.get(t.mediaSourceId);r&&(e.sourceWidth=r.width||0,e.sourceHeight=r.height||0,e.sourceFps=r.framesPerSecond||0)}}}(g,t,p,m,i),"audio"===n&&function(e,t,r){const n=t.packetsDiscarded-((null==r?void 0:r.packetsDiscarded)||0);if(e.packetsDiscarded=(e.packetsDiscarded||0)+n,"in"===e.direction){const n=t.totalAudioEnergy-((null==r?void 0:r.totalAudioEnergy)||0),i=t.totalSamplesDuration-((null==r?void 0:r.totalSamplesDuration)||0);e.audioLevel=Math.sqrt(n/i);const s=t.totalSamplesReceived||0,o=t.concealmentEvents||0,a=s-((null==r?void 0:r.totalSamplesReceived)||0),c=t.concealedSamples||0,d=c-((null==r?void 0:r.concealedSamples)||0),l=(t.silentConcealedSamples||0)-((null==r?void 0:r.silentConcealedSamples)||0),u=(t.insertedSamplesForDeceleration||0)-((null==r?void 0:r.insertedSamplesForDeceleration)||0),p=(t.removedSamplesForAcceleration||0)-((null==r?void 0:r.removedSamplesForAcceleration)||0);e.audioSamples=s,e.audioConcealmentEvents=o,e.audioConcealedSamples=c,e.audioConcealment=d?d/a:0,e.audioSilentConcealment=l?l/a:0,e.audioAcceleration=p?p/a:0,e.audioDeceleration=u?u/a:0}}(g,t,p)}}),s._oldReport=i,Object.keys(s.previousSSRCs).filter(e=>!s.currentSSRCs[e]).forEach(t=>{const r=s.previousSSRCs[t];if(r){const n=e.statsByView[r];n&&Object.values(n.tracks).forEach(e=>{e.ssrcs[t]&&delete e.ssrcs[t]})}})}),s=e.statsByView,o=e.lastUpdateTime,Object.entries(s).forEach(([e,t])=>{void 0!==t.updated&&t.updated<o?delete s[e]:Object.entries(t.tracks).forEach(([e,r])=>{r.updated<o?delete t.tracks[e]:Object.entries(r.ssrcs).forEach(([e,t])=>{t.updated<o&&delete r.ssrcs[e]})})}),Object.entries((null==d?void 0:d.candidatePairs)||{}).forEach(([t,r])=>{const n=r.lastRtcStatsTime===e.lastUpdateTime;r.active=n,n||(r.state="old/inactive",r.inactiveFromTime?e.lastUpdateTime-r.inactiveFromTime>4e3&&delete d.candidatePairs[t]:r.inactiveFromTime=e.lastUpdateTime)}),n)return e.statsByView;e.subscriptions.forEach(t=>{var r;return null===(r=t.onUpdatedStats)||void 0===r?void 0:r.call(t,e.statsByView,a)})}catch(r){t.warn(r),e.numFailedStatsReports++,nl.sendEvent("collectStatsFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message})}var s,o;e.nextTimeout=setTimeout(i,r)})}const pl={};function hl(e,t=pl,r=window.document){e.forEach(({hostnamePattern:e,token:n})=>{const i=`${e}-${n}`;if(!t[i]&&e.test(r.location.hostname)){const e=r.createElement("meta");e.httpEquiv="origin-trial",e.content=n,r.head.append(e),t[i]=!0}})}const fl={sampleRate:1,originTrials:[{hostnamePattern:/hereby\.dev/,token:"AkSNPHJw6EK08X0QU7kORnK9NABzRLAC7dqfXOwk5JwFAQG4Ey7WxLXxsnhieCgC1QHUdevE2EFICy7uBGDANwUAAABqeyJvcmlnaW4iOiJodHRwczovL2hlcmVieS5kZXY6NDQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="},{hostnamePattern:/whereby\.com/,token:"Asc2wu8KpSx648i932NICteQDFcB05yl2QUUSHD7AQo8JGP2Fp6FF91TvYVJBsKGzLMH349rysPw5q9tqPC/PAUAAABqeyJvcmlnaW4iOiJodHRwczovL3doZXJlYnkuY29tOjQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="}]};const ml={currentMonitor:null,getClients:()=>[],lastUpdateTime:0,statsByView:{},subscriptions:[],numFailedStatsReports:0},gl={interval:2e3,logger:new Ld},vl=()=>{var e;return null===(e=ml.currentMonitor)||void 0===e?void 0:e.getUpdatedStats()};function bl(e,{interval:t,logger:r}){const n=ul.bind(null,e,{interval:t,logger:r});let i;try{i=function(e,{sampleRate:t,originTrials:r}=fl,n=globalThis.window){let i;if(hl(r),"PressureObserver"in n)return i=new n.PressureObserver(e,{sampleRate:t}),i.observe("cpu",{sampleInterval:1e3*t}),{stop:()=>{i.unobserve("cpu")}}}(t=>e.lastPressureObserverRecord=t.pop())}catch(e){r.warn("Failed to observe CPU pressure",e)}return setTimeout(n,t),{getUpdatedStats:()=>n(!0),stop:()=>{clearTimeout(e.nextTimeout),null==i||i.stop()}}}const yl="fetch_mediaserver_config",_l="start_screenshare",wl="stop_screenshare",Sl="audio_enabled",Cl="client_left",kl="mediaserver_config",Tl="new_client",Pl="screenshare_started",Rl="screenshare_stopped",El="room_joined",Ol="video_enabled",xl="ice_candidate",Il="ice_endofcandidates",Dl="ready_to_receive_offer",Ml="sdp_answer",jl="sdp_offer",Al="pending_client_left",Ll="media_quality_changed",Nl=new Ld;class Fl extends Ro{constructor(e){super(),this.reconnectThresholdInMs=0,this._socket=e,this._clients={},this._signalDisconnectTime=void 0,this.rtcManager=void 0,this.metrics={roomJoinedLate:0,pendingClientCanceled:0,evaluationFailed:0,roomJoined:0},e.on("disconnect",()=>{this._signalDisconnectTime=Date.now()}),e.on(El,e=>this._onRoomJoined(e)),e.on(Tl,e=>this._onNewClient(e)),e.on(Cl,e=>this._onClientLeft(e)),e.on(Al,e=>this._onPendingClientLeft(e)),e.on(Sl,e=>this._onAudioEnabled(e)),e.on(Ol,e=>this._onVideoEnabled(e)),e.on(Pl,e=>this._onScreenshareChanged(e,!0)),e.on(Rl,e=>this._onScreenshareChanged(e,!1))}_onRoomJoined(e){return Td(this,void 0,void 0,function*(){var t;if(this.reconnectThresholdInMs=.8*(e.disconnectTimeout||0),null==e?void 0:e.error)return void this.emit(El,e);if(!e.selfId)return void this.emit(El,e);const r=null===(t=e.room.clients.find(t=>e.selfId===t.id))||void 0===t?void 0:t.deviceId;if(!r)return void this.emit(El,e);if(!this._signalDisconnectTime)return this._resetClientState(e),e.room.clients=e.room.clients.filter(e=>!(e.deviceId===r&&e.isPendingToLeave)),void this.emit(El,e);const n=.8*e.disconnectTimeout;if(Date.now()-this._signalDisconnectTime>n)return this._resetClientState(e),this.emit(El,e),void this.metrics.roomJoinedLate++;e.room.clients=e.room.clients.filter(e=>!(e.deviceId===r&&e.isPendingToLeave));const i=yield vl();e.room.clients.forEach(t=>{var r;try{if(t.id===e.selfId)return;if(!this._clients[t.id])return void this._addClientToState(t);if(!(null===(r=this.rtcManager)||void 0===r?void 0:r.hasClient(t.id)))return;if(this._hasClientStateChanged({clientId:t.id,webcam:t.isVideoEnabled,mic:t.isAudioEnabled,screenShare:t.streams.length>1}))return;if(this._wasClientSendingMedia(t.id)&&!this._isClientMediaActive(i,t.id))return;t.mergeWithOldClientState=!0}catch(e){Nl.error("Failed to evaluate if we should merge client state %o",e),this.metrics.evaluationFailed++}}),e.room.clients.forEach(e=>{e.isPendingToLeave&&this._onPendingClientLeft({clientId:e.id})}),this.metrics.roomJoined++,this.emit(El,e)})}_onClientLeft(e){var t;const{clientId:r}=e,n=this._clients[r];n&&(clearTimeout(n.timeout),delete this._clients[r]),null===(t=this.rtcManager)||void 0===t||t.disconnect(r,null,e.eventClaim),this.emit(Cl,e)}_onPendingClientLeft(e){const{clientId:t}=e,r=this._clients[t];r?r.isPendingToLeave||(r.isPendingToLeave=!0,this._wasClientSendingMedia(t)&&(r.checkActiveMediaAttempts=0,this._abortIfNotActive(e))):Nl.warn(`client ${t} not found`)}_onNewClient(e){const{client:{id:t,deviceId:r}}=e,n=this._clients[t];if(n&&n.isPendingToLeave)return clearTimeout(n.timeoutHandler),n.isPendingToLeave=!1,void this.metrics.pendingClientCanceled++;this._getPendingClientsByDeviceId(r).forEach(e=>{clearTimeout(e.timeoutHandler),e.isPendingToLeave=void 0,this.emit(Cl,{clientId:e.clientId})}),this._addClientToState(e.client),this.emit(Tl,e)}_abortIfNotActive(e){return Td(this,void 0,void 0,function*(){const{clientId:t}=e;let r=this._clients[t];if(!(null==r?void 0:r.isPendingToLeave))return;if(r.checkActiveMediaAttempts++,r.checkActiveMediaAttempts>3)return;(yield this._checkIsActive(t))?r.timeoutHandler=setTimeout(()=>this._abortIfNotActive(e),500):(r=this._clients[t],(null==r?void 0:r.isPendingToLeave)&&(clearTimeout(r.timeoutHandler),delete this._clients[t],this.emit(Cl,e)))})}_checkIsActive(e){return Td(this,void 0,void 0,function*(){const t=yield vl();return this._isClientMediaActive(t,e)})}_isClientMediaActive(e,t){const r=null==e?void 0:e[t];let n=!1;return r&&Object.entries(r.tracks).forEach(([e,t])=>{"probator"!==e&&Object.values(t.ssrcs).forEach(e=>{(e.bitrate||0)>0&&(n=!0)})}),n}_onAudioEnabled(e){const{clientId:t,isAudioEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isAudioEnabled:r})}_onVideoEnabled(e){const{clientId:t,isVideoEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isVideoEnabled:r})}_onScreenshareChanged(e,t){const{clientId:r}=e;this._clients[r]=Object.assign(Object.assign({},this._clients[r]||{}),{isScreenshareEnabled:t})}_hasClientStateChanged({clientId:e,webcam:t,mic:r,screenShare:n}){const i=this._clients[e];if(!i)throw new Error(`Client ${e} not found in ReconnectManager state`);return t!==i.isVideoEnabled||(r!==i.isAudioEnabled||n!==i.isScreenshareEnabled)}_addClientToState(e){this._clients[e.id]=Object.assign(Object.assign({},this._clients[e.id]||{}),{isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled,isScreenshareEnabled:e.streams.length>1,deviceId:e.deviceId,isPendingToLeave:e.isPendingToLeave,clientId:e.id})}_wasClientSendingMedia(e){const t=this._clients[e];if(!t)throw new Error(`Client ${e} not found in ReconnectManager state`);return t.isAudioEnabled||t.isVideoEnabled||t.isScreenshareEnabled}_getPendingClientsByDeviceId(e){return Object.values(this._clients).filter(t=>t.deviceId===e&&t.isPendingToLeave)}_resetClientState(e){this._clients={},e.room.clients.forEach(t=>{t.id!==e.selfId&&this._addClientToState(t)})}}var Bl;const zl=null!==(Bl=ko.default)&&void 0!==Bl?Bl:ko;class Ul{constructor(e,t,r=!1){this._wasConnectedUsingWebsocket=!1,this._reconnectManager=null,this._socket=cc(e,Object.assign({path:"/protocol/socket.io/v4",randomizationFactor:.5,reconnectionDelay:250,reconnectionDelayMax:5e3,timeout:5e3,transports:["websocket"],withCredentials:!0},t)),this.joinRoomFinished=!1,this._socket.io.on("reconnect",()=>{this._socket.sendBuffer=[]}),this._socket.io.on("reconnect_attempt",()=>{var e;this._wasConnectedUsingWebsocket?(this._socket.io.opts.transports=["websocket"],"safari"!==(null===(e=zl.browserDetails)||void 0===e?void 0:e.browser)&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["websocket","polling"]}),r&&(this._reconnectManager=new Fl(this._socket)),this._socket.on("room_joined",e=>{const{error:t}=e;t||(this.joinRoomFinished=!0)}),this._socket.on("connect",()=>{"websocket"===this.getTransport()&&(this._wasConnectedUsingWebsocket=!0,this.noopKeepaliveInterval||(this.noopKeepaliveInterval=setInterval(()=>{try{this._socket.connected&&this._socket.io.engine.sendPacket("noop")}catch(e){}},2e3)))}),this._socket.on("disconnect",()=>{this.joinRoomFinished=!1,this.disconnectTimestamp=Date.now(),this.noopKeepaliveInterval&&(clearInterval(this.noopKeepaliveInterval),this.noopKeepaliveInterval=null)})}setRtcManager(e){this._reconnectManager&&(this._reconnectManager.rtcManager=e)}connect(){this.isConnected()||this.isConnecting()||this._socket.open()}disconnect(){this._socket.disconnect()}emit(e,...t){this._socket.emit.apply(this._socket,arguments)}getTransport(){var e,t,r,n;return null===(n=null===(r=null===(t=null===(e=this._socket)||void 0===e?void 0:e.io)||void 0===t?void 0:t.engine)||void 0===r?void 0:r.transport)||void 0===n?void 0:n.name}getManager(){return this._socket.io}isConnecting(){return this._socket&&this._socket.connecting}isConnected(){return this._socket&&this._socket.connected}on(e,t){const r=[El,Cl,Tl];return this._reconnectManager&&r.includes(e)?this._interceptEvent(e,t):(this._socket.on(e,t),()=>{this._socket.off(e,t)})}onEngineEvent(e,t){var r;return null===(r=this._socket.io)||void 0===r||r.on(e,t),()=>{var r;null===(r=this._socket.io)||void 0===r||r.off(e,t)}}once(e,t){this._socket.once(e,t)}off(e,t){this._socket.off(e,t)}_interceptEvent(e,t){return this._reconnectManager&&this._reconnectManager.on(e,t),()=>{this._reconnectManager&&this._reconnectManager.removeListener(e,t)}}getGlitchFreeMetrics(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.metrics}getReconnectThreshold(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.reconnectThresholdInMs}}const Vl=(e,t)=>{if(!t.useOnlyTURN)return;e.iceTransportPolicy="relay";const r={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[t.useOnlyTURN];r&&(e.iceServers=e.iceServers.filter(e=>e.url&&e.url.match(r)||e.urls&&(e.urls=(e.urls.some?e.urls:[e.urls]).filter(e=>e.match(r)),e.urls.length>0)?e:void 0))},$l=(e,t)=>{if(t&&e){const r=t,n=r.indexOf(":")>0?"":":443",i=":"+r+n;return e.map(e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,i)),t.urls&&(t.urls=t.urls.map(e=>e.replace(/:[^?]*/,i))),t})}return e},Gl=[{pattern:/^(?:([^.]+)[.])?(server:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?(localhost:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?((\d+[.]){3}:?\d*)$/,separator:"."},{pattern:/^(?:([^.]+)-)?(ip-[^.]*[.](?:hereby[.]dev|rfc1918[.]disappear[.]at)(?::\d+|))$/,separator:"-"},{pattern:/^(?:([^.]+)[.])?((:?[^.]+[.]){1,}[^.]+)$/,separator:"."}];function ql({host:e="whereby.com",protocol:t="https:"}={}){let r="",n=e,i=".";for(const{separator:t,pattern:s}of Gl){const o=s.exec(e);if(o){r=o[1]||"",n=o[2],i=t;break}}const s=r?`${r}${i}${n}`:n;return{domain:n,domainWithSeparator:`${i}${n}`,organizationDomain:s,organization:`${t}//${s}`,service:`${t}//${n}`,subdomain:r}}ql(window&&window.location);const Hl=new Ld,Wl={print:(...e)=>console.debug(e[0],...e.slice(1))};Hl.withDebugLogger(Wl);var Jl,Kl;const Ql=null!==(Jl=ko.default)&&void 0!==Jl?Jl:ko,Yl=new Ld,Xl=null===(Kl=Ql.browserDetails)||void 0===Kl?void 0:Kl.browser,Zl=Ql.browserDetails.version;function eu(e,t){let r=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),n=t.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/);r||(r=e.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/),n=t.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/));for(let e=1;e<r.length;e++)t=t.replace(new RegExp(n[e],"g"),r[e]);return t}function tu(e){return"firefox"!==Xl?e:ho.splitLines(e.trim()).map(e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e).join("\r\n")+"\r\n"}function ru(e){return function(e,t,r=!1,n=!1){var i,s;try{const o=Wt(e);if((null===(i=null==o?void 0:o.ext)||void 0===i?void 0:i.length)&&o.ext.length>0)return e;if((null==o?void 0:o.media.length)<1)return e;const a=null==o?void 0:o.media.flatMap(e=>e.ext||[]),c=(null===(s=a.find(e=>e.uri===t))||void 0===s?void 0:s.value)||[...new Set([0,15,...a.map(e=>e.value)])].sort((e,t)=>e-t).find((e,t,r)=>e+1!==r[t+1])+1;return o.media.forEach(e=>{var i;(r&&"audio"===e.type||n&&"video"===e.type)&&((null===(i=e.ext)||void 0===i?void 0:i.find(e=>e.uri===t))||(Array.isArray(e.ext)?e.ext.push({value:c,uri:t}):e.ext=[{value:c,uri:t}]))}),Ht(o)}catch(e){console.error("Error during addAbsCaptureTimeExtMap: ",e)}return e}(e,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",!0,!0)}function nu(e,t,r=console){const n=e.getSenders().find(e=>e.track&&"video"===e.track.kind);if(!n)return Promise.resolve();const i=n.getParameters();return i.encodings&&0===i.encodings.length?Promise.resolve():(i.encodings||(i.encodings=[{}]),0===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,n.setParameters(i).catch(e=>{r.error("setParameters err: ",e)}))}var iu;const su=null!==(iu=ko.default)&&void 0!==iu?iu:ko,ou=new Ld;class au{constructor({peerConnectionId:e,bandwidth:t,deprioritizeH264Encoding:r}){this.peerConnectionId=e,this.relayCandidateSeen=!1,this.serverReflexiveCandidateSeen=!1,this.publicHostCandidateSeen=!1,this.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this.pc=null,this.wasEverConnected=!1,this.connectionStatus=null,this.stats={totalSent:0,totalRecv:0},this.bandwidth=t||0,this.pending=[],this.isOperationPending=!1,this.streamIds=[],this.streams=[],this.earlyIceCandidates=[],this.afterConnected=new Promise(e=>{this.registerConnected=e}),this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._deprioritizeH264Encoding=r}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:r,shouldAddLocalVideo:n}){return this.peerConnectionConfig=r,this.shouldAddLocalVideo=n,this.clientId=e,this.pc=new RTCPeerConnection(r),this.signalingState=this.pc.signalingState,this.pc.addEventListener("signalingstatechange",()=>{if(this.signalingState!==this.pc.signalingState&&(this.signalingState=this.pc.signalingState,"stable"===this.pc.signalingState)){this.isOperationPending=!1;const e=this.pending.shift();e&&e.apply()}}),this.pc}addStream(e){this.streamIds.push(e.id),this.streams.push(e),RTCPeerConnection.prototype.addTrack?(e.getAudioTracks().forEach(t=>{this.pc.addTrack(t,e)}),e.getVideoTracks().forEach(t=>{this.pc.addTrack(t,e)})):this.pc.addStream(e)}addTrack(e,t){t||(t=this.streams[0]),null==t||t.addTrack(e),this.pc.addTrack(e,t)}removeTrack(e){this.streams[0].removeTrack(e);const t=this.pc.getSenders().find(t=>t.track===e);t&&this.pc.removeTrack(t)}removeStream(e){for(let t=0;t<this.streamIds.length;t++)this.streamIds[t]===e.id&&(this.streamIds.splice(t,1),this.streams.splice(t,1));this.pc&&(this.pc.removeTrack?e.getTracks().forEach(e=>{const t=this.pc.getSenders().find(t=>t.track===e);t&&this.pc.removeTrack(t)}):this.pc.removeStream&&this.pc.removeStream(e))}_setRemoteDescription(e){return this._deprioritizeH264Encoding&&(e.sdp=function(e){return ho.splitSections(e).map(e=>{if("video"!==ho.getKind(e))return e;const t=ho.matchPrefix(e,"a=rtpmap:").map(e=>ho.parseRtpMap(e)).filter(e=>/h264/i.test(e.name)).map(e=>""+e.payloadType);if(!t.length)return e;const r=ho.matchPrefix(e,"m=video")[0],n=/(\s\d+)+$/i.exec(r),i=n?n[0]:"",s=[...i.split(" ").filter(e=>e&&!t.includes(e)),...t].join(" "),o=r.replace(i," "+s);return e.replace(r,o)}).join("")}(e.sdp)),this.srdComplete=this.pc.setRemoteDescription(e),this.srdComplete.then(()=>{this.earlyIceCandidates.forEach(e=>this.pc.addIceCandidate(e)),this.earlyIceCandidates=[]})}handleOffer(e){if(!this.canModifyPeerConnection())return new Promise(t=>{this.pending.push(()=>this.handleOffer(e).then(t))});this.isOperationPending=!0;let t=e.sdp;t=function(e){return"safari"!==Xl&&("firefox"!==Xl||Zl&&Zl>=63||60===Zl)?e:ho.splitLines(e.trim()).filter(e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==ho.parseExtmap(e).uri).join("\r\n")+"\r\n"}(t),t=tu(t);const r={type:e.type,sdp:t};let n;return this._setRemoteDescription(r).then(()=>this.pc.createAnswer()).then(e=>(n=e,this.pc.setLocalDescription(e))).then(()=>nu(this.pc,this.bandwidth)).then(()=>n)}handleAnswer(e){const t=tu(e.sdp),r={type:e.type,sdp:t};return this._setRemoteDescription(r).then(()=>nu(this.pc,this.bandwidth),e=>{ou.warn("Could not set remote description from remote answer: ",e)})}addIceCandidate(e){this.srdComplete?this.srdComplete.then(()=>{var t;"closed"!==this.pc.signalingState&&("safari"===(null===(t=su.browserDetails)||void 0===t?void 0:t.browser)&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch(t=>{ou.warn("Failed to add ICE candidate ('%s'): %s",e?e.candidate:null,t)}))}):this.earlyIceCandidates.push(e)}canModifyPeerConnection(){return"stable"===this.pc.signalingState&&!this.isOperationPending}close(){const e=this.pc;if(e){e.oniceconnectionstatechange=null,e.onicecandidate=null,e.ontrack=null;try{e.close()}catch(e){ou.warn("failures during close of session",e)}}}hasConnectedPeerConnection(){return this.pc&&"connected"===this.pc.connectionState}replaceTrack(e,t){const r=this.pc;if(!r)return!1;const n=r.getSenders();if(e||(e=(n.find(e=>e.track&&e.track.kind===t.kind)||{}).track),window.RTCRtpSender&&window.RTCRtpSender.prototype.replaceTrack){if(e){const r=()=>{for(let r=0;r<n.length;r++){const i=n[r].track;if((null==i?void 0:i.id)===t.id)return Promise.resolve(t);if((null==i?void 0:i.id)===e.id)return n[r].replaceTrack(t)}return null};let i=r();if(i)return i;let s=null,o=null;i=new Promise((e,t)=>{s=e,o=t});let a=0,c=setInterval(()=>Td(this,void 0,void 0,function*(){const e=r();if(!e)return void(3<++a&&(clearInterval(c),c=null,o("No sender track to replace")));clearInterval(c),c=null;const t=yield e;s(t)}),1e3);return i}const i=this.streams.find(e=>e.getTracks().find(e=>e.id===t.id))||this.streams[0];return i?r.addTrack(t,i):Promise.reject(new Error("replaceTrack: No stream?"))}if(!this.canModifyPeerConnection())return void this.pending.push(()=>{this.replaceTrack(e,t)});this.isOperationPending=!0;const i=r.onnegotiationneeded;return r.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout(()=>{r.onnegotiationneeded=i},0),"offer"===r.localDescription.type?r.createOffer().then(e=>(e.sdp=eu(r.localDescription.sdp,e.sdp),r.setLocalDescription(e))).then(()=>this._setRemoteDescription(r.remoteDescription)):this._setRemoteDescription(r.remoteDescription).then(()=>r.createAnswer()).then(e=>(e.sdp=eu(r.localDescription.sdp,e.sdp),r.setLocalDescription(e)))}changeBandwidth(e){e!==this.bandwidth&&(this.canModifyPeerConnection()?(this.bandwidth=e,this.pc.localDescription&&""!==this.pc.localDescription.type&&nu(this.pc,this.bandwidth)):this.pending.push(()=>this.changeBandwidth(e)))}setAudioOnly(e,t=[]){this.pc.getTransceivers().filter(e=>{var r,n,i,s,o,a;return"recvonly"!==(null==e?void 0:e.direction)&&"video"===(null===(n=null===(r=null==e?void 0:e.receiver)||void 0===r?void 0:r.track)||void 0===n?void 0:n.kind)&&!t.includes(null===(s=null===(i=null==e?void 0:e.receiver)||void 0===i?void 0:i.track)||void 0===s?void 0:s.id)&&!t.includes(null===(a=null===(o=null==e?void 0:e.sender)||void 0===o?void 0:o.track)||void 0===a?void 0:a.id)}).forEach(t=>{t.direction=e?"sendonly":"sendrecv"})}}const cu=400;var du;const lu=null!==(du=ko.default)&&void 0!==du?du:ko;const uu="client_connection_status_changed",pu="stream_added",hu="rtc_manager_created",fu="rtc_manager_destroyed",mu="local_stream_track_added",gu="local_stream_track_removed",vu="connecting",bu="connection_failed",yu="connection_successful",_u="connection_disconnected",wu="camera",Su="screen_share";var Cu,ku,Tu,Pu="connection_blocked_by_network",Ru="ice_ipv6_seen",Eu="ice_mdns_seen",Ou="ice_no_public_ip_gathered",xu="ice_no_public_ip_gathered_3sec",Iu="ice_restart",Du="microphone_not_working",Mu="microphone_stopped_working",ju="camera_stopped_working",Au="new_pc",Lu="sfu_connection_open",Nu="sfu_connection_closed",Fu="sfu_connection_info",Bu="dominant_speaker",zu="pc_sld_failure",Uu="pc_on_answer_failure",Vu="pc_on_offer_failure";const $u=null!==(Cu=ko.default)&&void 0!==Cu?Cu:ko,Gu=new Ld,qu=class{constructor(e,t){this.id=""+e,this.type=t,this.isEnabled=!0,this.hasSupportForAutoSuperSize=!1,this.isAudioEnabled=!0,this.isVideoEnabled=!0,this.status=vu,this.stream=null,this.streamId=null}setup(e){return this.stream=e,this.streamId=e.id,this.setVideoEnabled(this.isVideoEnabled&&e.getVideoTracks().length>0),this.setAudioEnabled(this.isAudioEnabled&&e.getAudioTracks().length>0),this}setStatus(e){return this.status=e,this}setVideoEnabled(e){this.isVideoEnabled=e,this.stream&&this.stream.getVideoTracks().forEach(t=>{t.enabled=e})}setAudioEnabled(e){this.isAudioEnabled=e,this.stream&&this.stream.getAudioTracks().forEach(t=>{t.enabled=e})}static getCameraId(){return"0"}static getTypeFromId(e){return"0"===""+e?wu:Su}}.getCameraId(),Hu=null===(ku=$u.browserDetails)||void 0===ku?void 0:ku.browser,Wu=$u.browserDetails.version;"firefox"===Hu&&$u.browserShim&&"shimGetDisplayMedia"in $u.browserShim&&(null===(Tu=$u.browserShim)||void 0===Tu||Tu.shimGetDisplayMedia(window,"screen"));let Ju=!1;"chrome"===Hu&&window.document.addEventListener("beforeunload",()=>{Ju=!0});class Ku{constructor({selfId:e,room:t,emitter:r,serverSocket:n,webrtcProvider:i,features:s}){const{name:o,session:a,iceServers:c,turnServers:d,sfuServer:l,mediaserverConfigTtlSeconds:u}=t;this._selfId=e,this._roomName=o,this._roomSessionId=a&&a.id,this.peerConnections={},this.localStreams={},this.enabledLocalStreamIds=[],this._screenshareVideoTrackIds=[],this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction=null,this._emitter=r,this._serverSocket=n,this._webrtcProvider=i,this._features=s||{},this._isAudioOnlyMode=!1,this._closed=!1,this.skipEmittingServerMessageCount=0,this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._audioTrackOnEnded=()=>{nl.sendEvent("audio_ended",{unloading:Ju}),this._emit(Mu,{})},this._videoTrackOnEnded=()=>{nl.sendEvent("video_ended",{unloading:Ju}),this._emit(ju,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:u}),this.totalSessionsCreated=0}numberOfPeerconnections(){return Object.keys(this.peerConnections).length}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._roomName===t&&r===!!this._sfuServer}supportsScreenShareAudio(){return!0}addNewStream(e,t,r,n,i=[]){if(t!==this.localStreams[e]){if(this._addLocalStream(e,t),e===qu){this._addStreamToPeerConnections(t);const e=t.getAudioTracks()[0],r=t.getVideoTracks()[0];if(e){e.effectTrack||this._monitorAudioTrack(e);const t=i.find(e=>"audio"===e.kind);t&&this._monitorAudioTrack(t)}if(r){r.effectTrack||this._monitorVideoTrack(r);const e=i.find(e=>"video"===e.kind);e&&this._monitorVideoTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const n=e=>{const{enable:t,track:r}=e.detail;this._handleStopOrResumeVideo({enable:t,track:r})};return t.addEventListener("stopresumevideo",n),void(this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",n)})}this._screenshareVideoTrackIds.push(t.getVideoTracks()[0].id),this._shareScreen(e,t)}}replaceTrack(e,t){return"audio"!==t.kind||t.effectTrack||this._monitorAudioTrack(t),"video"!==t.kind||t.effectTrack||this._monitorVideoTrack(t),this._replaceTrackToPeerConnections(e,t)}close(){this._closed=!0,this.disconnectAll()}disconnectAll(){Object.keys(this.peerConnections).forEach(e=>{this.disconnect(e)}),this.peerConnections={},this._socketListenerDeregisterFunctions.forEach(e=>{e()}),this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null)}fixChromeAudio(e){if("chrome"!==Hu)return;const t=this._getLocalCameraStream(),r=t.getAudioTracks()[0];return r&&"ended"===r.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then(e=>{const n=e.getAudioTracks()[0];return n.enabled=r.enabled,t.removeTrack(r),t.addTrack(n),this.replaceTrack(r,n)}):void 0}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on(kl,e=>{e.error?Gu.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)}),this._serverSocket.on(Dl,e=>{this._connect(e.clientId)}),this._serverSocket.on(xl,e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):Gu.warn("No RTCPeerConnection on ICE_CANDIDATE",e)}),this._serverSocket.on(Il,e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):Gu.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)}),this._serverSocket.on(jl,e=>{var t,r;const n=this._getSession(e.clientId);if(!n)return void Gu.warn("No RTCPeerConnection on SDP_OFFER",e);const i=this._transformIncomingSdp(e.message,n.pc);null===(r=(t=n.handleOffer(i).then(t=>{this._emitServerEvent(Ml,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})})).catch)||void 0===r||r.call(t,e=>{this._emit(Vu,e)})}),this._serverSocket.on(Ml,e=>{var t,r;const n=this._getSession(e.clientId);if(!n)return void Gu.warn("No RTCPeerConnection on SDP_ANSWER",e);const i=this._transformIncomingSdp(e.message,n.pc);null===(r=null===(t=n.handleAnswer(i))||void 0===t?void 0:t.catch)||void 0===r||r.call(t,e=>{this._emit(Uu,e)})}),this._serverSocket.on(El,e=>{var t,r;if(null==e?void 0:e.error)return;if(null!==(r=null===(t=null==e?void 0:e.room)||void 0===t?void 0:t.sfuServer)&&void 0!==r&&r||!this._wasScreenSharing)return;const n=Object.keys(this.localStreams).find(e=>e!==qu);if(!n)return;const i=this.localStreams[n];if(!i)return void Gu.warn("screenshare stream %s not found",n);const s=i.getAudioTracks().length>0;this._emitServerEvent(_l,{streamId:n,hasAudioTrack:s})})]}sendAudioMutedStats(e){nl.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){nl.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){nl.sendEvent(e,t)}rtcStatsDisconnect(){nl.server.close()}rtcStatsReconnect(){nl.server.connected||nl.server.connect()}setAudioOnly(e){this._isAudioOnlyMode=e,this._forEachPeerConnection(e=>{e.hasConnectedPeerConnection()&&this._withForcedRenegotiation(e,()=>e.setAudioOnly(this._isAudioOnlyMode,this._screenshareVideoTrackIds))})}setRemoteScreenshareVideoTrackIds(e=[]){const t=this._getFirstLocalNonCameraStream();this._screenshareVideoTrackIds=[...(null==t?void 0:t.track)?[t.track.id]:[],...e]}setRoomSessionId(e){this._roomSessionId=e}_setConnectionStatus(e,t,r){const n=e.connectionStatus;n!==t&&e.peerConnectionId!==this._selfId&&(n===_u&&t===vu||(e.connectionStatus=t,setTimeout(()=>{this._emit(uu,{streamIds:e.streamIds,clientId:r,status:t,previous:n})},0)))}_setJitterBufferTarget(e){try{e.getReceivers().forEach(e=>{e.jitterBufferTarget=cu,e.playoutDelayHint=.4})}catch(e){Gu.error("Error during setting jitter buffer target:",e)}}_emitServerEvent(e,t){this._closed?Gu.warn("RtcManager closed. Will not send event",e,t):this._features.awaitJoinRoomFinished&&!this._serverSocket.joinRoomFinished?(nl.sendEvent("skip_emitting_server_message",{eventName:e}),this.skipEmittingServerMessageCount++):this._serverSocket.emit(e,t)}_emit(e,t){this._emitter.emit(e,t)}_addEnabledLocalStreamId(e){this.enabledLocalStreamIds.push(e)}_deleteEnabledLocalStreamId(e){const t=this.enabledLocalStreamIds.indexOf(e);-1!==t&&this.enabledLocalStreamIds.splice(t,1)}_getSession(e){return e in this.peerConnections?this.peerConnections[e]:null}_getOrCreateSession(e,t){let r=this.peerConnections[e];if(void 0===r){const n="safari"===Hu&&Wu&&Wu>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=r=new au({peerConnectionId:e,bandwidth:t,deprioritizeH264Encoding:n}),this.totalSessionsCreated++}return r}_getLocalCameraStream(){return this.localStreams[qu]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter(e=>e!==qu)}_isScreensharingLocally(){return this._getNonLocalCameraStreamIds().length>0}_getFirstLocalNonCameraStream(){const e=this._getNonLocalCameraStreamIds();return 0===e.length?null:this.localStreams[e[0]]}_transformIncomingSdp(e,t){return{type:e.type,sdp:e.sdpU}}_transformOutgoingSdp(e){return{type:e.type,sdpU:e.sdp}}_createSession({clientId:e,initialBandwidth:t,isOfferer:r,peerConnectionId:n,shouldAddLocalVideo:i}){if(!n)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const s=this._getOrCreateSession(n,t),o={optional:[]};"chrome"===Hu&&o.optional.push({googCpuOveruseDetection:!0}),o.optional.push({rtcStatsRoomSessionId:this._roomSessionId}),o.optional.push({rtcStatsClientId:this._selfId}),o.optional.push({rtcStatsPeerId:n}),o.optional.push({rtcStatsConferenceId:this._roomName});const a={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};var c,d;a.iceServers=$l(a.iceServers,this._features.turnServerOverrideHost),c=a,(d=this._features).addGoogleStunServers&&(c.iceServers=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun2.l.google.com:19302"},...c.iceServers]),d.addCloudflareStunServers&&(c.iceServers=[{urls:"stun:stun.cloudflare.com:3478"},{urls:"stun:stun.cloudflare.com:53"},...c.iceServers]),Vl(a,this._features),"chrome"===Hu&&(a.sdpSemantics="unified-plan");const l=s.setAndGetPeerConnection({constraints:o,peerConnectionConfig:a,shouldAddLocalVideo:i,clientId:e});setTimeout(()=>this._emit(Au),0),l.ontrack=t=>{const r=t.streams[0];"default"===r.id&&0===r.getAudioTracks().length||-1===s.streamIds.indexOf(r.id)&&(s.streamIds.push(r.id),this._emit(pu,{clientId:e,stream:r}),s.connectionStatus===yu&&setTimeout(()=>{this._emit(uu,{streamIds:s.streamIds,clientId:e,status:s.connectionStatus,previous:vu})},0))},l.oniceconnectionstatechange=()=>{let t;const r=s.connectionStatus;switch(l.iceConnectionState){case"checking":t=vu;break;case"connected":case"completed":t=yu,s.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach(e=>{"function"==typeof e&&e()}),this._pendingActionsForConnectedPeerConnections=[]),!s.wasEverConnected&&(l.iceConnectionState.match(/connected|completed/)||"chrome"===Hu&&l.localDescription&&"answer"===l.localDescription.type)&&(s.wasEverConnected=!0),this._isAudioOnlyMode&&s.setAudioOnly(!0,this._screenshareVideoTrackIds),s.registerConnected();break;case"disconnected":t=_u,setTimeout(()=>{"disconnected"===l.iceConnectionState&&this._maybeRestartIce(e,s)},2e3);break;case"failed":t=bu,r!==t&&this._maybeRestartIce(e,s),null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(Pu);break;default:return}this._setConnectionStatus(s,t,e)},l.onconnectionstate=()=>{switch(l.connectionState){case"connected":setTimeout(()=>{(function(e){var t,r;if("chrome"!==(null===(t=lu.browserDetails)||void 0===t?void 0:t.browser)||(null===(r=lu.browserDetails)||void 0===r?void 0:r.browser)<58||"closed"===e.signalingState)return Promise.resolve(!1);const n=e.getSenders().some(e=>e.track&&"audio"===e.track.kind),i=e.getReceivers().some(e=>e.track&&"audio"===e.track.kind);return e.getStats(null).then(e=>{let t=!1;return e.forEach(e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!n?"inbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!i||0===e.bytesReceived&&(t="inbound"):0===e.bytesSent&&(t="outbound")}),t})})(s.pc).then(t=>{!1!==t&&this._emit(Du,{failureDirection:t,clientId:e})})},3e3),s.registerConnected();break;case"failed":const t=bu;null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(Pu),this._setConnectionStatus(s,t,e)}};const u=this.localStreams[qu];return i&&u&&s.addStream(u),i&&Object.keys(this.localStreams).forEach(e=>{if(e===qu)return;const t=this.localStreams[e];r?s.addStream(t):s.afterConnected.then(()=>{this._emitServerEvent(_l,{receiverId:s.clientId,streamId:t.id,hasAudioTrack:!!t.getAudioTracks().length}),this._withForcedRenegotiation(s,()=>s.addStream(t))})}),s}_cleanup(e){const t=this._getSession(e);t?(t.close(),delete this.peerConnections[e]):Gu.warn("No RTCPeerConnection in RTCManager.disconnect()",e)}_forEachPeerConnection(e){Object.values(this.peerConnections).forEach(t=>{e(t)})}_addStreamToPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.addStream(e))})}_addTrackToPeerConnections(e,t){this._forEachPeerConnection(r=>{this._withForcedRenegotiation(r,()=>r.addTrack(e,t))})}_replaceTrackToPeerConnections(e,t){const r=[];return this._forEachPeerConnection(n=>{if(!n.hasConnectedPeerConnection()){Gu.info("Session doesn't have a connected PeerConnection, adding pending action!");const i=this._pendingActionsForConnectedPeerConnections;if(!i)return void Gu.warn("No pending action is created to replace track, because the pending actions array is null");const s=new Promise((r,s)=>{i.push(()=>{const i=n.replaceTrack(e,t);if(!i)return Gu.error("replaceTrack returned false!"),void s("ReplaceTrack returned false");i.then(e=>r(e)).catch(e=>s(e))})});return void r.push(s)}const i=n.replaceTrack(e,t);i?r.push(i):Gu.error("replaceTrack returned false!")}),Promise.all(r)}_removeStreamFromPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.removeStream(e))})}_removeTrackFromPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.removeTrack(e))})}_addLocalStream(e,t){this._addEnabledLocalStreamId(e),this.localStreams[e]=t}_removeLocalStream(e){delete this.localStreams[e],this._deleteEnabledLocalStreamId(e)}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,mediaserverConfigTtlSeconds:n}){this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._mediaserverConfigTtlSeconds=n,this._clearMediaServersRefresh(),n&&(this._fetchMediaServersTimer=setTimeout(()=>this._emitServerEvent(yl),1e3*n))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_connect(e){let t=this._getSession(e),r=t&&t.bandwidth||0;return t?(Gu.warn("Replacing peer session",e),this._cleanup(e)):r=this._changeBandwidthForAllClients(!0),t=this._createP2pSession({clientId:e,initialBandwidth:r,shouldAddLocalVideo:!0,isOfferer:!0}),this._negotiatePeerConnection(e,t),Promise.resolve(t)}_maybeRestartIce(e,t){const r=t.pc;"disconnected"!==r.iceConnectionState&&"failed"!==r.iceConnectionState||"offer"===r.localDescription.type&&(t.wasEverConnected=!1,t.relayCandidateSeen=!1,t.serverReflexiveCandidateSeen=!1,t.publicHostCandidateSeen=!1,t.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this._emit(Iu),this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_setCodecPreferences(e){return Td(this,void 0,void 0,function*(){const{p2pAv1On:t,redOn:r}=this._features;try{const n=e.getTransceivers().filter(e=>{var t,r;return"audio"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)});n.forEach(e=>{if(void 0===RTCRtpSender.getCapabilities)return;const t=RTCRtpSender.getCapabilities("audio");for(let e=0;e<t.codecs.length;e++)if(r&&"audio/red"===t.codecs[e].mimeType.toLowerCase()){t.codecs.unshift(t.codecs.splice(e,1)[0]);break}void 0!==e.setCodecPreferences&&e.setCodecPreferences(t.codecs)});const i=e.getTransceivers().filter(e=>{var t,r;return"video"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)});yield Promise.all(i.map(e=>Td(this,void 0,void 0,function*(){if(void 0===RTCRtpReceiver.getCapabilities)return;if(void 0===e.setCodecPreferences)return;const r=RTCRtpReceiver.getCapabilities("video");r.codecs=yield Yd(r.codecs,{av1On:t}),e.setCodecPreferences(r.codecs)})))}catch(e){Gu.error("Error during setting setCodecPreferences:",e)}})}_negotiatePeerConnection(e,t,r){if(!t)return void Gu.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const n=t.pc;if(!t.canModifyPeerConnection())return void t.pending.push(()=>{this._negotiatePeerConnection(e,t,r)});t.isOperationPending=!0;const{redOn:i,rtpAbsCaptureTimeOn:s,cleanSdpOn:o}=this._features;this._setCodecPreferences(n).then(()=>n.createOffer(r||this.offerOptions).then(t=>{s&&(t.sdp=ru(t.sdp)),"firefox"===Hu&&(t.sdp=function(e,t){var r,n;try{const i=Wt(e);if(Array.isArray(null==i?void 0:i.media)){const e=i.media.find(e=>"audio"===e.type);if(Array.isArray(null==e?void 0:e.rtp)){const n=e.rtp;for(let i=0;i<n.length;i++)if(t&&"red"===n[i].codec){const t=null===(r=e.payloads)||void 0===r?void 0:r.split(" "),s=null==t?void 0:t.indexOf(""+n[i].payload);s&&-1!==s&&s>=0&&(null==t||t.unshift(t.splice(s,1)[0]),e.payloads=null==t?void 0:t.join(" "))}}const s=i.media.find(e=>"video"===e.type);if(Array.isArray(null==s?void 0:s.rtp)){const e=s.rtp;for(let t=0;t<e.length;t++)if("VP9"===e[t].codec){const r=null===(n=s.payloads)||void 0===n?void 0:n.split(" "),i=null==r?void 0:r.indexOf(""+e[t].payload);i&&-1!==i&&i>=0&&(null==r||r.unshift(r.splice(i,1)[0]),s.payloads=null==r?void 0:r.join(" "))}}}return Ht(i)}catch(e){Yl.error("setCodecPreferenceSDP error:",e)}}(t.sdp,i)),o&&(t.sdp=function(e){try{const t=Wt(e);return t.media.forEach(e=>{const t={};e.payloads&&(e.payloads=(""+e.payloads).split(" ").filter(e=>!t[e]&&(t[e]=!0)).join(" "));const r={};e.rtp=e.rtp.filter(e=>!e.payload||t[e.payload]&&!r[e.payload]&&(r[e.payload]=!0));const n={};e.fmtp&&(e.fmtp=e.fmtp.filter(e=>!e.payload||t[e.payload]&&!n[e.payload]&&(n[e.payload]=!0)));const i={};e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter(e=>!e.payload||t[e.payload]&&!i[e.payload+e.type+e.subtype]&&(i[e.payload+e.type+e.subtype]=!0)))}),Ht(t)}catch(e){}return e}(t.sdp)),n.setLocalDescription(t).catch(e=>{throw Gu.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e),this._emit(zu,e),e}).then(()=>{this._emitServerEvent(jl,{receiverId:e,message:this._transformOutgoingSdp(t)})})}).catch(e=>{Gu.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))}_withForcedRenegotiation(e,t){const r=e.pc,n=r.onnegotationneeded;r.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout(()=>r.onnegotiationneeded=n,0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);const r=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:0,2:384,3:256,4:192,5:128,6:128,7:64}[t];return void 0===r?0:(this._forEachPeerConnection(e=>{e.changeBandwidth(r)}),r)}_createP2pSession({clientId:e,initialBandwidth:t,shouldAddLocalVideo:r=!1,isOfferer:n=!1}){const i=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:r,isOfferer:n}),s=i.pc;this._features.increaseIncomingMediaBufferOn&&this._setJitterBufferTarget(s);const o=this.localStreams[qu];return r&&o&&!o.getVideoTracks().length&&this._stoppedVideoTrack&&s.addTrack(this._stoppedVideoTrack,o),s.onicegatheringstatechange=e=>{switch(e.target.iceGatheringState){case"gathering":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=setTimeout(()=>{i.publicHostCandidateSeen||i.relayCandidateSeen||i.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState&&"completed"===s.iceConnectionState||this._emit(xu)},3e3);break;case"complete":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=void 0}},s.onicecandidate=t=>{var r,n;if(t.candidate){switch(null===(r=t.candidate)||void 0===r?void 0:r.type){case"host":const e=null===(n=null==t?void 0:t.candidate)||void 0===n?void 0:n.address;try{if(jd.v4({exact:!0}).test(e)){fd(e).isPublicIp&&(i.publicHostCandidateSeen=!0)}else if(jd.v6({exact:!0}).test(e.replace(/^\[(.*)\]/,"$1"))){const t=new dc.Address6(e.replace(/^\[(.*)\]/,"$1"));i.ipv6HostCandidateSeen=!0,"Global"===t.getScope()&&(i.publicHostCandidateSeen=!0),t.isTeredo()&&(i.ipv6HostCandidateTeredoSeen=!0),t.is6to4()&&(i.ipv6HostCandidate6to4Seen=!0)}else{const t=e.replace(/.local/,"");t&&_d(t,4)&&(i.mdnsHostCandidateSeen=!0)}}catch(e){Gu.info("Error during parsing candidates! Error: ",{error:e})}break;case"srflx":i.serverReflexiveCandidateSeen||(i.serverReflexiveCandidateSeen=!0);break;case"relay":case"relayed":i.relayCandidateSeen||(i.relayCandidateSeen=!0)}this._emitServerEvent(xl,{receiverId:e,message:t.candidate})}else this._emitServerEvent(Il,{receiverId:e}),i.publicHostCandidateSeen||i.relayCandidateSeen||i.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState||"completed"===s.iceConnectionState||this._emit(Ou),i.ipv6HostCandidateSeen&&this._emit(Ru,{teredoSeen:i.ipv6HostCandidateTeredoSeen,sixtofourSeen:i.ipv6HostCandidate6to4Seen}),i.mdnsHostCandidateSeen&&this._emit(Eu)},s.onnegotiationneeded=()=>{"new"!==s.iceConnectionState&&i.connectionStatus&&this._negotiatePeerConnection(e,i)},i}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:r}){let n=this._getSession(t);if(n&&e!==t)return n;let i=n&&n.bandwidth||0;return n?(Gu.warn("Replacing peer session",t),this._cleanup(t)):i=this._changeBandwidthForAllClients(!0),n=this._createP2pSession({clientId:t,initialBandwidth:i,shouldAddLocalVideo:!!r,isOfferer:!1}),this._emitServerEvent(Dl,{receiverId:t}),n}disconnect(e){this._cleanup(e),this._changeBandwidthForAllClients(!1);0===this.numberOfPeerconnections()&&setTimeout(()=>{0===this.numberOfPeerconnections()&&this.rtcStatsDisconnect()},6e4)}updateStreamResolution(){}stopOrResumeAudio(){}_handleStopOrResumeVideo({enable:e,track:t}){e?this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,t),delete this._stoppedVideoTrack):this._addTrackToPeerConnections(t):this._stoppedVideoTrack=t}stopOrResumeVideo(e,t){var r;if(["chrome","safari"].includes(Hu))if(!1===t){const n="ended"===(null===(r=e.getVideoTracks().find(e=>!e.enabled))||void 0===r?void 0:r.readyState)?0:5e3;setTimeout(()=>{e.getVideoTracks().forEach(r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emit(gu,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))})},n)}else if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;if(!r)return;navigator.mediaDevices.getUserMedia({video:r}).then(r=>{const n=r.getVideoTracks()[0];e.addTrack(n),this._monitorVideoTrack(n),this._emit(mu,{streamId:e.id,tracks:[n],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:n})})}}_shareScreen(e,t){this._emitServerEvent(_l,{streamId:e,hasAudioTrack:!!t.getAudioTracks().length}),this._wasScreenSharing=!0,this._addStreamToPeerConnections(t)}removeStream(e,t,r){this._removeLocalStream(e),this._removeStreamFromPeerConnections(t),this._wasScreenSharing=!1,this._emitServerEvent(wl,{streamId:e,requestedByClientId:r})}hasClient(e){return Object.keys(this.peerConnections).includes(e)}}var Qu=Object.freeze({__proto__:null,KalmanFilter:class{constructor({R:e=.01,Q:t=2,A:r=1.1,B:n=1,C:i=1.2}={R:.01,Q:2,A:1.1,B:1,C:1.2}){this.R=e,this.Q=t,this.A=r,this.C=i,this.B=n,this.cov=NaN,this.x=NaN}filter(e,t=0){if(isNaN(this.x))this.x=1/this.C*e,this.cov=1/this.C*this.Q*(1/this.C);else{const r=this.predict(t),n=this.uncertainty(),i=n*this.C*(1/(this.C*n*this.C+this.Q));this.x=r+i*(e-this.C*r),this.cov=n-i*this.C*n}return this.x}predict(e=0){return this.A*this.x+this.B*e}uncertainty(){return this.A*this.cov*this.A+this.R}lastMeasurement(){return this.x}setMeasurementNoise(e){this.Q=e}setProcessNoise(e){this.R=e}},calculateStd:e=>{const t=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,r)=>e.concat(Math.pow(r-t,2)),[]).reduce((e,t)=>e+t,0)/e.length},createACFCalculator:()=>{let e=-1,t=0,r=0;return n=>{const i=n.reduce((e,t)=>e+t,0)/n.length;if(e=e<0?i:.95*e+.05*i,++r<2)return t=i,0;const s=(i-e)*(t-e);return t=i,s}},standardDeviation:e=>{const t=e.reduce((e,t)=>e+t,0)/e.length;return{mean:t,SD:Math.sqrt(e.reduce((e,r)=>e+Math.pow(r-t,2),0)/e.length)}},variance:(e,t=!1)=>{const r=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,t)=>e.concat(Math.pow(t-r,2)),[]).reduce((e,t)=>e+t,0)/(e.length-(t?0:1))}});const Yu={minDecibels:-80,maxDecibels:-10,smoothingTimeConstant:.8,aggSize:1,sampleRate:10,reportRate:2,bins:32,bands:[[0,1,2,3],[4,5,6,7]],separateTrack:{autoGainControl:!1,noiseSupression:!1},binFormula:"bin",scoreFormula:"300 * bands[1].avg / Math.max(bands[1].avg + bands[0].avg, 0.01)",outFormula:"score"},Xu=new Ld;const Zu=new Ld,ep=Object.freeze({ok:"ok",warning:"warning",critical:"critical"});class tp extends Ro{constructor(){super(),this._clients={},this._producers={},this._startMonitor()}close(){clearInterval(this._intervalHandle),delete this._intervalHandle,this._producers={},this._clients={}}_startMonitor(){this._intervalHandle=setInterval(()=>{Object.entries(this._producers).forEach(([e,t])=>{this._evaluateClient(e,t)})},600)}_evaluateClient(e,t){this._clients[e]||(this._clients[e]={audio:{currentQuality:ep.ok,trend:[]},video:{currentQuality:ep.ok,trend:[]}}),this._evaluateProducer(e,Object.values(t).filter(e=>"audio"===e.kind),"audio"),this._evaluateProducer(e,Object.values(t).filter(e=>"video"===e.kind),"video")}_evaluateProducer(e,t,r){if(0===t.length)return;const n=t.reduce((e,t)=>e+t.score,0)/t.length,i=this._evaluateScore(n);this._updateTrend(i,this._clients[e][r])&&this.emit(Ll,{clientId:e,kind:r,quality:i})}_updateTrend(e,t){return t.trend.push(e),t.trend.length>3&&t.trend.shift(),!(e===t.currentQuality||!t.trend.every(e=>e!==t.currentQuality))&&(t.currentQuality=e,!0)}addProducer(e,t){e&&t&&"string"==typeof e&&"string"==typeof t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Zu.warn("Missing clientId or producerId")}removeProducer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addConsumer(e,t){e&&t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Zu.warn("Missing clientId or consumerId")}removeConsumer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addProducerScore(e,t,r,n){Array.isArray(n)&&0!==n.length&&!n.some(e=>!e||!e.hasOwnProperty("score")||"number"!=typeof e.score||isNaN(e.score))?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(n.map(e=>e.score))}:Zu.warn("Unexpected producer score format")}addConsumerScore(e,t,r,n){n&&n.hasOwnProperty("producerScores")&&Array.isArray(n.producerScores)?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(n.producerScores)}:Zu.warn("Unexpected consumer score format")}_evaluateScore(e){return e<=9&&e>7?ep.warning:e<=7&&e>0?ep.critical:ep.ok}_calcAvgProducerScore(e){try{if(!Array.isArray(e)||0===e.length)return 0;let t=0,r=0;return e.forEach(e=>{e>0&&(t+=e,r++)}),0===t||0===r?0:t/r}catch(e){return Zu.error(e),0}}}class rp{static parse(e){let t;try{t=JSON.parse(e)}catch(e){return}if("object"==typeof t&&!Array.isArray(t))return t.request?rp._handleRequest(t):t.response?rp._handleResponse(t):t.message?rp._handleMessage(t):void 0}static _handleRequest(e){const t={request:!0};if("string"==typeof e.method&&"number"==typeof e.id)return t.id=e.id,t.method=e.method,t.data=e.data||{},t}static _handleResponse(e){const t={response:!0};if("number"==typeof e.id)return t.id=e.id,e.ok?(t.ok=!0,t.data=e.data||{}):(t.ok=!1,t.errorCode=e.errorCode,t.errorReason=e.errorReason),t}static _handleMessage(e){const t={message:!0};if("string"==typeof e.method)return t.method=e.method,t.data=e.data||{},t}static createRequest(e,t){return{request:!0,id:Math.round(1e7*Math.random()),method:e,data:t||{}}}static createSuccessResponse(e,t){return{response:!0,id:e.id,ok:!0,data:t||{}}}static createErrorResponse(e,t,r){return{response:!0,id:e.id,errorCode:t,errorReason:r}}static createMessage(e,t){return{message:!0,method:e,data:t||{}}}}const np=new Ld;class ip extends Ro{constructor(e,t="whereby-sfu#v4"){super(),this.socket=null,this.wsUrl=e,this.protocol=t,this.sents=new Map,this._setupSocket()}_setupSocket(){this.socket=new WebSocket(this.wsUrl,this.protocol),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onclose=this._onClose.bind(this),this.socket.onerror=this._onError.bind(this)}_tearDown(){null!==this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket=null,this.sents.forEach(e=>e.close()),this.emit("close"))}close(){var e;null===(e=this.socket)||void 0===e||e.close()}_onOpen(){np.info("Connected"),this.emit("open")}_onMessage(e){const t=rp.parse(e.data);np.info("Received message",t),(null==t?void 0:t.response)?this._handleResponse(t):(null==t?void 0:t.message)&&this.emit("message",t)}_onClose(){np.info("Disconnected"),this._tearDown()}_onError(e){np.info("Error",e)}_handleResponse(e){const t=this.sents.get(e.id);if(e.ok)t.resolve(e.data);else{const r=new Error(e.errorReason);t.reject(r)}}send(e){try{this.socket&&this.socket.send(JSON.stringify(e))}catch(e){}}message(e,t={}){const r=rp.createMessage(e,t);this.send(r)}request(e,t={},r=1500*(15+.1*this.sents.size)){const n=rp.createRequest(e,t);return this.send(n),new Promise((e,t)=>{const i={id:n.id,method:n.method,resolve:t=>{this.sents.delete(n.id)&&(clearTimeout(i.timer),e(t))},reject:e=>{this.sents.delete(n.id)&&(clearTimeout(i.timer),t(e))},timer:setTimeout(()=>{this.sents.delete(n.id)&&t(new Error("request timeout"))},r),close:()=>{clearTimeout(i.timer),t(new Error("transport closed"))}};this.sents.set(n.id,i)})}}function sp(e){let t,r,n,i,s=[];const o=e=>{s=function(e){return"string"==typeof e?e.split(",").filter(Boolean).map(e=>{const[t,r]=/\|/.test(e)?e.split("|"):["",e];return{host:r,dc:t}}):e.filter(e=>e.host).map(e=>({host:e.host,dc:e.dc||""}))}(e)};let a=!1,c=!1;const d=()=>{if(a)return void(c=!0);a=!0,c=!1;let o=s;if(t){const e=Date.now();e-3e3>(r||0)&&((!i||(n||0)>i)&&e-3e3>(n||0))||(o=[{host:t.host,dc:t.dc}])}const l={};let u=0;o.forEach(({dc:e})=>{void 0===l[e]&&(l[e]=u++)});let p=0;const h={};let f,m=o.length,g=!1,v=!1;const b=i,y=()=>{var t;m--,0!==m||g||(a=!1,c?setTimeout(d,0):null===(t=e.onFailed)||void 0===t||t.call(e))},_=[];o.forEach(({host:n,dc:s},d)=>{if(d>0){p+=500;const e=(h[s]||0)+2e3;p=Math.max(p,e)}h[s]=p,_.push(setTimeout(()=>{var u;if(_.shift(),v)return;if(b!==i)return y(),void _.forEach(e=>{clearTimeout(e),y()});const p=new ip((null===(u=e.getUrlForHost)||void 0===u?void 0:u.call(e,n))||n);let h=!1;p.on("open",()=>{setTimeout(()=>{var r;if(!h)if(f||v)p.close();else{f=p,v=!0;const i=[...new Set(o.slice(0,d).filter(e=>e.host!==n).map(e=>e.host))],u=[...new Set(o.slice(0,d).filter(e=>e.dc!==s).map(e=>e.dc))];t=t?Object.assign(Object.assign({},t),{host:n,dc:s,failedHosts:[...new Set([...i,...t.failedHosts])].filter(e=>e!==n&&!t.usedHosts.includes(e)),failedDCs:[...new Set([...u,...t.failedDCs])].filter(e=>e!==s&&!t.usedDCs.includes(e)),usedHosts:[...new Set([...t.usedHosts,n])],usedDCs:[...new Set([...t.usedDCs,s])],numConnections:t.numConnections+1}):{host:n,dc:s,initialHost:n,initialDC:s,initialHostIndex:d,initialDCIndex:l[s],failedHosts:i,failedDCs:u,usedHosts:[n],usedDCs:[s],numConnections:1,numUsedDCs:1,numUsedHosts:1,numFailedDCs:0,numFailedHosts:0},t.numUsedDCs=t.usedDCs.length,t.numUsedHosts=t.usedHosts.length,t.numFailedDCs=t.failedDCs.length,t.numFailedHosts=t.failedHosts.length,c=!1,a=!1,null===(r=e.onConnected)||void 0===r||r.call(e,p,t)}},100)}),p.on("close",()=>{var t;h=!0,p===f&&(f=void 0,r=Date.now(),g=!0,null===(t=e.onDisconnected)||void 0===t||t.call(e)),y()})},p))})};o(e.initialHostList);return{connect:d,updateHostList:o,networkIsUp:()=>{n=Math.max(Date.now(),n||0)},networkIsPossiblyDown:()=>{i=Date.now()}}}var op;const ap=null!==(op=ko.default)&&void 0!==op?op:ko,cp=new Ld,dp=ap.browserDetails.browser;let lp=!1;const up=Uo(),pp=Uo();"chrome"===dp&&window.document.addEventListener("beforeunload",()=>lp=!0);class hp{constructor({selfId:e,room:t,emitter:r,serverSocket:n,webrtcProvider:i,features:s,eventClaim:o}){const{session:a,iceServers:c,turnServers:d,sfuServer:l,sfuServers:u,mediaserverConfigTtlSeconds:p}=t;this._selfId=e,this._room=t,this._roomSessionId=null==a?void 0:a.id,this._emitter=r,this._serverSocket=n,this._webrtcProvider=i,this._features=s||{},this._eventClaim=o,this._vegaConnection=null,this._micAnalyser=null,this._micAnalyserDebugger=null,this._mediasoupDeviceInitializedAsync=(e=>Td(void 0,void 0,void 0,function*(){if(e.isNodeSdk)return new h.Device({handlerName:"Safari12"});let t=(yield h.detectDeviceAsync())||(/applecoremedia|applewebkit|safari/i.test(navigator.userAgent)?"Safari12":void 0);return/iphone|ipad/i.test(navigator.userAgent)&&(t="Safari12"),t||(t="Chrome111"),new h.Device({handlerName:t})}))(s),this._routerRtpCapabilities=null,this._sendTransport=null,this._receiveTransport=null,this._clientStates=new Map,this._streamIdToVideoConsumerId=new Map,this._streamIdToVideoResolution=new Map,this._consumers=new Map,this._dataConsumers=new Map,this._localStreamDeregisterFunction=null,this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._micProducer=null,this._micProducerPromise=null,this._micPaused=!1,this._micScoreProducer=null,this._micScoreProducerPromise=null,this._webcamProducer=null,this._webcamProducerPromise=null,this._webcamPaused=!1,this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._sndTransportIceRestartPromise=null,this._rcvTransportIceRestartPromise=null,this._colocation=null,this._stopCameraTimeout=null,this._audioTrackOnEnded=()=>{nl.sendEvent("audio_ended",{unloading:lp}),this._emitToPWA(Mu,{})},this._videoTrackOnEnded=()=>{nl.sendEvent("video_ended",{unloading:lp}),this._emitToPWA(ju,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,sfuServers:u,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:p}),this._socketListenerDeregisterFunctions=[],this._reconnect=!0,this._reconnectTimeOut=null,this._isConnectingOrConnected=!1,this._qualityMonitor=new tp,this._qualityMonitor.on(Ll,e=>{this._emitToPWA(Ll,e)}),this._networkIsDetectedUpBySignal=!1,this._cpuOveruseDetected=!1}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,sfuServers:n,mediaserverConfigTtlSeconds:i}){var s,o,a;this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._sfuServers=n,!n&&(null==r?void 0:r.fallbackServers)&&(this._sfuServers=r.fallbackServers.map(e=>({host:e.host||e.fqdn,dc:e.dc}))),this._mediaserverConfigTtlSeconds=i,null===(s=this._vegaConnectionManager)||void 0===s||s.updateHostList(this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||r.url);const c={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};c.iceServers=$l(c.iceServers,this._features.turnServerOverrideHost),null===(o=this._sendTransport)||void 0===o||o.updateIceServers(c),null===(a=this._receiveTransport)||void 0===a||a.updateIceServers(c),this._clearMediaServersRefresh(),i&&(this._fetchMediaServersTimer=setTimeout(()=>this._emitToSignal(yl),1e3*i))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_onNetworkIsDetectedUpBySignal(){var e;this._networkIsDetectedUpBySignal||(this._networkIsDetectedUpBySignal=!0,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsUp())}_onNetworkIsDetectedPossiblyDownBySignal(){var e;this._networkIsDetectedUpBySignal&&(this._networkIsDetectedUpBySignal=!1,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsPossiblyDown())}setupSocketListeners(){this._socketListenerDeregisterFunctions.push(()=>this._clearMediaServersRefresh(),this._serverSocket.on(kl,e=>{e.error?cp.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)}),this._serverSocket.on(El,e=>{(null==e?void 0:e.error)||(this._screenVideoTrack&&this._emitScreenshareStarted(),this._reconnect&&this._connect())}),this._serverSocket.on("connect",()=>this._onNetworkIsDetectedUpBySignal()),this._serverSocket.onEngineEvent("packet",()=>this._onNetworkIsDetectedUpBySignal()),this._serverSocket.on("disconnect",()=>this._onNetworkIsDetectedPossiblyDownBySignal())),this._connect()}_emitScreenshareStarted(){this._emitToSignal(_l,{streamId:pp,hasAudioTrack:Boolean(this._screenAudioTrack)})}_connect(){if(!this._isConnectingOrConnected){if(!this._serverSocket.isConnected()){const e=this._serverSocket.getReconnectThreshold();if(!e)return;if(Date.now()>(this._serverSocket.disconnectTimestamp||0)+e)return}if(this._reconnectTimeOut&&clearTimeout(this._reconnectTimeOut),!this._vegaConnectionManager){const e=this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||this._sfuServer.url;this._vegaConnectionManager=sp({initialHostList:e,getUrlForHost:e=>{const t=new URLSearchParams(Object.assign({clientId:this._selfId,organizationId:this._room.organizationId,roomName:this._room.name,eventClaim:this._room.isClaimed?this._eventClaim:null,lowBw:"true"},Object.keys(this._features||{}).filter(e=>this._features[e]&&/^sfu/.test(e)).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:this._features[t]}),{})));return`wss://${e}?${t.toString()}`},onConnected:(e,t)=>{this._vegaConnection=e,this._vegaConnection.on("message",e=>this._onMessage(e)),this._emitToPWA(Fu,t),this._join()},onDisconnected:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()},onFailed:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()}})}this._vegaConnectionManager.connect(),this._isConnectingOrConnected=!0}}_onClose(){var e,t;cp.info("_onClose()"),null===(e=this._sendTransport)||void 0===e||e.close(),null===(t=this._receiveTransport)||void 0===t||t.close(),this._sendTransport=null,this._receiveTransport=null,this._streamIdToVideoConsumerId.clear(),this._streamIdToVideoResolution.clear(),this._reconnect&&(this._reconnectTimeOut=setTimeout(()=>this._connect(),1e3)),this._qualityMonitor.close(),this._emitToPWA(Nu)}_join(){return Td(this,void 0,void 0,function*(){var e,t;cp.info("join()"),this._emitToPWA(Lu);try{const{routerRtpCapabilities:r}=yield this._vegaConnection.request("getCapabilities");if(!this._routerRtpCapabilities){const t=((e,t)=>{var r;const{vp9On:n,h264On:i}=t,s="chrome"===(null===(r=ko.browserDetails)||void 0===r?void 0:r.browser);if(!(null==e?void 0:e.codecs))return e;if(n&&s){const t=Kd(e.codecs,Jd.VP9);return Object.assign(Object.assign({},e),{codecs:t})}if(i){const t=Kd(e.codecs,Jd.H264);return Object.assign(Object.assign({},e),{codecs:t})}return e})(r,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}));this._routerRtpCapabilities=t,yield null===(e=yield this._mediasoupDeviceInitializedAsync)||void 0===e?void 0:e.load({routerRtpCapabilities:t})}this._vegaConnection.message("setCapabilities",{rtpCapabilities:null===(t=yield this._mediasoupDeviceInitializedAsync)||void 0===t?void 0:t.rtpCapabilities}),this._colocation&&this._vegaConnection.message("setColocation",{colocation:this._colocation}),yield Promise.all([this._createTransport(!0),this._createTransport(!1)]);const n=[];!this._micTrack||this._micProducer||this._micProducerPromise||n.push(this._internalSendMic()),!this._webcamTrack||this._webcamProducer||this._webcamProducerPromise||n.push(this._internalSendWebcam()),!this._screenVideoTrack||this._screenVideoProducer||this._screenVideoProducerPromise||n.push(this._internalSendScreenVideo()),!this._screenAudioTrack||this._screenAudioProducer||this._screenAudioProducerPromise||n.push(this._internalSendScreenAudio()),yield Promise.all(n)}catch(e){cp.error("_join() [error:%o]",e)}})}_createTransport(e){return Td(this,void 0,void 0,function*(){var t;const r=e?"createSendTransport":"createRecvTransport",n=yield this._vegaConnection.request("createTransport",{producing:e,consuming:!e,enableTcp:!0,enableUdp:!0,preferUdp:!0,sctpParameters:{enableSctp:!0,numSctpStreams:{OS:1024,MIS:1024},maxSctpMessageSize:262144,sctpSendBufferSize:262144}});n.iceServers=$l(this._features.turnServersOn?this._turnServers:this._iceServers,this._features.turnServerOverrideHost),Vl(n,this._features);const i=null===(t=yield this._mediasoupDeviceInitializedAsync)||void 0===t?void 0:t[r](n),s=t=>Td(this,void 0,void 0,function*(){if(cp.info(`Transport ConnectionStateChanged ${t}`),"disconnected"===t||"failed"===t)if(e){if(this._sndTransportIceRestartPromise)return;this._sndTransportIceRestartPromise=this._restartIce(i).finally(()=>{this._sndTransportIceRestartPromise=null})}else{if(this._rcvTransportIceRestartPromise)return;this._rcvTransportIceRestartPromise=this._restartIce(i).finally(()=>{this._rcvTransportIceRestartPromise=null})}});null==i||i.on("connect",({dtlsParameters:e},t)=>{var r;null===(r=this._vegaConnection)||void 0===r||r.message("connectTransport",{transportId:i.id,dtlsParameters:e}),t()}).on("connectionstatechange",s),null==i||i.observer.once("close",()=>{i.removeListener("connectionstatechange",s)}),e?(null==i||i.on("produce",(e,t,r)=>Td(this,[e,t,r],void 0,function*({kind:e,rtpParameters:t,appData:r},n,s){var o;try{const{paused:s}=r,{id:a}=yield null===(o=this._vegaConnection)||void 0===o?void 0:o.request("produce",{transportId:i.id,kind:e,rtpParameters:t,paused:s,appData:r});n({id:a})}catch(e){s(e)}})),null==i||i.on("producedata",(e,t,r)=>Td(this,[e,t,r],void 0,function*({appData:e,sctpStreamParameters:t},r,n){var s;try{const{id:n}=yield null===(s=this._vegaConnection)||void 0===s?void 0:s.request("produceData",{transportId:i.id,sctpStreamParameters:t,appData:e});r({id:n})}catch(e){n(e)}})),this._sendTransport=i):this._receiveTransport=i})}_restartIce(e){return Td(this,arguments,void 0,function*(e,t=0){if(!e||!("closed"in e)||!("connectionState"in e))return void cp.info("_restartIce: No transport or property closed or connectionState!");if(e.closed)return void cp.info("_restartIce: Transport is closed!");if("disconnected"!==e.connectionState&&"failed"!==e.connectionState)return void cp.info("_restartIce: Connection is healthy ICE restart no loneger needed!");const{iceRestartStarted:r}=e.appData,n=Date.now();if(Number.isFinite(r)&&n-r<3500)return;if(e.appData.iceRestartStarted=n,5<=t)return void cp.info("_restartIce: Reached restart ICE maximum retry count!");if(!this._vegaConnection)return void cp.info("_restartIce: Connection is undefined");const{iceParameters:i}=yield this._vegaConnection.request("restartIce",{transportId:e.id});cp.info("_restartIce: ICE restart iceParameters received from SFU: ",i);const s=yield e.restartIce({iceParameters:i}).then(()=>null).catch(e=>e);if(s)switch(cp.error(`_restartIce: ICE restart failed: ${s}`),s.message){case"missing transportId":case"no such transport":break;default:yield new Promise(e=>{setTimeout(()=>{e(void 0)},Math.min(3500*Math.pow(2,t),6e4))}),yield this._restartIce(e,t+1)}else yield new Promise(e=>{setTimeout(()=>{e(void 0)},6e4*Math.min(8,t+1))}),"failed"!==e.connectionState&&"disconnected"!==e.connectionState||(yield this._restartIce(e,t+1))})}_internalSendMic(){return Td(this,void 0,void 0,function*(){cp.info("_internalSendMic()"),this._micProducerPromise=(()=>Td(this,void 0,void 0,function*(){try{if(!this._micTrack||!this._sendTransport||this._micProducer)return void(this._micProducerPromise=null);const e=this._micPaused,t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._micTrack,disableTrackOnPause:!1,stopTracks:!1},qd("audio",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:up,sourceClientId:this._selfId,screenShare:!1,source:"mic",paused:e}}));e?t.pause():t.resume(),this._micProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",()=>{var e;cp.info('micProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._micProducer=null,this._micProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)}),this._micTrack!==this._micProducer.track&&(yield this._replaceMicTrack()),this._micPaused!==this._micProducer.paused&&this._pauseResumeMic()}catch(e){cp.error("micProducer failed:%o",e)}finally{this._micProducerPromise=null,this._micTrack||(this._stopProducer(this._micProducer),this._micProducer=null)}}))()})}_internalSetupMicScore(){return Td(this,void 0,void 0,function*(){cp.info("_internalSetupMicScore()"),this._micScoreProducerPromise=(()=>Td(this,void 0,void 0,function*(){try{if(!this._micProducer||!this._colocation||this._micScoreProducer)return void(this._micScoreProducerPromise=null);const e=yield this._sendTransport.produceData({ordered:!1,maxPacketLifeTime:3e3,label:"micscore",appData:{producerId:this._micProducer.id,clientId:this._selfId}});this._micScoreProducer=e,e.observer.once("close",()=>{var t;cp.info('micScoreProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeDataProducers",{dataProducerIds:[e.id]})),this._micScoreProducer=null,this._micScoreProducerPromise=null})}catch(e){cp.error("micScoreProducer failed:%o",e)}finally{this._micScoreProducerPromise=null,this._micProducer&&this._colocation||this._stopMicScoreProducer()}}))()})}_stopMicScoreProducer(){this._stopProducer(this._micScoreProducer),this._micScoreProducer=null}_replaceMicTrack(){return Td(this,void 0,void 0,function*(){var e;cp.info("_replaceMicTrack()"),this._micTrack&&this._micProducer&&!this._micProducer.closed&&this._micProducer.track!==this._micTrack&&(yield this._micProducer.replaceTrack({track:this._micTrack}),null===(e=this._micAnalyser)||void 0===e||e.setTrack(this._micTrack),yield this._replaceMicTrack())})}_pauseResumeMic(){var e,t;cp.info("_pauseResumeMic()"),this._micProducer&&!this._micProducer.closed&&this._micPaused!==this._micProducer.paused&&(this._micPaused?(this._micProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._micProducer.id]})):(this._micProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._micProducer.id]})),this._pauseResumeMic())}_sendMic(e){return Td(this,void 0,void 0,function*(){return cp.info("_sendMic() [track:%o]",e),this._micTrack=e,this._micProducer?yield this._replaceMicTrack():this._micProducerPromise?void 0:this._sendTransport?yield this._internalSendMic():void 0})}_sendMicScore(e){if(!isNaN(e)&&isFinite(e))if(this._micScoreProducer){if(this._micScoreProducer.closed)return void this._stopMicScoreProducer();try{this._micScoreProducer.send(JSON.stringify({score:e}))}catch(e){cp.error("_sendMicScore failed [error:%o]",e)}}else!this._micScoreProducerPromise&&this._micProducer&&this._colocation&&0!==e&&this._internalSetupMicScore()}_syncResourceUsage(){var e;if(this._webcamProducer){const t=!this._cpuOveruseDetected,r=this._webcamProducer.rtpParameters;if(3===(null===(e=null==r?void 0:r.encodings)||void 0===e?void 0:e.length)){const e=t?2:1;this._webcamProducer.maxSpatialLayer!==e&&(this._webcamProducer.setMaxSpatialLayer(e),nl.sendEvent("simulcast_layer_activation_changed",{layerIndex:2,active:t}))}}}_internalSendWebcam(){return Td(this,void 0,void 0,function*(){var e;cp.info("_internalSendWebcam()"),!this._sendTransport||this._webcamProducer||this._webcamProducerPromise||"live"!==(null===(e=this._webcamTrack)||void 0===e?void 0:e.readyState)||(this._webcamProducerPromise=(()=>Td(this,void 0,void 0,function*(){var e;try{const t=this._webcamPaused,r=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._webcamTrack,disableTrackOnPause:!1,stopTracks:!1},qd("video",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:up,sourceClientId:this._selfId,screenShare:!1,source:"webcam",paused:t}}));t?r.pause():r.resume();const n=this._features.producerCpuOveruseWatchOn?function({producer:e,onOveruse:t}){var r;const n=null===(r=e.rtpParameters)||void 0===r?void 0:r.encodings;let i=null;if(3===(null==n?void 0:n.length)){const{ssrc:r,rid:s}=n[0];let o=0,a=0;const c=2;i=setInterval(()=>Td(this,void 0,void 0,function*(){(yield e.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(r&&e.ssrc===r||s&&e.rid===s)&&(o&&e.frameHeight&&e.frameHeight<o?(a++,a>=c&&t()):a=0,o=Math.max(o,e.frameHeight||0))})}),2e3)}return()=>{i&&clearInterval(i)}}({producer:r,onOveruse:()=>{nl.sendEvent("producer_cpuoveruse_detected",{}),n(),this._cpuOveruseDetected=!0,this._syncResourceUsage()}}):()=>{};this._webcamProducer=r,this._qualityMonitor.addProducer(this._selfId,r.id),r.observer.once("close",()=>{var e;cp.info('webcamProducer "close" event'),r.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[r.id]})),n(),this._webcamProducer=null,this._webcamProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,r.id)}),this._webcamTrack&&this._webcamTrack!==(null===(e=this._webcamProducer)||void 0===e?void 0:e.track)&&(this._webcamProducerPromise=null,this._replaceWebcamTrack()),this._webcamPaused!==this._webcamProducer.paused&&this._pauseResumeWebcam()}catch(e){cp.error("webcamProducer failed:%o",e)}finally{this._webcamProducerPromise=null,this._webcamTrack||(this._stopProducer(this._webcamProducer),this._webcamProducer=null)}}))())})}_replaceWebcamTrack(){return Td(this,void 0,void 0,function*(){cp.info("_replaceWebcamTrack()"),this._sendTransport&&this._webcamTrack&&!this._webcamProducerPromise&&(this._webcamProducer||!this._webcamTrack.enabled?this._webcamProducer.track!==this._webcamTrack&&(yield this._webcamProducer.replaceTrack({track:this._webcamTrack}),yield this._replaceWebcamTrack()):yield this._internalSendWebcam())})}_pauseResumeWebcam(){var e,t;cp.info("_pauseResumeWebcam()"),this._webcamProducer&&!this._webcamProducer.closed&&this._webcamPaused!==this._webcamProducer.paused&&(this._webcamPaused?(this._webcamProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._webcamProducer.id]})):(this._webcamProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._webcamProducer.id]})),this._pauseResumeWebcam())}_sendWebcam(e){return Td(this,void 0,void 0,function*(){return cp.info("_sendWebcam() [track:%o]",e),this._webcamTrack=e,this._webcamProducer?yield this._replaceWebcamTrack():this._webcamProducerPromise?void 0:this._sendTransport?yield this._internalSendWebcam():void 0})}_internalSendScreenVideo(){return Td(this,void 0,void 0,function*(){cp.info("_internalSendScreenVideo()"),this._screenVideoProducerPromise=(()=>Td(this,void 0,void 0,function*(){var e,t;try{if(!this._screenVideoTrack||!this._sendTransport||this._screenVideoProducer)return void(this._screenVideoProducerPromise=null);const r=this._features.sfuVp9On?null===(t=null===(e=this._routerRtpCapabilities)||void 0===e?void 0:e.codecs)||void 0===t?void 0:t.find(e=>e.mimeType.match(/vp8/i)):void 0,n=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenVideoTrack,disableTrackOnPause:!1,stopTracks:!1,codec:r},qd("video",!0,Object.assign(Object.assign({},this._features),{vp9On:!1}),this._getAreTooManyAlreadyPresenting())),{appData:{streamId:pp,sourceClientId:this._selfId,screenShare:!0,source:"screenvideo",paused:!1}}));this._screenVideoProducer=n,this._qualityMonitor.addProducer(this._selfId,n.id),n.observer.once("close",()=>{var e;cp.info('screenVideoProducer "close" event'),n.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[n.id]})),this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,n.id)}),this._screenVideoTrack!==this._screenVideoProducer.track&&(yield this._replaceScreenVideoTrack())}catch(e){cp.error("screenVideoProducer failed:%o",e)}finally{this._screenVideoProducerPromise=null,this._screenVideoTrack||(yield this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null)}}))()})}_replaceScreenVideoTrack(){return Td(this,void 0,void 0,function*(){cp.info("_replaceScreenVideoTrack()"),this._screenVideoTrack&&this._screenVideoProducer&&!this._screenVideoProducer.closed&&this._screenVideoProducer.track!==this._screenVideoTrack&&(yield this._screenVideoProducer.replaceTrack({track:this._screenVideoTrack}),yield this._replaceScreenVideoTrack())})}_sendScreenVideo(e){return Td(this,void 0,void 0,function*(){return cp.info("_sendScreenVideo() [track:%o]",e),this._screenVideoTrack=e,this._screenVideoProducer?yield this._replaceScreenVideoTrack():this._screenVideoProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenVideo():void 0})}_internalSendScreenAudio(){return Td(this,void 0,void 0,function*(){cp.info("_internalSendScreenAudio()"),this._screenAudioProducerPromise=(()=>Td(this,void 0,void 0,function*(){try{if(!this._screenAudioTrack||!this._sendTransport||this._screenAudioProducer)return void(this._screenAudioProducerPromise=null);const e=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenAudioTrack,disableTrackOnPause:!1,stopTracks:!1},qd("audio",!0,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:pp,sourceClientId:this._selfId,screenShare:!0,source:"screenaudio",paused:!1}}));this._screenAudioProducer=e,this._qualityMonitor.addProducer(this._selfId,e.id),e.observer.once("close",()=>{var t;cp.info('screenAudioProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeProducers",{producerIds:[e.id]})),this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,e.id)}),this._screenAudioTrack!==this._screenAudioProducer.track&&(yield this._replaceScreenAudioTrack())}catch(e){cp.error("screenAudioProducer failed:%o",e)}finally{this._screenAudioProducerPromise=null,this._screenAudioTrack||(yield this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null)}}))()})}_replaceScreenAudioTrack(){return Td(this,void 0,void 0,function*(){cp.info("_replaceScreenAudioTrack()"),this._screenAudioTrack&&this._screenAudioProducer&&!this._screenAudioProducer.closed&&this._screenAudioProducer.track!==this._screenAudioTrack&&(yield this._screenAudioProducer.replaceTrack({track:this._screenAudioTrack}),yield this._replaceScreenAudioTrack())})}_sendScreenAudio(e){return Td(this,void 0,void 0,function*(){return cp.info("_sendScreenAudio() [track:%o]",e),this._screenAudioTrack=e,this._screenAudioProducer?yield this._replaceScreenAudioTrack():this._screenAudioProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenAudio():void 0})}_stopProducer(e){cp.info("_stopProducer()"),e&&!e.closed&&(e.appData.localClosed=!0,e.close())}_getAreTooManyAlreadyPresenting(){return[...this._clientStates.values()].filter(e=>e.hasAcceptedScreenStream&&e.screenStream).length>=3}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._room.name===t&&Boolean(r)}setEventClaim(e){var t;this._eventClaim=e,null===(t=this._vegaConnection)||void 0===t||t.message("eventClaim",{eventClaim:e})}setColocation(e){var t;this._colocation=e,null===(t=this._vegaConnection)||void 0===t||t.message("setColocation",{colocation:e}),e||!this._micScoreProducer||this._micScoreProducerPromise||this._stopMicScoreProducer(),this._syncMicAnalyser(),nl.sendEvent("colocation_changed",{colocation:e})}setAudioOnly(e){var t;null===(t=this._vegaConnection)||void 0===t||t.message(e?"enableAudioOnly":"disableAudioOnly")}setRemoteScreenshareVideoTrackIds(){}setRoomSessionId(e){this._roomSessionId=e}disconnect(e,t,r){var n;cp.info("disconnect() [clientIdOrStreamId:%s, eventClaim:%s]",e,r);const i=this._clientStates.get(e);i&&(i.hasAcceptedWebcamStream=!1,i.hasAcceptedScreenStream=!1,this._syncIncomingStreamsWithPWA(e)),r&&(this._eventClaim=r,null===(n=this._vegaConnection)||void 0===n||n.message("eventClaim",{eventClaim:r}))}replaceTrack(e,t){"audio"===t.kind&&(t.effectTrack||this._monitorAudioTrack(t),this._micTrack=t,this._replaceMicTrack()),"video"===t.kind&&(t.effectTrack||this._monitorVideoTrack(t),this._webcamTrack=t,this._replaceWebcamTrack())}removeStream(e,t,r){cp.info("removeStream() [streamId:%s, requestedByClientId:%s]",e,r),this._emitToSignal(wl,{streamId:pp,requestedByClientId:r}),this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._screenVideoTrack=null,this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null,this._screenAudioTrack=null}_onMicAnalyserScoreUpdated(e){var t,r;null===(r=null===(t=this._micAnalyserDebugger)||void 0===t?void 0:t.onScoreUpdated)||void 0===r||r.call(t,e),this._sendMicScore(this._micPaused?0:e.out)}addNewStream(e,t,r,n,i=[]){if("0"===e){this._micPaused=r,this._webcamPaused=n;const e=t.getVideoTracks()[0],s=t.getAudioTracks()[0];if(e){this._sendWebcam(e),e.effectTrack||this._monitorVideoTrack(e);const t=i.find(e=>"video"===e.kind);t&&this._monitorVideoTrack(t)}if(s){this._sendMic(s),this._syncMicAnalyser(),s.effectTrack||this._monitorAudioTrack(s);const e=i.find(e=>"audio"===e.kind);e&&this._monitorAudioTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const o=e=>{const{enable:t,track:r}=e.detail;this._webcamPaused=!t,this._pauseResumeWebcam(),this._handleStopOrResumeVideo({enable:t,track:r})};t.addEventListener("stopresumevideo",o),this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",o)}}else{const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];e&&this._sendScreenVideo(e),r&&this._sendScreenAudio(r),this._emitScreenshareStarted()}}_syncMicAnalyser(){if(!this._micTrack||!this._colocation||this._micAnalyser)return this._micAnalyser&&!this._colocation?(this._micAnalyser.close(),void(this._micAnalyser=null)):void 0;this._micAnalyser=function({micTrack:e,params:t,onScoreUpdated:r}){const n=new AudioContext;let i=null,s=null,o=null,a=!1;const c=e=>Td(this,void 0,void 0,function*(){if(o&&a&&o.stop(),a=!1,e&&t.separateTrack)try{const r=yield navigator.mediaDevices.getUserMedia({audio:Object.assign({deviceId:null==o?void 0:o.getSettings().deviceId},t.separateTrack),video:!1});e=r.getAudioTracks()[0],a=!0}catch(e){Xu.warn("unable to fetch new track for colocation speaker analysis, using current",e)}if(o=e,s&&(s.disconnect(),s=null),e){const t=new MediaStream([e]);s=n.createMediaStreamSource(t),s.connect(i)}});let d;const l=e=>{if(clearInterval(d),t=Object.assign(Object.assign({},Yu),e),!i||i.fftSize!==2*t.bins){let e=null;i&&(e=o,c(null)),i=n.createAnalyser(),i.fftSize=2*t.bins,e&&c(e)}const s=new Uint8Array(i.frequencyBinCount),a=[];i.minDecibels=t.minDecibels,i.maxDecibels=t.maxDecibels,i.smoothingTimeConstant=t.smoothingTimeConstant;const l=t.initScript&&new Function("f","setTrack","lastTrack",t.initScript.join("\n")),u=t.scoreScript&&new Function("bins","g","f",t.scoreScript.join("\n")),p=t.scoreFormula&&new Function("bands",`return ${t.scoreFormula}`),h=t.outFormula&&new Function("score","avg","max","scores",`return ${t.outFormula}`),f=t.binFormula&&new Function("bin","index",`return ${t.binFormula}`);let m=0;const g=l&&l(Qu,c,o);d=setInterval(()=>{i.getByteFrequencyData(s);let e=0;if(p){const r=t.bands.map(e=>{const t=e.map(e=>f(s[e]/255,e));return{avg:t.reduce((e,t)=>e+t,0)/e.length,min:t.reduce((e,t)=>Math.min(e,t/255),Number.MAX_VALUE),max:t.reduce((e,t)=>Math.max(e,t/255),0)}});e=p(r)||0}else u&&(e=u(s,g,Qu),isNaN(e)&&(e=0));if(a.push(e),a.length>t.aggSize&&a.shift(),m++,m>=t.reportRate){m=0;const t=a.reduce((e,t)=>Math.max(e,t),0),n=a.reduce((e,t)=>e+t,0)/a.length,i=h(e,n,t,a);r({bins:s,score:e,max:t,avg:n,out:i})}},1e3/t.sampleRate)};return l(t),c(e),{setParams:l,setTrack:c,close(){c(null),clearInterval(d),n.close()}}}({micTrack:this._micTrack,onScoreUpdated:this._onMicAnalyserScoreUpdated.bind(this)})}stopOrResumeAudio(e,t){cp.info("stopOrResumeAudio() [enabled:%s]",t),this._micPaused=!t,this._pauseResumeMic()}_handleStopOrResumeVideo({enable:e,track:t}){e?this._sendWebcam(t):this._webcamProducer&&!this._webcamProducer.closed&&this._webcamProducer.track===t&&(this._stopProducer(this._webcamProducer),this._webcamProducer=null,this._webcamTrack=null)}stopOrResumeVideo(e,t){var r;if(cp.info("stopOrResumeVideo() [enable:%s]",t),this._webcamPaused=!t,this._pauseResumeWebcam(),["chrome","safari"].includes(dp))if(t){if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;navigator.mediaDevices.getUserMedia({video:r}).then(r=>{const n=r.getVideoTracks()[0];e.addTrack(n),this._monitorVideoTrack(n),this._emitToPWA(mu,{streamId:e.id,tracks:[n],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:n})})}}else{clearTimeout(this._stopCameraTimeout);const n="ended"===(null===(r=e.getVideoTracks().find(e=>!e.enabled))||void 0===r?void 0:r.readyState)?0:5e3;this._stopCameraTimeout=setTimeout(()=>{e.getVideoTracks().forEach(r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emitToPWA(gu,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))})},n)}}supportsScreenShareAudio(){return!0}acceptNewStream({streamId:e,clientId:t}){cp.info("acceptNewStream()",{streamId:e,clientId:t});const r=this._getOrCreateClientState(t);e!==t?(r.hasAcceptedScreenStream=!0,r.hasEmittedScreenStream=!1):(r.hasAcceptedWebcamStream=!0,r.hasEmittedWebcamStream=!1),this._syncIncomingStreamsWithPWA(t)}updateStreamResolution(e,t,{width:r,height:n}){var i,s;cp.info("updateStreamResolution()",{streamId:e,width:r,height:n});const o=this._streamIdToVideoConsumerId.get(e),a=this._consumers.get(o);if(!a)return void this._streamIdToVideoResolution.set(e,{width:r,height:n});const c=function(e){let t=0;return e.forEach(e=>{var r,n;e._closed||e._paused||"webcam"!==(null===(r=e._appData)||void 0===r?void 0:r.source)&&"screenvideo"!==(null===(n=e._appData)||void 0===n?void 0:n.source)||t++}),t}(this._consumers),d=function(e){var t,r,n;return/T3/.test((null===(n=null===(r=null===(t=e._rtpParameters)||void 0===t?void 0:t.encodings)||void 0===r?void 0:r[0])||void 0===n?void 0:n.scalabilityMode)||"")?3:2}(a),{spatialLayer:l,temporalLayer:u}=function({width:e,height:t},{numberOfActiveVideos:r,numberOfTemporalLayers:n,uncappedSingleRemoteVideoOn:i}){const s=Math.max(e,t);let o=s>=480?s>=960?2:1:0,a=n-1;return s<100&&(a=Math.max(n-2,0)),r>8&&0===o&&(a=Math.max(n-2,0)),r<4&&s>300&&0===o&&(o=1),i&&1===r&&(o=2,a=n-1),{spatialLayer:o,temporalLayer:a}}({width:r,height:n},{numberOfActiveVideos:c,numberOfTemporalLayers:d,uncappedSingleRemoteVideoOn:null===(i=this._features)||void 0===i?void 0:i.uncappedSingleRemoteVideoOn});a.appData.spatialLayer===l&&a.appData.temporalLayer===u||(a.appData.spatialLayer=l,a.appData.temporalLayer=u,null===(s=this._vegaConnection)||void 0===s||s.message("setConsumersPreferredLayers",{consumerIds:[o],spatialLayer:l,temporalLayer:u}))}close(){this.disconnectAll()}disconnectAll(){var e,t,r,n;this._reconnect=!1,this._reconnectTimeOut&&(clearTimeout(this._reconnectTimeOut),this._reconnectTimeOut=null),this._socketListenerDeregisterFunctions.forEach(e=>{e()}),this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null),this._socketListenerDeregisterFunctions=[],null===(e=this._vegaConnection)||void 0===e||e.removeAllListeners(),null===(t=this._vegaConnection)||void 0===t||t.close(),null===(r=this._sendTransport)||void 0===r||r.close(),null===(n=this._receiveTransport)||void 0===n||n.close(),this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._streamIdToVideoConsumerId.clear(),this._mediasoupDeviceInitializedAsync=Promise.resolve(null)}sendAudioMutedStats(e){nl.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){nl.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){nl.sendEvent(e,t)}rtcStatsDisconnect(){nl.server.close()}rtcStatsReconnect(){nl.server.connected||nl.server.connect()}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_onMessage(e){return Td(this,void 0,void 0,function*(){const{method:t,data:r}=e;return Promise.resolve().then(()=>{switch(t){case"consumerReady":return this._onConsumerReady(r);case"consumerClosed":return this._onConsumerClosed(r);case"consumerPaused":return this._onConsumerPaused(r);case"consumerResumed":return this._onConsumerResumed(r);case"dataConsumerReady":return this._onDataConsumerReady(r);case"dataConsumerClosed":return this._onDataConsumerClosed(r);case"dominantSpeaker":return this._onDominantSpeaker(r);case"consumerScore":return this._onConsumerScore(r);case"producerScore":return this._onProducerScore(r);default:return void cp.info(`unknown message method "${t}"`)}}).catch(e=>{cp.error('"message" failed [error:%o]',e)})})}_onConsumerReady(e){return Td(this,void 0,void 0,function*(){cp.info("_onConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consume(e);if(t.pause(),t.appData.localPaused=!0,t.appData.spatialLayer=2,this._consumers.set(t.id,t),this._qualityMonitor.addConsumer(t.appData.sourceClientId,t.id),t.observer.once("close",()=>{this._consumers.delete(t.id),this._qualityMonitor.removeConsumer(t.appData.sourceClientId,t.id),this._consumerClosedCleanup(t)}),this._features.increaseIncomingMediaBufferOn&&t.rtpReceiver)try{t.rtpReceiver.jitterBufferTarget=cu,t.rtpReceiver.playoutDelayHint=.4}catch(e){cp.error("Error during setting jitter buffer target:",e)}const{sourceClientId:r,screenShare:n,streamId:i}=t.appData,s=this._getOrCreateClientState(r);n?(s.hasEmittedScreenStream=!1,s.screenShareStreamId=i):(s.hasEmittedWebcamStream=!1,s.camStreamId=i);let o=n?s.screenStream:s.webcamStream;o&&o.inboundId===i||(o=new MediaStream,o.inboundId=i,n?s.screenStream=o:s.webcamStream=o),"video"===t.kind&&this._streamIdToVideoConsumerId.set(o.id,t.id),o.addTrack(t.track),this._syncIncomingStreamsWithPWA(r);const a=this._streamIdToVideoResolution.get(o.id);a&&(this.updateStreamResolution(o.id,null,a),this._streamIdToVideoResolution.delete(o.id))})}_onConsumerClosed(e){return Td(this,arguments,void 0,function*({consumerId:e,reason:t}){var r;cp.info("_onConsumerClosed()",{consumerId:e,reason:t}),null===(r=this._consumers.get(e))||void 0===r||r.close()})}_onConsumerPaused({consumerId:e}){cp.info("_onConsumerPaused()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!0,t.pause())}_onConsumerResumed({consumerId:e}){cp.info("_onConsumerResumed()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!1,t.appData.localPaused||t.resume())}_onConsumerScore({consumerId:e,kind:t,score:r}){cp.info("_onConsumerScore()",{consumerId:e,kind:t,score:r});const{appData:{sourceClientId:n}}=this._consumers.get(e)||{appData:{}};n&&this._qualityMonitor.addConsumerScore(n,e,t,r)}_onProducerScore({producerId:e,kind:t,score:r}){cp.info("_onProducerScore()",{producerId:e,kind:t,score:r}),[this._micProducer,this._webcamProducer,this._screenVideoProducer,this._screenAudioProducer].forEach(n=>{(null==n?void 0:n.id)===e&&this._qualityMonitor.addProducerScore(this._selfId,e,t,r)})}_onDataConsumerReady(e){return Td(this,void 0,void 0,function*(){cp.info("_onDataConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consumeData(e);this._dataConsumers.set(t.id,t),t.once("close",()=>{this._dataConsumers.delete(t.id)});const{clientId:r}=t.appData;t.on("message",e=>{var r;if(!this._micAnalyserDebugger)return;if("string"!=typeof e)return;const{score:n}=JSON.parse(e);n&&(null===(r=this._micAnalyserDebugger)||void 0===r||r.onConsumerScore(t.appData.clientId,n))}),this._syncIncomingStreamsWithPWA(r)})}_onDataConsumerClosed(e){return Td(this,arguments,void 0,function*({dataConsumerId:e,reason:t}){cp.info("_onDataConsumerClosed()",{dataConsumerId:e,reason:t});const r=this._dataConsumers.get(e);null==r||r.close()})}_onDominantSpeaker({consumerId:e}){const t=this._consumers.get(e);if(!t)return;const{sourceClientId:r}=t.appData;this._emitToPWA(Bu,{clientId:r})}_consumerClosedCleanup(e){const{sourceClientId:t,screenShare:r}=e.appData,n=this._getOrCreateClientState(t),i=r?n.screenStream:n.webcamStream;i&&(i.removeTrack(e.track),0===i.getTracks().length&&(this._streamIdToVideoConsumerId.delete(i.id),this._streamIdToVideoResolution.delete(i.id),r?(n.screenStream=void 0,n.hasEmittedScreenStream=!1,n.screenShareStreamId=void 0):(n.hasEmittedWebcamStream=!1,n.camStreamId=void 0)))}_syncIncomingStreamsWithPWA(e){var t,r;const n=this._getOrCreateClientState(e),{webcamStream:i,screenStream:s,hasEmittedWebcamStream:o,hasEmittedScreenStream:a,hasAcceptedWebcamStream:c,hasAcceptedScreenStream:d,screenShareStreamId:l,camStreamId:u}=n,p=[],h=[];this._consumers.forEach(t=>{if(t.appData.sourceClientId!==e)return;const r=t.appData.screenShare?d:c;!t.appData.localPaused!==r&&(r?(t.appData.remotePaused||t.resume(),t.appData.localPaused=!1,h.push(t.id)):(t.pause(),t.appData.localPaused=!0,p.push(t.id)))}),p.length>0&&(null===(t=this._vegaConnection)||void 0===t||t.message("pauseConsumers",{consumerIds:p})),h.length>0&&(null===(r=this._vegaConnection)||void 0===r||r.message("resumeConsumers",{consumerIds:h})),i&&!o&&c&&(this._emitToPWA(pu,{clientId:e,stream:i,streamId:u,streamType:"webcam"}),n.hasEmittedWebcamStream=!0),s&&!a&&d&&(this._emitToPWA(pu,{clientId:e,stream:s,streamId:l,streamType:"screenshare"}),n.hasEmittedScreenStream=!0)}_getOrCreateClientState(e){let t=this._clientStates.get(e);return t||(t={hasAcceptedWebcamStream:!1,hasAcceptedScreenStream:!1,hasEmittedWebcamStream:!1,hasEmittedScreenStream:!1},this._clientStates.set(e,t)),t}_emitToPWA(e,t){this._emitter.emit(e,t)}_emitToSignal(e,t,r){this._serverSocket.emit(e,t,r)}shouldAcceptStreamsFromBothSides(){return!0}setMicAnalyserDebugger(e){this._micAnalyserDebugger=e}setMicAnalyserParams(e){var t;null===(t=this._micAnalyser)||void 0===t||t.setParams(e)}hasClient(e){return this._clientStates.has(e)}}class fp{constructor({emitter:e,serverSocket:t,webrtcProvider:r,features:n}){this.emitter=e,this.currentManager=null,t.on(El,({room:i,selfId:s,error:o,eventClaim:a})=>{if(o)return;const c={selfId:s,room:i,emitter:e,serverSocket:t,webrtcProvider:r,features:n,eventClaim:a},d=!!i.sfuServer;if(mp=d?"group":"normal",this.currentManager){if(this.currentManager.isInitializedWith({selfId:s,roomName:i.name,isSfu:d}))return void(this.currentManager.setEventClaim&&a&&this.currentManager.setEventClaim(a));this.currentManager.disconnectAll(),e.emit(fu)}let l=null;l=d?new hp(c):new Ku(c),l.rtcStatsReconnect(),l.setupSocketListeners(),e.emit(hu,{rtcManager:l}),this.currentManager=l,t.setRtcManager(l)})}stopRtcManager(){this.currentManager&&(this.currentManager.disconnectAll(),this.emitter.emit(fu))}}let mp="";const gp=()=>mp,vp=new class{constructor(){this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD=.04,this.END_PACKET_LOSS_PERIOD_THRESHOLD=.005,this.INTERVAL_DIFF_THRESHOLD_MS=4e3,this.STALE_MEASUREMENT_TIMEOUT_MS=1e4,this.MINIMUM_INTERVAL_MS=3e4,this.ssrcsHistory=new Map,this.staleMeasurementTimeouts=new Map}addPacketLossMeasurement(e,t,r){this.handleStaleMeasurements(e);const n=t>this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD;let i=this.ssrcsHistory.get(e);if(!i)return i={id:e,hasActivePacketLoss:n,currPeriod:n?{begin:r}:void 0,hasPeriodicPacketLoss:!1},void this.ssrcsHistory.set(e,i);i.hasActivePacketLoss?t<this.END_PACKET_LOSS_PERIOD_THRESHOLD&&(this.endPacketLossPeriod(i,r),i.prevIntervalInMs&&i.prevIntervalInMs<this.MINIMUM_INTERVAL_MS&&this.ssrcsHistory.delete(e)):n&&(i.hasActivePacketLoss=!0,i.currPeriod={begin:r})}hasPeriodicPacketLoss(e,t){const r=this.ssrcsHistory.get(e);return r&&this.prevIntervalExceeded(r,t)?(this.ssrcsHistory.delete(r.id),!1):(null==r?void 0:r.hasPeriodicPacketLoss)||!1}prevIntervalExceeded(e,t){if(e.prevPeriod&&e.prevIntervalInMs){return t>this.calculatePeriodCenterTimestamp(e.prevPeriod)+e.prevIntervalInMs+this.INTERVAL_DIFF_THRESHOLD_MS}return!1}handleStaleMeasurements(e){const t=this.staleMeasurementTimeouts.get(e);t&&clearTimeout(t),this.staleMeasurementTimeouts.set(e,setTimeout(()=>{Hl.debug("handleStaleMeasurements() [measurements invalid for ssrc: %s]",e),this.ssrcsHistory.delete(e)},this.STALE_MEASUREMENT_TIMEOUT_MS))}endPacketLossPeriod(e,t){if(Hl.debug("endPacketLossPeriod() [ssrcId: %s, timestamp: %s]",e.id,t),!e.currPeriod)throw new Error("No packet loss period for "+e.id);e.prevPeriod?(e.currPeriod.end=t,this.addNewPacketLossInterval(e)):e.prevPeriod=Object.assign(Object.assign({},e.currPeriod),{end:t}),delete e.currPeriod,e.hasActivePacketLoss=!1}addNewPacketLossInterval(e){if(Hl.debug("addNewPacketLossInterval() [ssrcId: %s, prevIntervalInMs: %s]",e.id,e.prevIntervalInMs),!e.currPeriod||!e.prevPeriod)throw new Error("missing period timestamps");const t=this.calculatePeriodCenterTimestamp(e.prevPeriod),r=this.calculatePeriodCenterTimestamp(e.currPeriod)-t;if(e.prevIntervalInMs){const t=Math.abs(e.prevIntervalInMs-r);e.hasPeriodicPacketLoss=t<this.INTERVAL_DIFF_THRESHOLD_MS,Hl.debug("addNewPacketLossInterval() [hasPeriodicPacketLoss: %s, intervalDiffInMs: %s]",t<this.INTERVAL_DIFF_THRESHOLD_MS,t)}e.prevIntervalInMs=r,e.prevPeriod=e.currPeriod}calculatePeriodCenterTimestamp(e){if(!e.end)throw new Error("Missing period end timestamp");return e.begin+(e.end-e.begin)/2}},bp=[{id:"desync",enabled:({client:e,track:t,stats:r})=>!e.isLocalClient&&"audio"===(null==t?void 0:t.kind)&&"object"==typeof(null==r?void 0:r.tracks)&&Object.keys(r.tracks).length>1,check:({stats:e})=>{if(!e)return!1;const t={audio:0,video:0};Object.values(e.tracks).flatMap(e=>Object.values(e.ssrcs)).forEach(e=>{"audio"===e.kind&&e.jitter&&e.jitter>t.audio&&(t.audio=e.jitter),"video"===e.kind&&e.jitter&&e.jitter>t.video&&(t.video=e.jitter)});return Math.abs(1e3*t.audio-1e3*t.video)>500}},{id:"no-track",enabled:()=>!0,check:({client:e,clients:t,kind:r,track:n})=>{if(!n&&!e.isLocalClient&&"video"===r){const e=t.find(e=>e.isLocalClient);if(e)return!e.isAudioOnlyModeEnabled}return!n}},{id:"ended-track",enabled:({track:e})=>!!e,check:({track:e})=>"ended"===(null==e?void 0:e.readyState)},{id:"no-track-stats",enabled:({hasLiveTrack:e})=>e,check:({client:e,clients:t,kind:r,ssrcs:n})=>{if(0===n.length&&!e.isLocalClient&&"video"===r){const e=t.find(e=>e.isLocalClient);if(e)return!e.isAudioOnlyModeEnabled}return 0===n.length}},{id:"dry-track",enabled:({hasLiveTrack:e,ssrcs:t})=>!(!e||!t),check:({client:e,clients:t,ssrcs:r})=>{let n=!1;if(r.forEach(e=>{n=n||((null==e?void 0:e.bitrate)||0)>0}),!n&&e.isLocalClient){const e=t.filter(e=>!e.isLocalClient);if(e.length>0)return!e.every(e=>e.isAudioOnlyModeEnabled)}return!n}},{id:"denoiser-context-suspended",enabled:({client:e,kind:t})=>{var r,n;return!!e.isLocalClient&&"audio"===t&&!!(null===(n=null===(r=e.audio)||void 0===r?void 0:r.track)||void 0===n?void 0:n._denoiserCtx)},check:({track:e})=>{var t;return!(!e||!("_denoiserCtx"in e))&&"suspended"===(null===(t=e._denoiserCtx)||void 0===t?void 0:t.state)}},{id:"low-layer0-bitrate",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:n})=>e&&"video"===r&&!!t&&!!(null==t?void 0:t.height)&&!n.isPresentation,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&(((null==e?void 0:e.height)||0)<200&&e.bitrate<3e4)},{id:"quality-limitation-bw",enabled:({hasLiveTrack:e,stats:t,client:r,clients:n,kind:i})=>{if("normal"===gp()){if(n.filter(e=>!e.isLocalClient).some(e=>e.isAudioOnlyModeEnabled))return!1}return e&&!!r.isLocalClient&&"video"===i&&!!t},check:({stats:e})=>!!e&&!!Object.values(e.tracks).find(e=>Object.values(e.ssrcs).find(e=>"bandwidth"===e.qualityLimitationReason))},{id:"quality-limitation-cpu",enabled:({hasLiveTrack:e,stats:t,client:r,kind:n})=>e&&!!r.isLocalClient&&"video"===n&&!!t,check:({stats:e})=>!!e&&!!Object.values(e.tracks).find(e=>Object.values(e.ssrcs).find(e=>"cpu"===e.qualityLimitationReason))},{id:"high-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>2},{id:"extreme-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>5},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.1},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.1},{id:"fps-below-20",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:n})=>e&&!!t&&!!t.height&&"video"===r&&!n.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.height)||0)>180&&((null==e?void 0:e.fps)||0)<20},{id:"fps-below-10",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:n})=>e&&!!t&&!!t.height&&"video"===r&&!n.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.fps)||0)<10},{id:"bad-network",enabled:({hasLiveTrack:e,ssrcs:t})=>e&&t.length>0,check:({client:e,clients:t,kind:r,ssrcs:n})=>{if(!n.some(e=>((null==e?void 0:e.bitrate)||0)>0)&&e.isLocalClient&&"video"===r){const e=t.filter(e=>!e.isLocalClient);if(e.length>0)return!e.every(e=>e.isAudioOnlyModeEnabled)}const i=n[0];return!!i&&(0===i.bitrate||(i.lossRatio||0)>.03||(i.fractionLost||0)>.03||!e.isPresentation&&"video"===r&&!!(null==i?void 0:i.bitrate)&&i.bitrate<3e4||"in"===i.direction&&!!i.pliRate&&i.pliRate>2)}},{id:"periodic-packet-loss",enabled:({client:e,hasLiveTrack:t,ssrc0:r})=>!!e.isLocalClient&&t&&!!(null==r?void 0:r.ssrc)&&"out"===(null==r?void 0:r.direction)&&((null==r?void 0:r.bitrate)||0)>0,check:({ssrc0:e})=>!(!e||!e.ssrc)&&(vp.addPacketLossMeasurement(e.ssrc,e.fractionLost||0,Date.now()),vp.hasPeriodicPacketLoss(e.ssrc,Date.now()))},{id:"cpu-pressure-serious",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"serious"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"cpu-pressure-critical",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"critical"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"concealed",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===(null==e?void 0:e.direction)&&((null==e?void 0:e.audioLevel)||0)>=.001&&((null==e?void 0:e.audioConcealment)||0)>=.1},{id:"decelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&((null==e?void 0:e.audioDeceleration)||0)>=.1},{id:"accelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&(e.audioAcceleration||0)>=.1}];let yp=[],_p=null;const wp=[{id:"bitrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&!!t&&!!r,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+((null==t?void 0:t.bitrate)||0),0)},{id:"pixelrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:n})=>e&&"video"===n&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+(t.fps||0)*(t.width||0)*(t.height||0),0)},{id:"height",enabled:({hasLiveTrack:e,track:t,trackStats:r,ssrc0:n,kind:i})=>e&&"video"===i&&!!r&&!!t&&!!n&&!!n.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>Math.max(e,t.fps&&t.height||0),0)},{id:"layer0-height",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:n})=>e&&"video"===n&&!!t&&!!r&&!!r.height&&!!r.fps&&"out"===r.direction,value:({ssrc0:e})=>(null==e?void 0:e.height)||0},{id:"sourceHeight",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:n})=>e&&"video"===n&&!!t&&!!r&&!!r.sourceHeight&&"out"===r.direction,value:({ssrc0:e})=>(null==e?void 0:e.sourceHeight)||NaN},{id:"packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate,value:({ssrc0:e})=>("in"===(null==e?void 0:e.direction)?e.lossRatio:null==e?void 0:e.fractionLost)||0},{id:"jitter",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"in"===t.direction,value:({ssrc0:e})=>(null==e?void 0:e.jitter)||NaN},{id:"mos",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"out"===t.direction,value:({ssrc0:e})=>{const t=((null==e?void 0:e.roundTripTime)||0)+2*((null==e?void 0:e.jitter)||0)+10;let r=t<160?93.2-t/40:93.2-(t-120)/10;r-=2.5*(100*((null==e?void 0:e.fractionLost)||0));return 1+.035*r+7e-6*r*(r-60)*(100-r)}},{id:"rendered",value:()=>1},{id:"active",value:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&t&&r?1:0},{id:"cpu-pressure",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},value:({stats:e})=>{var t;return{nominal:.25,fair:.5,serious:.75,critical:1}[(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)||""]||0}},{id:"turn-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some(e=>e.usingTurn)?1:0},{id:"turn-tls-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some(e=>"tls"===e.turnProtocol)?1:0},{id:"concealment",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>(null==e?void 0:e.audioConcealment)||NaN},{id:"deceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>(null==e?void 0:e.audioDeceleration)||NaN},{id:"acceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>(null==e?void 0:e.audioAcceleration)||NaN},{id:"qpf",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:n})=>e&&"video"===n&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+(t.qpf||0),0)}];let Sp,Cp,kp;const Tp=()=>{Sp={},Cp={},kp={aggregated:{issues:Cp,metrics:Sp}}};function Pp(e,t){const{client:r,kind:n}=t;if(e.global&&"global"!==n)return!1;if(!e.global&&"global"===n)return!1;let i="global"===n;return("audio"===n&&r.audio.enabled||"video"===n&&r.video.enabled)&&(i=!0),i&&(!e.enabled||e.enabled(t))}function Rp(e,t){Object.values(Sp).forEach(e=>{e.curTicks=0,e.curSum=0,e.curMax=0,e.curMin=0,e.curAvg=0}),Object.values(Cp).forEach(e=>{e.curTicks=0,e.curRegistered=0,e.active=!1}),t.find(e=>!e.isLocalClient)&&(t.forEach(r=>{const n=e[r.id];["video","audio","global"].forEach(e=>{if("global"===e&&!r.isLocalClient)return;let i=kp[r.id];i||(i={issues:{},metrics:{}},kp[r.id]=i);const s="audio"===e||"video"===e?r[e].track:void 0,o=!!s&&"ended"!==s.readyState,a=s&&n&&n.tracks[s.id],c=a?Object.values(a.ssrcs).sort((e,t)=>(e.height||Number.MAX_SAFE_INTEGER)-(t.height||Number.MAX_SAFE_INTEGER)):[],d=c[0],l={client:r,clients:t,kind:e,track:s,trackStats:a,stats:n,hasLiveTrack:o,ssrc0:d,ssrcs:c,issues:i.issues,metrics:i.metrics},u="global"===e?"global":`${r.isLocalClient?"loc":"rem"}-${r.isPresentation?"pres":"cam"}-${e}`;wp.forEach(e=>{if(Pp(e,l)){const t=`${u}-${e.id}`;let r=i.metrics[t];const n=e.value(l);r||(r={ticks:0,sum:0,avg:0,min:n,max:n},i.metrics[t]=r),r.ticks++,r.sum+=n,r.min=Math.min(r.min,n),r.max=Math.max(r.max,n),r.avg=r.sum/r.ticks;let s=Sp[t];s||(s={ticks:0,sum:0,min:n,max:n,avg:0,curTicks:0,curMin:0,curMax:0,curAvg:0,curSum:0,totTicks:0,totMin:0,totMax:0,totAvg:0,totSum:0},Sp[t]=s),s.ticks++,s.sum+=n,s.min=Math.min(s.min,n),s.max=Math.max(s.max,n),s.avg=s.sum/s.ticks,0===s.curTicks?(s.curMax=n,s.curMin=n,s.curSum=n):(s.curMax=Math.max(s.curMax,n),s.curMin=Math.min(s.curMin,n),s.curSum+=n),s.curTicks++}}),bp.forEach(e=>{const t=`${u}-${e.id}`,r=Pp(e,l);let n=i.issues[t],s=Cp[t];if(r){n||(n={active:!1,ticks:0,registered:0,initial:0,periods:0,current:0,longest:0},i.issues[t]=n),n.ticks++,s||(s={active:!1,ticks:0,registered:0,initial:0,curTicks:0,curRegistered:0},Cp[t]=s),s.ticks++,s.curTicks++;e.check(l)?(n.registered++,n.current++,n.active||(n.active=!0,n.periods++),n.ticks===n.initial+1&&(n.initial++,s.initial++),n.current>n.longest&&(n.longest=n.current),s.active=!0,s.registered++,s.curRegistered++):(n.active=!1,n.current=0)}else n&&(n.active=!1,n.current=0)})})}),Object.values(Sp).forEach(e=>{e.curTicks&&(e.curAvg=e.curSum/e.curTicks,0===e.totTicks&&(e.totMin=e.curSum,e.totMax=e.curSum),e.totTicks++,e.totSum+=e.curSum,e.totMin=Math.min(e.totMin,e.curSum),e.totMax=Math.max(e.totMax,e.curSum),e.totAvg=e.totSum/e.totTicks)}),Object.values(Cp).forEach(e=>{e.curTicks}),yp.forEach(r=>{var n;return null===(n=r.onUpdatedIssues)||void 0===n?void 0:n.call(r,kp,e,t)}))}function Ep(e){return yp.push(e),_p||(_p=function(e,t=gl,r=ml){return r.subscriptions.push(e),r.currentMonitor||(r.currentMonitor=bl(r,t)),{stop(){var t;r.subscriptions=r.subscriptions.filter(t=>t!==e),r.subscriptions.length||(null===(t=r.currentMonitor)||void 0===t||t.stop(),r.currentMonitor=null)}}}({onUpdatedStats:Rp}).stop),{stop(){yp=yp.filter(t=>t!==e),yp.length||(null==_p||_p(),_p=null,Tp())}}}var Op,xp;Tp();const Ip="safari"===(null===(xp=(null!==(Op=ko.default)&&void 0!==Op?Op:ko).browserDetails)||void 0===xp?void 0:xp.browser);function Dp({disableAEC:e,disableAGC:t,hd:r,lax:n,lowDataMode:i,preferredDeviceIds:s,resolution:o,simulcast:a,widescreen:c}){var d,l;let u=480,p=240;r&&(u=n||Ip?720:{min:360,ideal:720}),a&&(!1===r?(u=360,p=270):p=360);const h={audio:Object.assign({},s.audioId&&{deviceId:s.audioId}),video:Object.assign(Object.assign({},s.videoId?{deviceId:s.videoId}:{facingMode:"user"}),{height:i?p:u,frameRate:i&&!a?15:24})};if(n)return(null===(d=h.audio)||void 0===d?void 0:d.deviceId)||(h.audio=!0),null===(l=h.video)||void 0===l||delete l.facingMode,h;if(o){const[e,t,r]=o.split(/[^\d]/g).map(e=>parseInt(e,10));e&&(h.video.width={exact:e}),t&&(h.video.height={exact:t}),r&&(h.video.frameRate={exact:r}),delete h.video.facingMode}else h.video.aspectRatio=c?16/9:4/3;return t&&(h.audio.autoGainControl=!1),e&&(h.audio.echoCancellation=!1),h}function Mp({devices:e,videoId:t,audioId:r,options:n,type:i="ideal"}){const s=e.filter(e=>"audioinput"===e.kind),o=e.filter(e=>"videoinput"===e.kind),a=!r||!s.some(e=>e.deviceId===r),c=!t||!o.some(e=>e.deviceId===t),d=Dp(Object.assign({preferredDeviceIds:{audioId:a?null:{[i]:r},videoId:c?null:{[i]:t}}},n));return!1!==r&&s.length||delete d.audio,!1!==t&&o.length||delete d.video,d}const jp=new Ld,Ap=/mobi/i.test(navigator.userAgent);class Lp extends Error{constructor(...e){super(...e),this.name="nodevices"}}function Np(e){return e.audio||e.video?navigator.mediaDevices.getUserMedia(e).catch(t=>{const r=`${t}, ${JSON.stringify(e,null,2)}`;throw jp.error(`getUserMedia ${r}`),t}):Promise.reject(new Lp("No provided devices"))}function Fp(e,t,r,n){var i,s,o;let a={deviceId:null};return t?(a.label=t.label,t.getSettings&&(a=Object.assign(Object.assign({},a),t.getSettings())),a.deviceId?a:(t.getCapabilities&&(a.deviceId=t.getCapabilities().deviceId),a.deviceId?a:(t.label&&r&&(a.deviceId=null===(s=r.find(r=>t.label===r.label&&r.kind===e))||void 0===s?void 0:s.deviceId),a.deviceId||(a.deviceId=null===(o=t.getConstraints())||void 0===o?void 0:o.deviceId,a.broken=1),a))):(n&&r&&(a.deviceId=null===(i=r.find(t=>t.deviceId===n&&t.kind===e))||void 0===i?void 0:i.deviceId),a)}function Bp(e,t){t&&"audio"!==t||e.getAudioTracks().forEach(e=>e.stop()),t&&"video"!==t||e.getVideoTracks().forEach(e=>e.stop())}function zp(e){return Td(this,arguments,void 0,function*(e,{replaceStream:t,fallback:r=!0}={}){var n;let i,s,o,a=null;const c=!1===e.audioId?"video":!1===e.videoId&&"audio",d=Ap||"video"!==c,l=Mp(e),u=(e,t)=>e?(e.details=Object.assign({constraints:l,constraint:e.constraint||(null==t?void 0:t.constraint),newConstraints:s,fallback:r,stopTracks:d},e!==i&&{error:String(i)}),e):new Error("Unknown error"),p=t=>Td(this,void 0,void 0,function*(){if(l.audio&&l.video){try{a=yield Np(Mp(Object.assign(Object.assign({},e),{audioId:!1})))}catch(e){"NotFoundError"!==(null==e?void 0:e.name)&&u(e,t)}try{a||(a=yield Np(Mp(Object.assign(Object.assign({},e),{videoId:!1}))))}catch(e){u(e,t)}}});d&&t&&Bp(t,c);try{a=yield Np(l)}catch(s){if(i=s,!r)throw u(s);if("OverconstrainedError"===(null==s?void 0:s.name)){o={deviceId:{videoId:null,audioId:null},width:{lax:!0},height:{lax:!0},"":{audioId:null,videoId:null,lax:!0}}[s.constraint||""]}else if("NotFoundError"===(null==s?void 0:s.name))yield p(s);else if("NotAllowedError"===(null==s?void 0:s.name)||"NotReadableError"===(null==s?void 0:s.name)||"AbortError"===(null==s?void 0:s.name)){if(t&&!d&&(Bp(t,c),o=e),"NotAllowedError"===(null==s?void 0:s.name))yield p(s);else if("NotAllowedError"!==s.name){try{a=yield Np(Mp(Object.assign(Object.assign({},e),{options:Object.assign(Object.assign({},e.options),{lax:!0})})))}catch(e){jp.warn("Tried getting stream again with laxer constraints, but failed: "+(""+e))}const t=(""+s).toLowerCase(),r={audio:"audioId",video:"videoId"}[(null===(n=/(video|audio)/.exec(t))||void 0===n?void 0:n[0])||c||""];if(!a&&r)try{a=yield Np(Mp(Object.assign(Object.assign({},e),{[r]:null})))}catch(e){jp.warn(`Re-tried ${r} with no constraints, but failed: ${""+e}`)}if(!a){const t=r?[r]:["videoId","audioId"];for(const r of t){try{a=yield Np(Mp(Object.assign(Object.assign({},e),{[r]:!1})))}catch(e){jp.warn(`Re-tried without ${r}, but failed: ${""+e}`)}if(a)break}}}}else s||(yield p(s))}if(o){const t=c?{audio:{videoId:!1},video:{audioId:!1}}[c]:{};s=Mp(Object.assign(Object.assign(Object.assign(Object.assign({},e),o),{options:Object.assign(Object.assign({},e.options),{lax:o.lax})}),t));try{a=yield Np(s)}catch(e){throw u(e,i)}}if(!a)throw u(i);let h;return t&&(d||Bp(t,c),h=function(e,t,r){const n=[];return r&&"audio"!==r||(n.push(...e.getAudioTracks()),t.getAudioTracks().forEach(t=>{t.replacement=!0,e.addTrack(t)})),r&&"video"!==r||(n.push(...e.getVideoTracks()),t.getVideoTracks().forEach(t=>{t.replacement=!0,e.addTrack(t)})),n.forEach(t=>{t.replaced=!0,e.removeTrack(t)}),n}(t,a,c),a=t),{error:i&&u(i),stream:a,replacedTracks:h}})}function Up({oldDevices:e,newDevices:t,currentAudioId:r,currentVideoId:n,currentSpeakerId:i}){const s=function(e,t){const[r,n]=[e,t].map(e=>e.filter(e=>e.kind&&e.deviceId).reduce((e,t)=>Object.assign(Object.assign({},e),{[t.kind]:Object.assign(Object.assign({},e[t.kind]),{[t.deviceId]:t})}),{})),i={};return e.forEach(e=>{e.kind&&e.deviceId&&(i[e.kind]||(i[e.kind]={added:{},removed:{},changed:{}}),n[e.kind]&&n[e.kind][e.deviceId]||(i[e.kind].removed[e.deviceId]=e))}),t.forEach(e=>{e.kind&&e.deviceId&&(i[e.kind]||(i[e.kind]={added:{},removed:{},changed:{}}),r[e.kind]&&r[e.kind][e.deviceId]?r[e.kind][e.deviceId].label&&r[e.kind][e.deviceId].label!==e.label&&(i[e.kind].changed[e.deviceId]=e):i[e.kind].added[e.deviceId]=e)}),i}(e,t),o={},a={},c={};return[["audioinput",r],["videoinput",n],["audiooutput",i]].forEach(([e,r])=>{const n=s[e];if(n){if(r){if(n.removed[r]&&(a[e]={deviceId:null},"audiooutput"===e)){const r=t.find(e=>"audiooutput"===e.kind);a[e]={deviceId:null==r?void 0:r.deviceId}}n.changed[r]&&(a[e]={deviceId:r})}if(Object.keys(n.added).length>0){const[t]=Object.keys(n.added).slice(0,1),r=n.added[t];c[e]={deviceId:r.deviceId,label:r.label,kind:r.kind}}if(Object.keys(n.removed).length>0){const[t]=Object.keys(n.removed).slice(0,1);o[e]=n.removed[t]}}}),{addedDevices:c,changedDevices:a,removedDevices:o}}var Vp;function $p(e,t){return function(){return e.apply(t,arguments)}}!function(e){e.rtc_manager_created="rtc_manager_created",e.stream_added="stream_added"}(Vp||(Vp={}));const{toString:Gp}=Object.prototype,{getPrototypeOf:qp}=Object,{iterator:Hp,toStringTag:Wp}=Symbol,Jp=(e=>t=>{const r=Gp.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Kp=e=>(e=e.toLowerCase(),t=>Jp(t)===e),Qp=e=>t=>typeof t===e,{isArray:Yp}=Array,Xp=Qp("undefined");function Zp(e){return null!==e&&!Xp(e)&&null!==e.constructor&&!Xp(e.constructor)&&rh(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const eh=Kp("ArrayBuffer");const th=Qp("string"),rh=Qp("function"),nh=Qp("number"),ih=e=>null!==e&&"object"==typeof e,sh=e=>{if("object"!==Jp(e))return!1;const t=qp(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Wp in e||Hp in e)},oh=Kp("Date"),ah=Kp("File"),ch=Kp("Blob"),dh=Kp("FileList"),lh=Kp("URLSearchParams"),[uh,ph,hh,fh]=["ReadableStream","Request","Response","Headers"].map(Kp);function mh(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),Yp(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(Zp(e))return;const i=r?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(n=0;n<s;n++)o=i[n],t.call(null,e[o],o,e)}}function gh(e,t){if(Zp(e))return null;t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const vh="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,bh=e=>!Xp(e)&&e!==vh;const yh=(_h="undefined"!=typeof Uint8Array&&qp(Uint8Array),e=>_h&&e instanceof _h);var _h;const wh=Kp("HTMLFormElement"),Sh=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Ch=Kp("RegExp"),kh=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};mh(r,(r,i)=>{let s;!1!==(s=t(r,i,e))&&(n[i]=s||r)}),Object.defineProperties(e,n)};const Th=Kp("AsyncFunction"),Ph=(Rh="function"==typeof setImmediate,Eh=rh(vh.postMessage),Rh?setImmediate:Eh?(Oh=`axios@${Math.random()}`,xh=[],vh.addEventListener("message",({source:e,data:t})=>{e===vh&&t===Oh&&xh.length&&xh.shift()()},!1),e=>{xh.push(e),vh.postMessage(Oh,"*")}):e=>setTimeout(e));var Rh,Eh,Oh,xh;const Ih="undefined"!=typeof queueMicrotask?queueMicrotask.bind(vh):"undefined"!=typeof process&&process.nextTick||Ph;var Dh={isArray:Yp,isArrayBuffer:eh,isBuffer:Zp,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||rh(e.append)&&("formdata"===(t=Jp(e))||"object"===t&&rh(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&eh(e.buffer),t},isString:th,isNumber:nh,isBoolean:e=>!0===e||!1===e,isObject:ih,isPlainObject:sh,isEmptyObject:e=>{if(!ih(e)||Zp(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:uh,isRequest:ph,isResponse:hh,isHeaders:fh,isUndefined:Xp,isDate:oh,isFile:ah,isBlob:ch,isRegExp:Ch,isFunction:rh,isStream:e=>ih(e)&&rh(e.pipe),isURLSearchParams:lh,isTypedArray:yh,isFileList:dh,forEach:mh,merge:function e(){const{caseless:t}=bh(this)&&this||{},r={},n=(n,i)=>{const s=t&&gh(r,i)||i;sh(r[s])&&sh(n)?r[s]=e(r[s],n):sh(n)?r[s]=e({},n):Yp(n)?r[s]=n.slice():r[s]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&mh(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(mh(t,(t,n)=>{r&&rh(t)?e[n]=$p(t,r):e[n]=t},{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&qp(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Jp,kindOfTest:Kp,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Yp(e))return e;let t=e.length;if(!nh(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Hp]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:wh,hasOwnProperty:Sh,hasOwnProp:Sh,reduceDescriptors:kh,freezeMethods:e=>{kh(e,(t,r)=>{if(rh(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];rh(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach(e=>{r[e]=!0})};return Yp(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:gh,global:vh,isContextDefined:bh,isSpecCompliantForm:function(e){return!!(e&&rh(e.append)&&"FormData"===e[Wp]&&e[Hp])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(ih(e)){if(t.indexOf(e)>=0)return;if(Zp(e))return e;if(!("toJSON"in e)){t[n]=e;const i=Yp(e)?[]:{};return mh(e,(e,t)=>{const s=r(e,n+1);!Xp(s)&&(i[t]=s)}),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn:Th,isThenable:e=>e&&(ih(e)||rh(e))&&rh(e.then)&&rh(e.catch),setImmediate:Ph,asap:Ih,isIterable:e=>null!=e&&rh(e[Hp])};function Mh(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Dh.inherits(Mh,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Dh.toJSONObject(this.config),code:this.code,status:this.status}}});const jh=Mh.prototype,Ah={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Ah[e]={value:e}}),Object.defineProperties(Mh,Ah),Object.defineProperty(jh,"isAxiosError",{value:!0}),Mh.from=(e,t,r,n,i,s)=>{const o=Object.create(jh);return Dh.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Mh.call(o,e.message,t,r,n,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function Lh(e){return Dh.isPlainObject(e)||Dh.isArray(e)}function Nh(e){return Dh.endsWith(e,"[]")?e.slice(0,-2):e}function Fh(e,t,r){return e?e.concat(t).map(function(e,t){return e=Nh(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const Bh=Dh.toFlatObject(Dh,{},null,function(e){return/^is[A-Z]/.test(e)});function zh(e,t,r){if(!Dh.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=Dh.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!Dh.isUndefined(t[e])})).metaTokens,i=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&Dh.isSpecCompliantForm(t);if(!Dh.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Dh.isDate(e))return e.toISOString();if(Dh.isBoolean(e))return e.toString();if(!a&&Dh.isBlob(e))throw new Mh("Blob is not supported. Use a Buffer instead.");return Dh.isArrayBuffer(e)||Dh.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(Dh.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(Dh.isArray(e)&&function(e){return Dh.isArray(e)&&!e.some(Lh)}(e)||(Dh.isFileList(e)||Dh.endsWith(r,"[]"))&&(a=Dh.toArray(e)))return r=Nh(r),a.forEach(function(e,n){!Dh.isUndefined(e)&&null!==e&&t.append(!0===o?Fh([r],n,s):null===o?r:r+"[]",c(e))}),!1;return!!Lh(e)||(t.append(Fh(i,r,s),c(e)),!1)}const l=[],u=Object.assign(Bh,{defaultVisitor:d,convertValue:c,isVisitable:Lh});if(!Dh.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!Dh.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),Dh.forEach(r,function(r,s){!0===(!(Dh.isUndefined(r)||null===r)&&i.call(t,r,Dh.isString(s)?s.trim():s,n,u))&&e(r,n?n.concat(s):[s])}),l.pop()}}(e),t}function Uh(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Vh(e,t){this._pairs=[],e&&zh(e,this,t)}const $h=Vh.prototype;function Gh(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function qh(e,t,r){if(!t)return e;const n=r&&r.encode||Gh;Dh.isFunction(r)&&(r={serialize:r});const i=r&&r.serialize;let s;if(s=i?i(t,r):Dh.isURLSearchParams(t)?t.toString():new Vh(t,r).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}$h.append=function(e,t){this._pairs.push([e,t])},$h.toString=function(e){const t=e?function(t){return e.call(this,t,Uh)}:Uh;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Hh{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Dh.forEach(this.handlers,function(t){null!==t&&e(t)})}}var Wh={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Jh={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Vh,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const Kh="undefined"!=typeof window&&"undefined"!=typeof document,Qh="object"==typeof navigator&&navigator||void 0,Yh=Kh&&(!Qh||["ReactNative","NativeScript","NS"].indexOf(Qh.product)<0),Xh="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Zh=Kh&&window.location.href||"http://localhost";var ef={...Object.freeze({__proto__:null,hasBrowserEnv:Kh,hasStandardBrowserEnv:Yh,hasStandardBrowserWebWorkerEnv:Xh,navigator:Qh,origin:Zh}),...Jh};function tf(e){function t(e,r,n,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&Dh.isArray(n)?n.length:s,a)return Dh.hasOwnProp(n,s)?n[s]=[n[s],r]:n[s]=r,!o;n[s]&&Dh.isObject(n[s])||(n[s]=[]);return t(e,r,n[s],i)&&Dh.isArray(n[s])&&(n[s]=function(e){const t={},r=Object.keys(e);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],t[s]=e[s];return t}(n[s])),!o}if(Dh.isFormData(e)&&Dh.isFunction(e.entries)){const r={};return Dh.forEachEntry(e,(e,n)=>{t(function(e){return Dh.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),n,r,0)}),r}return null}const rf={transitional:Wh,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=Dh.isObject(e);i&&Dh.isHTMLForm(e)&&(e=new FormData(e));if(Dh.isFormData(e))return n?JSON.stringify(tf(e)):e;if(Dh.isArrayBuffer(e)||Dh.isBuffer(e)||Dh.isStream(e)||Dh.isFile(e)||Dh.isBlob(e)||Dh.isReadableStream(e))return e;if(Dh.isArrayBufferView(e))return e.buffer;if(Dh.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return zh(e,new ef.classes.URLSearchParams,{visitor:function(e,t,r,n){return ef.isNode&&Dh.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=Dh.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return zh(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),function(e,t,r){if(Dh.isString(e))try{return(t||JSON.parse)(e),Dh.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||rf.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(Dh.isResponse(e)||Dh.isReadableStream(e))return e;if(e&&Dh.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw Mh.from(e,Mh.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ef.classes.FormData,Blob:ef.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Dh.forEach(["delete","get","head","post","put","patch"],e=>{rf.headers[e]={}});const nf=Dh.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const sf=Symbol("internals");function of(e){return e&&String(e).trim().toLowerCase()}function af(e){return!1===e||null==e?e:Dh.isArray(e)?e.map(af):String(e)}function cf(e,t,r,n,i){return Dh.isFunction(n)?n.call(this,t,r):(i&&(t=r),Dh.isString(t)?Dh.isString(n)?-1!==t.indexOf(n):Dh.isRegExp(n)?n.test(t):void 0:void 0)}let df=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=of(t);if(!i)throw new Error("header name must be a non-empty string");const s=Dh.findKey(n,i);(!s||void 0===n[s]||!0===r||void 0===r&&!1!==n[s])&&(n[s||t]=af(e))}const s=(e,t)=>Dh.forEach(e,(e,r)=>i(e,r,t));if(Dh.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(Dh.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let r,n,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&nf[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t})(e),t);else if(Dh.isObject(e)&&Dh.isIterable(e)){let r,n,i={};for(const t of e){if(!Dh.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?Dh.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}s(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=of(e)){const r=Dh.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(Dh.isFunction(t))return t.call(this,e,r);if(Dh.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=of(e)){const r=Dh.findKey(this,e);return!(!r||void 0===this[r]||t&&!cf(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=of(e)){const i=Dh.findKey(r,e);!i||t&&!cf(0,r[i],i,t)||(delete r[i],n=!0)}}return Dh.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!cf(0,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return Dh.forEach(this,(n,i)=>{const s=Dh.findKey(r,i);if(s)return t[s]=af(n),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(i):String(i).trim();o!==i&&delete t[i],t[o]=af(n),r[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Dh.forEach(this,(r,n)=>{null!=r&&!1!==r&&(t[n]=e&&Dh.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[sf]=this[sf]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=of(e);t[n]||(!function(e,t){const r=Dh.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})})}(r,e),t[n]=!0)}return Dh.isArray(e)?e.forEach(n):n(e),this}};function lf(e,t){const r=this||rf,n=t||r,i=df.from(n.headers);let s=n.data;return Dh.forEach(e,function(e){s=e.call(r,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function uf(e){return!(!e||!e.__CANCEL__)}function pf(e,t,r){Mh.call(this,null==e?"canceled":e,Mh.ERR_CANCELED,t,r),this.name="CanceledError"}function hf(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new Mh("Request failed with status code "+r.status,[Mh.ERR_BAD_REQUEST,Mh.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}df.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Dh.reduceDescriptors(df.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),Dh.freezeMethods(df),Dh.inherits(pf,Mh,{__CANCEL__:!0});const ff=(e,t,r=3)=>{let n=0;const i=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];i||(i=c),r[s]=a,n[s]=c;let l=o,u=0;for(;l!==s;)u+=r[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let r,n,i=0,s=1e3/t;const o=(t,s=Date.now())=>{i=s,r=null,n&&(clearTimeout(n),n=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=s?o(e,t):(r=e,n||(n=setTimeout(()=>{n=null,o(r)},s-a)))},()=>r&&o(r)]}(r=>{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-n,c=i(a);n=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})},r)},mf=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},gf=e=>(...t)=>Dh.asap(()=>e(...t));var vf=ef.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,ef.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(ef.origin),ef.navigator&&/(msie|trident)/i.test(ef.navigator.userAgent)):()=>!0,bf=ef.hasStandardBrowserEnv?{write(e,t,r,n,i,s){const o=[e+"="+encodeURIComponent(t)];Dh.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Dh.isString(n)&&o.push("path="+n),Dh.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function yf(e,t,r){let n=!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const _f=e=>e instanceof df?{...e}:e;function wf(e,t){t=t||{};const r={};function n(e,t,r,n){return Dh.isPlainObject(e)&&Dh.isPlainObject(t)?Dh.merge.call({caseless:n},e,t):Dh.isPlainObject(t)?Dh.merge({},t):Dh.isArray(t)?t.slice():t}function i(e,t,r,i){return Dh.isUndefined(t)?Dh.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function s(e,t){if(!Dh.isUndefined(t))return n(void 0,t)}function o(e,t){return Dh.isUndefined(t)?Dh.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,s){return s in t?n(r,i):s in e?n(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>i(_f(e),_f(t),0,!0)};return Dh.forEach(Object.keys({...e,...t}),function(n){const s=c[n]||i,o=s(e[n],t[n],n);Dh.isUndefined(o)&&s!==a||(r[n]=o)}),r}var Sf=e=>{const t=wf({},e);let r,{data:n,withXSRFToken:i,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=df.from(a),t.url=qh(yf(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Dh.isFormData(n))if(ef.hasStandardBrowserEnv||ef.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(ef.hasStandardBrowserEnv&&(i&&Dh.isFunction(i)&&(i=i(t)),i||!1!==i&&vf(t.url))){const e=s&&o&&bf.read(o);e&&a.set(s,e)}return t};var Cf="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const n=Sf(e);let i=n.data;const s=df.from(n.headers).normalize();let o,a,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=n;function f(){d&&d(),l&&l(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let m=new XMLHttpRequest;function g(){if(!m)return;const n=df.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());hf(function(e){t(e),f()},function(e){r(e),f()},{data:u&&"text"!==u&&"json"!==u?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new Mh("Request aborted",Mh.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new Mh("Network Error",Mh.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||Wh;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new Mh(t,i.clarifyTimeoutError?Mh.ETIMEDOUT:Mh.ECONNABORTED,e,m)),m=null},void 0===i&&s.setContentType(null),"setRequestHeader"in m&&Dh.forEach(s.toJSON(),function(e,t){m.setRequestHeader(t,e)}),Dh.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),u&&"json"!==u&&(m.responseType=n.responseType),h&&([c,l]=ff(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,d]=ff(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(n.cancelToken||n.signal)&&(o=t=>{m&&(r(!t||t.type?new pf(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);v&&-1===ef.protocols.indexOf(v)?r(new Mh("Unsupported protocol "+v+":",Mh.ERR_BAD_REQUEST,e)):m.send(i||null)})};const kf=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof Mh?t:new pf(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,i(new Mh(`timeout ${t} of ms exceeded`,Mh.ETIMEDOUT))},t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:a}=n;return a.unsubscribe=()=>Dh.asap(o),a}},Tf=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,i=0;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},Pf=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},Rf=(e,t,r,n)=>{const i=async function*(e,t){for await(const r of Pf(e))yield*Tf(r,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let s=n.byteLength;if(r){let e=o+=s;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},Ef="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Of=Ef&&"function"==typeof ReadableStream,xf=Ef&&("function"==typeof TextEncoder?(If=new TextEncoder,e=>If.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var If;const Df=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},Mf=Of&&Df(()=>{let e=!1;const t=new Request(ef.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),jf=Of&&Df(()=>Dh.isReadableStream(new Response("").body)),Af={stream:jf&&(e=>e.body)};var Lf;Ef&&(Lf=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Af[e]&&(Af[e]=Dh.isFunction(Lf[e])?t=>t[e]():(t,r)=>{throw new Mh(`Response type '${e}' is not supported`,Mh.ERR_NOT_SUPPORT,r)})}));const Nf=async(e,t)=>{const r=Dh.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(Dh.isBlob(e))return e.size;if(Dh.isSpecCompliantForm(e)){const t=new Request(ef.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Dh.isArrayBufferView(e)||Dh.isArrayBuffer(e)?e.byteLength:(Dh.isURLSearchParams(e)&&(e+=""),Dh.isString(e)?(await xf(e)).byteLength:void 0)})(t):r};var Ff=Ef&&(async e=>{let{url:t,method:r,data:n,signal:i,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=Sf(e);d=d?(d+"").toLowerCase():"text";let h,f=kf([i,s&&s.toAbortSignal()],o);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&Mf&&"get"!==r&&"head"!==r&&0!==(g=await Nf(l,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(Dh.isFormData(n)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=mf(g,ff(gf(c)));n=Rf(r.body,65536,e,t)}}Dh.isString(u)||(u=u?"include":"omit");const i="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:n,duplex:"half",credentials:i?u:void 0});let s=await fetch(h,p);const o=jf&&("stream"===d||"response"===d);if(jf&&(a||o&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=Dh.toFiniteNumber(s.headers.get("content-length")),[r,n]=a&&mf(t,ff(gf(a),!0))||[];s=new Response(Rf(s.body,65536,r,()=>{n&&n(),m&&m()}),e)}d=d||"text";let v=await Af[Dh.findKey(Af,d)||"text"](s,e);return!o&&m&&m(),await new Promise((t,r)=>{hf(t,r,{data:v,headers:df.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})})}catch(t){if(m&&m(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new Mh("Network Error",Mh.ERR_NETWORK,e,h),{cause:t.cause||t});throw Mh.from(t,t&&t.code,e,h)}});const Bf={http:null,xhr:Cf,fetch:Ff};Dh.forEach(Bf,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const zf=e=>`- ${e}`,Uf=e=>Dh.isFunction(e)||null===e||!1===e;var Vf=e=>{e=Dh.isArray(e)?e:[e];const{length:t}=e;let r,n;const i={};for(let s=0;s<t;s++){let t;if(r=e[s],n=r,!Uf(r)&&(n=Bf[(t=String(r)).toLowerCase()],void 0===n))throw new Mh(`Unknown adapter '${t}'`);if(n)break;i[t||"#"+s]=n}if(!n){const e=Object.entries(i).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new Mh("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(zf).join("\n"):" "+zf(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function $f(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new pf(null,e)}function Gf(e){$f(e),e.headers=df.from(e.headers),e.data=lf.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Vf(e.adapter||rf.adapter)(e).then(function(t){return $f(e),t.data=lf.call(e,e.transformResponse,t),t.headers=df.from(t.headers),t},function(t){return uf(t)||($f(e),t&&t.response&&(t.response.data=lf.call(e,e.transformResponse,t.response),t.response.headers=df.from(t.response.headers))),Promise.reject(t)})}const qf="1.11.0",Hf={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Hf[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Wf={};Hf.transitional=function(e,t,r){function n(e,t){return"[Axios v"+qf+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,s)=>{if(!1===e)throw new Mh(n(i," has been removed"+(t?" in "+t:"")),Mh.ERR_DEPRECATED);return t&&!Wf[i]&&(Wf[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,s)}},Hf.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var Jf={assertOptions:function(e,t,r){if("object"!=typeof e)throw new Mh("options must be an object",Mh.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const s=n[i],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new Mh("option "+s+" must be "+r,Mh.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new Mh("Unknown option "+s,Mh.ERR_BAD_OPTION)}},validators:Hf};const Kf=Jf.validators;let Qf=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Hh,response:new Hh}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=wf(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&Jf.assertOptions(r,{silentJSONParsing:Kf.transitional(Kf.boolean),forcedJSONParsing:Kf.transitional(Kf.boolean),clarifyTimeoutError:Kf.transitional(Kf.boolean)},!1),null!=n&&(Dh.isFunction(n)?t.paramsSerializer={serialize:n}:Jf.assertOptions(n,{encode:Kf.function,serialize:Kf.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Jf.assertOptions(t,{baseUrl:Kf.spelling("baseURL"),withXsrfToken:Kf.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&Dh.merge(i.common,i[t.method]);i&&Dh.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=df.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))});const c=[];let d;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let l,u=0;if(!a){const e=[Gf.bind(this),void 0];for(e.unshift(...o),e.push(...c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=Gf.call(this,p)}catch(e){return Promise.reject(e)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return qh(yf((e=wf(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};Dh.forEach(["delete","get","head","options"],function(e){Qf.prototype[e]=function(t,r){return this.request(wf(r||{},{method:e,url:t,data:(r||{}).data}))}}),Dh.forEach(["post","put","patch"],function(e){function t(t){return function(r,n,i){return this.request(wf(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Qf.prototype[e]=t(),Qf.prototype[e+"Form"]=t(!0)});const Yf={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Yf).forEach(([e,t])=>{Yf[t]=e});const Xf=function e(t){const r=new Qf(t),n=$p(Qf.prototype.request,r);return Dh.extend(n,Qf.prototype,r,{allOwnKeys:!0}),Dh.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(wf(t,r))},n}(rf);Xf.Axios=Qf,Xf.CanceledError=pf,Xf.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const n=new Promise(e=>{r.subscribe(e),t=e}).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e(function(e,n,i){r.reason||(r.reason=new pf(e,n,i),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},Xf.isCancel=uf,Xf.VERSION=qf,Xf.toFormData=zh,Xf.AxiosError=Mh,Xf.Cancel=Xf.CanceledError,Xf.all=function(e){return Promise.all(e)},Xf.spread=function(e){return function(t){return e.apply(null,t)}},Xf.isAxiosError=function(e){return Dh.isObject(e)&&!0===e.isAxiosError},Xf.mergeConfig=wf,Xf.AxiosHeaders=df,Xf.formToJSON=e=>tf(Dh.isHTMLForm(e)?new FormData(e):e),Xf.getAdapter=Vf,Xf.HttpStatusCode=Yf,Xf.default=Xf;const{Axios:Zf,AxiosError:em,CanceledError:tm,isCancel:rm,CancelToken:nm,VERSION:im,all:sm,Cancel:om,isAxiosError:am,spread:cm,toFormData:dm,AxiosHeaders:lm,HttpStatusCode:um,formToJSON:pm,getAdapter:hm,mergeConfig:fm}=Xf;var mm=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),gm=()=>Math.random().toString(36).substring(7).split("").join("."),vm={INIT:`@@redux/INIT${gm()}`,REPLACE:`@@redux/REPLACE${gm()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${gm()}`};function bm(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function ym(e){if(void 0===e)return"undefined";if(null===e)return"null";const t=typeof e;switch(t){case"boolean":case"string":case"number":case"symbol":case"function":return t}if(Array.isArray(e))return"array";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";const r=function(e){return"function"==typeof e.constructor?e.constructor.name:null}(e);switch(r){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return r}return Object.prototype.toString.call(e).slice(8,-1).toLowerCase().replace(/\s/g,"")}function _m(e){let t=typeof e;return t=ym(e),t}function wm(e,t,r){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${_m(e)}'`);if("function"==typeof t&&"function"==typeof r||"function"==typeof r&&"function"==typeof arguments[3])throw new Error("It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if("function"==typeof t&&void 0===r&&(r=t,t=void 0),void 0!==r){if("function"!=typeof r)throw new Error(`Expected the enhancer to be a function. Instead, received: '${_m(r)}'`);return r(wm)(e,t)}let n=e,i=t,s=new Map,o=s,a=0,c=!1;function d(){o===s&&(o=new Map,s.forEach((e,t)=>{o.set(t,e)}))}function l(){if(c)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return i}function u(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${_m(e)}'`);if(c)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");let t=!0;d();const r=a++;return o.set(r,e),function(){if(t){if(c)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");t=!1,d(),o.delete(r),s=null}}}function p(e){if(!bm(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${_m(e)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if("string"!=typeof e.type)throw new Error(`Action "type" property must be a string. Instead, the actual type was: '${_m(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,i=n(i,e)}finally{c=!1}return(s=o).forEach(e=>{e()}),e}p({type:vm.INIT});return{dispatch:p,subscribe:u,getState:l,replaceReducer:function(e){if("function"!=typeof e)throw new Error(`Expected the nextReducer to be a function. Instead, received: '${_m(e)}`);n=e,p({type:vm.REPLACE})},[mm]:function(){const e=u;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(`Expected the observer to be an object. Instead, received: '${_m(t)}'`);function r(){const e=t;e.next&&e.next(l())}r();return{unsubscribe:e(r)}},[mm](){return this}}}}}function Sm(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function Cm(e){const t=Object.keys(e),r={};for(let n=0;n<t.length;n++){const i=t[n];void 0===e[i]&&Sm(`No reducer provided for key "${i}"`),"function"==typeof e[i]&&(r[i]=e[i])}const n=Object.keys(r);let i,s;i={};try{!function(e){Object.keys(e).forEach(t=>{const r=e[t];if(void 0===r(void 0,{type:vm.INIT}))throw new Error(`The slice reducer for key "${t}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);if(void 0===r(void 0,{type:vm.PROBE_UNKNOWN_ACTION()}))throw new Error(`The slice reducer for key "${t}" returned undefined when probed with a random type. Don't try to handle '${vm.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`)})}(r)}catch(e){s=e}return function(e={},t){if(s)throw s;{const n=function(e,t,r,n){const i=Object.keys(t),s=r&&r.type===vm.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===i.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!bm(e))return`The ${s} has unexpected type of "${_m(e)}". Expected argument to be an object with the following keys: "${i.join('", "')}"`;const o=Object.keys(e).filter(e=>!t.hasOwnProperty(e)&&!n[e]);return o.forEach(e=>{n[e]=!0}),r&&r.type===vm.REPLACE?void 0:o.length>0?`Unexpected ${o.length>1?"keys":"key"} "${o.join('", "')}" found in ${s}. Expected to find one of the known reducer keys instead: "${i.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,r,t,i);n&&Sm(n)}let o=!1;const a={};for(let i=0;i<n.length;i++){const s=n[i],c=r[s],d=e[s],l=c(d,t);if(void 0===l){const e=t&&t.type;throw new Error(`When called with an action of type ${e?`"${String(e)}"`:"(unknown type)"}, the slice reducer for key "${s}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`)}a[s]=l,o=o||l!==d}return o=o||n.length!==Object.keys(e).length,o?a:e}}function km(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce((e,t)=>(...r)=>e(t(...r)))}function Tm(e){return bm(e)&&"type"in e&&"string"==typeof e.type}var Pm=Symbol.for("immer-nothing"),Rm=Symbol.for("immer-draftable"),Em=Symbol.for("immer-state"),Om=[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}];function xm(e,...t){{const r=Om[e],n="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${n}`)}}var Im=Object.getPrototypeOf;function Dm(e){return!!e&&!!e[Em]}function Mm(e){return!!e&&(Am(e)||Array.isArray(e)||!!e[Rm]||!!e.constructor?.[Rm]||zm(e)||Um(e))}var jm=Object.prototype.constructor.toString();function Am(e){if(!e||"object"!=typeof e)return!1;const t=Im(e);if(null===t)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===jm}function Lm(e,t){0===Nm(e)?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Nm(e){const t=e[Em];return t?t.type_:Array.isArray(e)?1:zm(e)?2:Um(e)?3:0}function Fm(e,t){return 2===Nm(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Bm(e,t,r){const n=Nm(e);2===n?e.set(t,r):3===n?e.add(r):e[t]=r}function zm(e){return e instanceof Map}function Um(e){return e instanceof Set}function Vm(e){return e.copy_||e.base_}function $m(e,t){if(zm(e))return new Map(e);if(Um(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=Am(e);if(!0===t||"class_only"===t&&!r){const t=Object.getOwnPropertyDescriptors(e);delete t[Em];let r=Reflect.ownKeys(t);for(let n=0;n<r.length;n++){const i=r[n],s=t[i];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(t[i]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[i]})}return Object.create(Im(e),t)}{const t=Im(e);if(null!==t&&r)return{...e};const n=Object.create(t);return Object.assign(n,e)}}function Gm(e,t=!1){return Hm(e)||Dm(e)||!Mm(e)||(Nm(e)>1&&(e.set=e.add=e.clear=e.delete=qm),Object.freeze(e),t&&Object.entries(e).forEach(([e,t])=>Gm(t,!0))),e}function qm(){xm(2)}function Hm(e){return Object.isFrozen(e)}var Wm,Jm={};function Km(e){const t=Jm[e];return t||xm(0,e),t}function Qm(){return Wm}function Ym(e,t){t&&(Km("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Xm(e){Zm(e),e.drafts_.forEach(tg),e.drafts_=null}function Zm(e){e===Wm&&(Wm=e.parent_)}function eg(e){return Wm={drafts_:[],parent_:Wm,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function tg(e){const t=e[Em];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function rg(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[Em].modified_&&(Xm(t),xm(4)),Mm(e)&&(e=ng(t,e),t.parent_||sg(t,e)),t.patches_&&Km("Patches").generateReplacementPatches_(r[Em].base_,e,t.patches_,t.inversePatches_)):e=ng(t,r,[]),Xm(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Pm?e:void 0}function ng(e,t,r){if(Hm(t))return t;const n=t[Em];if(!n)return Lm(t,(i,s)=>ig(e,n,t,i,s,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return sg(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const t=n.copy_;let i=t,s=!1;3===n.type_&&(i=new Set(t),t.clear(),s=!0),Lm(i,(i,o)=>ig(e,n,t,i,o,r,s)),sg(e,t,!1),r&&e.patches_&&Km("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function ig(e,t,r,n,i,s,o){if(i===r&&xm(5),Dm(i)){const o=ng(e,i,s&&t&&3!==t.type_&&!Fm(t.assigned_,n)?s.concat(n):void 0);if(Bm(r,n,o),!Dm(o))return;e.canAutoFreeze_=!1}else o&&r.add(i);if(Mm(i)&&!Hm(i)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;ng(e,i),t&&t.scope_.parent_||"symbol"==typeof n||!Object.prototype.propertyIsEnumerable.call(r,n)||sg(e,i)}}function sg(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Gm(t,r)}var og={get(e,t){if(t===Em)return e;const r=Vm(e);if(!Fm(r,t))return function(e,t,r){const n=dg(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}(e,r,t);const n=r[t];return e.finalized_||!Mm(n)?n:n===cg(e.base_,t)?(ug(e),e.copy_[t]=pg(n,e)):n},has:(e,t)=>t in Vm(e),ownKeys:e=>Reflect.ownKeys(Vm(e)),set(e,t,r){const n=dg(Vm(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const n=cg(Vm(e),t),o=n?.[Em];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((i=r)===(s=n)?0!==i||1/i==1/s:i!=i&&s!=s)&&(void 0!==r||Fm(e.base_,t)))return!0;ug(e),lg(e)}var i,s;return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==cg(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,ug(e),lg(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=Vm(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:r[t]}:n},defineProperty(){xm(11)},getPrototypeOf:e=>Im(e.base_),setPrototypeOf(){xm(12)}},ag={};function cg(e,t){const r=e[Em];return(r?Vm(r):e)[t]}function dg(e,t){if(!(t in e))return;let r=Im(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=Im(r)}}function lg(e){e.modified_||(e.modified_=!0,e.parent_&&lg(e.parent_))}function ug(e){e.copy_||(e.copy_=$m(e.base_,e.scope_.immer_.useStrictShallowCopy_))}Lm(og,(e,t)=>{ag[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),ag.deleteProperty=function(e,t){return isNaN(parseInt(t))&&xm(13),ag.set.call(this,e,t,void 0)},ag.set=function(e,t,r){return"length"!==t&&isNaN(parseInt(t))&&xm(14),og.set.call(this,e[0],t,r,e[0])};function pg(e,t){const r=zm(e)?Km("MapSet").proxyMap_(e,t):Um(e)?Km("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Qm(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=n,s=og;r&&(i=[n],s=ag);const{revoke:o,proxy:a}=Proxy.revocable(i,s);return n.draft_=a,n.revoke_=o,a}(e,t);return(t?t.scope_:Qm()).drafts_.push(r),r}function hg(e){if(!Mm(e)||Hm(e))return e;const t=e[Em];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=$m(e,t.scope_.immer_.useStrictShallowCopy_)}else r=$m(e,!0);return Lm(r,(e,t)=>{Bm(r,e,hg(t))}),t&&(t.finalized_=!1),r}var fg=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,r)=>{if("function"==typeof e&&"function"!=typeof t){const r=t;t=e;const n=this;return function(e=r,...i){return n.produce(e,e=>t.call(this,e,...i))}}let n;if("function"!=typeof t&&xm(6),void 0!==r&&"function"!=typeof r&&xm(7),Mm(e)){const i=eg(this),s=pg(e,void 0);let o=!0;try{n=t(s),o=!1}finally{o?Xm(i):Zm(i)}return Ym(i,r),rg(n,i)}if(!e||"object"!=typeof e){if(n=t(e),void 0===n&&(n=e),n===Pm&&(n=void 0),this.autoFreeze_&&Gm(n,!0),r){const t=[],i=[];Km("Patches").generateReplacementPatches_(e,n,t,i),r(t,i)}return n}xm(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,t=>e(t,...r));let r,n;const i=this.produce(e,t,(e,t)=>{r=e,n=t});return[i,r,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Mm(e)||xm(8),Dm(e)&&(e=function(e){Dm(e)||xm(10,e);return hg(e)}(e));const t=eg(this),r=pg(e,void 0);return r[Em].isManual_=!0,Zm(t),r}finishDraft(e,t){const r=e&&e[Em];r&&r.isManual_||xm(9);const{scope_:n}=r;return Ym(n,t),rg(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));const n=Km("Patches").applyPatches_;return Dm(e)?n(e,t):this.produce(e,e=>n(e,t))}},mg=fg.produce;fg.produceWithPatches.bind(fg),fg.setAutoFreeze.bind(fg),fg.setUseStrictShallowCopy.bind(fg),fg.applyPatches.bind(fg),fg.createDraft.bind(fg),fg.finishDraft.bind(fg);var gg=(e,t,r)=>{if(1===t.length&&t[0]===r){let t=!1;try{const r={};e(r)===r&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},vg=(e,t,r)=>{const{memoize:n,memoizeOptions:i}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,a=n(()=>({}),...i);if(!(a.apply(null,s)===a.apply(null,o))){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:r,firstInputs:s,secondInputs:o,stack:e})}},bg={inputStabilityCheck:"once",identityFunctionCheck:"once"};var yg=e=>Array.isArray(e)?e:[e];function _g(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const r=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${r}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function wg(e,t){const r=[],{length:n}=e;for(let i=0;i<n;i++)r.push(e[i].apply(null,t));return r}var Sg="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function Cg(){return{s:0,v:void 0,o:null,p:null}}function kg(e,t={}){let r={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:n}=t;let i,s=0;function o(){let t=r;const{length:o}=arguments;for(let e=0,r=o;e<r;e++){const r=arguments[e];if("function"==typeof r||"object"==typeof r&&null!==r){let e=t.o;null===e&&(t.o=e=new WeakMap);const n=e.get(r);void 0===n?(t=Cg(),e.set(r,t)):t=n}else{let e=t.p;null===e&&(t.p=e=new Map);const n=e.get(r);void 0===n?(t=Cg(),e.set(r,t)):t=n}}const a=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),s++,n){const e=i?.deref?.()??i;null!=e&&n(e,c)&&(c=e,0!==s&&s--);i="object"==typeof c&&null!==c||"function"==typeof c?new Sg(c):c}return a.s=1,a.v=c,c}return o.clearCache=()=>{r={s:0,v:void 0,o:null,p:null},o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function Tg(e,...t){const r="function"==typeof e?{memoize:e,memoizeOptions:t}:e,n=(...e)=>{let t,n=0,i=0,s={},o=e.pop();"object"==typeof o&&(s=o,o=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);const a={...r,...s},{memoize:c,memoizeOptions:d=[],argsMemoize:l=kg,argsMemoizeOptions:u=[],devModeChecks:p={}}=a,h=yg(d),f=yg(u),m=_g(e),g=c(function(){return n++,o.apply(null,arguments)},...h);let v=!0;const b=l(function(){i++;const e=wg(m,arguments);t=g.apply(null,e);{const{identityFunctionCheck:r,inputStabilityCheck:n}=((e,t)=>{const{identityFunctionCheck:r,inputStabilityCheck:n}={...bg,...t};return{identityFunctionCheck:{shouldRun:"always"===r||"once"===r&&e,run:gg},inputStabilityCheck:{shouldRun:"always"===n||"once"===n&&e,run:vg}}})(v,p);if(r.shouldRun&&r.run(o,e,t),n.shouldRun){const t=wg(m,arguments);n.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:h},arguments)}v&&(v=!1)}return t},...f);return Object.assign(b,{resultFunc:o,memoizedResultFunc:g,dependencies:m,dependencyRecomputations:()=>i,resetDependencyRecomputations:()=>{i=0},lastResult:()=>t,recomputations:()=>n,resetRecomputations:()=>{n=0},memoize:c,argsMemoize:l})};return Object.assign(n,{withTypes:()=>n}),n}var Pg=Tg(kg),Rg=Object.assign((e,t=Pg)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const r=Object.keys(e),n=t(r.map(t=>e[t]),(...e)=>e.reduce((e,t,n)=>(e[r[n]]=t,e),{}));return n},{withTypes:()=>Rg});function Eg(e){return({dispatch:t,getState:r})=>n=>i=>"function"==typeof i?i(t,r,e):n(i)}var Og=Eg(),xg=Eg,Ig="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?km:km.apply(null,arguments)},Dg=e=>e&&"function"==typeof e.match;function Mg(e,t){function r(...r){if(t){let n=t(...r);if(!n)throw new Error("prepareAction did not return an object");return{type:e,payload:n.payload,..."meta"in n&&{meta:n.meta},..."error"in n&&{error:n.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>Tm(t)&&t.type===e,r}function jg(e){return"function"==typeof e&&"type"in e&&Dg(e)}function Ag(e,t){let r=0;return{measureTime(e){const t=Date.now();try{return e()}finally{const e=Date.now();r+=e-t}},warnIfExceeded(){r>e&&console.warn(`${t} took ${r}ms, which is more than the warning threshold of ${e}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`)}}}var Lg=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Ng(e){return Mm(e)?mg(e,()=>{}):e}function Fg(e,t,r){return e.has(t)?e.get(t):e.set(t,r(t)).get(t)}function Bg(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function zg(e,t,r){const n=Ug(e,t,r);return{detectMutations:()=>Vg(e,t,n,r)}}function Ug(e,t=[],r,n="",i=new Set){const s={value:r};if(!e(r)&&!i.has(r)){i.add(r),s.children={};for(const i in r){const o=n?n+"."+i:i;t.length&&-1!==t.indexOf(o)||(s.children[i]=Ug(e,t,r[i],o))}}return s}function Vg(e,t=[],r,n,i=!1,s=""){const o=r?r.value:void 0,a=o===n;if(i&&!a&&!Number.isNaN(n))return{wasMutated:!0,path:s};if(e(o)||e(n))return{wasMutated:!1};const c={};for(let e in r.children)c[e]=!0;for(let e in n)c[e]=!0;const d=t.length>0;for(let i in c){const o=s?s+"."+i:i;if(d){if(t.some(e=>e instanceof RegExp?e.test(o):o===e))continue}const c=Vg(e,t,r.children[i],n[i],a,o);if(c.wasMutated)return c}return{wasMutated:!1}}function $g(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||bm(e)}function Gg(e,t="",r=$g,n,i=[],s){let o;if(!r(e))return{keyPath:t||"<root>",value:e};if("object"!=typeof e||null===e)return!1;if(s?.has(e))return!1;const a=null!=n?n(e):Object.entries(e),c=i.length>0;for(const[e,d]of a){const a=t?t+"."+e:e;if(c){if(i.some(e=>e instanceof RegExp?e.test(a):a===e))continue}if(!r(d))return{keyPath:a,value:d};if("object"==typeof d&&(o=Gg(d,a,r,n,i,s),o))return o}return s&&qg(e)&&s.add(e),!1}function qg(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!qg(t))return!1;return!0}function Hg(e){return"boolean"==typeof e}var Wg=()=>function(e){const{thunk:t=!0,immutableCheck:r=!0,serializableCheck:n=!0,actionCreatorCheck:i=!0}=e??{};let s=new Lg;if(t&&(Hg(t)?s.push(Og):s.push(xg(t.extraArgument))),r){let e={};Hg(r)||(e=r),s.unshift(function(e={}){{let t=function(e,t,n,i){return JSON.stringify(e,r(t,i),n)},r=function(e,t){let r=[],n=[];return t||(t=function(e,t){return r[0]===t?"[Circular ~]":"[Circular ~."+n.slice(0,r.indexOf(t)).join(".")+"]"}),function(i,s){if(r.length>0){var o=r.indexOf(this);~o?r.splice(o+1):r.push(this),~o?n.splice(o,1/0,i):n.push(i),~r.indexOf(s)&&(s=t.call(this,i,s))}else r.push(s);return null==e?s:e.call(this,i,s)}},{isImmutable:n=Bg,ignoredPaths:i,warnAfter:s=32}=e;const o=zg.bind(null,n,i);return({getState:e})=>{let r,n=e(),i=o(n);return a=>c=>{const d=Ag(s,"ImmutableStateInvariantMiddleware");d.measureTime(()=>{if(n=e(),r=i.detectMutations(),i=o(n),r.wasMutated)throw new Error(`A state mutation was detected between dispatches, in the path '${r.path||""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)});const l=a(c);return d.measureTime(()=>{if(n=e(),r=i.detectMutations(),i=o(n),r.wasMutated)throw new Error(`A state mutation was detected inside a dispatch, in the path: ${r.path||""}. Take a look at the reducer(s) handling the action ${t(c)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)}),d.warnIfExceeded(),l}}}}(e))}if(n){let e={};Hg(n)||(e=n),s.push(function(e={}){{const{isSerializable:t=$g,getEntries:r,ignoredActions:n=[],ignoredActionPaths:i=["meta.arg","meta.baseQueryMeta"],ignoredPaths:s=[],warnAfter:o=32,ignoreState:a=!1,ignoreActions:c=!1,disableCache:d=!1}=e,l=!d&&WeakSet?new WeakSet:void 0;return e=>d=>u=>{if(!Tm(u))return d(u);const p=d(u),h=Ag(o,"SerializableStateInvariantMiddleware");return c||n.length&&-1!==n.indexOf(u.type)||h.measureTime(()=>{const e=Gg(u,"",t,r,i,l);if(e){const{keyPath:t,value:r}=e;console.error(`A non-serializable value was detected in an action, in the path: \`${t}\`. Value:`,r,"\nTake a look at the logic that dispatched this action: ",u,"\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)","\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)")}}),a||(h.measureTime(()=>{const n=Gg(e.getState(),"",t,r,s,l);if(n){const{keyPath:e,value:t}=n;console.error(`A non-serializable value was detected in the state, in the path: \`${e}\`. Value:`,t,`\nTake a look at the reducer(s) handling this action type: ${u.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`)}}),h.warnIfExceeded()),p}}}(e))}if(i){let e={};Hg(i)||(e=i),s.unshift(function(e={}){const{isActionCreator:t=jg}=e;return()=>e=>r=>(t(r)&&console.warn(function(e){const t=e?`${e}`.split("/"):[],r=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \`dispatch(${r}())\` instead of \`dispatch(${r})\`. This is necessary even if the action has no payload.`}(r.type)),e(r))}(e))}return s},Jg=e=>t=>{setTimeout(t,e)},Kg=e=>function(t){const{autoBatch:r=!0}=t??{};let n=new Lg(e);return r&&n.push(((e={type:"raf"})=>t=>(...r)=>{const n=t(...r);let i=!0,s=!1,o=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?"undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:Jg(10):"callback"===e.type?e.queueNotification:Jg(e.timeout),d=()=>{o=!1,s&&(s=!1,a.forEach(e=>e()))};return Object.assign({},n,{subscribe(e){const t=n.subscribe(()=>i&&e());return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return i=!e?.meta?.RTK_autoBatch,s=!i,s&&(o||(o=!0,c(d))),n.dispatch(e)}finally{i=!0}}})})("object"==typeof r?r:void 0)),n};function Qg(e){const t=Wg(),{reducer:r,middleware:n,devTools:i=!0,duplicateMiddlewareCheck:s=!0,preloadedState:o,enhancers:a}=e||{};let c,d;if("function"==typeof r)c=r;else{if(!bm(r))throw new Error("`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");c=Cm(r)}if(n&&"function"!=typeof n)throw new Error("`middleware` field must be a callback");if("function"==typeof n){if(d=n(t),!Array.isArray(d))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else d=t();if(d.some(e=>"function"!=typeof e))throw new Error("each middleware provided to configureStore must be a function");if(s){let e=new Set;d.forEach(t=>{if(e.has(t))throw new Error("Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");e.add(t)})}let l=km;i&&(l=Ig({trace:!0,..."object"==typeof i&&i}));const u=function(...e){return t=>(r,n)=>{const i=t(r,n);let s=()=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")};const o={getState:i.getState,dispatch:(e,...t)=>s(e,...t)},a=e.map(e=>e(o));return s=km(...a)(i.dispatch),{...i,dispatch:s}}}(...d),p=Kg(u);if(a&&"function"!=typeof a)throw new Error("`enhancers` field must be a callback");let h="function"==typeof a?a(p):p();if(!Array.isArray(h))throw new Error("`enhancers` callback must return an array");if(h.some(e=>"function"!=typeof e))throw new Error("each enhancer provided to configureStore must be a function");d.length&&!h.includes(u)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return wm(c,o,l(...h))}function Yg(e){const t={},r=[];let n;const i={addCase(e,s){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(n)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");const o="string"==typeof e?e:e.type;if(!o)throw new Error("`builder.addCase` cannot be called with an empty action type");if(o in t)throw new Error(`\`builder.addCase\` cannot be called with two reducers for the same action type '${o}'`);return t[o]=s,i},addMatcher(e,t){if(n)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),i},addDefaultCase(e){if(n)throw new Error("`builder.addDefaultCase` can only be called once");return n=e,i}};return e(i),[t,r,n]}function Xg(...e){return t=>e.some(e=>((e,t)=>Dg(e)?e.match(t):e(t))(e,t))}var Zg=(e=21)=>{let t="",r=e;for(;r--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t},ev=["name","message","stack","code"],tv=class{constructor(e,t){this.payload=e,this.meta=t}_type},rv=class{constructor(e,t){this.payload=e,this.meta=t}_type},nv=e=>{if("object"==typeof e&&null!==e){const t={};for(const r of ev)"string"==typeof e[r]&&(t[r]=e[r]);return t}return{message:String(e)}},iv="External signal was aborted",sv=(()=>{function e(e,t,r){const n=Mg(e+"/fulfilled",(e,t,r,n)=>({payload:e,meta:{...n||{},arg:r,requestId:t,requestStatus:"fulfilled"}})),i=Mg(e+"/pending",(e,t,r)=>({payload:void 0,meta:{...r||{},arg:t,requestId:e,requestStatus:"pending"}})),s=Mg(e+"/rejected",(e,t,n,i,s)=>({payload:i,error:(r&&r.serializeError||nv)(e||"Rejected"),meta:{...s||{},arg:n,requestId:t,rejectedWithValue:!!i,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}}));return Object.assign(function(e,{signal:o}={}){return(a,c,d)=>{const l=r?.idGenerator?r.idGenerator(e):Zg(),u=new AbortController;let p,h;function f(e){h=e,u.abort()}o&&(o.aborted?f(iv):o.addEventListener("abort",()=>f(iv),{once:!0}));const m=async function(){let o;try{let s=r?.condition?.(e,{getState:c,extra:d});if(function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(s)&&(s=await s),!1===s||u.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise((e,t)=>{p=()=>{t({name:"AbortError",message:h||"Aborted"})},u.signal.addEventListener("abort",p)});a(i(l,e,r?.getPendingMeta?.({requestId:l,arg:e},{getState:c,extra:d}))),o=await Promise.race([m,Promise.resolve(t(e,{dispatch:a,getState:c,extra:d,requestId:l,signal:u.signal,abort:f,rejectWithValue:(e,t)=>new tv(e,t),fulfillWithValue:(e,t)=>new rv(e,t)})).then(t=>{if(t instanceof tv)throw t;return t instanceof rv?n(t.payload,l,e,t.meta):n(t,l,e)})])}catch(t){o=t instanceof tv?s(null,l,e,t.payload,t.meta):s(t,l,e)}finally{p&&u.signal.removeEventListener("abort",p)}return r&&!r.dispatchConditionRejection&&s.match(o)&&o.meta.condition||a(o),o}();return Object.assign(m,{abort:f,requestId:l,arg:e,unwrap:()=>m.then(ov)})}},{pending:i,rejected:s,fulfilled:n,settled:Xg(s,n),typePrefix:e})}return e.withTypes=()=>e,e})();function ov(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var av=Symbol.for("rtk-slice-createasyncthunk");function cv(e,t){return`${e}/${t}`}function dv({creators:e}={}){const t=e?.asyncThunk?.[av];return function(e){const{name:r,reducerPath:n=r}=e;if(!r)throw new Error("`name` is a required option for createSlice");const i=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},s=Object.keys(i),o={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},a={addCase(e,t){const r="string"==typeof e?e:e.type;if(!r)throw new Error("`context.addCase` cannot be called with an empty action type");if(r in o.sliceCaseReducersByType)throw new Error("`context.addCase` cannot be called with two reducers for the same action type: "+r);return o.sliceCaseReducersByType[r]=t,a},addMatcher:(e,t)=>(o.sliceMatchers.push({matcher:e,reducer:t}),a),exposeAction:(e,t)=>(o.actionCreators[e]=t,a),exposeCaseReducer:(e,t)=>(o.sliceCaseReducersByName[e]=t,a)};function c(){if("object"==typeof e.extraReducers)throw new Error("The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");const[t={},r=[],n]="function"==typeof e.extraReducers?Yg(e.extraReducers):[e.extraReducers],i={...t,...o.sliceCaseReducersByType};return function(e,t){if("object"==typeof t)throw new Error("The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");let r,[n,i,s]=Yg(t);if("function"==typeof e)r=()=>Ng(e());else{const t=Ng(e);r=()=>t}function o(e=r(),t){let o=[n[t.type],...i.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return 0===o.filter(e=>!!e).length&&(o=[s]),o.reduce((e,r)=>{if(r){if(Dm(e)){const n=r(e,t);return void 0===n?e:n}if(Mm(e))return mg(e,e=>r(e,t));{const n=r(e,t);if(void 0===n){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return n}}return e},e)}return o.getInitialState=r,o}(e.initialState,e=>{for(let t in i)e.addCase(t,i[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of r)e.addMatcher(t.matcher,t.reducer);n&&e.addDefaultCase(n)})}s.forEach(n=>{const s=i[n],o={reducerName:n,type:cv(r,n),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(s)?function({type:e,reducerName:t,createNotation:r},n,i){let s,o;if("reducer"in n){if(r&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(n))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");s=n.reducer,o=n.prepare}else s=n;i.addCase(e,s).exposeCaseReducer(t,s).exposeAction(t,o?Mg(e,o):Mg(e))}(o,s,a):function({type:e,reducerName:t},r,n,i){if(!i)throw new Error("Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");const{payloadCreator:s,fulfilled:o,pending:a,rejected:c,settled:d,options:l}=r,u=i(e,s,l);n.exposeAction(t,u),o&&n.addCase(u.fulfilled,o);a&&n.addCase(u.pending,a);c&&n.addCase(u.rejected,c);d&&n.addMatcher(u.settled,d);n.exposeCaseReducer(t,{fulfilled:o||pv,pending:a||pv,rejected:c||pv,settled:d||pv})}(o,s,a,t)});const d=e=>e,l=new Map,u=new WeakMap;let p;function h(e,t){return p||(p=c()),p(e,t)}function f(){return p||(p=c()),p.getInitialState()}function m(t,r=!1){function n(e){let i=e[t];if(void 0===i){if(!r)throw new Error("selectSlice returned undefined for an uninjected slice reducer");i=Fg(u,n,f)}return i}function i(t=d){const n=Fg(l,r,()=>new WeakMap);return Fg(n,t,()=>{const n={};for(const[i,s]of Object.entries(e.selectors??{}))n[i]=lv(s,t,()=>Fg(u,t,f),r);return n})}return{reducerPath:t,getSelectors:i,get selectors(){return i(n)},selectSlice:n}}const g={name:r,reducer:h,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:f,...m(n),injectInto(e,{reducerPath:t,...r}={}){const i=t??n;return e.inject({reducerPath:i,reducer:h},r),{...g,...m(i,!0)}}};return g}}function lv(e,t,r,n){function i(i,...s){let o=t(i);if(void 0===o){if(!n)throw new Error("selectState returned undefined for an uninjected slice reducer");o=r()}return e(o,...s)}return i.unwrapped=e,i}var uv=dv();function pv(){}var hv="listener",fv="completed",mv="cancelled",gv=`task-${mv}`,vv=`task-${fv}`,bv=`${hv}-${mv}`,yv=`${hv}-${fv}`,_v=class{constructor(e){this.code=e,this.message=`task ${mv} (reason: ${e})`}name="TaskAbortError";message},wv=(e,t)=>{if("function"!=typeof e)throw new TypeError(`${t} is not a function`)},Sv=()=>{},Cv=(e,t=Sv)=>(e.catch(t),e),kv=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Tv=(e,t)=>{const r=e.signal;r.aborted||("reason"in r||Object.defineProperty(r,"reason",{enumerable:!0,value:t,configurable:!0,writable:!0}),e.abort(t))},Pv=e=>{if(e.aborted){const{reason:t}=e;throw new _v(t)}};function Rv(e,t){let r=Sv;return new Promise((n,i)=>{const s=()=>i(new _v(e.reason));e.aborted?s():(r=kv(e,s),t.finally(()=>r()).then(n,i))}).finally(()=>{r=Sv})}var Ev=e=>t=>Cv(Rv(e,t).then(t=>(Pv(e),t))),Ov=e=>{const t=Ev(e);return e=>t(new Promise(t=>setTimeout(t,e)))},{assign:xv}=Object,Iv={},Dv="listenerMiddleware",Mv=(e,t)=>(r,n)=>{wv(r,"taskExecutor");const i=new AbortController;var s;s=i,kv(e,()=>Tv(s,e.reason));const o=(async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof _v?"cancelled":"rejected",error:e}}finally{t?.()}})(async()=>{Pv(e),Pv(i.signal);const t=await r({pause:Ev(i.signal),delay:Ov(i.signal),signal:i.signal});return Pv(i.signal),t},()=>Tv(i,vv));return n?.autoJoin&&t.push(o.catch(Sv)),{result:Ev(e)(o),cancel(){Tv(i,gv)}}},jv=(e,t)=>(r,n)=>Cv((async(r,n)=>{Pv(t);let i=()=>{};const s=[new Promise((t,n)=>{let s=e({predicate:r,effect:(e,r)=>{r.unsubscribe(),t([e,r.getState(),r.getOriginalState()])}});i=()=>{s(),n()}})];null!=n&&s.push(new Promise(e=>setTimeout(e,n,null)));try{const e=await Rv(t,Promise.race(s));return Pv(t),e}finally{i()}})(r,n)),Av=e=>{let{type:t,actionCreator:r,matcher:n,predicate:i,effect:s}=e;if(t)i=Mg(t).match;else if(r)t=r.type,i=r.match;else if(n)i=n;else if(!i)throw new Error("Creating or removing a listener requires one of the known fields for matching an action");return wv(s,"options.listener"),{predicate:i,type:t,effect:s}},Lv=xv(e=>{const{type:t,predicate:r,effect:n}=Av(e);return{id:Zg(),effect:n,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error("Unsubscribe not initialized")}}},{withTypes:()=>Lv}),Nv=(e,t)=>{const{type:r,effect:n,predicate:i}=Av(t);return Array.from(e.values()).find(e=>("string"==typeof r?e.type===r:e.predicate===i)&&e.effect===n)},Fv=e=>{e.pending.forEach(e=>{Tv(e,bv)})},Bv=(e,t,r)=>{try{e(t,r)}catch(e){setTimeout(()=>{throw e},0)}},zv=xv(Mg(`${Dv}/add`),{withTypes:()=>zv}),Uv=Mg(`${Dv}/removeAll`),Vv=xv(Mg(`${Dv}/remove`),{withTypes:()=>Vv}),$v=(...e)=>{console.error(`${Dv}/error`,...e)};let Gv,qv=class{constructor(e={}){this.data=void 0===e.data?{}:e.data,this.headers=e.headers||{},this.status=e.status||200,this.statusText=e.statusText||"OK",this.url=e.url||null}};function Hv(e,t){return kd.ok(e,`${t} is required`),e}function Wv(e,t){return kd.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function Jv(e,t){return kd.ok("number"==typeof e,`${t}<number> is required`),e}function Kv(e,t){return kd.ok("string"==typeof e,`${t}<string> is required`),e}function Qv(e,t,r){const n=r||t.name[0].toLowerCase()+t.name.substring(1);return kd.ok(e instanceof t,`${n}<${t.name}> is required`),e}function Yv(e,t){return kd.ok(Array.isArray(e),`${t}<array> is required`),e}function Xv(e,t){if(null==e||"object"!=typeof e||Array.isArray(e))throw new Error(`${t} must be a record. ${JSON.stringify(e)}`);return e}function Zv(e,t,r){Kv(t,"name"),function(e,t,r){Kv(r,"name");const n=`${r} must be null or of type ${t}`;kd.ok(null===e||typeof e===t,n)}(e,"string",t)}function eb({baseUrl:e,url:t}){return e?e+t:t}class tb{constructor({baseUrl:e}){Kv(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const r=Object.assign({},t,{url:e,baseURL:this._baseUrl});return Xf.request(r)}request(e,t){return Kv(e,"url"),kd.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),kd.ok(t,"options are required"),this._requestAxios(e,t).then(e=>{const{data:t,headers:r,status:n,statusText:i,config:s}=e,o=s&&s.url?eb({baseUrl:s.baseURL,url:s.url}):null;return new qv({data:t,headers:r,status:n,statusText:i,url:o})}).catch(e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:r,headers:n,status:i,statusText:s,config:o}=t,a=o&&o.url?eb({baseUrl:o.baseURL,url:o.url}):null;return Promise.reject(new qv({data:r,headers:n,status:i,statusText:s,url:a}))})}}class rb{constructor({httpClient:e}){kd.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){kd.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach(r=>{const n=e[r];t.append(r,n)}),t}request(e,t={}){const r=Object.assign(t.headers||{},{"Content-Type":void 0});return this._httpClient.request(e,Object.assign(t,{headers:r,transformRequest:rb.dataToFormData}))}}Gv="object"==typeof window?window.btoa||p:"object"==typeof global&&global.btoa||p;const nb=()=>Promise.resolve(null);class ib{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then(r=>{const n=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${Gv(t)}`}}return{}}(r),{"X-Appearin-Device-Platform":"web"}),i=Object.assign({},t,{headers:n});return this._httpClient.request(e,i)})}}class sb{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=nb}={}){this.authenticatedHttpClient=new ib({httpClient:new tb({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new rb({httpClient:this.authenticatedHttpClient})}request(e,t){return Kv(e,"url"),kd.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),kd.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return Kv(e,"url"),kd.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),kd.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function ob(e,t){return Kv(Xv(e,"data")[t],t)}const ab=(cb=ob,(e,t)=>{const r=Xv(e,"data")[t];return null==r?null:cb(e,t)});var cb;function db(e,t,r){return function(e,t){return Yv(Xv(e,"data")[t],t)}(e,t).map(e=>r(e))}class lb{constructor(e,t,r=void 0){this.credentials={uuid:e},this.hmac=t,this.userId=r}toJson(){return Object.assign({credentials:this.credentials,hmac:this.hmac},this.userId&&{userId:this.userId})}static fromJson(e){return new lb(ob(function(e,t){const r=Xv(e,"data")[t];return void 0===r?null:r}(e,"credentials"),"uuid"),ob(e,"hmac"),ab(e,"userId")||void 0)}}class ub{constructor({apiClient:e}){this._apiClient=e}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then(({data:e})=>lb.fromJson(e)).catch(e=>{if(e.response&&404===e.response.status)return null;throw e})}}class pb{constructor(e,t){this._key=e,this._chromeStorage=t}loadOrDefault(e){return new Promise(t=>{this._chromeStorage.get(this._key,r=>{t(r[this._key]||e)})})}save(e){return new Promise(t=>{this._chromeStorage.set({[this._key]:e},()=>{t()})})}}class hb{constructor(e,t){Hv(t,"localStorage"),this._key=Kv(e,"key"),this._localStorage=t}loadOrDefault(e){try{const t=this._localStorage.getItem(this._key);if(t)try{return Promise.resolve(JSON.parse(t))}catch(e){}return Promise.resolve(e)}catch(t){return console.warn("Error getting access to storage. Are cookies blocked?",t),Promise.resolve(e)}}save(e){try{return this._localStorage.setItem(this._key,JSON.stringify(e)),Promise.resolve()}catch(e){return console.warn("Error getting access to storage. Are cookies blocked?",e),Promise.reject(e)}}}let fb;try{fb=self.localStorage}catch(Op){fb={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var mb=fb;const gb="credentials_saved";class vb extends Ro{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=e,this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:r="localStorage"}){const n=new ub({apiClient:new sb({baseUrl:e})});let i=null;if("localStorage"===r)i=new hb(t,mb);else{if("chromeStorage"!==r)throw new Error(`Unknown store type: ${r}`);i=new pb(t,window.chrome.storage.local)}return new vb({deviceService:n,credentialsStore:i})}_fetchNewCredentialsFromApi(){const e=this._credentialsStore;return new Promise(t=>{const r=()=>{this._deviceService.getCredentials().then(r=>e.save(r?r.toJson():null).then(()=>t(r))).catch(()=>{setTimeout(r,2e3)})};r()})}getCurrentCredentials(){return this._credentialsStore.loadOrDefault(null).then(e=>e?lb.fromJson(e):null)}getCredentials(){return this.credentialsPromise||(this.credentialsPromise=this.getCurrentCredentials().then(e=>e||this._fetchNewCredentialsFromApi())),this.credentialsPromise}saveCredentials(e){return this.credentialsPromise=void 0,this._credentialsStore.save(e.toJson()).then(()=>(this.emit(gb,e),e))}setUserId(e){return this.getCurrentCredentials().then(t=>{t||console.error("Illegal state: no credentials to set user id for.");if(null===t||t.userId!==e)return this._credentialsStore.save(Object.assign({},null==t?void 0:t.toJson(),{userId:e}))}).then(()=>{})}}class bb{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:r,totalMinutesUsed:n}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=r,this.totalMinutesUsed=n}static fromJson(e){return new bb({isExhausted:Wv(e.isExhausted,"isExhausted"),renewsAt:new Date(Kv(e.renewsAt,"renewsAt")),totalMinutesLimit:Jv(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:Jv(e.totalMinutesUsed,"totalMinutesUsed")})}}class yb{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:r,isOnTrial:n,onTrialUntil:i,trialStatus:s}){this.basePlanId=e,this.isDeactivated=r,this.isOnTrial=n,this.onTrialUntil=i||null,this.trialStatus=s||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new yb({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:Wv(e.isDeactivated,"isDeactivated"),isOnTrial:Wv(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?bb.fromJson(e.embeddedFreeTierStatus):null})}}function _b(e){return null!=e}function wb(e={}){return{maxNumberOfInvitationsAndUsers:_b(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:_b(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:_b(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:_b(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:_b(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class Sb{constructor(e){this.logoImageUrl=null,this.roomBackgroundImageUrl=null,this.roomBackgroundThumbnailUrl=null,this.roomKnockPageBackgroundImageUrl=null,this.roomKnockPageBackgroundThumbnailUrl=null,this.preferences=null,this.onboardingSurvey=null,this.type=null,Qv(e,Object,"properties"),Kv(e.organizationId,"organizationId"),Kv(e.organizationName,"organizationName"),Kv(e.subdomain,"subdomain"),Qv(e.permissions,Object,"permissions"),Qv(e.limits,Object,"limits"),this.organizationId=e.organizationId,this.organizationName=e.organizationName,this.subdomain=e.subdomain,this.permissions=e.permissions,this.limits=e.limits,this.account=e.account?new yb(e.account):null,this.logoImageUrl=e.logoImageUrl,this.roomBackgroundImageUrl=e.roomBackgroundImageUrl,this.roomBackgroundThumbnailUrl=e.roomBackgroundThumbnailUrl,this.roomKnockPageBackgroundImageUrl=e.roomKnockPageBackgroundImageUrl,this.roomKnockPageBackgroundThumbnailUrl=e.roomKnockPageBackgroundThumbnailUrl,this.preferences=e.preferences,this.onboardingSurvey=e.onboardingSurvey,this.type=e.type}static fromJson(e){const t=Qv(e,Object,"data"),r=(null==t?void 0:t.preferences)||{},n=(null==t?void 0:t.onboardingSurvey)||null,i=Qv(t.permissions,Object,"permissions");return new Sb({organizationId:Kv(t.organizationId,"organizationId"),organizationName:Kv(t.organizationName,"organizationName"),subdomain:Kv(t.subdomain,"subdomain"),permissions:i,limits:wb(Qv(t.limits,Object,"limits")),account:t.account?yb.fromJson(t.account):null,logoImageUrl:"string"==typeof t.logoImageUrl?t.logoImageUrl:null,roomBackgroundImageUrl:"string"==typeof t.roomBackgroundImageUrl?t.roomBackgroundImageUrl:null,roomBackgroundThumbnailUrl:"string"==typeof t.roomBackgroundThumbnailUrl?t.roomBackgroundThumbnailUrl:null,roomKnockPageBackgroundImageUrl:"string"==typeof t.roomKnockPageBackgroundImageUrl?t.roomKnockPageBackgroundImageUrl:null,roomKnockPageBackgroundThumbnailUrl:"string"==typeof t.roomKnockPageBackgroundThumbnailUrl?t.roomKnockPageBackgroundThumbnailUrl:null,preferences:r,onboardingSurvey:n,type:"string"==typeof t.type?t.type:null})}}Sb.GLOBAL_ORGANIZATION_ID="1";class Cb{constructor({apiClient:e}){this._apiClient=e}createOrganization({organizationName:e,subdomain:t,owner:r}){const{displayName:n,consents:i}=r||{},s="email"in r?{value:r.email,verificationCode:Kv(r.verificationCode,"owner.verificationCode")}:null,o="idToken"in r?r.idToken:null;if(Kv(t,"subdomain"),Kv(e,"organizationName"),Kv(n,"owner.displayName"),kd.ok(s||o,"owner.email or owner.idToken is required"),i){Yv(i,"consents");for(const{consentRevisionId:e,action:t}of i)Kv(e,"consentRevisionId"),Zv(t,"action")}return this._apiClient.request("/organizations",{method:"POST",data:{organizationName:e,type:"private",subdomain:t,owner:Object.assign(Object.assign(Object.assign(Object.assign({},s&&{email:s}),o&&{idToken:o}),i&&{consents:i}),{displayName:n})}}).then(({data:e})=>ob(e,"organizationId"))}getOrganizationBySubdomain(e){return Kv(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then(({data:e})=>Sb.fromJson(e)).catch(e=>{if(e instanceof qv){if(404===e.status)return null;throw new Error(e.statusText)}throw e})}getOrganizationByOrganizationId(e){return Kv(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then(({data:e})=>Sb.fromJson(e)).catch(e=>{if(e instanceof qv){if(404===e.status)return null;throw new Error(e.statusText)}throw e})}getOrganizationsByContactPoint(e){const{code:t}=e,r="email"in e?e.email:null,n="phoneNumber"in e?e.phoneNumber:null;kd.ok((r||n)&&!(r&&n),"either email or phoneNumber is required"),Kv(t,"code");const i=r?{type:"email",value:r}:{type:"phoneNumber",value:n};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:i,code:t}}).then(({data:e})=>db(e,"organizations",e=>Sb.fromJson(e)))}getOrganizationsByIdToken({idToken:e}){return Kv(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then(({data:e})=>db(e,"organizations",e=>Sb.fromJson(Object.assign({permissions:{},limits:{}},Xv(e,"organization")))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then(({data:e})=>db(e,"organizations",e=>Sb.fromJson(Object.assign({permissions:{},limits:{}},Xv(e,"organization")))))}getSubdomainAvailability(e){return Kv(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then(({data:e})=>(Qv(e,Object,"data"),{status:ob(e,"status")}))}updatePreferences({organizationId:e,preferences:t}){return Hv(e,"organizationId"),Hv(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then(()=>{})}deleteOrganization({organizationId:e}){return Hv(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then(()=>{})}}class kb{constructor({organizationService:e,subdomain:t}){this._organizationService=e,this._subdomain=t,this._organizationPromise=null}initOrganization(){return this.fetchOrganization().then(()=>{})}fetchOrganization(){return this._organizationPromise||(this._organizationPromise=this._organizationService.getOrganizationBySubdomain(this._subdomain)),this._organizationPromise}}const Tb="https://api.whereby.dev";function Pb(e,{delay:t=500,edges:r}={}){let n,i=0;return(...s)=>{i+=1,r&&1===i&&e(...s),clearTimeout(n),n=setTimeout(()=>{(!r||i>1)&&e(...s),n=void 0,i=0},t)}}const Rb=((e={})=>{const t=new Map,{extra:r,onError:n=$v}=e;wv(n,"onError");const i=e=>(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&Fv(e)}))(Nv(t,e)??Lv(e));xv(i,{withTypes:()=>i});const s=e=>{const r=Nv(t,e);return r&&(r.unsubscribe(),e.cancelActive&&Fv(r)),!!r};xv(s,{withTypes:()=>s});const o=async(e,s,o,a)=>{const c=new AbortController,d=jv(i,c.signal),l=[];try{e.pending.add(c),await Promise.resolve(e.effect(s,xv({},o,{getOriginalState:a,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:Ov(c.signal),pause:Ev(c.signal),extra:r,signal:c.signal,fork:Mv(c.signal,l),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach((e,t,r)=>{e!==c&&(Tv(e,bv),r.delete(e))})},cancel:()=>{Tv(c,bv),e.pending.delete(c)},throwIfCancelled:()=>{Pv(c.signal)}})))}catch(e){e instanceof _v||Bv(n,e,{raisedBy:"effect"})}finally{await Promise.all(l),Tv(c,yv),e.pending.delete(c)}},a=(e=>()=>{e.forEach(Fv),e.clear()})(t);return{middleware:e=>r=>c=>{if(!Tm(c))return r(c);if(zv.match(c))return i(c.payload);if(Uv.match(c))return void a();if(Vv.match(c))return s(c.payload);let d=e.getState();const l=()=>{if(d===Iv)throw new Error(`${Dv}: getOriginalState can only be called synchronously`);return d};let u;try{if(u=r(c),t.size>0){const r=e.getState(),i=Array.from(t.values());for(const t of i){let i=!1;try{i=t.predicate(c,r,d)}catch(e){i=!1,Bv(n,e,{raisedBy:"predicate"})}i&&o(t,c,e,l)}}}finally{d=Iv}return u},startListening:i,stopListening:s,clearListeners:a}})(),Eb=Rb.startListening,Ob=(e,t)=>Eb({predicate:(t,r,n)=>{const i=e.map(e=>e(n)),s=e.map(e=>e(r));return i.some((e,t)=>e!==s[t])},effect:(r,{dispatch:n,getState:i,extra:s})=>{const o=e.map(e=>e(i()));t({dispatch:n,getState:i,extra:s},...o)}}),xb="1.2.8",Ib=uv({name:"app",initialState:{isNodeSdk:!1,isActive:!1,isDialIn:!1,isAssistant:!1,ignoreBreakoutGroups:!1,roomName:null,roomUrl:null,displayName:null,userAgent:`core:${xb}`,externalId:null},reducers:{doAppStart:(e,t)=>{const r=new URL(t.payload.roomUrl);return Object.assign(Object.assign(Object.assign({},e),t.payload),{roomName:r.pathname,initialConfig:Object.assign({},t.payload),isActive:!0,isAssistant:Boolean(t.payload.assistantKey)})},doAppStop:e=>Object.assign(Object.assign({},e),{isActive:!1})}}),{doAppStop:Db,doAppStart:Mb}=Ib.actions,jb=e=>e.app.isActive,Ab=e=>e.app.isDialIn,Lb=e=>e.app.roomName,Nb=e=>e.app.displayName,Fb=e=>e.app.userAgent,Bb=e=>e.app.externalId;function zb(e){return Mg(`signalConnection/event/${e}`)}const Ub={audioEnabled:zb("audioEnabled"),audioEnableRequested:zb("audioEnableRequested"),breakoutGroupJoined:zb("breakoutGroupJoined"),breakoutMoveToGroup:zb("breakoutMoveToGroup"),breakoutMoveToMain:zb("breakoutMoveToMain"),breakoutSessionUpdated:zb("breakoutSessionUpdated"),chatMessage:zb("chatMessage"),clientLeft:zb("clientLeft"),clientKicked:zb("clientKicked"),clientMetadataReceived:zb("clientMetadataReceived"),clientUnableToJoin:zb("clientUnableToJoin"),cloudRecordingStarted:zb("cloudRecordingStarted"),cloudRecordingStopped:zb("cloudRecordingStopped"),disconnect:zb("disconnect"),knockerLeft:zb("knockerLeft"),knockHandled:zb("knockHandled"),newClient:zb("newClient"),roomJoined:zb("roomJoined"),roomKnocked:zb("roomKnocked"),roomLeft:zb("roomLeft"),roomLocked:zb("roomLocked"),roomSessionEnded:zb("roomSessionEnded"),screenshareStarted:zb("screenshareStarted"),screenshareStopped:zb("screenshareStopped"),spotlightAdded:zb("spotlightAdded"),spotlightRemoved:zb("spotlightRemoved"),streamingStopped:zb("streamingStopped"),videoEnabled:zb("videoEnabled"),videoEnableRequested:zb("videoEnableRequested"),liveTranscriptionStarted:zb("liveTranscriptionStarted"),liveTranscriptionStopped:zb("liveTranscriptionStopped"),liveCaptionsStarted:zb("liveCaptionsStarted"),liveCaptionsStopped:zb("liveCaptionsStopped")},Vb={canLockRoom:["host"],canRequestAudioEnable:["host"],canRequestVideoEnable:["host"],canKickClient:["host"],canEndMeeting:["host"],canAskToSpeak:["host"],canSpotlight:["host"]},$b=uv({name:"authorization",initialState:{roomKey:null,assistantKey:null,roleName:"none"},reducers:{setRoomKey:(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload})},extraReducers:e=>{e.addCase(Mb,(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload.roomKey,assistantKey:t.payload.assistantKey})),e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r,selfId:n}=t.payload||{},i=null==r?void 0:r.clients.find(e=>e.id===n);return i?Object.assign(Object.assign({},e),{roleName:(null==i?void 0:i.role.roleName)||"none"}):e})}}),{setRoomKey:Gb}=$b.actions,qb=e=>e.authorization.roomKey,Hb=e=>e.authorization.roleName,Wb=Pg(Hb,e=>Vb.canLockRoom.includes(e)),Jb=Pg(Hb,e=>Vb.canRequestAudioEnable.includes(e)),Kb=Pg(Hb,e=>Vb.canRequestVideoEnable.includes(e)),Qb=Pg(Hb,e=>Vb.canKickClient.includes(e)),Yb=Pg(Hb,e=>Vb.canEndMeeting.includes(e)),Xb=Pg(Hb,e=>Vb.canAskToSpeak.includes(e)),Zb=Pg(Hb,e=>Vb.canSpotlight.includes(e));function ey(e,t){return sv(e,t)}function ty(e,t){return r=>(n,i,s)=>e(i())?t(r)(n,i,s):(console.warn("Not authorized to perform this action"),!1)}function ry(e){return t=>(r,n,i)=>"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):e(t)(r,n,i)}function ny(e,t){return ey(e,(e,r)=>{const{getState:n}=r;return"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),Promise.reject("Action cannot be performed outside of a connected room")):t(e,r)})}function iy(e,t){return r=>(n,i,s)=>"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):ty(e,t)(r)(n,i,s)}function sy(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}function oy(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r(function(t){t(e)})}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const ay=uv({name:"deviceCredentials",initialState:{isFetching:!1,data:null},reducers:{},extraReducers:e=>{e.addCase(cy.pending,e=>Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(cy.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload})),e.addCase(cy.rejected,e=>Object.assign(Object.assign({},e),{isFetching:!0}))}}),cy=ey("deviceCredentials/doGetDeviceCredentials",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{extra:t}){try{return yield t.services.credentialsService.getCredentials()}catch(e){console.error(e)}})),dy=e=>e.deviceCredentials,ly=e=>{var t,r;return null===(r=null===(t=e.deviceCredentials.data)||void 0===t?void 0:t.credentials)||void 0===r?void 0:r.uuid};Ob([Pg(jb,dy,(e,t)=>!(!e||t.isFetching||t.data))],({dispatch:e},t)=>{t&&e(cy())});const uy=uv({name:"signalConnection",initialState:{deviceIdentified:!1,isIdentifyingDevice:!1,status:"ready",socket:null},reducers:{socketConnecting:e=>Object.assign(Object.assign({},e),{status:"connecting"}),socketConnected:(e,t)=>Object.assign(Object.assign({},e),{socket:t.payload,status:"connected"}),socketDisconnected:e=>Object.assign(Object.assign({},e),{socket:null,deviceIdentified:!1,status:"disconnected"}),socketReconnecting:e=>Object.assign(Object.assign({},e),{status:"reconnecting"}),deviceIdentifying:e=>Object.assign(Object.assign({},e),{isIdentifyingDevice:!0}),deviceIdentified:e=>Object.assign(Object.assign({},e),{deviceIdentified:!0,isIdentifyingDevice:!1})},extraReducers:e=>{e.addCase(Ub.disconnect,e=>Object.assign(Object.assign({},e),{deviceIdentified:!1,status:"disconnected"}))}}),{deviceIdentifying:py,deviceIdentified:hy,socketConnected:fy,socketConnecting:my,socketDisconnected:gy,socketReconnecting:vy}=uy.actions,by=()=>(e,t)=>{if(ky(t()))return;e(my());const r=function(){const e=new URL("wss://signal.appearin.net").origin;return new Ul(e,{autoConnect:!1})}();r.on("connect",()=>e(fy(r))),r.on("device_identified",()=>e(hy())),r.getManager().on("reconnect",()=>e(vy())),function(e,t){e.on("room_joined",e=>t(Ub.roomJoined(e))),e.on("new_client",e=>t(Ub.newClient(e))),e.on("client_left",e=>t(Ub.clientLeft(e))),e.on("client_kicked",e=>t(Ub.clientKicked(e))),e.on("client_unable_to_join",e=>t(Ub.clientUnableToJoin(e))),e.on("audio_enabled",e=>t(Ub.audioEnabled(e))),e.on("video_enabled",e=>t(Ub.videoEnabled(e))),e.on("audio_enable_requested",e=>t(Ub.audioEnableRequested(e))),e.on("client_metadata_received",e=>t(Ub.clientMetadataReceived(e))),e.on("chat_message",e=>t(Ub.chatMessage(e))),e.on("disconnect",()=>t(Ub.disconnect())),e.on("room_knocked",e=>t(Ub.roomKnocked(e))),e.on("room_left",()=>t(Ub.roomLeft())),e.on("room_locked",e=>t(Ub.roomLocked(e))),e.on("room_session_ended",e=>t(Ub.roomSessionEnded(e))),e.on("knocker_left",e=>t(Ub.knockerLeft(e))),e.on("knock_handled",e=>t(Ub.knockHandled(e))),e.on("screenshare_started",e=>t(Ub.screenshareStarted(e))),e.on("screenshare_stopped",e=>t(Ub.screenshareStopped(e))),e.on("cloud_recording_started",e=>t(Ub.cloudRecordingStarted(e))),e.on("cloud_recording_stopped",()=>t(Ub.cloudRecordingStopped())),e.on("streaming_stopped",()=>t(Ub.streamingStopped())),e.on("spotlight_added",e=>t(Ub.spotlightAdded(e))),e.on("spotlight_removed",e=>t(Ub.spotlightRemoved(e))),e.on("live_transcription_started",e=>t(Ub.liveTranscriptionStarted(e))),e.on("live_transcription_stopped",e=>t(Ub.liveTranscriptionStopped(e))),e.on("live_captions_started",()=>t(Ub.liveCaptionsStarted())),e.on("live_captions_stopped",()=>t(Ub.liveCaptionsStopped())),e.on("video_enable_requested",e=>t(Ub.videoEnableRequested(e))),e.on("breakout_group_joined",e=>t(Ub.breakoutGroupJoined(e))),e.on("breakout_session_updated",e=>t(Ub.breakoutSessionUpdated(e))),e.on("breakout_move_to_group",()=>t(Ub.breakoutMoveToGroup())),e.on("breakout_move_to_main",()=>t(Ub.breakoutMoveToMain()))}(r,e),r.connect()},yy=({deviceCredentials:e})=>(t,r)=>{const n=r(),i=ky(n),s=Sy(n);i&&(s||(i.emit("identify_device",{deviceCredentials:e}),t(py())))},_y=()=>(e,t)=>{const r=t();if("connected"===Cy(r)){const t=wy(r).socket;null==t||t.disconnect(),e(gy())}},wy=e=>e.signalConnection,Sy=e=>e.signalConnection.deviceIdentified,Cy=e=>e.signalConnection.status,ky=e=>e.signalConnection.socket;Ob([Pg(jb,Cy,(e,t)=>!(!e||!["ready","reconnecting"].includes(t)))],({dispatch:e},t)=>{t&&e(by())});const Ty=Pg(dy,Cy,Sy,e=>e.signalConnection.isIdentifyingDevice,(e,t,r,n)=>!(!e.data||"connected"!==t||r||n));Ob([Ty,dy],({dispatch:e},t,r)=>{t&&r.data&&e(yy({deviceCredentials:r.data}))}),Eb({actionCreator:Ub.roomLeft,effect:(e,{dispatch:t})=>{t(_y())}}),Eb({actionCreator:Ub.clientKicked,effect:(e,{dispatch:t})=>{t(_y())}});const Py=uv({name:"localMedia",initialState:{busyDeviceIds:[],cameraEnabled:!1,currentSpeakerDeviceId:"default",devices:[],isSettingCameraDevice:!1,isSettingMicrophoneDevice:!1,isSettingSpeakerDevice:!1,isTogglingCamera:!1,lowDataMode:!1,microphoneEnabled:!1,status:"inactive",stream:void 0,isSwitchingStream:!1},reducers:{deviceBusy:(e,t)=>e.busyDeviceIds.includes(t.payload.deviceId)?e:Object.assign(Object.assign({},e),{busyDeviceIds:[...e.busyDeviceIds,t.payload.deviceId]}),toggleCameraEnabled(e,t){var r;return Object.assign(Object.assign({},e),{cameraEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.cameraEnabled})},setCurrentCameraDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentCameraDeviceId:t.payload.deviceId}),toggleMicrophoneEnabled(e,t){var r;return Object.assign(Object.assign({},e),{microphoneEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.microphoneEnabled})},setCurrentMicrophoneDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentMicrophoneDeviceId:t.payload.deviceId}),setCurrentSpeakerDeviceId(e,t){var r;return Object.assign(Object.assign({},e),{currentSpeakerDeviceId:null!==(r=t.payload.deviceId)&&void 0!==r?r:"default"})},toggleLowDataModeEnabled(e,t){var r;return Object.assign(Object.assign({},e),{lowDataMode:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.lowDataMode})},setDevices:(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}),setLocalMediaStream:(e,t)=>Object.assign(Object.assign({},e),{stream:t.payload.stream}),setLocalMediaOptions:(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.options}),localMediaStopped:e=>Object.assign(Object.assign({},e),{status:"stopped",stream:void 0}),localStreamMetadataUpdated(e,t){const{audio:r,video:n}=t.payload;return Object.assign(Object.assign({},e),{currentCameraDeviceId:n.deviceId,currentMicrophoneDeviceId:r.deviceId,busyDeviceIds:e.busyDeviceIds.filter(e=>e!==r.deviceId&&e!==n.deviceId)})}},extraReducers:e=>{e.addCase(Mb,(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.localMediaOptions})),e.addCase(Uy.pending,(e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:n,isSettingMicrophoneDevice:r})}),e.addCase(Uy.fulfilled,(e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!n&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice})}),e.addCase(Uy.rejected,(e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!n&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice,cameraDeviceError:n?t.error:e.cameraDeviceError,microphoneDeviceError:r?t.error:e.microphoneDeviceError})}),e.addCase(Fy.pending,e=>Object.assign(Object.assign({},e),{isTogglingCamera:!0})),e.addCase(Fy.fulfilled,e=>Object.assign(Object.assign({},e),{isTogglingCamera:!1})),e.addCase(Vy.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices})),e.addCase(Gy.pending,e=>Object.assign(Object.assign({},e),{status:"starting"})),e.addCase(Gy.fulfilled,(e,{payload:{stream:t,onDeviceChange:r}})=>{let n,i,s=!1,o=!1;const a=null==t?void 0:t.getAudioTracks()[0],c=null==t?void 0:t.getVideoTracks()[0];return a&&(i=a.getSettings().deviceId,o=a.enabled),c&&(s=c.enabled,n=c.getSettings().deviceId),Object.assign(Object.assign({},e),{stream:t,status:"started",currentCameraDeviceId:n,currentMicrophoneDeviceId:i,cameraEnabled:s,microphoneEnabled:o,onDeviceChange:r})}),e.addCase(Gy.rejected,(e,t)=>Object.assign(Object.assign({},e),{status:"error",startError:t.error})),e.addCase($y.pending,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!0})),e.addCase($y.fulfilled,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1})),e.addCase($y.rejected,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1}))}}),{deviceBusy:Ry,setCurrentCameraDeviceId:Ey,setCurrentMicrophoneDeviceId:Oy,setCurrentSpeakerDeviceId:xy,toggleCameraEnabled:Iy,toggleMicrophoneEnabled:Dy,toggleLowDataModeEnabled:My,setLocalMediaOptions:jy,setLocalMediaStream:Ay,localMediaStopped:Ly,localStreamMetadataUpdated:Ny}=Py.actions,Fy=ey("localMedia/doToggleCamera",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t,rejectWithValue:r}){const n=t(),i=r_(n);if(!i)return;let s=i.getVideoTracks()[0];const o=Ky(n);try{if(o)if(s)s.enabled=!0;else{const e=i_(n),t=Wy(n);yield zp(Object.assign(Object.assign({},e),{audioId:!1,videoId:t,type:"exact"}),{replaceStream:i}),s=i.getVideoTracks()[0]}else{if(!s)return;s.enabled=!1,s.stop(),i.removeTrack(s)}i.dispatchEvent(new CustomEvent("stopresumevideo",{detail:{track:s,enable:o}}))}catch(e){return r(e)}})),By=ey("localMedia/doToggleMicrophone",(e,{getState:t})=>{var r;const n=t(),i=r_(n);if(!i)return;const s=Qy(n),o=null===(r=i.getAudioTracks())||void 0===r?void 0:r[0];o&&(o.enabled=s)}),zy=()=>(e,t)=>{const r=t();if(!r_(r))return;const n=Wy(r),i=Jy(r);e($y({audioId:i,videoId:n}))},Uy=ey("localMedia/reactSetDevice",(e,t)=>oy(void 0,[e,t],void 0,function*({audio:e,video:t},{getState:r,rejectWithValue:n}){try{const n=r(),i=r_(n);if(!i)throw new Error("No stream");const s=!!e&&Jy(n),o=!!t&&Wy(n),a=i_(n),{replacedTracks:c}=yield zp(Object.assign(Object.assign({},a),{audioId:s,videoId:o,type:"exact"}),{replaceStream:i}),d=Qy(n);i.getAudioTracks().forEach(e=>e.enabled=d);const l=Ky(n);return i.getVideoTracks().forEach(e=>e.enabled=l),{replacedTracks:c}}catch(e){return n(e)}})),Vy=ey("localMedia/doUpdateDeviceList",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t,dispatch:r,rejectWithValue:n}){var i,s,o,a;const c=t();let d=[],l=[];const u=r_(c);try{d=yield navigator.mediaDevices.enumerateDevices(),l=Xy(c);if(!(u&&!n_(c)&&d&&l&&l.find(e=>e.deviceId)))return{devices:d};const{changedDevices:e,addedDevices:t}=Up({oldDevices:l,newDevices:d});let n=null===(i=e.audioinput)||void 0===i?void 0:i.deviceId,p=null===(s=e.videoinput)||void 0===s?void 0:s.deviceId;return void 0===n&&(n=null===(o=t.audioinput)||void 0===o?void 0:o.deviceId),void 0===p&&(p=null===(a=t.videoinput)||void 0===a?void 0:a.deviceId),void 0===n&&void 0===p||r($y({audioId:n,videoId:p})),{devices:d}}catch(e){return n(e)}})),$y=ey("localMedia/doSwitchLocalStream",(e,t)=>oy(void 0,[e,t],void 0,function*({audioId:e,videoId:t},{dispatch:r,getState:n,rejectWithValue:i}){const s=n(),o=r_(s),a=i_(s),c=!(!t||e)||!(t||!e);if(o)try{const{replacedTracks:n}=yield zp(Object.assign(Object.assign({},a),{audioId:void 0!==e&&e,videoId:void 0!==t&&t,type:"exact"}),{replaceStream:o}),i=e||t;return c&&i&&r(Ry({deviceId:i})),{replacedTracks:n}}catch(n){console.error(n);const s=e||t;return c&&s&&r(Ry({deviceId:s})),i(n)}})),Gy=ey("localMedia/doStartLocalMedia",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t,dispatch:r,rejectWithValue:n}){const i=Pb(()=>{r(Vy())},{delay:500});if(navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",i),"getTracks"in e)return Promise.resolve({stream:e,onDeviceChange:i});if(!e.audio&&!e.video)return{stream:void 0,onDeviceChange:i};r(jy({options:e}));try{yield r(Vy());const n=t(),s=i_(n),{stream:o}=yield zp(Object.assign(Object.assign({},s),{audioId:e.audio,videoId:e.video}));return{stream:o,onDeviceChange:i}}catch(e){return n(e)}})),qy=()=>(e,t)=>{const r=r_(t()),n=e_(t()).onDeviceChange;null==r||r.getTracks().forEach(e=>{e.stop()}),navigator.mediaDevices&&n&&navigator.mediaDevices.removeEventListener("devicechange",n),e(Ly())},Hy=e=>e.localMedia.busyDeviceIds,Wy=e=>e.localMedia.currentCameraDeviceId,Jy=e=>e.localMedia.currentMicrophoneDeviceId,Ky=e=>e.localMedia.cameraEnabled,Qy=e=>e.localMedia.microphoneEnabled,Yy=e=>e.localMedia.lowDataMode,Xy=e=>e.localMedia.devices,Zy=e=>e.localMedia.options;Pg(Zy,e=>!!e);const e_=e=>e.localMedia,t_=e=>e.localMedia.status,r_=e=>e.localMedia.stream,n_=e=>e.localMedia.isSwitchingStream,i_=Pg(Xy,Wy,Jy,Yy,(e,t,r,n)=>({devices:e,videoId:t,audioId:r,options:{disableAEC:!1,disableAGC:!1,hd:!0,lax:!1,lowDataMode:n,simulcast:!0,widescreen:!0}})),s_=Pg(t_,e=>"starting"===e),o_=Pg(Xy,Hy,(e,t)=>e.filter(e=>"videoinput"===e.kind).filter(e=>!t.includes(e.deviceId))),a_=Pg(Xy,Hy,(e,t)=>e.filter(e=>"audioinput"===e.kind).filter(e=>!t.includes(e.deviceId))),c_=Pg(Xy,e=>e.filter(e=>"audiooutput"===e.kind));Ob([Pg(jb,t_,Zy,(e,t,r)=>{if(e&&["inactive","stopped"].includes(t)&&r)return r})],({dispatch:e},t)=>{t&&e(Gy(t))});Ob([Pg(jb,t_,Zy,(e,t,r)=>!e&&"inactive"!==t&&!!r)],({dispatch:e},t)=>{t&&e(qy())}),Eb({predicate:(e,t,r)=>{const n=Qy(r),i=Qy(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(By())}}),Eb({predicate:(e,t,r)=>{const n=Yy(r),i=Yy(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(zy())}}),Eb({predicate:(e,t,r)=>{if(t.localMedia.isTogglingCamera)return!1;const n=Ky(r),i=Ky(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(Fy())}}),Eb({predicate:(e,t,r)=>{const n=Wy(r),i=Wy(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(Uy({audio:!1,video:!0}))}}),Eb({predicate:(e,t,r)=>{const n=Jy(r),i=Jy(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(Uy({audio:!0,video:!1}))}}),Eb({matcher:Xg(Gy.fulfilled,Vy.fulfilled,$y.fulfilled,$y.rejected),effect:(e,{dispatch:t,getState:r})=>{const n=r(),i=r_(n),s=Xy(n);if(!i)return;const o=function({audioTrack:e,videoTrack:t,devices:r,stoppedVideoTrack:n,lastAudioId:i,lastVideoId:s}){const o=e=>"live"===(null==e?void 0:e.readyState)?e:null;return t=o(t)||n,e=o(e),{video:Fp("videoinput",t,r,s),audio:Fp("audioinput",e,r,i)}}({audioTrack:i.getAudioTracks()[0],videoTrack:i.getVideoTracks()[0],devices:s});t(Ny(o))}}),Eb({actionCreator:Ub.audioEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Dy({enabled:!1}))}}),Eb({actionCreator:Ub.videoEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Iy({enabled:!1}))}}),Eb({actionCreator:Ub.breakoutSessionUpdated,effect:({payload:e},{dispatch:t})=>{var r;!1===(null===(r=e.initiatedBy)||void 0===r?void 0:r.active)&&t(Dy({enabled:!1}))}});const d_=["recorder","streamer"],l_=e=>e.localParticipant,u_=e=>e.localParticipant.id,p_=e=>e.localParticipant.displayName,h_=e=>e.localParticipant.stickyReaction,f_=Pg(l_,r_,(e,t)=>{const r={id:e.id,clientId:e.id,breakoutGroup:e.breakoutGroup,displayName:e.displayName,stream:t,isLocalClient:!0,isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled};return d_.includes(e.roleName)?null:r});function m_({assignments:e,groups:t,startedAt:r,initiatedBy:n,breakoutStartedAt:i,breakoutEndedAt:s,breakoutNotification:o,breakoutTimerDuration:a,autoMoveToGroup:c,moveToGroupGracePeriod:d,autoMoveToMain:l,moveToMainGracePeriod:u,enforceAssignment:p,breakoutTimerSetting:h}={}){return{assignments:e||null,groups:t||null,startedAt:r?new Date(r):null,initiatedBy:n,breakoutStartedAt:i||null,breakoutEndedAt:s||null,breakoutNotification:o||null,breakoutTimerDuration:a||1800,autoMoveToGroup:c||!1,moveToGroupGracePeriod:d||10,autoMoveToMain:l||!1,moveToMainGracePeriod:u||30,enforceAssignment:p||!1,breakoutTimerSetting:h||!1}}const g_=uv({name:"breakout",initialState:Object.assign(Object.assign({},m_()),{groupId:null}),reducers:{},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{breakout:r}=t.payload||{};return r?Object.assign(Object.assign({},e),m_(r)):e}),e.addCase(Ub.breakoutSessionUpdated,(e,t)=>Object.assign(Object.assign({},e),m_(t.payload))),e.addCase(Ub.breakoutGroupJoined,(e,t)=>{var r;return(null===(r=t.meta)||void 0===r?void 0:r.localParticipantId)!==t.payload.clientId?e:Object.assign(Object.assign({},e),{groupId:t.payload.group})})}}),v_=e=>(t,r)=>{const n=r(),{socket:i}=wy(n);null==i||i.emit("join_breakout_group",{group:e.group})},b_=e=>e.breakout,y_=e=>!!e.breakout.startedAt,__=e=>e.breakout.assignments,w_=Pg(b_,e=>e.localParticipant.breakoutGroup,(e,t)=>e.groupId||t||""),S_=Pg(b_,w_,(e,t)=>{var r;const n=null===(r=e.groups)||void 0===r?void 0:r[t];return n?{id:t,name:n}:null});Eb({actionCreator:Ub.breakoutMoveToGroup,effect:(e,{dispatch:t,getState:r})=>{const n=r(),i=l_(n).breakoutGroupAssigned;i&&t(v_({group:i}))}}),Eb({actionCreator:Ub.breakoutMoveToMain,effect:(e,{dispatch:t})=>{t(v_({group:""}))}}),Eb({actionCreator:Ub.breakoutSessionUpdated,effect:({payload:e},{dispatch:t,getState:r})=>{var n;const i=r(),s=b_(i).autoMoveToMain;!1===(null===(n=e.initiatedBy)||void 0===n?void 0:n.active)&&(s||t(v_({group:""})))}});const C_=uv({name:"chat",initialState:{chatMessages:[]},reducers:{},extraReducers(e){e.addCase(Ub.chatMessage,(e,t)=>{const r={senderId:t.payload.senderId,timestamp:t.payload.timestamp,text:t.payload.text};return Object.assign(Object.assign({},e),{chatMessages:[...e.chatMessages,r]})})}}),k_=ry(e=>(t,r)=>{const n=r(),i=wy(n).socket,s=w_(n);null==i||i.emit("chat_message",Object.assign(Object.assign({text:e.text},s&&{breakoutGroup:s}),e.isBroadcast&&{broadcast:!0}))}),T_=uv({name:"cloudRecording",initialState:{isInitiator:!1,isRecording:!1,error:null,startedAt:void 0},reducers:{recordingRequestStarted:e=>Object.assign(Object.assign({},e),{isInitiator:!0,status:"requested"})},extraReducers:e=>{e.addCase(Ub.cloudRecordingStopped,e=>Object.assign(Object.assign({},e),{isInitiator:!1,isRecording:!1,status:void 0})),e.addCase(Ub.cloudRecordingStarted,(e,t)=>{const{payload:r}=t;return r.error?Object.assign(Object.assign({},e),{isInitiator:!1,isRecording:!1,status:"error",error:r.error}):e}),e.addCase(Ub.newClient,(e,{payload:t})=>{var r;const{client:n}=t;return"recorder"===(null===(r=n.role)||void 0===r?void 0:r.roleName)?Object.assign(Object.assign({},e),{isRecording:!0,status:"recording",startedAt:n.startedCloudRecordingAt?new Date(n.startedCloudRecordingAt).getTime():(new Date).getTime()}):e})}}),{recordingRequestStarted:P_}=T_.actions,R_=ry(()=>(e,t)=>{const r=t(),n=wy(r).socket,i=O_(r);i&&["recording","requested"].includes(i)||(null==n||n.emit("start_recording",{recording:"cloud"}),e(P_()))}),E_=ry(()=>(e,t)=>{const r=t(),n=wy(r).socket;null==n||n.emit("stop_recording")}),O_=e=>e.cloudRecording.status,x_=e=>e.cloudRecording.isRecording,I_=e=>e.cloudRecording.isInitiator,D_=e=>e.roomConnection.status;function M_(e){return Mg(`rtcConnection/event/${e}`)}const j_={rtcManagerCreated:M_("rtcManagerCreated"),rtcManagerDestroyed:M_("rtcManagerDestroyed"),streamAdded:M_("streamAdded"),clientConnectionStatusChanged:M_("clientConnectionStatusChanged")};function A_(e,t=!1){const{streams:r,role:n,breakoutGroup:i}=e,s=sy(e,["streams","role","breakoutGroup"]);return Object.assign(Object.assign({},s),{stream:null,streams:r.map(e=>({id:e,state:t?"new_accept":"to_accept"})),isLocalParticipant:!1,roleName:(null==n?void 0:n.roleName)||"none",presentationStream:null,breakoutGroup:i||null,newJoiner:t})}function L_(e,t){const r=e.remoteParticipants.findIndex(e=>e.id===t);return{index:r,participant:e.remoteParticipants[r]}}function N_(e,t,r){const{participant:n,index:i}=L_(e,t);return n?Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.slice(0,i),Object.assign(Object.assign({},n),r),...e.remoteParticipants.slice(i+1)]}):(console.error(`Did not find client for update ${t}`),e)}function F_(e,t,r,n){const{participant:i}=L_(e,t);if(!i)return console.error(`No client ${t} found to update stream ${r} ${n}`),e;const s=i.streams.findIndex(e=>e.id===r),o=[...i.streams];return o[s]=Object.assign(Object.assign({},o[s]),{state:n}),N_(e,t,{streams:o})}function B_(e,t,r){const{participant:n}=L_(e,t);return!n||n.streams.find(e=>e.id===r)?(console.warn(`No participant ${t} or stream ${r} already exists`),e):N_(e,t,{streams:[...n.streams,{id:r,state:"to_accept"}]})}const z_=uv({name:"remoteParticipants",initialState:{remoteParticipants:[]},reducers:{streamStatusUpdated:(e,t)=>{let r=e;for(const{clientId:e,streamId:n,state:i}of t.payload)r=F_(r,e,n,i);return r},participantStreamAdded:(e,t)=>{const{clientId:r,stream:n}=t.payload;return N_(e,r,{stream:n})},participantStreamIdAdded:(e,t)=>{const{clientId:r,streamId:n}=t.payload;return B_(e,r,n)}},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r,selfId:n}=t.payload||{};return(null==r?void 0:r.clients)?Object.assign(Object.assign({},e),{remoteParticipants:r.clients.filter(e=>e.id!==n).map(e=>A_(e))}):e}),e.addCase(j_.streamAdded,(e,t)=>function(e,t){const{clientId:r,stream:n,streamType:i}=t;let{streamId:s}=t;const{participant:o}=L_(e,r);if(!o)return console.error(`Did not find client ${r} for adding stream`),e;const a=e.remoteParticipants;s||(s=n.id);const c=a.find(e=>e.id===r);if(!c)return e;const d=c.streams.find(e=>e.id===s);return c.stream&&(c.stream.id===s||c.stream.inboundId===s)||!c.stream&&"webcam"===i||!c.stream&&!i&&!d?N_(e,r,{stream:n}):N_(e,r,{presentationStream:n})}(e,t.payload)),e.addCase(Ub.newClient,(e,t)=>{const{client:r}=t.payload;return function(e,t){const{participant:r}=L_(e,t.id);return r?(console.warn(`Client already existing ${t.id}. Ignoring`),e):Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t]})}(e,A_(r,!0))}),e.addCase(Ub.clientLeft,(e,t)=>{const{clientId:r}=t.payload;return function(e,t){return Object.assign(Object.assign({},e),{remoteParticipants:e.remoteParticipants.filter(e=>e.id!==t)})}(e,r)}),e.addCase(Ub.audioEnabled,(e,t)=>{const{clientId:r,isAudioEnabled:n}=t.payload;return N_(e,r,{isAudioEnabled:n})}),e.addCase(Ub.videoEnabled,(e,t)=>{const{clientId:r,isVideoEnabled:n}=t.payload;return N_(e,r,{isVideoEnabled:n})}),e.addCase(Ub.clientMetadataReceived,(e,t)=>{const{error:r,payload:n}=t.payload;if(r||!n)return console.warn(r||"Client metadata error received"),e;const{clientId:i,displayName:s,stickyReaction:o}=n;return N_(e,i,{displayName:s,stickyReaction:o})}),e.addCase(Ub.breakoutGroupJoined,(e,t)=>{const{clientId:r,group:n}=t.payload;return N_(e,r,{breakoutGroup:n||null})}),e.addCase(Ub.screenshareStarted,(e,t)=>{const{clientId:r,streamId:n}=t.payload;return B_(e,r,n)}),e.addCase(Ub.screenshareStopped,(e,t)=>{const{clientId:r,streamId:n}=t.payload;return function(e,t,r){var n,i;const{participant:s}=L_(e,t);if(!s)return console.error(`No participant ${t} found to remove stream ${r}`),e;const o=s.stream&&s.stream.id,a=(null===(n=s.presentationStream)||void 0===n?void 0:n.inboundId)||(null===(i=s.presentationStream)||void 0===i?void 0:i.id),c=s.streams.findIndex(e=>e.id===r);return N_(e,t,Object.assign(Object.assign({streams:s.streams.filter((e,t)=>t!==c)},o===r&&{stream:null}),a===r&&{presentationStream:null}))}(e,r,n)})}}),{participantStreamAdded:U_,participantStreamIdAdded:V_,streamStatusUpdated:$_}=z_.actions,G_=iy(e=>Jb(e),e=>(t,r)=>{const n=r(),i=Xb(n);if(e.enable&&!i)return void console.warn("Not authorized to perform this action");const s=wy(n).socket;null==s||s.emit("request_audio_enable",e)}),q_=iy(e=>Kb(e),e=>(t,r)=>{const n=r(),i=wy(n).socket;null==i||i.emit("request_video_enable",e)}),H_=e=>e.remoteParticipants.remoteParticipants,W_=Pg(H_,e=>e.filter(e=>!d_.includes(e.roleName))),J_=Pg(H_,e=>e.length+1);Pg(W_,l_,(e,t)=>d_.includes(t.roleName)?e.length:e.length+1);const K_=uv({name:"localScreenshare",initialState:{status:"inactive",stream:null,error:null},reducers:{stopScreenshare:(e,t)=>Object.assign(Object.assign({},e),{status:"inactive",stream:null})},extraReducers:e=>{e.addCase(Y_.pending,e=>Object.assign(Object.assign({},e),{status:"starting"})),e.addCase(Y_.fulfilled,(e,{payload:{stream:t}})=>Object.assign(Object.assign({},e),{status:"active",stream:t})),e.addCase(Y_.rejected,(e,{payload:t})=>Object.assign(Object.assign({},e),{error:t,status:"inactive",stream:null}))}}),{stopScreenshare:Q_}=K_.actions,Y_=ny("localScreenshare/doStartScreenshare",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{dispatch:t,getState:r,rejectWithValue:n}){var i;try{const e=r(),n=Z_(e);if(n)return{stream:n};const s=yield navigator.mediaDevices.getDisplayMedia(),o=()=>{t(X_())};return"oninactive"in s?s.addEventListener("inactive",o):null===(i=s.getVideoTracks()[0])||void 0===i||i.addEventListener("ended",o),{stream:s}}catch(e){return n(e)}})),X_=ry(()=>(e,t)=>{const r=t(),n=Z_(r);n&&(n.getTracks().forEach(e=>e.stop()),e(Q_({stream:n})))}),Z_=e=>e.localScreenshare.stream;function ew(e){return"streamer"===e.roleName}function tw(e){return"recorder"===e.roleName}Eb({actionCreator:Ly,effect:(e,{getState:t})=>{const r=t(),n=Z_(r);n&&(null==n||n.getTracks().forEach(e=>{e.stop()}))}});const rw=uv({name:"room",initialState:{isLocked:!1},reducers:{},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return"room_locked"===t.payload.error?Object.assign(Object.assign({},e),{isLocked:Boolean(t.payload.isLocked)}):e;const{room:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r.isLocked)})}),e.addCase(Ub.roomLocked,(e,t)=>{const{isLocked:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r)})})}}),nw=ty(e=>Wb(e),e=>(t,r)=>{const n=r(),{socket:i}=wy(n);null==i||i.emit("set_lock",{locked:e.locked})}),iw=ty(e=>Qb(e),e=>(t,r)=>{const n=r(),{socket:i}=wy(n);null==i||i.emit("kick_client",{clientId:e.clientId,reasonId:"kick"})}),sw=ty(e=>Yb(e),e=>(t,r)=>{const n=r(),i=H_(n).map(e=>e.id);if(i.length){const{socket:e}=wy(n);null==e||e.emit("kick_client",{clientIds:i,reasonId:"end-meeting"})}e.stayBehind||t(Db())}),ow=Pg(Z_,l_,W_,(e,t,r)=>{const n=[];e&&n.push({id:e.id||"local-screenshare",participantId:"local",hasAudioTrack:e.getTracks().some(e=>"audio"===e.kind),breakoutGroup:t.breakoutGroup,stream:e,isLocal:!0});for(const e of r)e.presentationStream&&n.push({id:e.presentationStream.id||`pres-${e.id}`,participantId:e.id,hasAudioTrack:e.presentationStream.getTracks().some(e=>"audio"===e.kind),breakoutGroup:e.breakoutGroup,stream:e.presentationStream,isLocal:!1});return n}),aw=Pg(Z_,l_,W_,w_,__,(e,t,r,n,i)=>{const s=[];if(e){const r=!!e.getAudioTracks().length;s.push({clientId:t.id,displayName:"Your screenshare",id:"local-screenshare",isAudioEnabled:r,isLocalClient:!0,isPresentation:!0,isVideoEnabled:!0,stream:e,breakoutGroup:n||""})}for(const e of r){if(ew(e)||tw(e))continue;const{presentationStream:t}=e,r=sy(e,["presentationStream"]),n=e.displayName||"Guest",o=t&&t.active,a="pres-"+e.id,c=e.stream&&e.stream.active,d=e.isVideoEnabled;s.push(Object.assign(Object.assign(Object.assign({},r),{breakoutGroupAssigned:(null==i?void 0:i[e.deviceId])||"",clientId:e.id,displayName:n,hasActivePresentation:!!o}),e.isVideoEnabled?{isVideoEnabled:d}:{})),o&&s.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,stream:e.presentationStream,displayName:`Screenshare (${n})`,id:a,isPresentation:!0,isVideoEnabled:!0}),c&&{isRecording:null}))}return s}),cw=Pg(f_,aw,(e,t)=>[...e?[e]:[],...t]),dw=Pg(cw,y_,w_,(e,t,r)=>t&&r?e.filter(e=>e.isLocalClient||e.breakoutGroup===(r||"")||e.breakoutGroupAssigned&&e.breakoutGroupAssigned===r):e),lw=Pg(cw,y_,e=>e.breakout.groups,(e,t,r)=>{if(!t||!r)return[];return[{clients:e.filter(e=>!e.breakoutGroup||""===e.breakoutGroup),group:{id:"",name:""}},...Object.entries(r).map(([t,r])=>({clients:e.filter(e=>!e.isPresentation&&e.breakoutGroup===t),group:{id:t,name:r}}))]});function uw({isPresentation:e,stream:t}){var r,n;return e?null!==(n=null!==(r=null==t?void 0:t.outboundId)&&void 0!==r?r:null==t?void 0:t.inboundId)&&void 0!==n?n:null==t?void 0:t.id:"0"}function pw(e,t){const r=e.find(e=>e.clientId===t.clientId&&e.streamId===t.streamId);return r?e:e.concat(t)}const hw=uv({name:"spotlights",initialState:{sorted:[]},reducers:{addSpotlight(e,t){const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:pw(e.sorted,{clientId:r,streamId:n})})},removeSpotlight(e,t){const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>!(e.clientId===r&&e.streamId===n))})}},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{var r;if("error"in t.payload)return e;const{room:n}=t.payload||{};return n?Object.assign(Object.assign({},e),{sorted:null!==(r=n.spotlights)&&void 0!==r?r:e.sorted}):e}),e.addCase(Ub.spotlightAdded,(e,t)=>{const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:pw(e.sorted,{clientId:r,streamId:n})})}),e.addCase(Ub.spotlightRemoved,(e,t)=>{const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>!(e.clientId===r&&e.streamId===n))})}),e.addMatcher(Xg(Ub.clientKicked,Ub.clientLeft),(e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>e.clientId!==r)})})}}),{addSpotlight:fw,removeSpotlight:mw}=hw.actions,gw=ty(e=>Zb(e),({id:e})=>(t,r)=>{const n=r(),i=cw(n).find(t=>t.clientId===e);if(!i)return;const{socket:s}=wy(n),o=uw(i),a={clientId:i.id,streamId:null!=o?o:"0"};null==s||s.emit("add_spotlight",a)}),vw=ty(e=>Zb(e),({id:e})=>(t,r)=>{const n=r(),i=cw(n).find(t=>t.clientId===e);if(!i)return;const{socket:s}=wy(n),o=uw(i),a={clientId:i.id,streamId:null!=o?o:"0"};null==s||s.emit("remove_spotlight",a)}),bw=e=>e.spotlights.sorted;Pg(l_,bw,(e,t)=>function({spotlights:e,isPresentation:t,clientId:r,stream:n}){return!!e.find(e=>{const i=uw({isPresentation:t,stream:n});return e.clientId===r&&e.streamId===i})}({clientId:e.id,stream:e.stream,spotlights:t}));const yw=Pg(cw,bw,(e,t)=>function(e,t){return e.reduce((e,r)=>{const n=t.find(e=>r.clientId===e.clientId&&r.streamId===uw(e));return n&&!e.includes(n)&&e.push(n),e},[])}(t,e));Eb({actionCreator:Y_.fulfilled,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:n}=e,i=t(),s=l_(i);s&&r(fw({clientId:s.id,streamId:n.id}))}}),Eb({actionCreator:Q_,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:n}=e,i=t(),s=l_(i);s&&r(mw({clientId:s.id,streamId:n.id}))}});const _w=e=>({emit:(t,r)=>{"rtc_manager_created"===t?e(Aw(r)):"stream_added"===t?e(j_.streamAdded(r)):"rtc_manager_destroyed"===t?e(Rw()):"client_connection_status_changed"===t&&e(j_.clientConnectionStatusChanged(r))}}),ww={dispatcherCreated:!1,error:null,isCreatingDispatcher:!1,reportedStreamResolutions:{},rtcManager:null,rtcManagerDispatcher:null,rtcManagerInitialized:!1,status:"inactive",isAcceptingStreams:!1},Sw=uv({name:"rtcConnection",initialState:ww,reducers:{isAcceptingStreams:(e,t)=>Object.assign(Object.assign({},e),{isAcceptingStreams:t.payload}),resolutionReported:(e,t)=>{const{streamId:r,width:n,height:i}=t.payload;return Object.assign(Object.assign({},e),{reportedStreamResolutions:Object.assign(Object.assign({},e.reportedStreamResolutions),{[r]:{width:n,height:i}})})},rtcDisconnected:()=>Object.assign({},ww),rtcDispatcherCreated:(e,t)=>Object.assign(Object.assign({},e),{dispatcherCreated:!0,rtcManagerDispatcher:t.payload}),rtcManagerCreated:(e,t)=>Object.assign(Object.assign({},e),{rtcManager:t.payload,status:"ready"}),rtcManagerDestroyed:e=>Object.assign(Object.assign({},e),{rtcManager:null}),rtcManagerInitialized:e=>Object.assign(Object.assign({},e),{rtcManagerInitialized:!0}),rtcClientConnectionStatusChanged:{reducer:e=>e,prepare:e=>({payload:{},meta:{localParticipantId:e.localParticipantId}})}},extraReducers:e=>{e.addCase(vy,e=>Object.assign(Object.assign({},e),{status:"reconnecting"})),e.addCase(Ub.roomJoined,(e,t)=>"error"in t.payload?e:Object.assign(Object.assign({},e),{status:"reconnecting"===e.status?"ready":e.status}))}}),{resolutionReported:Cw,rtcDispatcherCreated:kw,rtcDisconnected:Tw,rtcManagerCreated:Pw,rtcManagerDestroyed:Rw,rtcManagerInitialized:Ew,isAcceptingStreams:Ow,rtcClientConnectionStatusChanged:xw}=Sw.actions,Iw=()=>(e,t)=>{const r=t(),n=wy(r).socket,i=Nw(r).rtcManagerDispatcher,s=Ky(r),o=Qy(r),a=(e=>e.app.isNodeSdk)(r);if(i||!n)return;const c={getMediaConstraints:()=>({audio:o,video:s}),deferrable(e){const r=W_(t()).find(t=>t.id===e);return function({client:e,breakoutCurrentId:t}){return!(!e||(t||!e.breakoutGroup)&&(e.isAudioEnabled||e.isVideoEnabled))}({client:r,breakoutCurrentId:w_(t())||""})}},d=new fp({emitter:_w(e),serverSocket:n,webrtcProvider:c,features:{isNodeSdk:a,lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,sfuVp9On:!1,h264On:!1,simulcastScreenshareOn:!1}});e(kw(d))},Dw=()=>(e,t)=>{const{rtcManager:r}=Nw(t());r&&r.disconnectAll(),e(Tw())},Mw=e=>(t,r)=>{var n;t(Ow(!0));const i=r(),s=Nw(i).rtcManager,o=H_(i);if(!s)throw new Error("No rtc manager");const a=y_(i),c=null===(n=s.shouldAcceptStreamsFromBothSides)||void 0===n?void 0:n.call(s),d=[];for(const{clientId:t,streamId:r,state:n}of e){const e=o.find(e=>e.id===t);if(e){if("to_accept"===n||"new_accept"===n&&c||"old_accept"===n&&!c)s.acceptNewStream({streamId:"0"===r?t:r,clientId:t,shouldAddLocalVideo:"0"===r,activeBreakout:a});else if("new_accept"===n||"old_accept"===n);else if("to_unaccept"===n)null==s||s.disconnect("0"===r?t:r,a);else if("done_accept"!==n)continue;d.push({clientId:t,streamId:r,state:n.replace(/to_|new_|old_/,"done_")})}}t($_(d)),t(Ow(!1))},jw=({streamId:e,width:t,height:r})=>(n,i)=>{const{reportedStreamResolutions:s,rtcManager:o}=Nw(i()),a=r_(i());if(!o||(null==a?void 0:a.id)===e)return;const c=s[e];c&&c.width===t&&c.height===r||o.updateStreamResolution(e,null,{width:t||1,height:r||1}),n(Cw({streamId:e,width:t,height:r}))},Aw=e=>t=>{const{rtcManager:r}=e;t(Pw(r))},Lw=()=>(e,t)=>{const r=r_(t()),n=Nw(t()).rtcManager,i=Ky(t()),s=Qy(t());r&&n&&n.addNewStream("0",r,!s,!i),e(Ew())},Nw=e=>e.rtcConnection,Fw=e=>e.rtcConnection.rtcManagerInitialized,Bw=e=>e.rtcConnection.rtcManager,zw=e=>e.rtcConnection.status;Eb({actionCreator:Uy.fulfilled,effect:({payload:e},{getState:t})=>{const{replacedTracks:r}=e,{rtcManager:n}=Nw(t()),i=r_(t());null==r||r.forEach(e=>{((e,t)=>{const r=null==i?void 0:i.getTracks().find(t=>t.kind===e);r&&(null==n||n.replaceTrack(t,r))})(e.kind,e)})}}),Eb({actionCreator:Y_.fulfilled,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:n}=Nw(t());null==n||n.addNewStream(r.id,r,!1,!0)}}),Eb({actionCreator:Db,effect:(e,{getState:t})=>{const r=Bw(t());null==r||r.rtcStatsDisconnect()}}),Eb({actionCreator:Q_,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:n}=Nw(t());null==n||n.removeStream(r.id,r,null)}}),Eb({actionCreator:$y.fulfilled,effect:({payload:e},{getState:t})=>{var r;const n=r_(t()),{rtcManager:i}=Nw(t());if(n&&i){const t=(e,t)=>{const r=n.getTracks().find(t=>t.kind===e);return r&&i.replaceTrack(t,r)};null===(r=null==e?void 0:e.replacedTracks)||void 0===r||r.forEach(e=>{t(e.kind,e)})}}}),Eb({actionCreator:j_.clientConnectionStatusChanged,effect:(e,{dispatch:t,getState:r})=>{const n=l_(r());t(xw({localParticipantId:n.id}))}}),Eb({actionCreator:Gy.fulfilled,effect:({payload:e},{getState:t})=>{const{rtcManager:r,rtcManagerInitialized:n}=Nw(t());if(!r||!n)return;const i=Ky(t()),s=Qy(t()),{stream:o}=e;o&&r.addNewStream("0",e.stream,!s,!i)}});Ob([Pg(zw,jb,e=>e.rtcConnection.dispatcherCreated,e=>e.rtcConnection.isCreatingDispatcher,ky,(e,t,r,n,i)=>!(!t||"inactive"!==e||r||n||!i))],({dispatch:e},t)=>{t&&e(Iw())});const Uw=Pg(Bw,Fw,t_,(e,t,r)=>!("started"!==r||!e||t));Ob([Uw],({dispatch:e},t)=>{t&&e(Lw())});Ob([Pg(zw,jb,(e,t)=>!t&&!["inactive","disconnected"].includes(e))],({dispatch:e},t)=>{t&&e(Dw())});const Vw=Pg(zw,H_,w_,bw,e=>e.app.ignoreBreakoutGroups,(e,t,r,n,i)=>{if("ready"!==e)return[];const s=[];for(const e of t){const{streams:t,id:o,newJoiner:a}=e,c=n.find(t=>t.clientId===e.id&&"0"===t.streamId);for(let n=0;n<t.length;n++){let d=t[n].id,l=t[n].state;if((null==t?void 0:t.length)>1&&"0"===t[1].id&&(0===n?(d=t[1].id,l=t[1].state):1===n&&(d=t[0].id,l=t[0].state)),!e.breakoutGroup&&!r||e.breakoutGroup===r||""===e.breakoutGroup&&c||i){if("done_accept"===l)continue;s.push({clientId:o,streamId:d,state:(a&&"0"===d?"new":"to")+"_accept"})}else{if("done_unaccept"===l)continue;s.push({clientId:o,streamId:d,state:"to_unaccept"})}}}return s});Ob([Vw,e=>e.rtcConnection.isAcceptingStreams],({dispatch:e},t,r)=>{0<t.length&&!r&&e(Mw(t))});const $w={running:!1},Gw=uv({name:"connectionMonitor",initialState:$w,reducers:{connectionMonitorStarted:(e,t)=>Object.assign(Object.assign({},e),{running:!0,stopCallbackFunction:t.payload.stopIssueSubscription}),connectionMonitorStopped:()=>Object.assign({},$w)}}),{connectionMonitorStarted:qw,connectionMonitorStopped:Hw}=Gw.actions,Ww=()=>(e,t)=>{var r;r=()=>{const e=t(),r=cw(e).map(e=>{var t,r;return{id:e.id,clientId:e.clientId,isLocalClient:e.isLocalClient,audio:{enabled:e.isAudioEnabled,track:null===(t=e.stream)||void 0===t?void 0:t.getAudioTracks()[0]},video:{enabled:e.isVideoEnabled,track:null===(r=e.stream)||void 0===r?void 0:r.getVideoTracks()[0]},isPresentation:e.isPresentation}});return r},ml.getClients=r;const n=Ep({onUpdatedIssues:e=>{var r;const n=t(),i=Bw(n);if(!i)return;let s=0,o=0,a=0,c=0;Object.entries(e.aggregated.metrics).forEach(([e,t])=>{/loc.*packetloss/.test(e)&&(s=Math.max(s,t.curMax)),/rem.*packetloss/.test(e)&&(o=Math.max(o,t.curMax)),/loc.*bitrate/.test(e)&&(a+=t.curSum),/rem.*bitrate/.test(e)&&(c+=t.curSum)}),i.sendStatsCustomEvent("insightsStats",{ls:Math.round(1e3*s)/1e3,lr:Math.round(1e3*o)/1e3,bs:Math.round(a),br:Math.round(c),cpu:null===(r=e.aggregated.metrics["global-cpu-pressure"])||void 0===r?void 0:r.curSum,_time:Date.now()})}});e(qw({stopIssueSubscription:n.stop}))},Jw=()=>(e,t)=>{const r=t(),n=Qw(r);n&&n(),e(Hw())},Kw=e=>e.connectionMonitor.running,Qw=e=>e.connectionMonitor.stopCallbackFunction,Yw=Pg(D_,Kw,(e,t)=>!t&&"connected"===e),Xw=Pg(D_,Kw,(e,t)=>!(!t||!["kicked","left"].includes(e)));Ob([Yw],({dispatch:e},t)=>{t&&e(Ww())}),Ob([Xw],({dispatch:e},t)=>{t&&e(Jw())});const Zw=uv({name:"localParticipant",initialState:{displayName:"",id:"",breakoutGroup:null,breakoutGroupAssigned:"",isAudioEnabled:!0,isVideoEnabled:!0,isLocalParticipant:!0,stream:void 0,isScreenSharing:!1,roleName:"none",clientClaim:void 0,stickyReaction:void 0,isDialIn:!1},reducers:{setDisplayName:(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}),setBreakoutGroupAssigned:(e,t)=>Object.assign(Object.assign({},e),{breakoutGroupAssigned:t.payload.breakoutGroupAssigned})},extraReducers:e=>{e.addCase(Mb,(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName})),e.addCase(rS.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isAudioEnabled:t.payload})),e.addCase(nS.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isVideoEnabled:t.payload})),e.addCase(iS.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{stickyReaction:t.payload})),e.addCase(Ub.roomJoined,(e,t)=>{var r;if("error"in t.payload)return"room_locked"===t.payload.error?Object.assign(Object.assign({},e),{id:t.payload.selfId}):e;const{room:n,selfId:i,clientClaim:s}=t.payload||{},o=n.clients.find(e=>e.id===i);return Object.assign(Object.assign({},e),{id:i,roleName:(null===(r=null==o?void 0:o.role)||void 0===r?void 0:r.roleName)||"none",clientClaim:s,breakoutGroup:(null==o?void 0:o.breakoutGroup)||null})}),e.addCase(Ub.breakoutGroupJoined,(e,t)=>{var r,n;return(null===(r=t.payload)||void 0===r?void 0:r.clientId)!==e.id?e:Object.assign(Object.assign({},e),{breakoutGroup:null===(n=t.payload)||void 0===n?void 0:n.group})})}}),{setDisplayName:eS,setBreakoutGroupAssigned:tS}=Zw.actions,rS=ny("localParticipant/doEnableAudio",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{dispatch:t,getState:r}){const n=r(),i=wy(n).socket;return null==i||i.emit("enable_audio",{enabled:e.enabled}),e.enabled&&t(iS({enabled:!1})),e.enabled})),nS=ny("localParticipant/doEnableVideo",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t}){const r=t(),n=wy(r).socket;return null==n||n.emit("enable_video",{enabled:e.enabled}),e.enabled})),iS=ny("localParticipant/doSetLocalStickyReaction",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t,rejectWithValue:r}){var n;const i=t(),s=h_(i),o=Boolean(s),a=null!==(n=e.enabled)&&void 0!==n?n:!o;if(a===o)return r(s);return a?{reaction:"✋",timestamp:(new Date).toISOString()}:null})),sS=ry(()=>(e,t)=>{const r=t(),n=wy(r).socket,i={displayName:p_(r),stickyReaction:h_(r)};null==n||n.emit("send_client_metadata",{type:"UserData",payload:i})});Eb({actionCreator:Iy,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:n}=e,{isVideoEnabled:i}=l_(r());"connected"===D_(r())&&t(nS({enabled:n||!i}))}}),Eb({actionCreator:Dy,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:n}=e,{isAudioEnabled:i}=l_(r());"connected"===D_(r())&&t(rS({enabled:n||!i}))}}),Ob([p_,h_,D_,e=>e.app.isAssistant],({dispatch:e},t,r,n,i)=>{"connected"!==n||i||e(sS())}),Ob([__,ly,l_],({dispatch:e},t,r,n)=>{const i=(null==t?void 0:t[r||""])||"";n.breakoutGroupAssigned!==i&&e(tS({breakoutGroupAssigned:i}))});function oS(e){return Object.assign(Object.assign({},e),{timestamp:Date.now()})}const aS=uv({name:"notifications",initialState:{emitter:new Ro,events:[]},reducers:{addNotification:(e,t)=>Object.assign(Object.assign({},e),{events:[...e.events,Object.assign({},t.payload)]}),doClearNotifications:e=>Object.assign(Object.assign({},e),{events:[]})}}),{doClearNotifications:cS}=aS.actions,dS=e=>(t,r)=>{t(aS.actions.addNotification(e));const n=r(),i=lS(n);i.emit(e.type,e),i.emit("*",e)},lS=e=>e.notifications.emitter;Eb({actionCreator:Ub.chatMessage,effect:({payload:e},{dispatch:t,getState:r})=>{const n=r(),i=W_(n).find(({id:t})=>t===e.senderId);i?t(dS(oS({type:"chatMessageReceived",message:`${i.displayName} says: ${e.text}`,props:{client:i,chatMessage:{senderId:e.senderId,timestamp:e.timestamp,text:e.text}}}))):console.warn("Could not find remote client that sent chat message")}}),Eb({actionCreator:Ub.audioEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:n,requestedByClientId:i}=e,s=r(),o=W_(s).find(({id:e})=>e===i);o?t(dS(oS({type:n?"requestAudioEnable":"requestAudioDisable",message:n?`${o.displayName} has requested for you to speak`:`${o.displayName} has muted your microphone`,props:{client:o,enable:n}}))):console.warn("Could not find remote client that requested a local audio change")}}),Eb({actionCreator:Ub.videoEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:n,requestedByClientId:i}=e,s=r(),o=W_(s).find(({id:e})=>e===i);o?t(dS(oS({type:n?"requestVideoEnable":"requestVideoDisable",message:n?`${o.displayName} has requested for you to start video`:`${o.displayName} has stopped your video`,props:{client:o,enable:n}}))):console.warn("Could not find remote client that requested a local video change")}}),Eb({actionCreator:Ub.clientMetadataReceived,effect:(e,{dispatch:t,getOriginalState:r,getState:n})=>{var i;const{error:s,payload:o}=e.payload;if(s||!o)return;const{clientId:a,stickyReaction:c}=o,d=n();if(!Xb(d))return;const l=W_(d).find(({id:e})=>e===a);if(!l)return void console.warn("Could not find remote client that provided updated metadata");const u=r(),p=W_(u).find(({id:e})=>e===a);(c||(null==p?void 0:p.stickyReaction))&&(null==c?void 0:c.timestamp)!==(null===(i=null==p?void 0:p.stickyReaction)||void 0===i?void 0:i.timestamp)&&t(dS(oS({type:c?"remoteHandRaised":"remoteHandLowered",message:`${l.displayName} ${c?"raised":"lowered"} their hand`,props:{client:l,stickyReaction:c}})))}}),Ob([Cy],({dispatch:e,getState:t},r)=>{const n=t(),i=D_(n);["left","kicked"].includes(i)||("disconnected"===r?e(dS(oS({type:"signalTrouble",message:"Network connection lost. Trying to reconnect you...",props:{}}))):"connected"===r&&e(dS(oS({type:"signalOk",message:"Network connection available",props:{}}))))}),Eb({actionCreator:Ub.clientUnableToJoin,effect:(e,{dispatch:t})=>{var r;"room_full"===(null===(r=e.payload)||void 0===r?void 0:r.error)&&t(dS(oS({type:"clientUnableToJoinFullRoom",message:"Someone tried to join but the room is full and at capacity.",props:{}})))}});const uS=uv({name:"organization",initialState:{data:null,isFetching:!1,error:null},reducers:{},extraReducers:e=>{e.addCase(pS.pending,e=>Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(pS.fulfilled,(e,t)=>t.payload?Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}):Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(pS.rejected,e=>Object.assign(Object.assign({},e),{isFetching:!1,error:!0}))}}),pS=ey("organization/doOrganizationFetch",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{extra:t,getState:r}){try{const e=r().app.roomUrl,n=yield t.services.fetchOrganizationFromRoomUrl(e||"");if(!n)throw new Error("Invalid room url");return n}catch(e){console.error(e)}})),hS=e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.organizationId};Ob([Pg(jb,e=>e.organization,dy,(e,t,r)=>!(!e||t.data||t.isFetching||t.error||r.isFetching))],({dispatch:e},t)=>{t&&e(pS())});const fS=uv({name:"roomConnection",initialState:{session:null,status:"ready",error:null},reducers:{connectionStatusChanged:(e,t)=>Object.assign(Object.assign({},e),{status:t.payload})},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{var r;if("error"in t.payload)return"room_locked"===t.payload.error&&t.payload.isLocked?Object.assign(Object.assign({},e),{status:"room_locked"}):Object.assign(Object.assign({},e),{status:"disconnected",error:t.payload.error});const{room:n}=t.payload;return Object.assign(Object.assign({},e),{status:"connected",session:null!==(r=n.session)&&void 0!==r?r:null})}),e.addCase(Ub.disconnect,e=>["kicked","left"].includes(e.status)?Object.assign({},e):Object.assign(Object.assign({},e),{status:"disconnected"})),e.addCase(Ub.newClient,(e,t)=>{var r,n;return Object.assign(Object.assign({},e),{session:null!==(n=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==n?n:null})}),e.addCase(Ub.roomSessionEnded,(e,t)=>{var r;return(null===(r=e.session)||void 0===r?void 0:r.id)!==t.payload.roomSessionId?e:Object.assign(Object.assign({},e),{session:null})}),e.addCase(Ub.clientKicked,e=>Object.assign(Object.assign({},e),{status:"kicked"})),e.addCase(Ub.roomLeft,e=>Object.assign(Object.assign({},e),{status:"left"})),e.addCase(vy,e=>Object.assign(Object.assign({},e),{status:"reconnecting"}))}}),{connectionStatusChanged:mS}=fS.actions,gS=()=>(e,t)=>{const r=t(),n=wy(r).socket,i=Lb(r),s=qb(r),o=Nb(r),a=Ab(r),c=Fb(r),d=Bb(r),l=hS(r);"room_locked"===D_(r)?(null==n||n.emit("knock_room",{avatarUrl:null,config:{isAudioEnabled:!0,isVideoEnabled:!0},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:a,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:i,userAgent:c,externalId:d}),e(mS("knocking"))):console.warn("Room is not locked, knock aborted")},vS=()=>(e,t)=>{const r=t(),n=wy(r).socket,i=Lb(r),s=qb(r),o=(e=>e.authorization.assistantKey)(r),a=Nb(r),c=Fb(r),d=Bb(r),l=Ab(r),u=hS(r),p=Ky(t()),h=Qy(t()),f=(e=>e.localParticipant.clientClaim)(t());null==n||n.emit("join_room",Object.assign({avatarUrl:null,config:{isAudioEnabled:h,isVideoEnabled:p},deviceCapabilities:{canScreenshare:!0},displayName:a,isCoLocated:!1,isDialIn:l,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:u,roomKey:s,assistantKey:o,roomName:i,userAgent:c,externalId:d},f&&{clientClaim:f})),e(mS("connecting"))};Ob([Pg([jb,hS,D_,Sy,t_,e=>e.roomConnection.error],(e,t,r,n,i,s)=>!(!(e&&"started"===i&&n&&t&&["ready","reconnecting","disconnected"].includes(r))||s))],({dispatch:e},t)=>{t&&e(vS())}),Eb({actionCreator:Ub.knockHandled,effect:({payload:e},{dispatch:t,getState:r})=>{const{clientId:n,resolution:i}=e,s=r();n===u_(s)&&("accepted"===i?(t(Gb(e.metadata.roomKey)),t(vS())):"rejected"===i&&t(mS("knock_rejected")))}}),Eb({actionCreator:Db,effect:(e,{dispatch:t,getState:r})=>{const n=r();if("connected"===D_(n)){const e=wy(n).socket;null==e||e.emit("leave_room"),t(mS("leaving"))}else _y()}});const bS={audioEnabled:{actions:[rS.fulfilled],rtcEventName:"audioEnabled",getValue:e=>Qy(e),getOutput:e=>({enabled:e})},videoEnabled:{actions:[nS.fulfilled],rtcEventName:"videoEnabled",getValue:e=>Ky(e),getOutput:e=>({enabled:e})},localStream:{actions:[Uy.fulfilled],rtcEventName:"localStream",getValue:e=>{var t;return null===(t=r_(e))||void 0===t?void 0:t.getTracks().map(e=>({id:e.id,kind:e.kind,label:e.label}))},getOutput:e=>({stream:e})},localScreenshareStream:{actions:[Y_.fulfilled],rtcEventName:"localScreenshareStream",getValue:e=>{var t;return null===(t=Z_(e))||void 0===t?void 0:t.getTracks().map(e=>({id:e.id,kind:e.kind,label:e.label}))},getOutput:e=>({tracks:e})},localScreenshareStreamStopped:{actions:[Q_],rtcEventName:"localScreenshareStream",getValue:()=>()=>null,getOutput:()=>({})},displayName:{actions:[eS],rtcEventName:"displayName",getValue:e=>{const t=p_(e),r=(e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.preferences})(e);return(null==r?void 0:r.hideInsightsDisplayNames)?"[[redacted]]":t},getOutput:e=>({displayName:e})},clientId:{actions:null,rtcEventName:"clientId",getValue:e=>u_(e),getOutput:e=>({clientId:e})},deviceId:{actions:null,rtcEventName:"deviceId",getValue:e=>ly(e),getOutput:e=>({deviceId:e})},externalId:{actions:null,rtcEventName:"externalId",getValue:e=>Bb(e),getOutput:e=>({externalId:e})},organizationId:{actions:null,rtcEventName:"organizationId",getValue:e=>hS(e),getOutput:e=>({organizationId:e})},signalConnectionStatus:{actions:null,rtcEventName:"signalConnectionStatus",getValue:e=>Cy(e),getOutput:e=>({status:e})},recording:{actions:[Ub.newClient],rtcEventName:"recording",getValue:e=>({local:!1,cloud:!(!x_(e)||!I_(e))}),getOutput:e=>e},roomSessionId:{actions:[Ub.newClient,Ub.roomJoined,Ub.roomSessionEnded,Ub.clientLeft],rtcEventName:"roomSessionId",getValue:e=>(e=>{var t;return null===(t=e.roomConnection.session)||void 0===t?void 0:t.id})(e),getOutput:e=>({roomSessionId:e})},rtcConnectionStatus:{actions:null,rtcEventName:"rtcConnectionStatus",getValue:e=>zw(e),getOutput:e=>({status:e})},userRole:{actions:null,rtcEventName:"userRole",getValue:e=>Hb(e),getOutput:e=>({userRole:e})}},yS=Object.values(bS).flatMap(({actions:e})=>{var t;return null!==(t=null==e?void 0:e.map(e=>e))&&void 0!==t?t:null}).filter(e=>null!==e),_S=e=>"object"==typeof e?JSON.stringify(e):e,wS=uv({name:"rtcAnalytics",initialState:{reportedValues:{}},reducers:{updateReportedValues:(e,t)=>Object.assign(Object.assign({},e),{reportedValues:Object.assign(Object.assign({},e.reportedValues),{[t.payload.rtcEventName]:t.payload.value})})}}),SS=()=>(e,t)=>{const r=t(),n=Nw(r).rtcManager;n&&(n.sendStatsCustomEvent("insightsStats",{_time:Date.now(),ls:0,lr:0,bs:0,br:0,cpu:0}),Object.values(bS).forEach(({rtcEventName:t,getValue:i,getOutput:s})=>{var o;const a=i(r),c=Object.assign(Object.assign({},s(a)),{_time:Date.now()}),d=_S(a);(null===(o=r.rtcAnalytics.reportedValues)||void 0===o?void 0:o[t])!==d&&(n.sendStatsCustomEvent(t,c),e(CS({rtcEventName:t,value:a})))}))},{updateReportedValues:CS}=wS.actions;Eb({matcher:Xg(...yS),effect:({type:e},{getState:t,dispatch:r})=>{var n;const i=t(),s=Nw(i).rtcManager;if(!s)return;const o=Object.values(bS).find(({actions:t})=>null==t?void 0:t.map(e=>e.type).includes(e));if(!o)return;const{getValue:a,getOutput:c,rtcEventName:d}=o,l=a(i),u=_S(l),p=Object.assign(Object.assign({},c(l)),{_time:Date.now()});(null===(n=i.rtcAnalytics.reportedValues)||void 0===n?void 0:n[d])!==u&&(s.sendStatsCustomEvent(d,p),r(CS({rtcEventName:d,value:l})))}}),Ob([Fw],({dispatch:e},t)=>{t&&e(SS())});const kS=uv({name:"streaming",initialState:{isStreaming:!1,error:null,startedAt:void 0},reducers:{doHandleStreamingStarted:e=>Object.assign(Object.assign({},e),{isStreaming:!0,error:null,startedAt:(new Date).getTime()}),doHandleStreamingStopped:e=>Object.assign(Object.assign({},e),{isStreaming:!1})}}),{doHandleStreamingStarted:TS,doHandleStreamingStopped:PS}=kS.actions,RS=uv({name:"waitingParticipants",initialState:{waitingParticipants:[]},reducers:{},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r}=t.payload;return r.knockers.length?Object.assign(Object.assign({},e),{waitingParticipants:r.knockers.map(e=>({id:e.clientId,displayName:e.displayName}))}):e}),e.addCase(Ub.roomKnocked,(e,t)=>{const{clientId:r,displayName:n}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:r,displayName:n}]})}),e.addCase(Ub.knockerLeft,(e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter(e=>e.id!==r)})})}}),ES=ry(e=>(t,r)=>{const{participantId:n}=e,i=r(),s=ky(i);null==s||s.emit("handle_knock",{action:"accept",clientId:n,response:{}})}),OS=ry(e=>(t,r)=>{const{participantId:n}=e,i=r(),s=ky(i);null==s||s.emit("handle_knock",{action:"reject",clientId:n,response:{}})}),xS=Cm({app:Ib.reducer,authorization:$b.reducer,breakout:g_.reducer,chat:C_.reducer,cloudRecording:T_.reducer,connectionMonitor:Gw.reducer,deviceCredentials:ay.reducer,localMedia:Py.reducer,localParticipant:Zw.reducer,localScreenshare:K_.reducer,notifications:aS.reducer,organization:uS.reducer,remoteParticipants:z_.reducer,room:rw.reducer,roomConnection:fS.reducer,rtcAnalytics:wS.reducer,rtcConnection:Sw.reducer,signalConnection:uy.reducer,spotlights:hw.reducer,streaming:kS.reducer,waitingParticipants:RS.reducer}),IS=(e,t)=>{var r;if(Mb.match(t)){const n={app:Object.assign(Object.assign({},Ib.getInitialState()),{initialConfig:null===(r=null==e?void 0:e.app)||void 0===r?void 0:r.initialConfig}),localMedia:Object.assign(Object.assign({},Py.getInitialState()),null==e?void 0:e.localMedia)};return xS(n,t)}return xS(e,t)},DS=Pg(cw,yw,J_,(e,t,r)=>({allClientViews:e,spotlightedParticipants:t,numParticipants:r}));class MS extends Ro{constructor(e){super(),this.stateSubscribers=new Set,this.store=e,this.previousState=this.getState(),this.setupEventBridge()}subscribe(e){return this.stateSubscribers.add(e),()=>this.stateSubscribers.delete(e)}setupEventBridge(){this.store.subscribe(()=>{const e=this.getState();e!==this.previousState&&(this.handleStateChanges(e,this.previousState),this.stateSubscribers.forEach(t=>t(e)),this.previousState=e)})}destroy(){this.stateSubscribers.clear(),this.removeAllListeners()}}class jS extends MS{constructor(e){super(e),this.clientViewSubscribers=new Set,this.spotlightedSubscribers=new Set,this.numberOfClientViewsSubscribers=new Set}handleStateChanges(e,t){e.allClientViews!==t.allClientViews&&(this.clientViewSubscribers.forEach(t=>t(e.allClientViews)),this.emit("grid:client-view-changed",e.allClientViews)),e.spotlightedParticipants!==t.spotlightedParticipants&&(this.spotlightedSubscribers.forEach(t=>t(e.spotlightedParticipants)),this.emit("grid:client-view-spotlights-changed",e.spotlightedParticipants)),e.numParticipants!==t.numParticipants&&(this.numberOfClientViewsSubscribers.forEach(t=>t(e.numParticipants)),this.emit("grid:number-of-client-views-changed",e.numParticipants))}getState(){return DS(this.store.getState())}subscribeClientViews(e){return this.clientViewSubscribers.add(e),()=>this.clientViewSubscribers.delete(e)}subscribeSpotlightedParticipants(e){return this.spotlightedSubscribers.add(e),()=>this.spotlightedSubscribers.delete(e)}subscribeNumberOfClientViews(e){return this.numberOfClientViewsSubscribers.add(e),()=>this.numberOfClientViewsSubscribers.delete(e)}spotlightParticipant(e){this.store.dispatch(gw({id:e}))}removeSpotlight(e){this.store.dispatch(vw({id:e}))}destroy(){super.destroy(),this.clientViewSubscribers.clear(),this.spotlightedSubscribers.clear(),this.numberOfClientViewsSubscribers.clear(),this.removeAllListeners()}}const AS=Pg(e=>e.localMedia.cameraDeviceError,o_,Wy,Jy,e=>e.localMedia.currentSpeakerDeviceId,e=>e.localMedia.isSettingCameraDevice,e=>e.localMedia.isSettingMicrophoneDevice,s_,r_,e=>e.localMedia.microphoneDeviceError,a_,c_,e=>e.localMedia.startError,(e,t,r,n,i,s,o,a,c,d,l,u,p)=>({cameraDeviceError:e,cameraDevices:t,currentCameraDeviceId:r,currentMicrophoneDeviceId:n,currentSpeakerDeviceId:i,isSettingCameraDevice:s,isSettingMicrophoneDevice:o,isStarting:a,localStream:c,microphoneDeviceError:d,microphoneDevices:l,speakerDevices:u,startError:p})),LS="local-media:current-speaker-changed";class NS extends MS{constructor(e){super(e),this.cameraDeviceErrorSubscribers=new Set,this.cameraDeviceSubscribers=new Set,this.isSettingCameraDeviceSubscribers=new Set,this.isSettingMicrophoneDeviceSubscribers=new Set,this.microphoneDeviceErrorSubscribers=new Set,this.microphoneDeviceSubscribers=new Set,this.speakerDeviceSubscribers=new Set,this.currentCameraSubscribers=new Set,this.currentMicrophoneSubscribers=new Set,this.currentSpeakerSubscribers=new Set,this.localMediaStartingSubscribers=new Set,this.localStreamSubscribers=new Set,this.localMediaStartErrorSubscribers=new Set}handleStateChanges(e,t){e.cameraDeviceError!==t.cameraDeviceError&&(this.cameraDeviceErrorSubscribers.forEach(t=>t(e.cameraDeviceError)),this.emit("local-media:camera-device-error-changed",e.cameraDeviceError)),e.cameraDevices!==t.cameraDevices&&(this.cameraDeviceSubscribers.forEach(t=>t(e.cameraDevices)),this.emit("local-media:camera-devices-changed",e.cameraDevices)),e.isSettingCameraDevice!==t.isSettingCameraDevice&&(this.isSettingCameraDeviceSubscribers.forEach(t=>t(e.isSettingCameraDevice)),this.emit("local-media:is-setting-camera-device",e.isSettingCameraDevice)),e.isSettingMicrophoneDevice!==t.isSettingMicrophoneDevice&&(this.isSettingMicrophoneDeviceSubscribers.forEach(t=>t(e.isSettingMicrophoneDevice)),this.emit("local-media:is-setting-microphone-device",e.isSettingMicrophoneDevice)),e.microphoneDeviceError!==t.microphoneDeviceError&&(this.microphoneDeviceErrorSubscribers.forEach(t=>t(e.microphoneDeviceError)),this.emit("local-media:microphone-device-error-changed",e.microphoneDeviceError)),e.microphoneDevices!==t.microphoneDevices&&(this.microphoneDeviceSubscribers.forEach(t=>t(e.microphoneDevices)),this.emit("local-media:microphone-devices-changed",e.microphoneDevices)),e.speakerDevices!==t.speakerDevices&&(this.speakerDeviceSubscribers.forEach(t=>t(e.speakerDevices)),this.emit("local-media:speaker-devices-changed",e.speakerDevices)),e.currentCameraDeviceId!==t.currentCameraDeviceId&&(this.currentCameraSubscribers.forEach(t=>t(e.currentCameraDeviceId)),this.emit("local-media:current-camera-changed",e.currentCameraDeviceId)),e.currentMicrophoneDeviceId!==t.currentMicrophoneDeviceId&&(this.currentMicrophoneSubscribers.forEach(t=>t(e.currentMicrophoneDeviceId)),this.emit("local-media:current-microphone-changed",e.currentMicrophoneDeviceId)),e.currentSpeakerDeviceId!==t.currentSpeakerDeviceId&&(this.currentSpeakerSubscribers.forEach(t=>t(e.currentSpeakerDeviceId)),this.emit(LS,e.currentSpeakerDeviceId)),e.isStarting!==t.isStarting&&(this.localMediaStartingSubscribers.forEach(t=>t(e.isStarting)),this.emit("local-media:starting",e.isStarting)),e.localStream!==t.localStream&&(this.localStreamSubscribers.forEach(t=>t(e.localStream)),this.emit("local-media:local-stream-changed",e.localStream)),e.startError!==t.startError&&(this.localMediaStartErrorSubscribers.forEach(t=>t(e.startError)),this.emit("local-media:start-error-changed",e.startError))}getState(){return AS(this.store.getState())}subscribeCameraDeviceError(e){return this.cameraDeviceErrorSubscribers.add(e),()=>this.cameraDeviceErrorSubscribers.delete(e)}subscribeCameraDevices(e){return this.cameraDeviceSubscribers.add(e),()=>this.cameraDeviceSubscribers.delete(e)}subscribeIsSettingCameraDevice(e){return this.isSettingCameraDeviceSubscribers.add(e),()=>this.isSettingCameraDeviceSubscribers.delete(e)}subscribeIsSettingMicrophoneDevice(e){return this.isSettingMicrophoneDeviceSubscribers.add(e),()=>this.isSettingMicrophoneDeviceSubscribers.delete(e)}subscribeMicrophoneDeviceError(e){return this.microphoneDeviceErrorSubscribers.add(e),()=>this.microphoneDeviceErrorSubscribers.delete(e)}subscribeMicrophoneDevices(e){return this.microphoneDeviceSubscribers.add(e),()=>this.microphoneDeviceSubscribers.delete(e)}subscribeSpeakerDevices(e){return this.speakerDeviceSubscribers.add(e),()=>this.speakerDeviceSubscribers.delete(e)}subscribeCurrentCamera(e){return this.currentCameraSubscribers.add(e),()=>this.currentCameraSubscribers.delete(e)}subscribeCurrentMicrophone(e){return this.currentMicrophoneSubscribers.add(e),()=>this.currentMicrophoneSubscribers.delete(e)}subscribeCurrentSpeaker(e){return this.currentSpeakerSubscribers.add(e),()=>this.currentSpeakerSubscribers.delete(e)}subscribeLocalMediaStarting(e){return this.localMediaStartingSubscribers.add(e),()=>this.localMediaStartingSubscribers.delete(e)}subscribeLocalStream(e){return this.localStreamSubscribers.add(e),()=>this.localStreamSubscribers.delete(e)}subscribeLocalMediaStartError(e){return this.localMediaStartErrorSubscribers.add(e),()=>this.localMediaStartErrorSubscribers.delete(e)}startMedia(){return oy(this,arguments,void 0,function*(e={audio:!0,video:!0}){return yield this.store.dispatch(Gy(e))})}toggleCamera(e){this.store.dispatch(Iy({enabled:e}))}toggleMicrophone(e){this.store.dispatch(Dy({enabled:e}))}toggleLowDataMode(e){this.store.dispatch(My({enabled:e}))}setCameraDevice(e){this.store.dispatch(Ey({deviceId:e}))}setMicrophoneDevice(e){this.store.dispatch(Oy({deviceId:e}))}setSpeakerDevice(e){this.store.dispatch(xy({deviceId:e}))}stopMedia(){return this.store.dispatch(qy())}destroy(){super.destroy(),this.stopMedia(),this.removeAllListeners(),this.cameraDeviceSubscribers.clear(),this.microphoneDeviceSubscribers.clear(),this.speakerDeviceSubscribers.clear(),this.currentCameraSubscribers.clear(),this.currentMicrophoneSubscribers.clear(),this.currentSpeakerSubscribers.clear(),this.cameraDeviceErrorSubscribers.clear(),this.microphoneDeviceErrorSubscribers.clear(),this.isSettingCameraDeviceSubscribers.clear(),this.isSettingMicrophoneDeviceSubscribers.clear(),this.localMediaStartingSubscribers.clear(),this.localStreamSubscribers.clear(),this.localMediaStartErrorSubscribers.clear()}}const FS=Pg(e=>e.chat.chatMessages,e=>e.cloudRecording,S_,y_,lw,dw,l_,r_,W_,ow,D_,e=>e.streaming,e=>e.waitingParticipants.waitingParticipants,lS,yw,(e,t,r,n,i,s,o,a,c,d,l,u,p,h,f)=>({chatMessages:e,cloudRecording:t.isRecording?{status:"recording"}:void 0,breakout:{isActive:n,currentGroup:r,groupedParticipants:i,participantsInCurrentGroup:s},connectionStatus:l,events:h,liveStream:u.isStreaming?{status:"streaming",startedAt:u.startedAt}:void 0,localScreenshareStatus:o.isScreenSharing?"active":void 0,localParticipant:Object.assign(Object.assign({},o),{stream:a}),remoteParticipants:c,screenshares:d,waitingParticipants:p,spotlightedParticipants:f}));class BS extends MS{constructor(e){super(e),this.selfId=null,this.chatMessageSubscribers=new Set,this.cloudRecordingSubscribers=new Set,this.breakoutSubscribers=new Set,this.connectionStatusSubscribers=new Set,this.liveStreamSubscribers=new Set,this.localScreenshareStatusSubscribers=new Set,this.localParticipantSubscribers=new Set,this.remoteParticipantsSubscribers=new Set,this.screenshareSubscribers=new Set,this.waitingParticipantsSubscribers=new Set,this.spotlightedParticipantsSubscribers=new Set,this.options={},this.registerAppListeners()}handleStateChanges(e,t){var r;if(e.chatMessages!==t.chatMessages&&this.chatMessageSubscribers.forEach(t=>t(e.chatMessages)),e.cloudRecording!==t.cloudRecording&&(this.cloudRecordingSubscribers.forEach(t=>t(e.cloudRecording?{status:"recording"}:void 0)),this.emit("cloud-recording:status-changed",e.cloudRecording?{status:"recording"}:void 0)),e.breakout!==t.breakout&&(this.breakoutSubscribers.forEach(t=>t(e.breakout)),this.emit("breakout:config-changed",e.breakout)),e.connectionStatus!==t.connectionStatus&&(this.connectionStatusSubscribers.forEach(t=>t(e.connectionStatus)),this.emit("connection:status-changed",e.connectionStatus)),e.liveStream!==t.liveStream&&(this.liveStreamSubscribers.forEach(t=>t(e.liveStream)),"streaming"===(null===(r=e.liveStream)||void 0===r?void 0:r.status)?this.emit("streaming:started",e.liveStream):this.emit("streaming:stopped")),e.localScreenshareStatus!==t.localScreenshareStatus&&(this.localScreenshareStatusSubscribers.forEach(t=>t(e.localScreenshareStatus)),this.emit("local-screenshare:status-changed",e.localScreenshareStatus)),e.localParticipant!==t.localParticipant&&(this.localParticipantSubscribers.forEach(t=>t(e.localParticipant)),this.emit("local-participant:changed",e.localParticipant)),e.remoteParticipants!==t.remoteParticipants&&(this.remoteParticipantsSubscribers.forEach(t=>t(e.remoteParticipants)),this.emit("remote-participants:changed",e.remoteParticipants)),e.screenshares!==t.screenshares){this.screenshareSubscribers.forEach(t=>t(e.screenshares));const r=e.screenshares.filter(e=>!t.screenshares.some(t=>t.id===e.id)),n=t.screenshares.filter(t=>!e.screenshares.some(e=>e.id===t.id));r.forEach(e=>{this.emit("screenshare:started",e)}),n.forEach(e=>{this.emit("screenshare:stopped",e.id)})}if(e.waitingParticipants!==t.waitingParticipants){this.waitingParticipantsSubscribers.forEach(t=>t(e.waitingParticipants));const r=e.waitingParticipants.filter(e=>!t.waitingParticipants.some(t=>t.id===e.id)),n=t.waitingParticipants.filter(t=>!e.waitingParticipants.some(e=>e.id===t.id));r.forEach(e=>{this.emit("waiting-participant:joined",e)}),n.forEach(e=>{this.emit("waiting-participant:left",e.id)})}if(e.spotlightedParticipants!==t.spotlightedParticipants){this.spotlightedParticipantsSubscribers.forEach(t=>t(e.spotlightedParticipants));const r=e.spotlightedParticipants.filter(e=>!t.spotlightedParticipants.some(t=>t.id===e.id)),n=t.spotlightedParticipants.filter(t=>!e.spotlightedParticipants.some(e=>e.id===t.id));r.forEach(e=>{this.emit("spotlight:participant-added",e)}),n.forEach(e=>{this.emit("spotlight:participant-removed",e.id)})}}registerAppListeners(){Eb({actionCreator:Ub.roomJoined,effect:({payload:e})=>{if("error"in e)return void this.emit("room:joined:error",e.error);const{selfId:t}=e;this.selfId=t,this.emit("room:joined",{isLocked:e.room.isLocked,selfId:t})}}),Eb({actionCreator:Ub.chatMessage,effect:({payload:e})=>{this.emit("chat:new-message",e)}})}subscribeToChatMessages(e){return this.chatMessageSubscribers.add(e),()=>this.chatMessageSubscribers.delete(e)}subscribeToCloudRecording(e){return this.cloudRecordingSubscribers.add(e),()=>this.cloudRecordingSubscribers.delete(e)}subscribeToBreakoutConfig(e){return this.breakoutSubscribers.add(e),()=>this.breakoutSubscribers.delete(e)}subscribeToConnectionStatus(e){return this.connectionStatusSubscribers.add(e),()=>this.connectionStatusSubscribers.delete(e)}subscribeToLiveStream(e){return this.liveStreamSubscribers.add(e),()=>this.liveStreamSubscribers.delete(e)}subscribeToLocalScreenshareStatus(e){return this.localScreenshareStatusSubscribers.add(e),()=>this.localScreenshareStatusSubscribers.delete(e)}subscribeToLocalParticipant(e){return this.localParticipantSubscribers.add(e),()=>this.localParticipantSubscribers.delete(e)}subscribeToRemoteParticipants(e){return this.remoteParticipantsSubscribers.add(e),()=>this.remoteParticipantsSubscribers.delete(e)}subscribeToScreenshares(e){return this.screenshareSubscribers.add(e),()=>this.screenshareSubscribers.delete(e)}subscribeToWaitingParticipants(e){return this.waitingParticipantsSubscribers.add(e),()=>this.waitingParticipantsSubscribers.delete(e)}subscribeToSpotlightedParticipants(e){return this.spotlightedParticipantsSubscribers.add(e),()=>this.spotlightedParticipantsSubscribers.delete(e)}getState(){return FS(this.store.getState())}getNotificationsEventEmitter(){return lS(this.store.getState())}initialize(e){this.options=e}joinRoom(){return oy(this,void 0,void 0,function*(){const{roomUrl:e}=this.options;if(!e)throw new Error("Room URL is required to join a room.");const t={localMediaOptions:this.options.localMediaOptions||void 0,displayName:this.options.displayName||"Guest",roomKey:this.options.roomKey||null,externalId:this.options.externalId||null,sdkVersion:`core:${xb}`,roomUrl:e,assistantKey:this.options.assistantKey||null,isNodeSdk:this.options.isNodeSdk||!1};let r,n;this.store.dispatch(Mb(t));const i=new Promise((e,t)=>{r=e,n=t}),s=this.store.dispatch(zv({actionCreator:Ub.roomJoined,effect:({payload:e})=>{s(),"error"in e?null==n||n(e.error):null==r||r(e)}}));return i})}sendChatMessage(e){this.store.dispatch(k_({text:e}))}knock(){this.store.dispatch(gS())}leaveRoom(){this.store.dispatch(Db()),this.selfId=null}setDisplayName(e){this.store.dispatch(eS({displayName:e}))}toggleCamera(e){this.store.dispatch(Iy({enabled:e}))}toggleMicrophone(e){this.store.dispatch(Dy({enabled:e}))}toggleLowDataMode(e){this.store.dispatch(My({enabled:e}))}toggleRaiseHand(e){this.store.dispatch(iS({enabled:e}))}askToSpeak(e){this.store.dispatch(G_({clientIds:[e],enable:!0}))}askToTurnOnCamera(e){this.store.dispatch(q_({clientIds:[e],enable:!0}))}acceptWaitingParticipant(e){this.store.dispatch(ES({participantId:e}))}rejectWaitingParticipant(e){this.store.dispatch(OS({participantId:e}))}startCloudRecording(){this.store.dispatch(R_())}stopCloudRecording(){this.store.dispatch(E_())}startScreenshare(){this.store.dispatch(Y_())}stopScreenshare(){this.store.dispatch(X_())}lockRoom(e){this.store.dispatch(nw({locked:e}))}muteParticipants(e){this.store.dispatch(G_({clientIds:e,enable:!1}))}turnOffParticipantCameras(e){this.store.dispatch(q_({clientIds:e,enable:!1}))}spotlightParticipant(e){this.store.dispatch(gw({id:e}))}removeSpotlight(e){this.store.dispatch(vw({id:e}))}kickParticipant(e){this.store.dispatch(iw({clientId:e}))}endMeeting(e=!1){this.store.dispatch(sw({stayBehind:e}))}joinBreakoutGroup(e){this.store.dispatch(v_({group:e}))}joinBreakoutMainRoom(){this.store.dispatch(v_({group:""}))}reportStreamResolution(e,t,r){this.store.dispatch(jw({streamId:e,width:t,height:r}))}destroy(){super.destroy(),this.store.dispatch(Db()),this.removeAllListeners(),this.selfId=null,this.chatMessageSubscribers.clear(),this.cloudRecordingSubscribers.clear(),this.breakoutSubscribers.clear(),this.connectionStatusSubscribers.clear(),this.liveStreamSubscribers.clear(),this.localScreenshareStatusSubscribers.clear(),this.localParticipantSubscribers.clear(),this.remoteParticipantsSubscribers.clear(),this.screenshareSubscribers.clear(),this.waitingParticipantsSubscribers.clear(),this.spotlightedParticipantsSubscribers.clear()}}class zS{constructor(){this.services=function(){const e=vb.create({baseUrl:Tb}),t=new sb({fetchDeviceCredentials:e.getCredentials.bind(e),baseUrl:Tb}),r=new Cb({apiClient:t});return{credentialsService:e,apiClient:t,organizationService:r,fetchOrganizationFromRoomUrl:e=>{const t=ql({host:new URL(e).host});return new kb({organizationService:r,subdomain:t.subdomain}).fetchOrganization()}}}(),this.store=(({preloadedState:e,injectServices:t})=>Qg({devTools:!1,reducer:IS,middleware:e=>e({thunk:{extraArgument:{services:t}},serializableCheck:!1}).prepend(Rb.middleware),preloadedState:e}))({injectServices:this.services}),this.localMediaClient=new NS(this.store),this.roomConnectionClient=new BS(this.store),this.gridClient=new jS(this.store)}getLocalMedia(){return this.localMediaClient}getRoomConnection(){return this.roomConnectionClient}getGrid(){return this.gridClient}getStore(){return this.store}destroy(){this.localMediaClient.destroy(),this.roomConnectionClient.destroy(),this.gridClient.destroy()}}const US=s.createContext(null);var VS=function(){return VS=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},VS.apply(this,arguments)};function $S(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}"function"==typeof SuppressedError&&SuppressedError;const GS=({stream:e,muted:t})=>{var r,n;const i=s.useRef(null),o=null===(r=s.useContext(US))||void 0===r?void 0:r.getLocalMedia(),[a,c]=s.useState(null!==(n=null==o?void 0:o.getState().currentSpeakerDeviceId)&&void 0!==n?n:"default"),d=s.useCallback(e=>{c(e)},[]);return s.useEffect(()=>(null==o||o.addListener(LS,d),()=>{null==o||o.removeListener(LS,d)}),[o]),s.useEffect(()=>{i.current&&!t&&e&&a&&(i.current.srcObject!==e&&(i.current.srcObject=e),i.current.setSinkId&&i.current.setSinkId(a))},[e,i,a,t]),i},qS=s.forwardRef((e,t)=>{var r,{muted:n,mirror:i=!1,stream:o,onVideoResize:a}=e,c=$S(e,["muted","mirror","stream","onVideoResize"]);const d=null===(r=s.useContext(US))||void 0===r?void 0:r.getRoomConnection(),l=s.useRef(null),u=GS({muted:n,stream:o});return s.useImperativeHandle(t,()=>Object.assign(l.current,{captureAspectRatio:()=>{if(!l.current)return null;const e=l.current.videoHeight,t=l.current.videoWidth;return t&&e&&t+e>20?t/e:null}})),s.useEffect(()=>{if(!l.current)return;const e=new ResizeObserver(Pb(()=>{if(l.current&&(null==o?void 0:o.id)){const e=l.current.clientWidth,t=l.current.clientHeight;null==d||d.reportStreamResolution(o.id,e,t),a&&a({width:e,height:t,stream:o})}},{delay:1e3,edges:!0}));return e.observe(l.current),()=>{e.disconnect()}},[o]),s.useEffect(()=>{l.current&&(l.current.srcObject!==o&&(l.current.srcObject=o),l.current.muted!==n&&(l.current.muted=Boolean(n)))},[n,o,l]),s.createElement(s.Fragment,null,s.createElement("video",Object.assign({ref:l,autoPlay:!0,playsInline:!0},c,{style:Object.assign({transform:i?"scaleX(-1)":"none",width:"100%",height:"100%"},c.style)})),s.createElement("audio",{ref:u,autoPlay:!0,playsInline:!0}))});qS.displayName="VideoView";const HS={chatMessages:[],cloudRecording:void 0,breakout:{isActive:!1,currentGroup:null,groupedParticipants:[],participantsInCurrentGroup:[]},localParticipant:void 0,remoteParticipants:[],screenshares:[],connectionStatus:"ready",waitingParticipants:[],spotlightedParticipants:[]},WS={localMediaOptions:{audio:!0,video:!0}};const JS={cameraDeviceError:null,isStarting:!1,isSettingCameraDevice:!1,isSettingMicrophoneDevice:!1,microphoneDeviceError:null,startError:null,cameraDevices:[],microphoneDevices:[],speakerDevices:[]};var KS={TABLET_BREAKPOINT:750,BOTTOM_TOOLBAR_HEIGHT:82,VIDEO_CONTROLS_MIN_WIDTH:420,SUBGRID_EMPTY_STAGE_MAX_WIDTH:800};function QS({top:e=0,left:t=0}={}){return{top:e,left:t}}function YS({width:e=0,height:t=0}={}){return{width:Math.max(e,0),height:Math.max(t,0)}}function XS({top:e=0,left:t=0,width:r=0,height:n=0}={}){return{bounds:YS({width:r,height:n}),origin:QS({top:e,left:t})}}function ZS({top:e=0,left:t=0,bottom:r=0,right:n=0}={}){return{top:e,left:t,bottom:r,right:n}}function eC(e){return!!e&&!(e.width<=0||e.height<=0)}function tC(e,t){const{width:r,height:n}=t,i=n,s=i*e,o=Math.min(r/s,n/i);return{width:s*o,height:i*o}}const rC=({vertical:e,width:t,height:r,count:n,aspectRatio:i})=>{const s=[1,2,3].map(s=>(({width:e,height:t,rows:r,cols:n,aspectRatio:i})=>{const s=tC(i,{width:e/n,height:t/r});return Math.round(s.width*s.height)})({width:t,height:r,rows:e?Math.ceil(n/s):s,cols:e?s:Math.ceil(n/s),aspectRatio:i})),o=Math.max(...s);return{splits:s.indexOf(o)+1,weight:o}};function nC({count:e,width:t,height:r,aspectRatio:n}){if(e<=1)return{rows:1,cols:1};const{splits:i,vertical:s}=(({width:e,height:t,count:r,aspectRatio:n})=>{const i=rC({vertical:!0,width:e,height:t,count:r,aspectRatio:n}),s=rC({vertical:!1,width:e,height:t,count:r,aspectRatio:n});return i.weight>s.weight?{splits:i.splits,vertical:!0}:{splits:s.splits,vertical:!1}})({width:t,height:r,count:e,aspectRatio:n});return s?{rows:Math.ceil(e/i),cols:i}:{rows:i,cols:Math.ceil(e/i)}}function iC(e){var{aspectRatio:t,children:r,className:n,height:i,style:o,width:a,withRoundedCorners:c=!1,withShadow:d=!0}=e,l=$S(e,["aspectRatio","children","className","height","style","width","withRoundedCorners","withShadow"]);let u=a,p=i,h=0,f=0;t&&(({width:u,height:p}=tC(t,{width:a,height:i})),h=(a-u)/2,f=(i-p)/2);const m=Object.assign({width:`${Math.round(u)}px`,height:`${Math.round(p)}px`},h||f?{transform:`translate3d(${Math.round(h)}px, ${Math.round(f)}px, 0)`}:{});return s.createElement("div",{className:n,style:Object.assign({position:"absolute",top:0,left:0},o)},s.createElement("div",Object.assign({style:m},l),s.cloneElement(r,{contentWidth:u,contentHeight:p,withRoundedCorners:c,withShadow:d})))}function sC({origin:e,bounds:t}){return{top:Math.round(e.top),left:Math.round(e.left),height:Math.round(t.height),width:Math.round(t.width)}}function oC({cell:e,child:t,clientId:r,style:n={},withRoundedCorners:i=!1,withShadow:o=!1}){const a=!eC(e.bounds);return s.createElement(iC,{width:e.bounds.width,height:e.bounds.height,aspectRatio:e.aspectRatio,style:a?{width:0,height:0}:n,withRoundedCorners:i,withShadow:o,key:r},t)}function aC({containerFrame:e,debug:t=!1,featureRoundedCornersOff:r=!1,floatingContent:n,gridContent:i=[],isConstrained:o=!1,layoutOverflowBackdropFrame:a=XS(),layoutVideoStage:c,presentationGridContent:d=[],subgridContent:l=[]}){const u=!r&&!o,p=[];return i.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:n,withShadow:i}){var o;const a=(null===(o=r.videoGrid)||void 0===o?void 0:o.cells)||[],c=e.map((e,o)=>{var c,d;if(!r.videoGrid)return null;const l=a[o],u={top:r.videoGrid.origin.top+r.videoGrid.paddings.top+l.origin.top,left:r.videoGrid.origin.left+r.videoGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return oC({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`video-${o}`}),clientId:h||`video-${o}`,withRoundedCorners:n,style:p,withShadow:i})});return c}({content:i,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),d.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:n,withShadow:i}){var o;const a=(null===(o=r.presentationGrid)||void 0===o?void 0:o.cells)||[];return e.map((e,o)=>{var c,d;if(!r.presentationGrid)return null;const l=a[o],u={top:r.presentationGrid.origin.top+r.presentationGrid.paddings.top+l.origin.top,left:r.presentationGrid.origin.left+r.presentationGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return oC({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`presentation-${o}`}),clientId:h||`presentation-${o}`,style:p,withRoundedCorners:n,withShadow:i})})}({content:d,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),n&&p.push(function({content:e,containerFrame:t,stageLayout:r,withRoundedCorners:n}){var i;if(!r.floatingContent)return null;const o=r.floatingContent,a=o.origin.top,c=o.origin.left,d={width:Math.round(o.bounds.width),height:Math.round(o.bounds.height),transform:`translate3d(${Math.round(t.origin.left+c)}px, ${Math.round(t.origin.top+a)}px, 0)`,position:"fixed",top:o.bounds.height/2,left:0,zIndex:40},l=(null===(i=e.props.client)||void 0===i?void 0:i.id)||"floating";return oC({cell:o,child:s.cloneElement(e,{isSmallCell:o.isSmallCell,isZoomedByDefault:!1,canZoom:!1,key:l,isDraggable:!1}),clientId:l,style:d,withRoundedCorners:n,withShadow:!1})}({content:n,containerFrame:e,stageLayout:c,withRoundedCorners:!r})),l.length&&p.push(...function({content:e,stageLayout:t,withRoundedCorners:r,withShadow:n}){const i=t.subgrid.cells;return e.map((e,o)=>{var a,c,d,l;const u=i[o],p={height:Math.round(u.bounds.height),width:Math.round(u.bounds.width),transform:""},h={top:t.subgrid.origin.top+u.origin.top,left:t.subgrid.origin.left+u.origin.left};p.transform=`translate3d(${Math.round(h.left)}px, ${Math.round(h.top)}px, 0)`;const f=null===(c=null===(a=null==e?void 0:e.props)||void 0===a?void 0:a.participant)||void 0===c?void 0:c.id,m=(null===(d=u.paddings)||void 0===d?void 0:d.left)||0,g=(null===(l=u.paddings)||void 0===l?void 0:l.right)||0;return oC({cell:u,child:s.cloneElement(e,{avatarSize:u.bounds.width-m-g,canZoom:!1,cellPaddings:u.paddings,isSmallCell:u.isSmallCell,isZoomedByDefault:!1,key:f||`subgrid-${o}`,style:p}),clientId:f||`subgrid-${o}`,style:p,withRoundedCorners:r,withShadow:n})})}({content:l,stageLayout:c,withRoundedCorners:!r,withShadow:!0})),s.createElement("div",{key:"video-stage-layout",style:{width:"100%",height:"100%",position:"relative"}},eC(a.bounds)&&s.createElement("div",{style:sC(a)}),p,t&&s.createElement(s.Fragment,null))}const cC=16/9,dC=4/3,lC=({value:e,min:t,max:r})=>Math.min(Math.max(e,t),r);function uC({choices:e=[]}){const t=Math.min(...e),r=Math.max(...e);let n=null;if(t===r)n=t;else{const t=function(...e){return new Set(e).size!==e.length}(e)?(i=e).sort((e,t)=>i.filter(t=>t===e).length-i.filter(e=>e===t).length).pop():r;n=lC({value:t||r,min:dC,max:cC})}var i;return{minAr:t,maxAr:r,chosenAr:n}}const pC="rows",hC="columns";function fC({layoutGrid:e,dim:t,secDim:r,index:n,count:i,gridGap:s}){const o=(t-s*(i-1))*(e.fractions?e.fractions[n]:1/i),a=e.lines[n];return[o,(r-s*(a-1))/a]}function mC({isHorizontal:e,layoutGrid:t,width:r,height:n,gridGap:i}){const s=[],o=0,a=0,c={x:0,y:0},d=t.lines.length,l=e?n:r,u=e?r:n;for(let r=0;r<d;r++){const n=fC({layoutGrid:t,dim:l,secDim:u,index:r,count:d,gridGap:i}),p={width:e?n[1]:n[0],height:e?n[0]:n[1]},h=t.lines[r];for(let t=0;t<h;t++)s.push({origin:Object.assign({},c),bounds:p}),e?c.x+=p.width+i:c.y+=p.height+i;e?(c.y+=p.height+i,c.x=o):(c.x+=p.width+i,c.y=a)}return s}function gC({layoutGrid:e,width:t,height:r,gridGap:n}){switch(e.type){case pC:return function({layoutGrid:e,width:t,height:r,gridGap:n}){return mC({isHorizontal:!0,layoutGrid:e,width:t,height:r,gridGap:n})}({layoutGrid:e,width:t,height:r,gridGap:n});case hC:return function({layoutGrid:e,width:t,height:r,gridGap:n}){return mC({isHorizontal:!1,layoutGrid:e,width:t,height:r,gridGap:n})}({layoutGrid:e,width:t,height:r,gridGap:n})}}function vC({width:e,height:t,cellCount:r,gridGap:n=0,paddings:i=ZS()}){const s=e-(i.left+i.right),o=t-(i.top+i.bottom),a=Math.round(s/o*10)/10<=1?function(e){return{1:{type:pC,lines:[1]},2:{type:pC,lines:[1,1]},3:{type:pC,lines:[2,1]},4:{type:pC,lines:[2,2]},5:{type:pC,lines:[2,2,1]},6:{type:pC,lines:[2,2,2]},7:{type:pC,lines:[3,2,2]},8:{type:pC,lines:[2,2,2,2]},9:{type:pC,lines:[3,2,2,2]},10:{type:pC,lines:[3,3,2,2]},11:{type:pC,lines:[3,3,3,2]},12:{type:pC,lines:[3,3,3,3]},13:{type:pC,lines:[2,2,3,3,3]},14:{type:pC,lines:[2,3,3,3,3]},15:{type:pC,lines:[3,3,3,3,3]},16:{type:pC,lines:[2,2,3,3,3,3]},17:{type:pC,lines:[2,3,3,3,3,3]},18:{type:pC,lines:[3,3,3,3,3,3]},19:{type:pC,lines:[2,2,3,3,3,3,3]},20:{type:pC,lines:[2,3,3,3,3,3,3]},21:{type:pC,lines:[3,3,3,3,3,3,3]},22:{type:pC,lines:[2,2,3,3,3,3,3,3]},23:{type:pC,lines:[2,3,3,3,3,3,3,3]},24:{type:pC,lines:[3,3,3,3,3,3,3,3]}}[e]||{type:pC,lines:[3,3,3,3,3,3,3,3]}}(r):function(e){return{1:{type:hC,lines:[1]},2:{type:hC,lines:[1,1]},3:{type:hC,lines:[2,1]},4:{type:hC,lines:[2,2]},5:{type:pC,lines:[3,2],fractions:[.45,.55]},6:{type:hC,lines:[2,2,2]},7:{type:pC,lines:[4,3],fractions:[.45,.55]},8:{type:hC,lines:[2,2,2,2]},9:{type:hC,lines:[3,2,2,2]},10:{type:hC,lines:[3,3,2,2]},11:{type:hC,lines:[3,3,3,2]},12:{type:hC,lines:[3,3,3,3]},13:{type:hC,lines:[4,3,3,3]},14:{type:hC,lines:[4,4,3,3]},15:{type:hC,lines:[3,3,3,3,3]},16:{type:hC,lines:[4,3,3,3,3]},17:{type:hC,lines:[4,4,3,3,3]},18:{type:hC,lines:[4,4,4,3,3]},19:{type:hC,lines:[4,4,4,4,3]},20:{type:hC,lines:[4,4,4,4,4]},21:{type:hC,lines:[5,4,4,4,4]},22:{type:hC,lines:[5,5,4,4,4]},23:{type:hC,lines:[5,5,5,4,4]},24:{type:hC,lines:[5,5,5,5,4]}}[e]||{type:hC,lines:[5,5,5,5,5]}}(r);return{cellRects:gC({layoutGrid:a,width:s,height:o,gridGap:n})||[],cellCount:r,gridGap:n,extraHorizontalPadding:0,extraVerticalPadding:0,paddings:i}}function bC({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:n,paddings:i=ZS()}){let s=0,o=0,a=0,c=0,d=0,l=0;const u=e.width-i.left-i.right,p=e.height-i.top-i.bottom;return r&&(t?(c=Math.floor(u/n.width),a=Math.ceil(r/c),s=u,o=a*n.height,d=(u-c*n.width)/2):(a=Math.floor(p/n.height),c=Math.ceil(r/a),s=c*n.width,o=p,l=(p-a*n.height)/2)),{isPortrait:t,width:s+i.left+i.right,height:o+i.top+i.bottom,cellBounds:n,cellCount:r,rows:a,cols:c,extraHorizontalPadding:d,extraVerticalPadding:l,paddings:i}}const{BOTTOM_TOOLBAR_HEIGHT:yC,VIDEO_CONTROLS_MIN_WIDTH:_C,TABLET_BREAKPOINT:wC,SUBGRID_EMPTY_STAGE_MAX_WIDTH:SC}=KS,CC=ZS({top:4,bottom:28,left:8,right:8});function kC({hasOverflow:e,hasStage:t}){return e&&t?[80]:[80,60]}function TC({cellCount:e}){const t=e<=6;return YS({width:t?250:300,height:t?150:200})}function PC({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}){const o=function({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}){let o;for(let a=0;a<n.length;a++){const c=n[a];if(o=bC({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:YS({width:c+i.left+i.right,height:c+i.top+i.bottom}),paddings:s}),o.width<=e.width&&o.height<=e.height)return o}return o}({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}),a=o.cellBounds.width-i.left-i.right===n[n.length-1],c=YS({width:Math.min(o.width,e.width),height:Math.min(o.height,e.height)}),d=YS({width:o.width,height:o.height});return 0===r?{bounds:c,contentBounds:d,videoCells:[]}:{bounds:c,contentBounds:d,videoCells:[...Array(r)].map((e,t)=>{const{top:r,left:n,width:s,height:c}=function({index:e,layout:t}){const{isPortrait:r,rows:n,cols:i,cellCount:s,cellBounds:o,extraHorizontalPadding:a,extraVerticalPadding:c,paddings:d}=t,l=r?Math.floor(e/i):Math.floor(e%n),u=r?Math.floor(e%i):Math.floor(e/n),p=function({index:e,isPortrait:t,rows:r,cols:n,cellBounds:i,cellCount:s}){const o=r*n,a=o-s;if(!a)return 0;const c=o-a-1;return e<c-((t?n:r)-a)+1||e>c?0:a*(t?i.width:i.height)/2}({index:e,isPortrait:r,rows:n,cols:i,cellBounds:o,cellCount:s});return{top:d.top+c+l*o.height+(r?0:p),left:d.left+a+u*o.width+(r?p:0),width:o.width,height:o.height}}({index:t,layout:o});return{origin:QS({top:r,left:n}),bounds:YS({width:s,height:c}),paddings:i,isSmallCell:a}})}}function RC({cellPaddings:e,cellSizeOptions:t,containerBounds:r,containerOrigin:n,gridGap:i,hasConstrainedOverflow:s,hasPresentationContent:o,hasVideoContent:a,isConstrained:c,isMaximizeMode:d,isPortrait:l,isSmallScreen:u,maxGridWidth:p,shouldOverflowSubgrid:h,subgridVideos:f}){const{width:m,height:g}=r,v=o||a,b=f.length>0;if(!b&&!v)return{isPortrait:l,videosContainer:XS(),subgrid:Object.assign(Object.assign({},XS()),{contentBounds:YS(),cells:[]}),hasOverflow:!1};if(!b)return{isPortrait:l,videosContainer:XS(Object.assign(Object.assign({},r),n)),subgrid:Object.assign(Object.assign({},XS()),{contentBounds:YS(),cells:[]}),hasOverflow:s};const y=h?20:0;let _=null;if(v)if(h){const n=t[0];let i=d?yC:yC+e.top+(c||u?n/2:n)+e.bottom;r.height-i<200&&(i=0),_=YS({width:r.width,height:i})}else _=YS(d?{width:r.width,height:t[0]+e.top+e.bottom}:l?{width:r.width,height:r.height/2}:{width:r.width/2,height:r.height});else _=YS({width:Math.min(SC,r.width),height:r.height});let w=0;_.width>p&&(w=(_.width-p)/2);const S=PC({containerBounds:_,isPortrait:l,cellCount:f.length,cellSizeOptions:t,cellPaddings:e,paddings:ZS({top:y,left:w,right:w})}),C=YS({width:S.contentBounds.width-_.width,height:S.contentBounds.height-_.height}),k=C.width>0||C.height>0;let T,P=null;P=!v||h||k?S.contentBounds:S.bounds;let R=P;v?(R=YS(h?{width:0,height:_.height+y+i}:l?{width:0,height:S.bounds.height+i}:{width:S.bounds.width+i,height:0}),T=function({bounds:e,fromBounds:t}){return{width:Math.max(t.width-e.width,0),height:Math.max(t.height-e.height,0)}}({bounds:R,fromBounds:r})):T=YS();const E=Object.assign({},n);let O;return O=QS(v?{top:l?Math.max(n.top+g-R.height+i,0):n.top,left:l?n.left:Math.max(n.left+m-P.width,0)}:{top:n.top+Math.max(0,(g-P.height)/2),left:n.left+Math.max(0,(m-P.width)/2)}),{isPortrait:l,videosContainer:XS(Object.assign(Object.assign({},T),E)),subgrid:Object.assign(Object.assign({},XS(Object.assign(Object.assign({},P),O))),{cells:S.videoCells.map((e,t)=>{var r,n;return Object.assign({aspectRatio:(null===(r=f[t])||void 0===r?void 0:r.aspectRatio)||1,type:"video",clientId:null===(n=f[t])||void 0===n?void 0:n.clientId},e)}),contentBounds:S.contentBounds}),hasOverflow:k||h||s,overflowNeedBounds:h?YS():C}}function EC({containerBounds:e,containerOrigin:t,gridGap:r,supersizedContentAspectRatio:n,hasPresentationContent:i,hasPresentationGrid:s,hasVideoContent:o,minGridBounds:a}){const{width:c,height:d}=e;let l=c<=d,u=YS(),p=QS(),h=o?Object.assign({},e):YS(),f=o?Object.assign({},t):QS();if(i){const i=function({bounds:e,aspectRatio:t,minGridContainerBounds:r,hasPresentationGrid:n}){const{width:i,height:s}=e;if(!(r.width>0))return{isPortrait:i<=s,supersizedContentBounds:e};const o=Math.round(i/2),a=Math.round(s/2),c=Math.max(i-r.width,0),d=Math.max(s-r.height,0);let l=c<=d,u=0,p=0;{const e=tC(t,{width:c,height:s}),r=tC(t,{width:i,height:d});if(l=t<=1?r.height>e.height:r.width>e.width,l){const e=d-Math.max(r.height,a);p=Math.max(e,0)}else{const t=c-Math.max(e.width,o);u=Math.max(t,0)}}return{isPortrait:l,supersizedContentBounds:{width:l?i:c-u,height:l?d-p:s}}}({bounds:e,aspectRatio:n,minGridContainerBounds:YS({width:o?a.width+r:0,height:o?a.height+r:0}),hasPresentationGrid:s});l=i.isPortrait,u=i.supersizedContentBounds,p=Object.assign({},t),o&&(h=YS({width:l?e.width:e.width-u.width-r,height:l?e.height-u.height-r:e.height}),f=QS({top:l?t.top+u.height+r:t.top,left:l?t.left:t.left+u.width+r}))}return{isPortrait:l,presentationGrid:Object.assign({},XS(Object.assign(Object.assign({},u),p))),videoGrid:XS(Object.assign(Object.assign({},h),f))}}function OC({containerBounds:e,paddings:t=ZS(),videos:r,isConstrained:n,maxGridWidth:i,gridGap:s}){const{width:o,height:a}=e,c=i?Math.min(o,i):o,d=r.length;let l=null,u=null;if(n){const e=vC({width:o,height:a,cellCount:d,gridGap:s,paddings:t}),n=d>4;u=r.map((t,r)=>{const i=function({index:e,layout:t}){const{cellRects:r}=t,n=r[e]||XS();return{top:n.origin.y,left:n.origin.x,width:n.bounds.width,height:n.bounds.height}}({index:r,layout:e});return{clientId:t.clientId,isDraggable:t.isDraggable,origin:QS({top:i.top,left:i.left}),bounds:YS({width:i.width,height:i.height}),aspectRatio:i.width/i.height,isSmallCell:n,type:"video"}}),l=e}else{const e=r.map(e=>e.aspectRatio||1),i=TC({cellCount:d}),o=function({width:e,height:t,cellCount:r,gridGap:n,cellAspectRatios:i=[dC],paddings:s=ZS()}){if(!r)return{cellCount:r,cellHeight:0,cellWidth:0,cols:0,rows:0,extraHorizontalPadding:0,extraVerticalPadding:0,gridGap:n,paddings:s};const o=e-(s.left+s.right),a=t-(s.top+s.bottom),c=uC({choices:i});let d=c.chosenAr;const{rows:l,cols:u}=nC({count:r,width:o,height:a,aspectRatio:d});1===l?d=lC({value:o/u/a,min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}):1===u&&(d=lC({value:o/(a/l),min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}));const{cellWidth:p,cellHeight:h,extraHorizontalPadding:f,extraVerticalPadding:m}=function({width:e,height:t,rows:r,cols:n,gridGap:i,aspectRatio:s}){const o=(e-(n-1)*i)/n,a=(t-(r-1)*i)/r,c=o/a;let d=0,l=0;return s<c?d=o-a*s:s>c&&(l=a-o/s),{cellWidth:o-d,cellHeight:a-l,extraHorizontalPadding:d*n/2,extraVerticalPadding:l*r/2}}({width:o,height:a,rows:l,cols:u,gridGap:n,aspectRatio:d});return{cellCount:r,cellHeight:h,cellWidth:p,cols:u,rows:l,extraHorizontalPadding:f,extraVerticalPadding:m,gridGap:n,paddings:s}}({width:c,height:a,cellCount:d,gridGap:s,cellAspectRatios:e,paddings:t});u=r.map((e,t)=>{const r=function({index:e,layout:t}){const{cellWidth:r,cellHeight:n,rows:i,cols:s,cellCount:o,gridGap:a}=t,c=Math.floor(e/s),d=Math.floor(e%s),l=function({rows:e,cols:t,cellWidth:r,index:n,cellCount:i,gridGap:s}){const o=e*t,a=o-i;if(!a)return 0;const c=o-a-1;return n>=c-(t-a)+1&&n<=c?a*r/2+s:0}({rows:i,cols:s,cellWidth:r,index:e,cellCount:o,gridGap:a});return{top:c*n+c*a,left:d*r+d*a+l,width:r,height:n}}({index:t,layout:o}),s=o.cellWidth<i.width,a=n||s?o.cellWidth/o.cellHeight:e.aspectRatio||1;return{clientId:e.clientId,isDraggable:e.isDraggable,origin:QS({top:r.top,left:r.left}),bounds:YS({width:r.width,height:r.height}),aspectRatio:a,isSmallCell:s,type:"video"}}),l=o}return{videoCells:u,extraHorizontalPadding:o!==c?l.extraHorizontalPadding+(o-c)/2:l.extraHorizontalPadding,extraVerticalPadding:l.extraVerticalPadding,paddings:l.paddings,gridGap:s}}function xC({a:e,b:t,gridGap:r,isPortrait:n}){const i=n?e.vertical:e.horizontal,s=n?t.vertical:t.horizontal;if(i===s)return{a:0,b:0};const o=i<s?e:t,a=n?o.vertical:o.horizontal,c=(r+(i+s)+a)/2-a;return{a:o===e?c:0,b:o===t?c:0}}function IC({gridGap:e,isConstrained:t,presentationVideos:r,videos:n,videosContainerLayout:i,gridLayoutPaddings:s=ZS(),presentationGridLayoutPaddings:o=ZS(),maxGridWidth:a}){return{gridLayout:OC({containerBounds:i.videoGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:s,videos:n}),presentationGridLayout:OC({containerBounds:i.presentationGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:o,videos:r})}}function DC({floatingVideo:e,frame:t,gridGap:r,isConstrained:n,isMaximizeMode:i=!1,isXLMeetingSize:s=!1,paddings:o=ZS(),presentationVideos:a=[],rebalanceLayout:c=!1,roomBounds:d,roomLayoutHasOverlow:l=!1,subgridCellPaddings:u=CC,subgridVideos:p=[],videoControlsHeight:h=0,videos:f=[],videoGridGap:m}){let g=s&&(!screen||screen.width<=2048);const v=!!a.length,b=a.length>1,y=v&&!b?a[0].aspectRatio:null,_=!!f.length,w=t.bounds.width-o.left-o.right;let S=t.bounds.height-o.top-o.bottom;const C=Math.max(2200,.8*w),k=n&&f.length>12,T=S/4,P=Math.ceil((f.length-12)/3);S=k?S+T*P:S;const R=YS({width:w,height:S}),E=QS({top:o.top,left:o.left}),O=TC({cellCount:f.length}),x=d.width<wC||d.height<wC,I=i||g||!(v||_)||R.width<=R.height,D={cellPaddings:u,containerBounds:R,containerOrigin:E,gridGap:r,hasPresentationContent:v,hasVideoContent:_,isConstrained:n,isMaximizeMode:i,isSmallScreen:x,subgridVideos:p,maxGridWidth:C};let M=RC(Object.assign(Object.assign({},D),{cellSizeOptions:kC({hasOverflow:g,hasStage:v||_}),isPortrait:I,shouldOverflowSubgrid:g,hasConstrainedOverflow:k})),j=!1;if(!g&&l&&!M.hasOverflow){RC(Object.assign(Object.assign({},D),{containerBounds:YS({width:R.width,height:R.height-yC}),cellSizeOptions:kC({hasOverflow:g,hasStage:v||_}),isPortrait:I,shouldOverflowSubgrid:g,hasConstrainedOverflow:k})).hasOverflow&&(j=!0)}(j||M.hasOverflow&&!g)&&(g=!0,M=RC(Object.assign(Object.assign({},D),{cellSizeOptions:kC({hasOverflow:!0,hasStage:v||_}),isPortrait:!0,shouldOverflowSubgrid:g,hasConstrainedOverflow:k})));const A=EC({containerBounds:M.videosContainer.bounds,containerOrigin:M.videosContainer.origin,gridGap:r,supersizedContentAspectRatio:y||1,hasPresentationContent:v,hasPresentationGrid:b,hasVideoContent:_,minGridBounds:O});let{gridLayout:L,presentationGridLayout:N}=IC({gridGap:m||r,isConstrained:n,presentationVideos:a,videos:f,videosContainerLayout:A,maxGridWidth:C});if(M.hasOverflow&&!g){const{vPaddings:e,hPaddings:t}=function({need:e,stageLayout:t,gridLayout:r,presentationGridLayout:n,videosContainerLayout:i}){let s={presentationGrid:0,grid:0},o={presentationGrid:0,grid:0};if(t.isPortrait){const t=Math.min(r.extraVerticalPadding,n.extraVerticalPadding);s={presentationGrid:Math.min(i.isPortrait?n.extraVerticalPadding:t,e.height),grid:Math.min(i.isPortrait?r.extraVerticalPadding:t,e.height)}}else{const t=Math.min(r.extraHorizontalPadding,n.extraHorizontalPadding);o={presentationGrid:Math.min(i.isPortrait?t:n.extraHorizontalPadding,e.width),grid:Math.min(i.isPortrait?t:r.extraHorizontalPadding,e.width)}}return{vPaddings:s,hPaddings:o}}({need:M.overflowNeedBounds||YS(),stageLayout:M,gridLayout:L,presentationGridLayout:N,videosContainerLayout:A});(e.presentationGrid||e.grid||t.presentationGrid||t.grid)&&(!function({vPaddings:e,hPaddings:t,stageLayout:r,videosContainerLayout:n}){if(r.isPortrait&&(e.presentationGrid||e.grid)){const t=n.isPortrait?2*e.presentationGrid+2*e.grid:e.presentationGrid+e.grid;r.videosContainer.bounds.height-=t,r.subgrid.origin.top-=t,r.subgrid.bounds.height+=t,n.presentationGrid.bounds.height-=2*e.presentationGrid,n.videoGrid.bounds.height-=2*e.grid,n.isPortrait&&(n.videoGrid.origin.top-=e.presentationGrid)}if(!r.isPortrait&&(t.presentationGrid||t.grid)){const e=n.isPortrait?t.presentationGrid+t.grid:2*t.presentationGrid+2*t.grid;r.videosContainer.bounds.width-=e,r.subgrid.origin.left-=e,r.subgrid.bounds.width+=e,n.presentationGrid.bounds.width-=2*t.presentationGrid,n.videoGrid.bounds.width-=2*t.grid,n.isPortrait||(n.videoGrid.origin.left-=t.grid)}}({vPaddings:e,hPaddings:t,stageLayout:M,videosContainerLayout:A}),({gridLayout:L,presentationGridLayout:N}=IC({gridGap:m||r,isConstrained:n,presentationVideos:a,videos:f,videosContainerLayout:A,maxGridWidth:C})))}const F=function({roomBounds:e,containerFrame:t,floatingVideo:r,videoControlsHeight:n,margin:i=8}){if(!r)return null;const s=tC(r.aspectRatio||0,{width:200,height:200}),o=!(e.height-t.bounds.height-t.origin.top),a=t.bounds.width-2*(s.width+i)<_C;let c=0;o&&a?c=-1*n:o||a||(c=n);const d=QS({top:t.origin.top+(t.bounds.height-s.height-i)+c,left:t.origin.left+(t.bounds.width-s.width-i)});return{clientId:r.clientId,isDraggable:r.isDraggable,origin:d,bounds:s,aspectRatio:r.aspectRatio,isSmallCell:!0}}({roomBounds:d,containerFrame:t,floatingVideo:e||null,videoControlsHeight:h});c&&function({videosContainerLayout:e,gridLayout:t,presentationGridLayout:r,stageLayout:n,gridGap:i,shouldOverflowSubgrid:s}){const o=e.presentationGrid.bounds.width>0,a=e.videoGrid.bounds.width>0,c=n.subgrid.bounds.width>0,d={vertical:0,horizontal:0};if(o&&a){const n=xC({a:{horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},b:{horizontal:t.extraHorizontalPadding,vertical:t.extraVerticalPadding},gridGap:i,isPortrait:e.isPortrait});e.isPortrait?(e.presentationGrid.origin.top+=n.a,e.videoGrid.origin.top-=n.b,d.vertical=n.b):(e.presentationGrid.origin.left+=n.a,e.videoGrid.origin.left-=n.b,d.horizontal=n.b)}if(c&&(o||a)&&!s){const s={horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},c={horizontal:t.extraHorizontalPadding+d.horizontal,vertical:t.extraVerticalPadding+d.vertical};let l;const u=o&&a;l=u&&e.isPortrait&&!n.isPortrait?s.horizontal<c.horizontal?s:c:u&&!e.isPortrait&&n.isPortrait?s.vertical<c.vertical?s:c:a?c:s;const p=xC({a:l,b:{horizontal:0,vertical:0},gridGap:i,isPortrait:n.isPortrait});n.isPortrait?n.subgrid.origin.top-=p.b:n.subgrid.origin.left-=p.b}}({videosContainerLayout:A,gridLayout:L,presentationGridLayout:N,stageLayout:M,gridGap:r,shouldOverflowSubgrid:g});let B=o.top+M.videosContainer.bounds.height+M.subgrid.bounds.height+o.bottom;return(v||_)&&(B+=r),{isPortrait:M.isPortrait,hasOverflow:M.hasOverflow,videosContainer:Object.assign(Object.assign({},A),{bounds:YS({width:M.videosContainer.bounds.width,height:M.videosContainer.bounds.height}),origin:QS({top:M.videosContainer.origin.top,left:M.videosContainer.origin.left})}),bounds:YS({height:g?B:t.bounds.height,width:t.bounds.width}),gridGap:r,presentationGrid:Object.assign(Object.assign({},A.presentationGrid),{cells:N.videoCells,paddings:ZS({top:N.paddings.top+N.extraVerticalPadding,bottom:N.paddings.bottom+N.extraVerticalPadding,left:N.paddings.left+N.extraHorizontalPadding,right:N.paddings.right+N.extraHorizontalPadding})}),videoGrid:Object.assign(Object.assign({},A.videoGrid),{cells:L.videoCells,paddings:ZS({top:L.paddings.top+L.extraVerticalPadding,bottom:L.paddings.bottom+L.extraVerticalPadding,left:L.paddings.left+L.extraHorizontalPadding,right:L.paddings.right+L.extraHorizontalPadding})}),subgrid:M.subgrid,floatingContent:Object.assign(Object.assign(Object.assign({},F),e),{origin:(null==F?void 0:F.origin)||QS(),bounds:(null==F?void 0:F.bounds)||YS(),aspectRatio:(null==e?void 0:e.aspectRatio)||1})}}function MC({aspectRatio:e,avatarSize:t,cellPaddings:r,client:n,isDraggable:i=!0,isPlaceholder:s=!1,isSubgrid:o=!1}){return{aspectRatio:e||16/9,avatarSize:t,cellPaddings:r,client:n,clientId:(null==n?void 0:n.id)||"",isDraggable:i,isPlaceholder:s,isSubgrid:o,type:"video"}}function jC({activeVideosSubgridTrigger:e=12,stageParticipantLimit:t=12,forceSubgrid:r=!0,enableSubgrid:n=!0,maximizedParticipant:i,floatingParticipant:o,isConstrained:a=!1}={}){var c;const[d,l]=s.useState({allClientViews:[],spotlightedParticipants:[],numParticipants:0}),u=null===(c=s.useContext(US))||void 0===c?void 0:c.getGrid();if(!u)throw new Error("useGridParticipants must be used within a WherebyProvider");const p=s.useCallback(e=>{l(t=>Object.assign(Object.assign({},t),{allClientViews:e}))},[l]),h=s.useCallback(e=>{l(t=>Object.assign(Object.assign({},t),{spotlightedParticipants:e}))},[l]),f=s.useCallback(e=>{l(t=>Object.assign(Object.assign({},t),{numParticipants:e}))},[l]);s.useEffect(()=>{const e=u.subscribeClientViews(p),t=u.subscribeSpotlightedParticipants(h),r=u.subscribeNumberOfClientViews(f);return()=>{e(),t(),r()}},[u]);const m=s.useMemo(()=>d.allClientViews,[d.allClientViews]),g=s.useMemo(()=>d.spotlightedParticipants,[d.spotlightedParticipants]),v=s.useMemo(()=>d.numParticipants,[d.numParticipants]),b=s.useMemo(()=>o,[o]),y=s.useMemo(()=>b?m.filter(e=>e.id!==b.id):m,[m,b]),_=s.useMemo(()=>!!n&&(!!r||v>t),[r,v,t,n]),w=s.useMemo(()=>function({clientViews:e,activeVideosSubgridTrigger:t,shouldShowSubgrid:r,spotlightedParticipants:n,maximizedParticipant:i,isPhoneResolution:s}){if(!r)return[];const o=n.length>0,a=(i?e.filter(e=>e.id!==i.id):e).filter(e=>!e.isPresentation&&!n.includes(e)),c=a.filter(e=>!e.isVideoEnabled),d=a.filter(e=>e.isVideoEnabled).length>t,l=a.filter(e=>!c.includes(e)&&e.isAudioEnabled),u=a.filter(e=>!c.includes(e)&&!e.isAudioEnabled);if(c.length&&o)return[...u,...c];if(s&&a.length>24){const e=[...l,...u],t=e.slice(0,24);return t.length<=24?[...e.filter(e=>!t.includes(e)),...c]:[...u,...c]}if(d&&u.length){const e=[...l,...u].slice(0,t);return e.length<=t?[...u.filter(t=>!e.includes(t)),...c]:[...u,...c]}return c}({clientViews:y,activeVideosSubgridTrigger:e,shouldShowSubgrid:_,spotlightedParticipants:g,maximizedParticipant:i,isPhoneResolution:a}),[y,_,e,g,a]),S=s.useMemo(()=>y.filter(e=>!w.includes(e)),[y,w]),C=s.useMemo(()=>i?[i]:g,[g,i]),k=s.useMemo(()=>S.filter(e=>!C.includes(e)),[S,C]);return{floatingClientView:b,clientViewsInGrid:k,clientViewsInPresentationGrid:C,clientViewsInSubgrid:w,spotlightedParticipants:g}}var AC={exports:{}};const LC=55296,NC=127995,FC=127999,BC=[776,2359,2359,2367,2367,2984,3007,3021,3633,3635,3648,3657,4352,4449,4520];function zC(e){if("string"!=typeof e)throw new Error("string cannot be undefined or null");const t=[];let r=0,n=0;for(;r<e.length;)n+=UC(r+n,e),qC(e[r+n])&&n++,$C(e[r+n])&&n++,GC(e[r+n])&&n++,HC(e[r+n])?n++:(t.push(e.substring(r,r+n)),r+=n,n=0);return t}function UC(e,t){const r=t[e];if(!function(e){return e&&JC(e[0].charCodeAt(0),LC,56319)}(r)||e===t.length-1)return 1;const n=r+t[e+1];let i=t.substring(e+2,e+5);return VC(n)&&VC(i)||function(e){return JC(WC(e),NC,FC)}(i)?4:2}function VC(e){return JC(WC(e),127462,127487)}function $C(e){return"string"==typeof e&&JC(e.charCodeAt(0),65024,65039)}function GC(e){return"string"==typeof e&&JC(e.charCodeAt(0),8400,8447)}function qC(e){return"string"==typeof e&&-1!==BC.indexOf(e.charCodeAt(0))}function HC(e){return"string"==typeof e&&8205===e.charCodeAt(0)}function WC(e){return(e.charCodeAt(0)-LC<<10)+(e.charCodeAt(1)-56320)+65536}function JC(e,t,r){return e>=t&&e<=r}AC.exports=zC,AC.exports.substr=function(e,t,r){const n=zC(e);if(void 0===t)return e;if(t>=n.length)return"";const i=n.length-t;let s=t+(void 0===r?i:r);return s>t+i&&(s=void 0),n.slice(t,s).join("")};var KC=c(AC.exports);const QC=({name:e})=>{const t=((e="")=>{if(e=e.trim())return e.split(/-| /).map(e=>KC(e)[0]).slice(0,3);return[]})(e),r=[0,56,48,40][t.length]||32,n=t.join("").toUpperCase();return s.createElement("svg",{viewBox:"-60 -60 120 120","aria-hidden":"true",style:{height:"100%",pointerEvents:"none",width:"100%"}},s.createElement("text",{x:0,y:0,textAnchor:"middle",dominantBaseline:"central",fontSize:r},n))};function YC(e){var{avatarUrl:t,className:r,size:n=40,name:i,variant:o="round"}=e,a=$S(e,["avatarUrl","className","size","name","variant"]);return s.createElement("div",Object.assign({style:{height:`${n}px`,width:`${n}px`,userSelect:"none",overflow:"hidden",borderRadius:"round"===o?"50%":"4px",backgroundColor:"#f8e3c8"},className:r,title:i},a),!t&&i?s.createElement(QC,{name:i}):s.createElement("img",{src:t||"",alt:"",style:{height:"100%",width:"100%",objectFit:"cover",maxWidth:"initial"}}))}function XC({avatarUrl:e,displayName:t,isSmallCell:r,withRoundedCorners:n,stream:i,muted:o}){const a=GS({stream:i,muted:o});return s.createElement(s.Fragment,null,s.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",position:"absolute",top:0,left:0,height:"100%",width:"100%",borderRadius:n?"8px":"0"}},s.createElement("div",{style:{height:r?60:80,width:r?60:80,pointerEvents:"none",position:"relative"}},s.createElement(YC,{variant:"square",avatarUrl:e,name:t,size:r?60:80}))),s.createElement("audio",{ref:a,autoPlay:!0,playsInline:!0}))}function ZC(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(e?.(n),!1===r||!n.defaultPrevented)return t?.(n)}}function ek(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function tk(...e){return t=>{let r=!1;const n=e.map(e=>{const n=ek(e,t);return r||"function"!=typeof n||(r=!0),n});if(r)return()=>{for(let t=0;t<n.length;t++){const r=n[t];"function"==typeof r?r():ek(e[t],null)}}}}function rk(...e){return s.useCallback(tk(...e),e)}var nk,ik={exports:{}},sk={};ik.exports=(nk||(nk=1,function(){function e(t){if(null==t)return null;if("function"==typeof t)return t.$$typeof===k?null:t.displayName||t.name||null;if("string"==typeof t)return t;switch(t){case h:return"Fragment";case m:return"Profiler";case f:return"StrictMode";case y:return"Suspense";case _:return"SuspenseList";case C:return"Activity"}if("object"==typeof t)switch("number"==typeof t.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case p:return"Portal";case v:return(t.displayName||"Context")+".Provider";case g:return(t._context.displayName||"Context")+".Consumer";case b:var r=t.render;return(t=t.displayName)||(t=""!==(t=r.displayName||r.name||"")?"ForwardRef("+t+")":"ForwardRef"),t;case w:return null!==(r=t.displayName||null)?r:e(t.type)||"Memo";case S:r=t._payload,t=t._init;try{return e(t(r))}catch(e){}}return null}function r(e){return""+e}function n(e){try{r(e);var t=!1}catch(e){t=!0}if(t){var n=(t=console).error,i="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return n.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",i),r(e)}}function i(t){if(t===h)return"<>";if("object"==typeof t&&null!==t&&t.$$typeof===S)return"<...>";try{var r=e(t);return r?"<"+r+">":"<...>"}catch(e){return"<...>"}}function s(){return Error("react-stack-top-frame")}function o(){var t=e(this.type);return O[t]||(O[t]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(t=this.props.ref)?t:null}function a(t,r,i,s,a,l,p,h){var f,m=r.children;if(void 0!==m)if(s)if(R(m)){for(s=0;s<m.length;s++)c(m[s]);Object.freeze&&Object.freeze(m)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else c(m);if(P.call(r,"key")){m=e(t);var g=Object.keys(r).filter(function(e){return"key"!==e});s=0<g.length?"{key: someKey, "+g.join(": ..., ")+": ...}":"{key: someKey}",D[m+s]||(g=0<g.length?"{"+g.join(": ..., ")+": ...}":"{}",console.error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',s,m,g,m),D[m+s]=!0)}if(m=null,void 0!==i&&(n(i),m=""+i),function(e){if(P.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(r)&&(n(r.key),m=""+r.key),"key"in r)for(var v in i={},r)"key"!==v&&(i[v]=r[v]);else i=r;return m&&function(e,t){function r(){d||(d=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}(i,"function"==typeof t?t.displayName||t.name||"Unknown":t),function(e,t,r,n,i,s,a,c){return r=s.ref,e={$$typeof:u,type:e,key:t,props:s,_owner:i},null!==(void 0!==r?r:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:o}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:a}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:c}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}(t,m,l,0,null===(f=T.A)?null:f.getOwner(),i,p,h)}function c(e){"object"==typeof e&&null!==e&&e.$$typeof===u&&e._store&&(e._store.validated=1)}var d,l=t,u=Symbol.for("react.transitional.element"),p=Symbol.for("react.portal"),h=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),m=Symbol.for("react.profiler"),g=Symbol.for("react.consumer"),v=Symbol.for("react.context"),b=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),_=Symbol.for("react.suspense_list"),w=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),C=Symbol.for("react.activity"),k=Symbol.for("react.client.reference"),T=l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,P=Object.prototype.hasOwnProperty,R=Array.isArray,E=console.createTask?console.createTask:function(){return null},O={},x=(l={"react-stack-bottom-frame":function(e){return e()}})["react-stack-bottom-frame"].bind(l,s)(),I=E(i(s)),D={};sk.Fragment=h,sk.jsx=function(e,t,r,n,s){var o=1e4>T.recentlyCreatedOwnerStacks++;return a(e,t,r,!1,0,s,o?Error("react-stack-top-frame"):x,o?E(i(e)):I)},sk.jsxs=function(e,t,r,n,s){var o=1e4>T.recentlyCreatedOwnerStacks++;return a(e,t,r,!0,0,s,o?Error("react-stack-top-frame"):x,o?E(i(e)):I)}}()),sk);var ok=ik.exports;function ak(e,t=[]){let r=[];const n=()=>{const t=r.map(e=>s.createContext(e));return function(r){const n=r?.[e]||t;return s.useMemo(()=>({[`__scope${e}`]:{...r,[e]:n}}),[r,n])}};return n.scopeName=e,[function(t,n){const i=s.createContext(n),o=r.length;r=[...r,n];const a=t=>{const{scope:r,children:n,...a}=t,c=r?.[e]?.[o]||i,d=s.useMemo(()=>a,Object.values(a));return ok.jsx(c.Provider,{value:d,children:n})};return a.displayName=t+"Provider",[a,function(r,a){const c=a?.[e]?.[o]||i,d=s.useContext(c);if(d)return d;if(void 0!==n)return n;throw new Error(`\`${r}\` must be used within \`${t}\``)}]},ck(n,...t)]}function ck(...e){const t=e[0];if(1===e.length)return t;const r=()=>{const r=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const n=r.reduce((t,{useScope:r,scopeName:n})=>({...t,...r(e)[`__scope${n}`]}),{});return s.useMemo(()=>({[`__scope${t.scopeName}`]:n}),[n])}};return r.scopeName=t.scopeName,r}function dk(e){const t=lk(e),r=s.forwardRef((e,r)=>{const{children:n,...i}=e,o=s.Children.toArray(n),a=o.find(pk);if(a){const e=a.props.children,n=o.map(t=>t===a?s.Children.count(e)>1?s.Children.only(null):s.isValidElement(e)?e.props.children:null:t);return ok.jsx(t,{...i,ref:r,children:s.isValidElement(e)?s.cloneElement(e,void 0,n):null})}return ok.jsx(t,{...i,ref:r,children:n})});return r.displayName=`${e}.Slot`,r}function lk(e){const t=s.forwardRef((e,t)=>{const{children:r,...n}=e;if(s.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),i=function(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{const t=s(...e);return i(...e),t}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}(n,r.props);return r.type!==s.Fragment&&(i.ref=t?tk(t,e):e),s.cloneElement(r,i)}return s.Children.count(r)>1?s.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var uk=Symbol("radix.slottable");function pk(e){return s.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===uk}var hk=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=dk(`Primitive.${t}`),n=s.forwardRef((e,n)=>{const{asChild:i,...s}=e,o=i?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),ok.jsx(o,{...s,ref:n})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function fk(e){const t=s.useRef(e);return s.useEffect(()=>{t.current=e}),s.useMemo(()=>(...e)=>t.current?.(...e),[])}var mk,gk="dismissableLayer.update",vk="dismissableLayer.pointerDownOutside",bk="dismissableLayer.focusOutside",yk=s.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),_k=s.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:a,onDismiss:c,...d}=e,l=s.useContext(yk),[u,p]=s.useState(null),h=u?.ownerDocument??globalThis?.document,[,f]=s.useState({}),m=rk(t,e=>p(e)),g=Array.from(l.layers),[v]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),b=g.indexOf(v),y=u?g.indexOf(u):-1,_=l.layersWithOutsidePointerEventsDisabled.size>0,w=y>=b,S=function(e,t=globalThis?.document){const r=fk(e),n=s.useRef(!1),i=s.useRef(()=>{});return s.useEffect(()=>{const e=e=>{if(e.target&&!n.current){let n=function(){Sk(vk,r,s,{discrete:!0})};const s={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",i.current),i.current=n,t.addEventListener("click",i.current,{once:!0})):n()}else t.removeEventListener("click",i.current);n.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",e),t.removeEventListener("click",i.current)}},[t,r]),{onPointerDownCapture:()=>n.current=!0}}(e=>{const t=e.target,r=[...l.branches].some(e=>e.contains(t));w&&!r&&(i?.(e),a?.(e),e.defaultPrevented||c?.())},h),C=function(e,t=globalThis?.document){const r=fk(e),n=s.useRef(!1);return s.useEffect(()=>{const e=e=>{if(e.target&&!n.current){Sk(bk,r,{originalEvent:e},{discrete:!1})}};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}(e=>{const t=e.target;[...l.branches].some(e=>e.contains(t))||(o?.(e),a?.(e),e.defaultPrevented||c?.())},h);return function(e,t=globalThis?.document){const r=fk(e);s.useEffect(()=>{const e=e=>{"Escape"===e.key&&r(e)};return t.addEventListener("keydown",e,{capture:!0}),()=>t.removeEventListener("keydown",e,{capture:!0})},[r,t])}(e=>{y===l.layers.size-1&&(n?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))},h),s.useEffect(()=>{if(u)return r&&(0===l.layersWithOutsidePointerEventsDisabled.size&&(mk=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(u)),l.layers.add(u),wk(),()=>{r&&1===l.layersWithOutsidePointerEventsDisabled.size&&(h.body.style.pointerEvents=mk)}},[u,h,r,l]),s.useEffect(()=>()=>{u&&(l.layers.delete(u),l.layersWithOutsidePointerEventsDisabled.delete(u),wk())},[u,l]),s.useEffect(()=>{const e=()=>f({});return document.addEventListener(gk,e),()=>document.removeEventListener(gk,e)},[]),ok.jsx(hk.div,{...d,ref:m,style:{pointerEvents:_?w?"auto":"none":void 0,...e.style},onFocusCapture:ZC(e.onFocusCapture,C.onFocusCapture),onBlurCapture:ZC(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:ZC(e.onPointerDownCapture,S.onPointerDownCapture)})});_k.displayName="DismissableLayer";function wk(){const e=new CustomEvent(gk);document.dispatchEvent(e)}function Sk(e,t,r,{discrete:n}){const i=r.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&i.addEventListener(e,t,{once:!0}),n?function(e,t){e&&o.flushSync(()=>e.dispatchEvent(t))}(i,s):i.dispatchEvent(s)}s.forwardRef((e,t)=>{const r=s.useContext(yk),n=s.useRef(null),i=rk(t,n);return s.useEffect(()=>{const e=n.current;if(e)return r.branches.add(e),()=>{r.branches.delete(e)}},[r.branches]),ok.jsx(hk.div,{...e,ref:i})}).displayName="DismissableLayerBranch";var Ck=0;function kk(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Tk="focusScope.autoFocusOnMount",Pk="focusScope.autoFocusOnUnmount",Rk={bubbles:!1,cancelable:!0},Ek=s.forwardRef((e,t)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...a}=e,[c,d]=s.useState(null),l=fk(i),u=fk(o),p=s.useRef(null),h=rk(t,e=>d(e)),f=s.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;s.useEffect(()=>{if(n){let e=function(e){if(f.paused||!c)return;const t=e.target;c.contains(t)?p.current=t:Dk(p.current,{select:!0})},t=function(e){if(f.paused||!c)return;const t=e.relatedTarget;null!==t&&(c.contains(t)||Dk(p.current,{select:!0}))},r=function(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&Dk(c)};document.addEventListener("focusin",e),document.addEventListener("focusout",t);const n=new MutationObserver(r);return c&&n.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),n.disconnect()}}},[n,c,f.paused]),s.useEffect(()=>{if(c){Mk.add(f);const t=document.activeElement;if(!c.contains(t)){const r=new CustomEvent(Tk,Rk);c.addEventListener(Tk,l),c.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const n of e)if(Dk(n,{select:t}),document.activeElement!==r)return}((e=Ok(c),e.filter(e=>"A"!==e.tagName)),{select:!0}),document.activeElement===t&&Dk(c))}return()=>{c.removeEventListener(Tk,l),setTimeout(()=>{const e=new CustomEvent(Pk,Rk);c.addEventListener(Pk,u),c.dispatchEvent(e),e.defaultPrevented||Dk(t??document.body,{select:!0}),c.removeEventListener(Pk,u),Mk.remove(f)},0)}}var e},[c,l,u,f]);const m=s.useCallback(e=>{if(!r&&!n)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){const t=e.currentTarget,[n,s]=function(e){const t=Ok(e),r=xk(t,e),n=xk(t.reverse(),e);return[r,n]}(t);n&&s?e.shiftKey||i!==s?e.shiftKey&&i===n&&(e.preventDefault(),r&&Dk(s,{select:!0})):(e.preventDefault(),r&&Dk(n,{select:!0})):i===t&&e.preventDefault()}},[r,n,f.paused]);return ok.jsx(hk.div,{tabIndex:-1,...a,ref:h,onKeyDown:m})});function Ok(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{const t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function xk(e,t){for(const r of e)if(!Ik(r,{upTo:t}))return r}function Ik(e,{upTo:t}){if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==t&&e===t)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function Dk(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&function(e){return e instanceof HTMLInputElement&&"select"in e}(e)&&t&&e.select()}}Ek.displayName="FocusScope";var Mk=function(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=jk(e,t),e.unshift(t)},remove(t){e=jk(e,t),e[0]?.resume()}}}();function jk(e,t){const r=[...e],n=r.indexOf(t);return-1!==n&&r.splice(n,1),r}var Ak=globalThis?.document?s.useLayoutEffect:()=>{},Lk=s[" useId ".trim().toString()]||(()=>{}),Nk=0;function Fk(e){const[t,r]=s.useState(Lk());return Ak(()=>{r(e=>e??String(Nk++))},[e]),e||(t?`radix-${t}`:"")}const Bk=["top","right","bottom","left"],zk=Math.min,Uk=Math.max,Vk=Math.round,$k=Math.floor,Gk=e=>({x:e,y:e}),qk={left:"right",right:"left",bottom:"top",top:"bottom"},Hk={start:"end",end:"start"};function Wk(e,t,r){return Uk(e,zk(t,r))}function Jk(e,t){return"function"==typeof e?e(t):e}function Kk(e){return e.split("-")[0]}function Qk(e){return e.split("-")[1]}function Yk(e){return"x"===e?"y":"x"}function Xk(e){return"y"===e?"height":"width"}const Zk=new Set(["top","bottom"]);function eT(e){return Zk.has(Kk(e))?"y":"x"}function tT(e){return Yk(eT(e))}function rT(e){return e.replace(/start|end/g,e=>Hk[e])}const nT=["left","right"],iT=["right","left"],sT=["top","bottom"],oT=["bottom","top"];function aT(e,t,r,n){const i=Qk(e);let s=function(e,t,r){switch(e){case"top":case"bottom":return r?t?iT:nT:t?nT:iT;case"left":case"right":return t?sT:oT;default:return[]}}(Kk(e),"start"===r,n);return i&&(s=s.map(e=>e+"-"+i),t&&(s=s.concat(s.map(rT)))),s}function cT(e){return e.replace(/left|right|bottom|top/g,e=>qk[e])}function dT(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function lT(e){const{x:t,y:r,width:n,height:i}=e;return{width:n,height:i,top:r,left:t,right:t+n,bottom:r+i,x:t,y:r}}function uT(e,t,r){let{reference:n,floating:i}=e;const s=eT(t),o=tT(t),a=Xk(o),c=Kk(t),d="y"===s,l=n.x+n.width/2-i.width/2,u=n.y+n.height/2-i.height/2,p=n[a]/2-i[a]/2;let h;switch(c){case"top":h={x:l,y:n.y-i.height};break;case"bottom":h={x:l,y:n.y+n.height};break;case"right":h={x:n.x+n.width,y:u};break;case"left":h={x:n.x-i.width,y:u};break;default:h={x:n.x,y:n.y}}switch(Qk(t)){case"start":h[o]-=p*(r&&d?-1:1);break;case"end":h[o]+=p*(r&&d?-1:1)}return h}async function pT(e,t){var r;void 0===t&&(t={});const{x:n,y:i,platform:s,rects:o,elements:a,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:l="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=Jk(t,e),f=dT(h),m=a[p?"floating"===u?"reference":"floating":u],g=lT(await s.getClippingRect({element:null==(r=await(null==s.isElement?void 0:s.isElement(m)))||r?m:m.contextElement||await(null==s.getDocumentElement?void 0:s.getDocumentElement(a.floating)),boundary:d,rootBoundary:l,strategy:c})),v="floating"===u?{x:n,y:i,width:o.floating.width,height:o.floating.height}:o.reference,b=await(null==s.getOffsetParent?void 0:s.getOffsetParent(a.floating)),y=await(null==s.isElement?void 0:s.isElement(b))&&await(null==s.getScale?void 0:s.getScale(b))||{x:1,y:1},_=lT(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:b,strategy:c}):v);return{top:(g.top-_.top+f.top)/y.y,bottom:(_.bottom-g.bottom+f.bottom)/y.y,left:(g.left-_.left+f.left)/y.x,right:(_.right-g.right+f.right)/y.x}}function hT(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function fT(e){return Bk.some(t=>e[t]>=0)}const mT=new Set(["left","top"]);function gT(){return"undefined"!=typeof window}function vT(e){return _T(e)?(e.nodeName||"").toLowerCase():"#document"}function bT(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function yT(e){var t;return null==(t=(_T(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function _T(e){return!!gT()&&(e instanceof Node||e instanceof bT(e).Node)}function wT(e){return!!gT()&&(e instanceof Element||e instanceof bT(e).Element)}function ST(e){return!!gT()&&(e instanceof HTMLElement||e instanceof bT(e).HTMLElement)}function CT(e){return!(!gT()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof bT(e).ShadowRoot)}const kT=new Set(["inline","contents"]);function TT(e){const{overflow:t,overflowX:r,overflowY:n,display:i}=NT(e);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&!kT.has(i)}const PT=new Set(["table","td","th"]);function RT(e){return PT.has(vT(e))}const ET=[":popover-open",":modal"];function OT(e){return ET.some(t=>{try{return e.matches(t)}catch(e){return!1}})}const xT=["transform","translate","scale","rotate","perspective"],IT=["transform","translate","scale","rotate","perspective","filter"],DT=["paint","layout","strict","content"];function MT(e){const t=jT(),r=wT(e)?NT(e):e;return xT.some(e=>!!r[e]&&"none"!==r[e])||!!r.containerType&&"normal"!==r.containerType||!t&&!!r.backdropFilter&&"none"!==r.backdropFilter||!t&&!!r.filter&&"none"!==r.filter||IT.some(e=>(r.willChange||"").includes(e))||DT.some(e=>(r.contain||"").includes(e))}function jT(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const AT=new Set(["html","body","#document"]);function LT(e){return AT.has(vT(e))}function NT(e){return bT(e).getComputedStyle(e)}function FT(e){return wT(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function BT(e){if("html"===vT(e))return e;const t=e.assignedSlot||e.parentNode||CT(e)&&e.host||yT(e);return CT(t)?t.host:t}function zT(e){const t=BT(e);return LT(t)?e.ownerDocument?e.ownerDocument.body:e.body:ST(t)&&TT(t)?t:zT(t)}function UT(e,t,r){var n;void 0===t&&(t=[]),void 0===r&&(r=!0);const i=zT(e),s=i===(null==(n=e.ownerDocument)?void 0:n.body),o=bT(i);if(s){const e=VT(o);return t.concat(o,o.visualViewport||[],TT(i)?i:[],e&&r?UT(e):[])}return t.concat(i,UT(i,[],r))}function VT(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function $T(e){const t=NT(e);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const i=ST(e),s=i?e.offsetWidth:r,o=i?e.offsetHeight:n,a=Vk(r)!==s||Vk(n)!==o;return a&&(r=s,n=o),{width:r,height:n,$:a}}function GT(e){return wT(e)?e:e.contextElement}function qT(e){const t=GT(e);if(!ST(t))return Gk(1);const r=t.getBoundingClientRect(),{width:n,height:i,$:s}=$T(t);let o=(s?Vk(r.width):r.width)/n,a=(s?Vk(r.height):r.height)/i;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}const HT=Gk(0);function WT(e){const t=bT(e);return jT()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:HT}function JT(e,t,r,n){void 0===t&&(t=!1),void 0===r&&(r=!1);const i=e.getBoundingClientRect(),s=GT(e);let o=Gk(1);t&&(n?wT(n)&&(o=qT(n)):o=qT(e));const a=function(e,t,r){return void 0===t&&(t=!1),!(!r||t&&r!==bT(e))&&t}(s,r,n)?WT(s):Gk(0);let c=(i.left+a.x)/o.x,d=(i.top+a.y)/o.y,l=i.width/o.x,u=i.height/o.y;if(s){const e=bT(s),t=n&&wT(n)?bT(n):n;let r=e,i=VT(r);for(;i&&n&&t!==r;){const e=qT(i),t=i.getBoundingClientRect(),n=NT(i),s=t.left+(i.clientLeft+parseFloat(n.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(n.paddingTop))*e.y;c*=e.x,d*=e.y,l*=e.x,u*=e.y,c+=s,d+=o,r=bT(i),i=VT(r)}}return lT({width:l,height:u,x:c,y:d})}function KT(e,t){const r=FT(e).scrollLeft;return t?t.left+r:JT(yT(e)).left+r}function QT(e,t,r){void 0===r&&(r=!1);const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-(r?0:KT(e,n)),y:n.top+t.scrollTop}}const YT=new Set(["absolute","fixed"]);function XT(e,t,r){let n;if("viewport"===t)n=function(e,t){const r=bT(e),n=yT(e),i=r.visualViewport;let s=n.clientWidth,o=n.clientHeight,a=0,c=0;if(i){s=i.width,o=i.height;const e=jT();(!e||e&&"fixed"===t)&&(a=i.offsetLeft,c=i.offsetTop)}return{width:s,height:o,x:a,y:c}}(e,r);else if("document"===t)n=function(e){const t=yT(e),r=FT(e),n=e.ownerDocument.body,i=Uk(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),s=Uk(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let o=-r.scrollLeft+KT(e);const a=-r.scrollTop;return"rtl"===NT(n).direction&&(o+=Uk(t.clientWidth,n.clientWidth)-i),{width:i,height:s,x:o,y:a}}(yT(e));else if(wT(t))n=function(e,t){const r=JT(e,!0,"fixed"===t),n=r.top+e.clientTop,i=r.left+e.clientLeft,s=ST(e)?qT(e):Gk(1);return{width:e.clientWidth*s.x,height:e.clientHeight*s.y,x:i*s.x,y:n*s.y}}(t,r);else{const r=WT(e);n={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return lT(n)}function ZT(e,t){const r=BT(e);return!(r===t||!wT(r)||LT(r))&&("fixed"===NT(r).position||ZT(r,t))}function eP(e,t,r){const n=ST(t),i=yT(t),s="fixed"===r,o=JT(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=Gk(0);function d(){c.x=KT(i)}if(n||!n&&!s)if(("body"!==vT(t)||TT(i))&&(a=FT(t)),n){const e=JT(t,!0,s,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else i&&d();s&&!n&&i&&d();const l=!i||n||s?Gk(0):QT(i,a);return{x:o.left+a.scrollLeft-c.x-l.x,y:o.top+a.scrollTop-c.y-l.y,width:o.width,height:o.height}}function tP(e){return"static"===NT(e).position}function rP(e,t){if(!ST(e)||"fixed"===NT(e).position)return null;if(t)return t(e);let r=e.offsetParent;return yT(e)===r&&(r=r.ownerDocument.body),r}function nP(e,t){const r=bT(e);if(OT(e))return r;if(!ST(e)){let t=BT(e);for(;t&&!LT(t);){if(wT(t)&&!tP(t))return t;t=BT(t)}return r}let n=rP(e,t);for(;n&&RT(n)&&tP(n);)n=rP(n,t);return n&&LT(n)&&tP(n)&&!MT(n)?r:n||function(e){let t=BT(e);for(;ST(t)&&!LT(t);){if(MT(t))return t;if(OT(t))return null;t=BT(t)}return null}(e)||r}const iP={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:r,offsetParent:n,strategy:i}=e;const s="fixed"===i,o=yT(n),a=!!t&&OT(t.floating);if(n===o||a&&s)return r;let c={scrollLeft:0,scrollTop:0},d=Gk(1);const l=Gk(0),u=ST(n);if((u||!u&&!s)&&(("body"!==vT(n)||TT(o))&&(c=FT(n)),ST(n))){const e=JT(n);d=qT(n),l.x=e.x+n.clientLeft,l.y=e.y+n.clientTop}const p=!o||u||s?Gk(0):QT(o,c,!0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+l.x+p.x,y:r.y*d.y-c.scrollTop*d.y+l.y+p.y}},getDocumentElement:yT,getClippingRect:function(e){let{element:t,boundary:r,rootBoundary:n,strategy:i}=e;const s="clippingAncestors"===r?OT(t)?[]:function(e,t){const r=t.get(e);if(r)return r;let n=UT(e,[],!1).filter(e=>wT(e)&&"body"!==vT(e)),i=null;const s="fixed"===NT(e).position;let o=s?BT(e):e;for(;wT(o)&&!LT(o);){const t=NT(o),r=MT(o);r||"fixed"!==t.position||(i=null),(s?!r&&!i:!r&&"static"===t.position&&i&&YT.has(i.position)||TT(o)&&!r&&ZT(e,o))?n=n.filter(e=>e!==o):i=t,o=BT(o)}return t.set(e,n),n}(t,this._c):[].concat(r),o=[...s,n],a=o[0],c=o.reduce((e,r)=>{const n=XT(t,r,i);return e.top=Uk(n.top,e.top),e.right=zk(n.right,e.right),e.bottom=zk(n.bottom,e.bottom),e.left=Uk(n.left,e.left),e},XT(t,a,i));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:nP,getElementRects:async function(e){const t=this.getOffsetParent||nP,r=this.getDimensions,n=await r(e.floating);return{reference:eP(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:r}=$T(e);return{width:t,height:r}},getScale:qT,isElement:wT,isRTL:function(e){return"rtl"===NT(e).direction}};function sP(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function oP(e,t,r,n){void 0===n&&(n={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=n,d=GT(e),l=i||s?[...d?UT(d):[],...UT(t)]:[];l.forEach(e=>{i&&e.addEventListener("scroll",r,{passive:!0}),s&&e.addEventListener("resize",r)});const u=d&&a?function(e,t){let r,n=null;const i=yT(e);function s(){var e;clearTimeout(r),null==(e=n)||e.disconnect(),n=null}return function o(a,c){void 0===a&&(a=!1),void 0===c&&(c=1),s();const d=e.getBoundingClientRect(),{left:l,top:u,width:p,height:h}=d;if(a||t(),!p||!h)return;const f={rootMargin:-$k(u)+"px "+-$k(i.clientWidth-(l+p))+"px "+-$k(i.clientHeight-(u+h))+"px "+-$k(l)+"px",threshold:Uk(0,zk(1,c))||1};let m=!0;function g(t){const n=t[0].intersectionRatio;if(n!==c){if(!m)return o();n?o(!1,n):r=setTimeout(()=>{o(!1,1e-7)},1e3)}1!==n||sP(d,e.getBoundingClientRect())||o(),m=!1}try{n=new IntersectionObserver(g,{...f,root:i.ownerDocument})}catch(e){n=new IntersectionObserver(g,f)}n.observe(e)}(!0),s}(d,r):null;let p,h=-1,f=null;o&&(f=new ResizeObserver(e=>{let[n]=e;n&&n.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),r()}),d&&!c&&f.observe(d),f.observe(t));let m=c?JT(e):null;return c&&function t(){const n=JT(e);m&&!sP(m,n)&&r();m=n,p=requestAnimationFrame(t)}(),r(),()=>{var e;l.forEach(e=>{i&&e.removeEventListener("scroll",r),s&&e.removeEventListener("resize",r)}),null==u||u(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}const aP=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var r,n;const{x:i,y:s,placement:o,middlewareData:a}=t,c=await async function(e,t){const{placement:r,platform:n,elements:i}=e,s=await(null==n.isRTL?void 0:n.isRTL(i.floating)),o=Kk(r),a=Qk(r),c="y"===eT(r),d=mT.has(o)?-1:1,l=s&&c?-1:1,u=Jk(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*l,y:p*d}:{x:p*d,y:h*l}}(t,e);return o===(null==(r=a.offset)?void 0:r.placement)&&null!=(n=a.arrow)&&n.alignmentOffset?{}:{x:i+c.x,y:s+c.y,data:{...c,placement:o}}}}},cP=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:n,placement:i}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:r}=e;return{x:t,y:r}}},...c}=Jk(e,t),d={x:r,y:n},l=await pT(t,c),u=eT(Kk(i)),p=Yk(u);let h=d[p],f=d[u];if(s){const e="y"===p?"bottom":"right";h=Wk(h+l["y"===p?"top":"left"],h,h-l[e])}if(o){const e="y"===u?"bottom":"right";f=Wk(f+l["y"===u?"top":"left"],f,f-l[e])}const m=a.fn({...t,[p]:h,[u]:f});return{...m,data:{x:m.x-r,y:m.y-n,enabled:{[p]:s,[u]:o}}}}}},dP=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var r,n;const{placement:i,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:d}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...g}=Jk(e,t);if(null!=(r=s.arrow)&&r.alignmentOffset)return{};const v=Kk(i),b=eT(a),y=Kk(a)===a,_=await(null==c.isRTL?void 0:c.isRTL(d.floating)),w=p||(y||!m?[cT(a)]:function(e){const t=cT(e);return[rT(e),t,rT(t)]}(a)),S="none"!==f;!p&&S&&w.push(...aT(a,m,f,_));const C=[a,...w],k=await pT(t,g),T=[];let P=(null==(n=s.flip)?void 0:n.overflows)||[];if(l&&T.push(k[v]),u){const e=function(e,t,r){void 0===r&&(r=!1);const n=Qk(e),i=tT(e),s=Xk(i);let o="x"===i?n===(r?"end":"start")?"right":"left":"start"===n?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=cT(o)),[o,cT(o)]}(i,o,_);T.push(k[e[0]],k[e[1]])}if(P=[...P,{placement:i,overflows:T}],!T.every(e=>e<=0)){var R,E;const e=((null==(R=s.flip)?void 0:R.index)||0)+1,t=C[e];if(t){if(!("alignment"===u&&b!==eT(t))||P.every(e=>e.overflows[0]>0&&eT(e.placement)===b))return{data:{index:e,overflows:P},reset:{placement:t}}}let r=null==(E=P.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:E.placement;if(!r)switch(h){case"bestFit":{var O;const e=null==(O=P.filter(e=>{if(S){const t=eT(e.placement);return t===b||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:O[0];e&&(r=e);break}case"initialPlacement":r=a}if(i!==r)return{reset:{placement:r}}}return{}}}},lP=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){var r,n;const{placement:i,rects:s,platform:o,elements:a}=t,{apply:c=()=>{},...d}=Jk(e,t),l=await pT(t,d),u=Kk(i),p=Qk(i),h="y"===eT(i),{width:f,height:m}=s.floating;let g,v;"top"===u||"bottom"===u?(g=u,v=p===(await(null==o.isRTL?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(v=u,g="end"===p?"top":"bottom");const b=m-l.top-l.bottom,y=f-l.left-l.right,_=zk(m-l[g],b),w=zk(f-l[v],y),S=!t.middlewareData.shift;let C=_,k=w;if(null!=(r=t.middlewareData.shift)&&r.enabled.x&&(k=y),null!=(n=t.middlewareData.shift)&&n.enabled.y&&(C=b),S&&!p){const e=Uk(l.left,0),t=Uk(l.right,0),r=Uk(l.top,0),n=Uk(l.bottom,0);h?k=f-2*(0!==e||0!==t?e+t:Uk(l.left,l.right)):C=m-2*(0!==r||0!==n?r+n:Uk(l.top,l.bottom))}await c({...t,availableWidth:k,availableHeight:C});const T=await o.getDimensions(a.floating);return f!==T.width||m!==T.height?{reset:{rects:!0}}:{}}}},uP=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:n="referenceHidden",...i}=Jk(e,t);switch(n){case"referenceHidden":{const e=hT(await pT(t,{...i,elementContext:"reference"}),r.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:fT(e)}}}case"escaped":{const e=hT(await pT(t,{...i,altBoundary:!0}),r.floating);return{data:{escapedOffsets:e,escaped:fT(e)}}}default:return{}}}}},pP=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:n,placement:i,rects:s,platform:o,elements:a,middlewareData:c}=t,{element:d,padding:l=0}=Jk(e,t)||{};if(null==d)return{};const u=dT(l),p={x:r,y:n},h=tT(i),f=Xk(h),m=await o.getDimensions(d),g="y"===h,v=g?"top":"left",b=g?"bottom":"right",y=g?"clientHeight":"clientWidth",_=s.reference[f]+s.reference[h]-p[h]-s.floating[f],w=p[h]-s.reference[h],S=await(null==o.getOffsetParent?void 0:o.getOffsetParent(d));let C=S?S[y]:0;C&&await(null==o.isElement?void 0:o.isElement(S))||(C=a.floating[y]||s.floating[f]);const k=_/2-w/2,T=C/2-m[f]/2-1,P=zk(u[v],T),R=zk(u[b],T),E=P,O=C-m[f]-R,x=C/2-m[f]/2+k,I=Wk(E,x,O),D=!c.arrow&&null!=Qk(i)&&x!==I&&s.reference[f]/2-(x<E?P:R)-m[f]/2<0,M=D?x<E?x-E:x-O:0;return{[h]:p[h]+M,data:{[h]:I,centerOffset:x-I-M,...D&&{alignmentOffset:M}},reset:D}}}),hP=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:r,y:n,placement:i,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:c=!0,crossAxis:d=!0}=Jk(e,t),l={x:r,y:n},u=eT(i),p=Yk(u);let h=l[p],f=l[u];const m=Jk(a,t),g="number"==typeof m?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(c){const e="y"===p?"height":"width",t=s.reference[p]-s.floating[e]+g.mainAxis,r=s.reference[p]+s.reference[e]-g.mainAxis;h<t?h=t:h>r&&(h=r)}if(d){var v,b;const e="y"===p?"width":"height",t=mT.has(Kk(i)),r=s.reference[u]-s.floating[e]+(t&&(null==(v=o.offset)?void 0:v[u])||0)+(t?0:g.crossAxis),n=s.reference[u]+s.reference[e]+(t?0:(null==(b=o.offset)?void 0:b[u])||0)-(t?g.crossAxis:0);f<r?f=r:f>n&&(f=n)}return{[p]:h,[u]:f}}}},fP=(e,t,r)=>{const n=new Map,i={platform:iP,...r},s={...i.platform,_c:n};return(async(e,t,r)=>{const{placement:n="bottom",strategy:i="absolute",middleware:s=[],platform:o}=r,a=s.filter(Boolean),c=await(null==o.isRTL?void 0:o.isRTL(t));let d=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:l,y:u}=uT(d,n,c),p=n,h={},f=0;for(let r=0;r<a.length;r++){const{name:s,fn:m}=a[r],{x:g,y:v,data:b,reset:y}=await m({x:l,y:u,initialPlacement:n,placement:p,strategy:i,middlewareData:h,rects:d,platform:o,elements:{reference:e,floating:t}});l=null!=g?g:l,u=null!=v?v:u,h={...h,[s]:{...h[s],...b}},y&&f<=50&&(f++,"object"==typeof y&&(y.placement&&(p=y.placement),y.rects&&(d=!0===y.rects?await o.getElementRects({reference:e,floating:t,strategy:i}):y.rects),({x:l,y:u}=uT(d,p,c))),r=-1)}return{x:l,y:u,placement:p,strategy:i,middlewareData:h}})(e,t,{...i,platform:s})};var mP="undefined"!=typeof document?t.useLayoutEffect:function(){};function gP(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if("function"==typeof e&&e.toString()===t.toString())return!0;let r,n,i;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(n=r;0!==n--;)if(!gP(e[n],t[n]))return!1;return!0}if(i=Object.keys(e),r=i.length,r!==Object.keys(t).length)return!1;for(n=r;0!==n--;)if(!{}.hasOwnProperty.call(t,i[n]))return!1;for(n=r;0!==n--;){const r=i[n];if(("_owner"!==r||!e.$$typeof)&&!gP(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function vP(e){if("undefined"==typeof window)return 1;return(e.ownerDocument.defaultView||window).devicePixelRatio||1}function bP(e,t){const r=vP(e);return Math.round(t*r)/r}function yP(e){const t=s.useRef(e);return mP(()=>{t.current=e}),t}const _P=e=>({name:"arrow",options:e,fn(t){const{element:r,padding:n}="function"==typeof e?e(t):e;return r&&function(e){return{}.hasOwnProperty.call(e,"current")}(r)?null!=r.current?pP({element:r.current,padding:n}).fn(t):{}:r?pP({element:r,padding:n}).fn(t):{}}}),wP=(e,t)=>({...aP(e),options:[e,t]}),SP=(e,t)=>({...cP(e),options:[e,t]}),CP=(e,t)=>({...hP(e),options:[e,t]}),kP=(e,t)=>({...dP(e),options:[e,t]}),TP=(e,t)=>({...lP(e),options:[e,t]}),PP=(e,t)=>({...uP(e),options:[e,t]}),RP=(e,t)=>({..._P(e),options:[e,t]});var EP=s.forwardRef((e,t)=>{const{children:r,width:n=10,height:i=5,...s}=e;return ok.jsx(hk.svg,{...s,ref:t,width:n,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:ok.jsx("polygon",{points:"0,0 30,0 15,10"})})});EP.displayName="Arrow";var OP=EP;var xP="Popper",[IP,DP]=ak(xP),[MP,jP]=IP(xP),AP=e=>{const{__scopePopper:t,children:r}=e,[n,i]=s.useState(null);return ok.jsx(MP,{scope:t,anchor:n,onAnchorChange:i,children:r})};AP.displayName=xP;var LP="PopperAnchor",NP=s.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:n,...i}=e,o=jP(LP,r),a=s.useRef(null),c=rk(t,a);return s.useEffect(()=>{o.onAnchorChange(n?.current||a.current)}),n?null:ok.jsx(hk.div,{...i,ref:c})});NP.displayName=LP;var FP="PopperContent",[BP,zP]=IP(FP),UP=s.forwardRef((e,t)=>{const{__scopePopper:r,side:n="bottom",sideOffset:i=0,align:a="center",alignOffset:c=0,arrowPadding:d=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:p=0,sticky:h="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:g,...v}=e,b=jP(FP,r),[y,_]=s.useState(null),w=rk(t,e=>_(e)),[S,C]=s.useState(null),k=function(e){const[t,r]=s.useState(void 0);return Ak(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver(t=>{if(!Array.isArray(t))return;if(!t.length)return;const n=t[0];let i,s;if("borderBoxSize"in n){const e=n.borderBoxSize,t=Array.isArray(e)?e[0]:e;i=t.inlineSize,s=t.blockSize}else i=e.offsetWidth,s=e.offsetHeight;r({width:i,height:s})});return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}r(void 0)},[e]),t}(S),T=k?.width??0,P=k?.height??0,R=n+("center"!==a?"-"+a:""),E="number"==typeof p?p:{top:0,right:0,bottom:0,left:0,...p},O=Array.isArray(u)?u:[u],x=O.length>0,I={padding:E,boundary:O.filter(qP),altBoundary:x},{refs:D,floatingStyles:M,placement:j,isPositioned:A,middlewareData:L}=function(e){void 0===e&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:i,elements:{reference:a,floating:c}={},transform:d=!0,whileElementsMounted:l,open:u}=e,[p,h]=s.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=s.useState(n);gP(f,n)||m(n);const[g,v]=s.useState(null),[b,y]=s.useState(null),_=s.useCallback(e=>{e!==k.current&&(k.current=e,v(e))},[]),w=s.useCallback(e=>{e!==T.current&&(T.current=e,y(e))},[]),S=a||g,C=c||b,k=s.useRef(null),T=s.useRef(null),P=s.useRef(p),R=null!=l,E=yP(l),O=yP(i),x=yP(u),I=s.useCallback(()=>{if(!k.current||!T.current)return;const e={placement:t,strategy:r,middleware:f};O.current&&(e.platform=O.current),fP(k.current,T.current,e).then(e=>{const t={...e,isPositioned:!1!==x.current};D.current&&!gP(P.current,t)&&(P.current=t,o.flushSync(()=>{h(t)}))})},[f,t,r,O,x]);mP(()=>{!1===u&&P.current.isPositioned&&(P.current.isPositioned=!1,h(e=>({...e,isPositioned:!1})))},[u]);const D=s.useRef(!1);mP(()=>(D.current=!0,()=>{D.current=!1}),[]),mP(()=>{if(S&&(k.current=S),C&&(T.current=C),S&&C){if(E.current)return E.current(S,C,I);I()}},[S,C,I,E,R]);const M=s.useMemo(()=>({reference:k,floating:T,setReference:_,setFloating:w}),[_,w]),j=s.useMemo(()=>({reference:S,floating:C}),[S,C]),A=s.useMemo(()=>{const e={position:r,left:0,top:0};if(!j.floating)return e;const t=bP(j.floating,p.x),n=bP(j.floating,p.y);return d?{...e,transform:"translate("+t+"px, "+n+"px)",...vP(j.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:t,top:n}},[r,d,j.floating,p.x,p.y]);return s.useMemo(()=>({...p,update:I,refs:M,elements:j,floatingStyles:A}),[p,I,M,j,A])}({strategy:"fixed",placement:R,whileElementsMounted:(...e)=>oP(...e,{animationFrame:"always"===m}),elements:{reference:b.anchor},middleware:[wP({mainAxis:i+P,alignmentAxis:c}),l&&SP({mainAxis:!0,crossAxis:!1,limiter:"partial"===h?CP():void 0,...I}),l&&kP({...I}),TP({...I,apply:({elements:e,rects:t,availableWidth:r,availableHeight:n})=>{const{width:i,height:s}=t.reference,o=e.floating.style;o.setProperty("--radix-popper-available-width",`${r}px`),o.setProperty("--radix-popper-available-height",`${n}px`),o.setProperty("--radix-popper-anchor-width",`${i}px`),o.setProperty("--radix-popper-anchor-height",`${s}px`)}}),S&&RP({element:S,padding:d}),HP({arrowWidth:T,arrowHeight:P}),f&&PP({strategy:"referenceHidden",...I})]}),[N,F]=WP(j),B=fk(g);Ak(()=>{A&&B?.()},[A,B]);const z=L.arrow?.x,U=L.arrow?.y,V=0!==L.arrow?.centerOffset,[$,G]=s.useState();return Ak(()=>{y&&G(window.getComputedStyle(y).zIndex)},[y]),ok.jsx("div",{ref:D.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:A?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:$,"--radix-popper-transform-origin":[L.transformOrigin?.x,L.transformOrigin?.y].join(" "),...L.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:ok.jsx(BP,{scope:r,placedSide:N,onArrowChange:C,arrowX:z,arrowY:U,shouldHideArrow:V,children:ok.jsx(hk.div,{"data-side":N,"data-align":F,...v,ref:w,style:{...v.style,animation:A?void 0:"none"}})})})});UP.displayName=FP;var VP="PopperArrow",$P={top:"bottom",right:"left",bottom:"top",left:"right"},GP=s.forwardRef(function(e,t){const{__scopePopper:r,...n}=e,i=zP(VP,r),s=$P[i.placedSide];return ok.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:ok.jsx(OP,{...n,ref:t,style:{...n.style,display:"block"}})})});function qP(e){return null!==e}GP.displayName=VP;var HP=e=>({name:"transformOrigin",options:e,fn(t){const{placement:r,rects:n,middlewareData:i}=t,s=0!==i.arrow?.centerOffset,o=s?0:e.arrowWidth,a=s?0:e.arrowHeight,[c,d]=WP(r),l={start:"0%",center:"50%",end:"100%"}[d],u=(i.arrow?.x??0)+o/2,p=(i.arrow?.y??0)+a/2;let h="",f="";return"bottom"===c?(h=s?l:`${u}px`,f=-a+"px"):"top"===c?(h=s?l:`${u}px`,f=`${n.floating.height+a}px`):"right"===c?(h=-a+"px",f=s?l:`${p}px`):"left"===c&&(h=`${n.floating.width+a}px`,f=s?l:`${p}px`),{data:{x:h,y:f}}}});function WP(e){const[t,r="center"]=e.split("-");return[t,r]}var JP=AP,KP=NP,QP=UP,YP=GP,XP=s.forwardRef((e,t)=>{const{container:n,...i}=e,[o,a]=s.useState(!1);Ak(()=>a(!0),[]);const c=n||o&&globalThis?.document?.body;return c?r.createPortal(ok.jsx(hk.div,{...i,ref:t}),c):null});XP.displayName="Portal";var ZP=e=>{const{present:t,children:r}=e,n=function(e){const[t,r]=s.useState(),n=s.useRef(null),i=s.useRef(e),o=s.useRef("none"),a=e?"mounted":"unmounted",[c,d]=function(e,t){return s.useReducer((e,r)=>t[e][r]??e,e)}(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return s.useEffect(()=>{const e=eR(n.current);o.current="mounted"===c?e:"none"},[c]),Ak(()=>{const t=n.current,r=i.current;if(r!==e){const n=o.current,s=eR(t);if(e)d("MOUNT");else if("none"===s||"none"===t?.display)d("UNMOUNT");else{d(r&&n!==s?"ANIMATION_OUT":"UNMOUNT")}i.current=e}},[e,d]),Ak(()=>{if(t){let e;const r=t.ownerDocument.defaultView??window,s=s=>{const o=eR(n.current).includes(s.animationName);if(s.target===t&&o&&(d("ANIMATION_END"),!i.current)){const n=t.style.animationFillMode;t.style.animationFillMode="forwards",e=r.setTimeout(()=>{"forwards"===t.style.animationFillMode&&(t.style.animationFillMode=n)})}},a=e=>{e.target===t&&(o.current=eR(n.current))};return t.addEventListener("animationstart",a),t.addEventListener("animationcancel",s),t.addEventListener("animationend",s),()=>{r.clearTimeout(e),t.removeEventListener("animationstart",a),t.removeEventListener("animationcancel",s),t.removeEventListener("animationend",s)}}d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:s.useCallback(e=>{n.current=e?getComputedStyle(e):null,r(e)},[])}}(t),i="function"==typeof r?r({present:n.isPresent}):s.Children.only(r),o=rk(n.ref,function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(i));return"function"==typeof r||n.isPresent?s.cloneElement(i,{ref:o}):null};function eR(e){return e?.animationName||"none"}ZP.displayName="Presence";var tR=s[" useInsertionEffect ".trim().toString()]||Ak;function rR({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){const[i,o,a]=function({defaultProp:e,onChange:t}){const[r,n]=s.useState(e),i=s.useRef(r),o=s.useRef(t);return tR(()=>{o.current=t},[t]),s.useEffect(()=>{i.current!==r&&(o.current?.(r),i.current=r)},[r,i]),[r,n,o]}({defaultProp:t,onChange:r}),c=void 0!==e,d=c?e:i;{const t=s.useRef(void 0!==e);s.useEffect(()=>{const e=t.current;if(e!==c){const t=e?"controlled":"uncontrolled",r=c?"controlled":"uncontrolled";console.warn(`${n} is changing from ${t} to ${r}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`)}t.current=c},[c,n])}const l=s.useCallback(t=>{if(c){const r=function(e){return"function"==typeof e}(t)?t(e):t;r!==e&&a.current?.(r)}else o(t)},[c,e,o,a]);return[d,l]}var nR=new WeakMap,iR=new WeakMap,sR={},oR=0,aR=function(e){return e&&(e.host||aR(e.parentNode))},cR=function(e,t,r,n){var i=function(e,t){return t.map(function(t){if(e.contains(t))return t;var r=aR(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(e){return Boolean(e)})}(t,Array.isArray(e)?e:[e]);sR[r]||(sR[r]=new WeakMap);var s=sR[r],o=[],a=new Set,c=new Set(i),d=function(e){e&&!a.has(e)&&(a.add(e),d(e.parentNode))};i.forEach(d);var l=function(e){e&&!c.has(e)&&Array.prototype.forEach.call(e.children,function(e){if(a.has(e))l(e);else try{var t=e.getAttribute(n),i=null!==t&&"false"!==t,c=(nR.get(e)||0)+1,d=(s.get(e)||0)+1;nR.set(e,c),s.set(e,d),o.push(e),1===c&&i&&iR.set(e,!0),1===d&&e.setAttribute(r,"true"),i||e.setAttribute(n,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}})};return l(t),a.clear(),oR++,function(){o.forEach(function(e){var t=nR.get(e)-1,i=s.get(e)-1;nR.set(e,t),s.set(e,i),t||(iR.has(e)||e.removeAttribute(n),iR.delete(e)),i||e.removeAttribute(r)}),--oR||(nR=new WeakMap,nR=new WeakMap,iR=new WeakMap,sR={})}},dR=function(e,t,r){void 0===r&&(r="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),i=function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live], script"))),cR(n,i,r,"aria-hidden")):function(){return null}},lR="right-scroll-bar-position",uR="width-before-scroll-bar";function pR(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var hR="undefined"!=typeof window?s.useLayoutEffect:s.useEffect,fR=new WeakMap;function mR(e,r){var n,i,s,o=(n=null,i=function(t){return e.forEach(function(e){return pR(e,t)})},s=t.useState(function(){return{value:n,callback:i,facade:{get current(){return s.value},set current(e){var t=s.value;t!==e&&(s.value=e,s.callback(e,t))}}}})[0],s.callback=i,s.facade);return hR(function(){var t=fR.get(o);if(t){var r=new Set(t),n=new Set(e),i=o.current;r.forEach(function(e){n.has(e)||pR(e,null)}),n.forEach(function(e){r.has(e)||pR(e,i)})}fR.set(o,e)},[e]),o}function gR(e){return e}var vR=function(e){var t=e.sideCar,r=$S(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return s.createElement(n,VS({},r))};vR.isSideCarExport=!0;var bR=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=gR);var r=[],n=!1;return{read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(e){var i=t(e,n);return r.push(i),function(){r=r.filter(function(e){return e!==i})}},assignSyncMedium:function(e){for(n=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){n=!0;var t=[];if(r.length){var i=r;r=[],i.forEach(e),t=r}var s=function(){var r=t;t=[],r.forEach(e)},o=function(){return Promise.resolve().then(s)};o(),r={push:function(e){t.push(e),o()},filter:function(e){return t=t.filter(e),r}}}}}(null);return t.options=VS({async:!0,ssr:!1},e),t}(),yR=function(){},_R=s.forwardRef(function(e,t){var r=s.useRef(null),n=s.useState({onScrollCapture:yR,onWheelCapture:yR,onTouchMoveCapture:yR}),i=n[0],o=n[1],a=e.forwardProps,c=e.children,d=e.className,l=e.removeScrollBar,u=e.enabled,p=e.shards,h=e.sideCar,f=e.noRelative,m=e.noIsolation,g=e.inert,v=e.allowPinchZoom,b=e.as,y=void 0===b?"div":b,_=e.gapMode,w=$S(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=h,C=mR([r,t]),k=VS(VS({},w),i);return s.createElement(s.Fragment,null,u&&s.createElement(S,{sideCar:bR,removeScrollBar:l,shards:p,noRelative:f,noIsolation:m,inert:g,setCallbacks:o,allowPinchZoom:!!v,lockRef:r,gapMode:_}),a?s.cloneElement(s.Children.only(c),VS(VS({},k),{ref:C})):s.createElement(y,VS({},k,{className:d,ref:C}),c))});_R.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},_R.classNames={fullWidth:uR,zeroRight:lR};function wR(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=function(){if("undefined"!=typeof __webpack_nonce__)return __webpack_nonce__}();return t&&e.setAttribute("nonce",t),e}var SR=function(){var e=0,t=null;return{add:function(r){var n,i;0==e&&(t=wR())&&(i=r,(n=t).styleSheet?n.styleSheet.cssText=i:n.appendChild(document.createTextNode(i)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},CR=function(){var e,t=(e=SR(),function(t,r){s.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])});return function(e){var r=e.styles,n=e.dynamic;return t(r,n),null}},kR={left:0,top:0,right:0,gap:0},TR=function(e){return parseInt(e||"",10)||0},PR=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return kR;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],n=t["padding"===e?"paddingTop":"marginTop"],i=t["padding"===e?"paddingRight":"marginRight"];return[TR(r),TR(n),TR(i)]}(e),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},RR=CR(),ER="data-scroll-locked",OR=function(e,t,r,n){var i=e.left,s=e.top,o=e.right,a=e.gap;return void 0===r&&(r="margin"),"\n .".concat("with-scroll-bars-hidden"," {\n overflow: hidden ").concat(n,";\n padding-right: ").concat(a,"px ").concat(n,";\n }\n body[").concat(ER,"] {\n overflow: hidden ").concat(n,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(n,";"),"margin"===r&&"\n padding-left: ".concat(i,"px;\n padding-top: ").concat(s,"px;\n padding-right: ").concat(o,"px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(a,"px ").concat(n,";\n "),"padding"===r&&"padding-right: ".concat(a,"px ").concat(n,";")].filter(Boolean).join(""),"\n }\n \n .").concat(lR," {\n right: ").concat(a,"px ").concat(n,";\n }\n \n .").concat(uR," {\n margin-right: ").concat(a,"px ").concat(n,";\n }\n \n .").concat(lR," .").concat(lR," {\n right: 0 ").concat(n,";\n }\n \n .").concat(uR," .").concat(uR," {\n margin-right: 0 ").concat(n,";\n }\n \n body[").concat(ER,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(a,"px;\n }\n")},xR=function(){var e=parseInt(document.body.getAttribute(ER)||"0",10);return isFinite(e)?e:0},IR=function(e){var t=e.noRelative,r=e.noImportant,n=e.gapMode,i=void 0===n?"margin":n;s.useEffect(function(){return document.body.setAttribute(ER,(xR()+1).toString()),function(){var e=xR()-1;e<=0?document.body.removeAttribute(ER):document.body.setAttribute(ER,e.toString())}},[]);var o=s.useMemo(function(){return PR(i)},[i]);return s.createElement(RR,{styles:OR(o,!t,i,r?"":"!important")})},DR=!1;if("undefined"!=typeof window)try{var MR=Object.defineProperty({},"passive",{get:function(){return DR=!0,!0}});window.addEventListener("test",MR,MR),window.removeEventListener("test",MR,MR)}catch(qE){DR=!1}var jR=!!DR&&{passive:!1},AR=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},LR=function(e,t){var r=t.ownerDocument,n=t;do{if("undefined"!=typeof ShadowRoot&&n instanceof ShadowRoot&&(n=n.host),NR(e,n)){var i=FR(e,n);if(i[1]>i[2])return!0}n=n.parentNode}while(n&&n!==r.body);return!1},NR=function(e,t){return"v"===e?function(e){return AR(e,"overflowY")}(t):function(e){return AR(e,"overflowX")}(t)},FR=function(e,t){return"v"===e?function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]}(t):function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]}(t)},BR=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},zR=function(e){return[e.deltaX,e.deltaY]},UR=function(e){return e&&"current"in e?e.current:e},VR=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},$R=0,GR=[];function qR(e){for(var t=null;null!==e;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var HR,WR=(HR=function(e){var t=s.useRef([]),r=s.useRef([0,0]),n=s.useRef(),i=s.useState($R++)[0],o=s.useState(CR)[0],a=s.useRef(e);s.useEffect(function(){a.current=e},[e]),s.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var t=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(UR),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),t.forEach(function(e){return e.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=s.useCallback(function(e,t){if("touches"in e&&2===e.touches.length||"wheel"===e.type&&e.ctrlKey)return!a.current.allowPinchZoom;var i,s=BR(e),o=r.current,c="deltaX"in e?e.deltaX:o[0]-s[0],d="deltaY"in e?e.deltaY:o[1]-s[1],l=e.target,u=Math.abs(c)>Math.abs(d)?"h":"v";if("touches"in e&&"h"===u&&"range"===l.type)return!1;var p=LR(u,l);if(!p)return!0;if(p?i=u:(i="v"===u?"h":"v",p=LR(u,l)),!p)return!1;if(!n.current&&"changedTouches"in e&&(c||d)&&(n.current=i),!i)return!0;var h=n.current||i;return function(e,t,r,n){var i=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),s=i*n,o=r.target,a=t.contains(o),c=!1,d=s>0,l=0,u=0;do{if(!o)break;var p=FR(e,o),h=p[0],f=p[1]-p[2]-i*h;(h||f)&&NR(e,o)&&(l+=f,u+=h);var m=o.parentNode;o=m&&m.nodeType===Node.DOCUMENT_FRAGMENT_NODE?m.host:m}while(!a&&o!==document.body||a&&(t.contains(o)||t===o));return(d&&Math.abs(l)<1||!d&&Math.abs(u)<1)&&(c=!0),c}(h,t,e,"h"===h?c:d)},[]),d=s.useCallback(function(e){var r=e;if(GR.length&&GR[GR.length-1]===o){var n="deltaY"in r?zR(r):BR(r),i=t.current.filter(function(e){return e.name===r.type&&(e.target===r.target||r.target===e.shadowParent)&&(t=e.delta,i=n,t[0]===i[0]&&t[1]===i[1]);var t,i})[0];if(i&&i.should)r.cancelable&&r.preventDefault();else if(!i){var s=(a.current.shards||[]).map(UR).filter(Boolean).filter(function(e){return e.contains(r.target)});(s.length>0?c(r,s[0]):!a.current.noIsolation)&&r.cancelable&&r.preventDefault()}}},[]),l=s.useCallback(function(e,r,n,i){var s={name:e,delta:r,target:n,should:i,shadowParent:qR(n)};t.current.push(s),setTimeout(function(){t.current=t.current.filter(function(e){return e!==s})},1)},[]),u=s.useCallback(function(e){r.current=BR(e),n.current=void 0},[]),p=s.useCallback(function(t){l(t.type,zR(t),t.target,c(t,e.lockRef.current))},[]),h=s.useCallback(function(t){l(t.type,BR(t),t.target,c(t,e.lockRef.current))},[]);s.useEffect(function(){return GR.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:h}),document.addEventListener("wheel",d,jR),document.addEventListener("touchmove",d,jR),document.addEventListener("touchstart",u,jR),function(){GR=GR.filter(function(e){return e!==o}),document.removeEventListener("wheel",d,jR),document.removeEventListener("touchmove",d,jR),document.removeEventListener("touchstart",u,jR)}},[]);var f=e.removeScrollBar,m=e.inert;return s.createElement(s.Fragment,null,m?s.createElement(o,{styles:VR(i)}):null,f?s.createElement(IR,{noRelative:e.noRelative,gapMode:e.gapMode}):null)},bR.useMedium(HR),vR),JR=s.forwardRef(function(e,t){return s.createElement(_R,VS({},e,{ref:t,sideCar:WR}))});JR.classNames=_R.classNames;var KR="Popover",[QR,YR]=ak(KR,[DP]),XR=DP(),[ZR,eE]=QR(KR),tE=e=>{const{__scopePopover:t,children:r,open:n,defaultOpen:i,onOpenChange:o,modal:a=!1}=e,c=XR(t),d=s.useRef(null),[l,u]=s.useState(!1),[p,h]=rR({prop:n,defaultProp:i??!1,onChange:o,caller:KR});return ok.jsx(JP,{...c,children:ok.jsx(ZR,{scope:t,contentId:Fk(),triggerRef:d,open:p,onOpenChange:h,onOpenToggle:s.useCallback(()=>h(e=>!e),[h]),hasCustomAnchor:l,onCustomAnchorAdd:s.useCallback(()=>u(!0),[]),onCustomAnchorRemove:s.useCallback(()=>u(!1),[]),modal:a,children:r})})};tE.displayName=KR;var rE="PopoverAnchor";s.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,i=eE(rE,r),o=XR(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:c}=i;return s.useEffect(()=>(a(),()=>c()),[a,c]),ok.jsx(KP,{...o,...n,ref:t})}).displayName=rE;var nE="PopoverTrigger",iE=s.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,i=eE(nE,r),s=XR(r),o=rk(t,i.triggerRef),a=ok.jsx(hk.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":gE(i.open),...n,ref:o,onClick:ZC(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:ok.jsx(KP,{asChild:!0,...s,children:a})});iE.displayName=nE;var sE="PopoverPortal",[oE,aE]=QR(sE,{forceMount:void 0}),cE=e=>{const{__scopePopover:t,forceMount:r,children:n,container:i}=e,s=eE(sE,t);return ok.jsx(oE,{scope:t,forceMount:r,children:ok.jsx(ZP,{present:r||s.open,children:ok.jsx(XP,{asChild:!0,container:i,children:n})})})};cE.displayName=sE;var dE="PopoverContent",lE=s.forwardRef((e,t)=>{const r=aE(dE,e.__scopePopover),{forceMount:n=r.forceMount,...i}=e,s=eE(dE,e.__scopePopover);return ok.jsx(ZP,{present:n||s.open,children:s.modal?ok.jsx(pE,{...i,ref:t}):ok.jsx(hE,{...i,ref:t})})});lE.displayName=dE;var uE=dk("PopoverContent.RemoveScroll"),pE=s.forwardRef((e,t)=>{const r=eE(dE,e.__scopePopover),n=s.useRef(null),i=rk(t,n),o=s.useRef(!1);return s.useEffect(()=>{const e=n.current;if(e)return dR(e)},[]),ok.jsx(JR,{as:uE,allowPinchZoom:!0,children:ok.jsx(fE,{...e,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ZC(e.onCloseAutoFocus,e=>{e.preventDefault(),o.current||r.triggerRef.current?.focus()}),onPointerDownOutside:ZC(e.onPointerDownOutside,e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey,n=2===t.button||r;o.current=n},{checkForDefaultPrevented:!1}),onFocusOutside:ZC(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})}),hE=s.forwardRef((e,t)=>{const r=eE(dE,e.__scopePopover),n=s.useRef(!1),i=s.useRef(!1);return ok.jsx(fE,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(n.current||r.triggerRef.current?.focus(),t.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(n.current=!0,"pointerdown"===t.detail.originalEvent.type&&(i.current=!0));const s=t.target,o=r.triggerRef.current?.contains(s);o&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&i.current&&t.preventDefault()}})}),fE=s.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:u,...p}=e,h=eE(dE,r),f=XR(r);return s.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??kk()),document.body.insertAdjacentElement("beforeend",e[1]??kk()),Ck++,()=>{1===Ck&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Ck--}},[]),ok.jsx(Ek,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:ok.jsx(_k,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1),children:ok.jsx(QP,{"data-state":gE(h.open),role:"dialog",id:h.contentId,...f,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),mE="PopoverClose";s.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,i=eE(mE,r);return ok.jsx(hk.button,{type:"button",...n,ref:t,onClick:ZC(e.onClick,()=>i.onOpenChange(!1))})}).displayName=mE;function gE(e){return e?"open":"closed"}s.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,i=XR(r);return ok.jsx(YP,{...i,...n,ref:t})}).displayName="PopoverArrow";var vE=cE,bE=lE;const yE=tE,_E=iE,wE=s.forwardRef((e,t)=>{var{style:r,align:n="center",sideOffset:i=4}=e,o=$S(e,["style","align","sideOffset"]);return s.createElement(vE,null,s.createElement(bE,Object.assign({ref:t,align:n,sideOffset:i,style:Object.assign({width:"200px",backgroundColor:"#fff",border:"1px solid #e5e5e5",borderRadius:"0.375rem",boxShadow:"0 1px 2px 0 rgb(0 0 0 / 0.05)",color:"#333",fontSize:"14px",lineHeight:"1.5",padding:"16px",zIndex:50,outline:"none"},r)},o)))});wE.displayName=bE.displayName;const SE=s.createContext({}),CE=s.createContext({}),kE=()=>{const e=s.useContext(SE),t=s.useContext(CE);if(!t)throw new Error("useGridCell must be used within a GridCell");return Object.assign(Object.assign({},e),t)},TE=s.createContext({}),PE=e=>{const{children:t}=e,r=$S(e,["children"]),[n,i]=s.useState(!1);return s.createElement(TE.Provider,{value:{open:n,setOpen:i}},s.createElement(yE,Object.assign({},r,{open:n,onOpenChange:i}),t))},RE=s.forwardRef((e,t)=>{var{children:r,style:n}=e,i=$S(e,["children","style"]);return s.createElement(wE,Object.assign({ref:t,style:Object.assign({display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minWidth:"180px",maxWidth:"300px",maxHeight:"100vh",overflowY:"auto",padding:0},n)},i),r)});RE.displayName="ParticipantMenuContent";const EE=s.forwardRef((e,t)=>{var{children:r,style:n}=e,i=$S(e,["children","style"]);return s.createElement(_E,Object.assign({ref:t,style:Object.assign({position:"absolute",top:"10px",right:"20px",textDecoration:"none",whiteSpace:"nowrap",border:"none",cursor:"pointer"},n)},i),r)});EE.displayName=_E.displayName;const OE=s.forwardRef((e,t)=>{var r,{children:n,style:i,participantAction:o}=e,a=$S(e,["children","style","participantAction"]);const{participant:c,setOpen:d,maximizedParticipant:l,setMaximizedParticipant:u,setFloatingParticipant:p,floatingParticipant:h}=(()=>{const e=s.useContext(TE),t=kE();if(!e)throw new Error("useParticipantMenu must be used within a ParticipantMenu");return Object.assign(Object.assign({},e),t)})(),f=null===(r=s.useContext(US))||void 0===r?void 0:r.getGrid(),{spotlightedParticipants:m}=jC(),g=m.find(e=>e.id===c.id),v=(null==l?void 0:l.id)===c.id,b=(null==h?void 0:h.id)===c.id;let y;switch(o){case"maximize":y=()=>{u(v?null:c),d(!1)};break;case"spotlight":y=()=>{g?null==f||f.removeSpotlight(c.id):null==f||f.spotlightParticipant(c.id),d(!1)};break;case"float":y=()=>{p(b?null:c),d(!1)}}return s.createElement("button",Object.assign({ref:t,role:"menuitem",tabIndex:-1,onClick:null!=y?y:a.onClick,style:Object.assign({alignItems:"stretch",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",height:"40px",lineHeight:"40px",minWidth:"140px",padding:"0 12px",textAlign:"left",textDecoration:"none",whiteSpace:"nowrap",width:"100%"},i)},a),n)});function xE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("g",null,s.createElement("circle",{cx:"6",cy:"12",r:"2"}),s.createElement("circle",{cx:"12",cy:"12",r:"2"}),s.createElement("circle",{cx:"18",cy:"12",r:"2"})))}function IE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m13.875 3c0 .62132.5037 1.125 1.125 1.125h3.284l-4.0795 4.0795c-.4393.43934-.4393 1.15166 0 1.591.4393.4393 1.1517.4393 1.591 0l4.0795-4.07951v3.28401c0 .62132.5037 1.125 1.125 1.125s1.125-.50368 1.125-1.125v-6c0-.15254-.0304-.29799-.0854-.43063-.0536-.12968-.1326-.25135-.2368-.35749l-.0147-.01469c-.203-.19928-.4812-.32219-.7881-.32219h-6c-.6213 0-1.125.50368-1.125 1.125zm-9.75 12c0-.6213-.50368-1.125-1.125-1.125s-1.125.5037-1.125 1.125v6c0 .3069.12291.5851.32219.7881.00486.005.00975.0099.01469.0147.10614.1042.22781.1832.35749.2368.13264.055.27809.0854.43063.0854h6c.62132 0 1.125-.5037 1.125-1.125s-.50368-1.125-1.125-1.125h-3.28401l4.07951-4.0795c.4393-.4393.4393-1.1517 0-1.591-.43934-.4393-1.15166-.4393-1.591 0l-4.0795 4.0795z"}))}function DE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m15.241.146691c-.1011-.1955882-.3809-.1955879-.482 0l-1.1063 2.139639c-.0258.04991-.0665.09058-.1164.11639l-2.1396 1.10629c-.1956.10113-.1956.38085 0 .48198l2.1396 1.10629c.0499.02581.0906.06648.1164.11639l1.1063 2.13964c.1011.19559.3809.19559.482 0l1.1063-2.13964c.0258-.04991.0665-.09058.1164-.11639l2.1396-1.10629c.1956-.10113.1956-.38085 0-.48198l-2.1396-1.10629c-.0499-.02581-.0906-.06648-.1164-.11639zm-13.741 2.900259v14.67495c0 .0511.00116.1018.00345.1523-.00229.0418-.00345.0837-.00345.1258 0 .5674.21005 1.1103.59339 1.6103.24265.3472.55042.6455.90566.8773 1.61225 1.213 4.36988 2.0124 7.50095 2.0124 4.3315 0 7.9484-1.53 8.8068-3.5681.0651-.1472.1148-.3024.1455-.4658.0315-.1532.0477-.3087.0477-.4661 0-.6032-.2374-1.1788-.668-1.7045-.1377-.1975-.2995-.4017-.4877-.6127l-14.22219-13.74809c-.28845-.27884-.67396-.43471-1.07516-.43471-.85436 0-1.54695.69259-1.54695 1.54695zm19.2646 4.59631c.0988-.19101.372-.19101.4708 0l.8546 1.65303c.0253.04874.065.08846.1137.11366l1.653.85465c.1911.0988.1911.372 0 .4708l-1.653.8546c-.0487.0253-.0884.065-.1137.1137l-.8546 1.653c-.0988.1911-.372.1911-.4708 0l-.8546-1.653c-.0253-.0487-.065-.0884-.1137-.1137l-1.653-.8546c-.1911-.0988-.1911-.372 0-.4708l1.653-.85465c.0487-.0252.0884-.06492.1137-.11366zm-3.2651 10.35684c0 .0769-.1144.6851-1.5305 1.3931-1.2964.6482-3.2274 1.1069-5.4695 1.1069s-4.17308-.4587-5.46952-1.1069c-1.41607-.708-1.53047-1.3162-1.53047-1.3931 0-.077.1144-.6851 1.53047-1.3932 1.29644-.6482 3.22742-1.1068 5.46952-1.1068s4.1731.4586 5.4695 1.1068c1.4161.7081 1.5305 1.3162 1.5305 1.3932z"}))}function ME(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm1.875 19.5c0-.6213.5037-1.125 1.125-1.125h3.284l-5.5795-5.5795c-.4393-.4393-.4393-1.1517 0-1.591s1.1517-.4393 1.591 0l5.5795 5.5795v-3.284c0-.6213.5037-1.125 1.125-1.125s1.125.5037 1.125 1.125v6c0 .308-.1238.5872-.3244.7903-.0033.0034-.0067.0068-.0101.0102-.1067.1054-.2292.1851-.3599.2391-.1326.055-.2781.0854-.4306.0854h-6c-.6213 0-1.125-.5037-1.125-1.125z"}))}function jE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm8.625 12c0 .6213-.5037 1.125-1.125 1.125h-3.284l5.5795 5.5795c.4393.4393.4393 1.1517 0 1.591s-1.1517.4393-1.591 0l-5.5795-5.5795v3.284c0 .6213-.5037 1.125-1.125 1.125s-1.125-.5037-1.125-1.125v-6c0-.3081.1238-.5872.3244-.7904.0034-.0034.0068-.0068.0102-.0102.1067-.1053.2292-.185.3598-.239.1326-.055.2781-.0854.4306-.0854h6c.6213 0 1.125.5037 1.125 1.125z"}))}function AE({participant:e}){const{spotlightedParticipants:t}=jC(),r=t.find(t=>t.id===e.id),{isHovered:n,maximizedParticipant:i,floatingParticipant:o}=kE(),a=(null==i?void 0:i.id)===e.id,c=(null==o?void 0:o.id)===e.id;return n?s.createElement(PE,null,s.createElement(EE,{style:{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"#fff",borderRadius:"6px",padding:"4px"}},s.createElement(xE,{height:20,width:20,transform:"rotate(90)"})),s.createElement(RE,null,e.isLocalClient?s.createElement(OE,{participantAction:"float",style:{display:"flex",alignItems:"center",gap:"10px"}},c?s.createElement(s.Fragment,null,s.createElement(jE,{height:16,width:16}),"Move to grid"):s.createElement(s.Fragment,null,s.createElement(ME,{height:16,width:16}),"Pop out")):null,s.createElement(OE,{participantAction:"maximize",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(IE,{height:16,width:16}),a?"Minimize":"Maximize"),s.createElement(OE,{participantAction:"spotlight",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(DE,{height:16,width:16}),r?"Remove spotlight":"Spotlight"))):null}OE.displayName="ParticipantMenuItem";const LE=s.forwardRef(({className:e,participant:t,children:r},n)=>{const[i,o]=s.useState(!1),a=s.useCallback(()=>{o(!0)},[]),c=s.useCallback(()=>{o(!1)},[]);return s.createElement(CE.Provider,{value:{participant:t,isHovered:i}},s.createElement("div",{ref:n,className:e,onMouseEnter:a,onMouseLeave:c,style:{height:"100%",width:"100%"}},r))});LE.displayName="GridCell";const NE=s.forwardRef((e,t)=>{var{stream:r,style:n}=e,i=$S(e,["stream","style"]);const o=s.useRef(null),{onSetClientAspectRatio:a,clientAspectRatios:c,participant:d,isConstrained:l}=kE();if(!d)return null;const u=c[d.id];s.useImperativeHandle(t,()=>o.current);const p=s.useCallback(()=>{const e=o.current&&o.current.captureAspectRatio();e&&e!==u&&d.id&&a({aspectRatio:e,clientId:d.id})},[c,d.id,a]),h=r||d.stream;return h&&d.isVideoEnabled?s.createElement(qS,Object.assign({ref:o,style:Object.assign(Object.assign({borderRadius:l?0:"8px"},l?{objectFit:"cover"}:{}),n),muted:d.isLocalClient},i,{stream:h,onVideoResize:p})):s.createElement(XC,{isSmallCell:!1,displayName:(null==d?void 0:d.displayName)||"Guest",withRoundedCorners:!0,muted:d.isLocalClient,stream:d.stream})});function FE({cellView:e,enableParticipantMenu:t,render:r}){const n=null==e?void 0:e.client;if(n)return"video"===e.type?s.createElement(LE,{participant:n},s.createElement(s.Fragment,null,r?r({participant:n}):s.createElement(s.Fragment,null,s.createElement(NE,null),t?s.createElement(AE,{participant:n}):null))):void 0}return NE.displayName="GridVideoView",e.GridCell=LE,e.GridVideoView=NE,e.ParticipantMenu=PE,e.ParticipantMenuContent=RE,e.ParticipantMenuItem=OE,e.ParticipantMenuTrigger=EE,e.VideoGrid=function({renderParticipant:e,renderFloatingParticipant:t,stageParticipantLimit:r,gridGap:n,videoGridGap:i,enableSubgrid:o,enableParticipantMenu:a,enableConstrainedGrid:c}){const d=s.useRef(null),{containerFrame:l,cellViewsFloating:u,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,videoStage:g,setContainerBounds:v,setClientAspectRatios:b,maximizedParticipant:y,setMaximizedParticipant:_,isConstrained:w,floatingParticipant:S,setFloatingParticipant:C}=function({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r=12,gridGap:n=8,videoGridGap:i=8,enableSubgrid:o=!0,enableConstrainedGrid:a=!0}={}){const[c,d]=s.useState({width:0,height:0}),[l,u]=s.useState(!1),[p,h]=s.useState({}),[f,m]=s.useState(null),[g,v]=s.useState(null),{clientViewsInGrid:b,clientViewsInPresentationGrid:y,clientViewsInSubgrid:_,floatingClientView:w}=jC({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r,enableSubgrid:o,maximizedParticipant:f,floatingParticipant:g,isConstrained:!!a&&!!l}),S=s.useMemo(()=>w?[MC({client:w,aspectRatio:p[w.id],avatarSize:0,cellPaddings:{top:0,right:0}})]:[],[w,p]),C=s.useMemo(()=>b.map(e=>MC({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})),[b,p]),k=s.useMemo(()=>y.map(e=>MC({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})),[y,p]),T=s.useMemo(()=>_.map(e=>MC({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0},isSubgrid:!0})),[_,p]),P=s.useMemo(()=>XS(c),[c]);s.useEffect(()=>{a&&u(c.width<500||c.height<500)},[c,a]);const R=s.useMemo(()=>DC({floatingVideo:S[0],frame:P,gridGap:n,isConstrained:l,roomBounds:P.bounds,videos:C,videoGridGap:i,presentationVideos:k,subgridVideos:T}),[P,S,C,k,T,n,i]);return{containerFrame:P,cellViewsFloating:S,cellViewsVideoGrid:C,cellViewsInPresentationGrid:k,cellViewsInSubgrid:T,clientAspectRatios:p,videoStage:R,setContainerBounds:d,setClientAspectRatios:h,maximizedParticipant:f,setMaximizedParticipant:m,floatingParticipant:g,setFloatingParticipant:v,isConstrained:l}}({activeVideosSubgridTrigger:12,stageParticipantLimit:r,gridGap:n,videoGridGap:i,enableSubgrid:o,enableConstrainedGrid:c}),k=s.useCallback(({aspectRatio:e,clientId:t})=>{b(r=>Object.assign(Object.assign({},r),{[t]:e}))},[b]),T=s.useMemo(()=>FE(Object.assign({cellView:u[0],enableParticipantMenu:a},t?{render:({participant:e})=>t({participant:e})}:{})),[u]),P=s.useMemo(()=>h.map(t=>FE(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))),[h]),R=s.useMemo(()=>p.map(t=>FE(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))),[p]),E=s.useMemo(()=>f.map(e=>FE({cellView:e,enableParticipantMenu:a})),[f]);return s.useEffect(()=>{if(!d.current)return;const e=new ResizeObserver(Pb(()=>{var e,t,r,n;v({width:null!==(t=null===(e=d.current)||void 0===e?void 0:e.clientWidth)&&void 0!==t?t:640,height:null!==(n=null===(r=d.current)||void 0===r?void 0:r.clientHeight)&&void 0!==n?n:480})},{delay:60,edges:!1}));return e.observe(d.current),()=>{e.disconnect()}},[]),s.createElement(SE.Provider,{value:{onSetClientAspectRatio:k,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,maximizedParticipant:y,setMaximizedParticipant:_,floatingParticipant:S,setFloatingParticipant:C,isConstrained:w}},s.createElement("div",{ref:d,style:{width:"100%",height:"100%",position:"relative"}},s.createElement(aC,{containerFrame:l,floatingContent:T,layoutVideoStage:g,presentationGridContent:P,gridContent:R,subgridContent:E})))},e.VideoView=qS,e.WherebyProvider=function({children:e}){const t=s.useMemo(()=>new zS,[]);return s.useEffect(()=>()=>{t.destroy()},[t]),s.createElement(US.Provider,{value:t},e)},e.useLocalMedia=function(e={audio:!0,video:!0}){var t;const r=null===(t=s.useContext(US))||void 0===t?void 0:t.getLocalMedia(),[n,i]=s.useState(()=>JS);if(!r)throw new Error("WherebyClient is not initialized. Please wrap your component with WherebyProvider.");return s.useEffect(()=>{r.startMedia(e);const t=r.subscribe(e=>{i(t=>Object.assign(Object.assign({},t),e))});return()=>{t(),r.stopMedia()}},[]),{state:n,actions:{setCameraDevice:s.useCallback(e=>r.setCameraDevice(e),[r]),setMicrophoneDevice:s.useCallback(e=>r.setMicrophoneDevice(e),[r]),setSpeakerDevice:s.useCallback(e=>r.setSpeakerDevice(e),[r]),toggleCameraEnabled:s.useCallback(e=>r.toggleCamera(e),[r]),toggleMicrophoneEnabled:s.useCallback(e=>r.toggleMicrophone(e),[r]),toggleLowDataModeEnabled:s.useCallback(e=>r.toggleLowDataMode(e),[r])}}},e.useRoomConnection=function(e,t=WS){var r;const n=null===(r=s.useContext(US))||void 0===r?void 0:r.getRoomConnection(),[i,o]=s.useState(()=>HS);if(!n)throw new Error("WherebyClient is not initialized. Please wrap your component with WherebyProvider.");const a=s.useMemo(()=>{const r=new URL(e),n=new URLSearchParams(r.search),i=t.roomKey||n.get("roomKey");return{displayName:t.displayName||"Guest",localMediaOptions:t.localMedia?void 0:t.localMediaOptions,roomKey:i,roomUrl:e,userAgent:"browser-sdk:3.14.10",externalId:t.externalId||null}},[e,t]);s.useEffect(()=>{const e=n.subscribe(e=>{o(t=>Object.assign(Object.assign({},t),e))}),t=n.getNotificationsEventEmitter();return o(e=>Object.assign(Object.assign({},e),{events:t})),()=>{e(),n.leaveRoom()}},[]);const c=s.useCallback(()=>(n.initialize(a),n.joinRoom()),[n]),d=s.useCallback(e=>n.sendChatMessage(e),[n]),l=s.useCallback(()=>n.knock(),[n]),u=s.useCallback(e=>n.setDisplayName(e),[n]),p=s.useCallback(e=>n.toggleCamera(e),[n]),h=s.useCallback(e=>n.toggleMicrophone(e),[n]),f=s.useCallback(e=>n.toggleLowDataMode(e),[n]),m=s.useCallback(e=>n.toggleRaiseHand(e),[n]),g=s.useCallback(e=>n.askToSpeak(e),[n]),v=s.useCallback(e=>n.askToTurnOnCamera(e),[n]),b=s.useCallback(e=>n.acceptWaitingParticipant(e),[n]),y=s.useCallback(e=>n.rejectWaitingParticipant(e),[n]),_=s.useCallback(()=>n.startCloudRecording(),[n]),w=s.useCallback(()=>n.startScreenshare(),[n]),S=s.useCallback(()=>n.stopCloudRecording(),[n]),C=s.useCallback(()=>n.stopScreenshare(),[n]),k=s.useCallback(()=>n.leaveRoom(),[n]),T=s.useCallback(e=>n.lockRoom(e),[n]),P=s.useCallback(e=>n.muteParticipants(e),[n]),R=s.useCallback(e=>n.turnOffParticipantCameras(e),[n]),E=s.useCallback(e=>n.spotlightParticipant(e),[n]),O=s.useCallback(e=>n.removeSpotlight(e),[n]),x=s.useCallback(e=>n.kickParticipant(e),[n]),I=s.useCallback(e=>n.endMeeting(e),[n]),D=s.useCallback(e=>n.joinBreakoutGroup(e),[n]),M=s.useCallback(()=>n.joinBreakoutMainRoom(),[n]),{events:j}=i;return{state:$S(i,["events"]),events:j,actions:{toggleLowDataMode:f,toggleRaiseHand:m,askToSpeak:g,askToTurnOnCamera:v,acceptWaitingParticipant:b,knock:l,joinRoom:c,leaveRoom:k,lockRoom:T,muteParticipants:P,turnOffParticipantCameras:R,kickParticipant:x,endMeeting:I,rejectWaitingParticipant:y,sendChatMessage:d,setDisplayName:u,startCloudRecording:_,startScreenshare:w,stopCloudRecording:S,stopScreenshare:C,toggleCamera:p,toggleMicrophone:h,spotlightParticipant:E,removeSpotlight:O,joinBreakoutGroup:D,joinBreakoutMainRoom:M}}},e}({},React,ReactDOM);
1
+ this.whereby=this.whereby||{},this.whereby.react=function(e,t,r){"use strict";function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}function i(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(r){if("default"!==r&&!(r in e)){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}})}),Object.freeze(e)}var s=n(t),o=n(r),a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var d={exports:{}};d.exports=function(e){return(e instanceof Buffer?e:Buffer.from(e.toString(),"binary")).toString("base64")};var l,u,p=c(d.exports),h={},f={exports:{}};function m(){if(u)return l;u=1;var e=1e3,t=60*e,r=60*t,n=24*r,i=7*n,s=365.25*n;function o(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return l=function(a,c){c=c||{};var d=typeof a;if("string"===d&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*i;case"days":case"day":case"d":return c*n;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===d&&isFinite(a))return c.long?function(i){var s=Math.abs(i);if(s>=n)return o(i,s,n,"day");if(s>=r)return o(i,s,r,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=n)return Math.round(i/n)+"d";if(s>=r)return Math.round(i/r)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},l}var g=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n}),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,i=-1,s=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(i=n,s=r,n++):(r++,n++);else{if(-1===i)return!1;n=i+1,s++,r=s}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=m(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))}),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!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`."))}})(),t.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"],t.log=console.debug||console.log||(()=>{}),e.exports=g(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(f,f.exports);var v=f.exports,b={};Object.defineProperty(b,"__esModule",{value:!0});var y={},_=Object.defineProperty,w=Object.getOwnPropertyDescriptor,S=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,k={};((e,t)=>{for(var r in t)_(e,r,{get:t[r],enumerable:!0})})(k,{BrowserDetector:()=>I,KnownBrowsers:()=>R,KnownPlatforms:()=>E,default:()=>D});var T,P=(T=k,((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of S(t))!C.call(e,i)&&i!==r&&_(e,i,{get:()=>t[i],enumerable:!(n=w(t,i))||n.enumerable});return e})(_({},"__esModule",{value:!0}),T)),R={chrome:"Google Chrome",brave:"Brave",crios:"Google Chrome",edge:"Microsoft Edge",edg:"Microsoft Edge",edgios:"Microsoft Edge",fennec:"Mozilla Firefox",jsdom:"JsDOM",mozilla:"Mozilla Firefox",fxios:"Mozilla Firefox",msie:"Microsoft Internet Explorer",opera:"Opera",opios:"Opera",opr:"Opera",opt:"Opera",rv:"Microsoft Internet Explorer",safari:"Safari",samsungbrowser:"Samsung Browser",electron:"Electron"},E={android:"Android",androidTablet:"Android Tablet",cros:"Chrome OS",fennec:"Android Tablet",ipad:"IPad",ipod:"IPod",iphone:"IPhone",jsdom:"JsDOM",linux:"Linux",mac:"Macintosh",tablet:"Android Tablet",win:"Windows","windows phone":"Windows Phone",xbox:"Microsoft Xbox"},O=(e,t=-1)=>{let r=new RegExp(`^-?\\d+(?:.\\d{0,${t}})?`),n=Number(e).toString().match(r);return n?n[0]:null},x=()=>typeof window<"u"?window.navigator:null,I=class{userAgent;constructor(e){this.userAgent=e||x()?.userAgent||null}static get VERSION(){return"4.1.0"}parseUserAgent(e){let t={},r=e||this.userAgent||"",n=r.toLowerCase().replace(/\s\s+/g," "),i=/(edge)\/([\w.]+)/.exec(n)||/(edg)[/]([\w.]+)/.exec(n)||/(opr)[/]([\w.]+)/.exec(n)||/(opt)[/]([\w.]+)/.exec(n)||/(fxios)[/]([\w.]+)/.exec(n)||/(edgios)[/]([\w.]+)/.exec(n)||/(jsdom)[/]([\w.]+)/.exec(n)||/(samsungbrowser)[/]([\w.]+)/.exec(n)||/(electron)[/]([\w.]+)/.exec(n)||/(chrome)[/]([\w.]+)/.exec(n)||/(crios)[/]([\w.]+)/.exec(n)||/(opios)[/]([\w.]+)/.exec(n)||/(version)(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(webkit)[/]([\w.]+).*(version)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(n)||/(webkit)[/]([\w.]+)/.exec(n)||/(opera)(?:.*version|)[/]([\w.]+)/.exec(n)||/(msie) ([\w.]+)/.exec(n)||/(fennec)[/]([\w.]+)/.exec(n)||n.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(n)||n.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(n)||[],s=/(ipad)/.exec(n)||/(ipod)/.exec(n)||/(iphone)/.exec(n)||/(jsdom)/.exec(n)||/(windows phone)/.exec(n)||/(xbox)/.exec(n)||/(win)/.exec(n)||/(tablet)/.exec(n)||/(android)/.test(n)&&!1===/(mobile)/.test(n)&&["androidTablet"]||/(android)/.exec(n)||/(mac)/.exec(n)||/(linux)/.exec(n)||/(cros)/.exec(n)||[],o=i[5]||i[3]||i[1]||null,a=s[0]||null,c=i[4]||i[2]||null,d=x();"chrome"===o&&"function"==typeof d?.brave?.isBrave&&(o="brave"),o&&(t[o]=!0),a&&(t[a]=!0);let l=!!(t.tablet||t.android||t.androidTablet),u=!!(t.ipad||t.tablet||t.androidTablet),p=!!(t.android||t.androidTablet||t.tablet||t.ipad||t.ipod||t.iphone||t["windows phone"]),h=!!(t.cros||t.mac||t.linux||t.win),f=!!(t.brave||t.chrome||t.crios||t.opr||t.safari||t.edg||t.electron),m=!(!t.msie&&!t.rv),g=!(!t.chrome&&!t.crios),v=!!(t.fxios||t.fennec||t.mozilla),b=!!t.safari,y=!!(t.opera||t.opios||t.opr||t.opt),_=!!(t.edg||t.edge||t.edgios);return{name:R[o]??null,platform:E[a]??null,userAgent:r,version:c,shortVersion:c?O(parseFloat(c),2):null,isAndroid:l,isTablet:u,isMobile:p,isDesktop:h,isWebkit:f,isIE:m,isChrome:g,isFireFox:v,isSafari:b,isOpera:y,isEdge:_}}getBrowserInfo(){let e=this.parseUserAgent();return{name:e.name,platform:e.platform,userAgent:e.userAgent,version:e.version,shortVersion:e.shortVersion}}},D=I,M={};Object.defineProperty(M,"__esModule",{value:!0}),M.Logger=void 0;const j=v,A="mediasoup-client";M.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,j.default)(`${A}:${e}`),this._warn=(0,j.default)(`${A}:WARN:${e}`),this._error=(0,j.default)(`${A}:ERROR:${e}`)):(this._debug=(0,j.default)(A),this._warn=(0,j.default)(`${A}:WARN`),this._error=(0,j.default)(`${A}: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}};var L,N={},F={exports:{}},B="object"==typeof Reflect?Reflect:null,z=B&&"function"==typeof B.apply?B.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};L=B&&"function"==typeof B.ownKeys?B.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var U=Number.isNaN||function(e){return e!=e};function V(){V.init.call(this)}F.exports=V,F.exports.once=function(e,t){return new Promise(function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}X(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&X(e,"error",t,r)}(e,i,{once:!0})})},V.EventEmitter=V,V.prototype._events=void 0,V.prototype._eventsCount=0,V.prototype._maxListeners=void 0;var $=10;function G(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function q(e){return void 0===e._maxListeners?V.defaultMaxListeners:e._maxListeners}function H(e,t,r,n){var i,s,o;if(G(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=q(e))>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,function(e){console&&console.warn&&console.warn(e)}(a)}return e}function W(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function J(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=W.bind(n);return i.listener=r,n.wrapFn=i,i}function K(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):Y(i,i.length)}function Q(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function Y(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function X(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){n.once&&e.removeEventListener(t,i),r(s)})}}Object.defineProperty(V,"defaultMaxListeners",{enumerable:!0,get:function(){return $},set:function(e){if("number"!=typeof e||e<0||U(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");$=e}}),V.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},V.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||U(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},V.prototype.getMaxListeners=function(){return q(this)},V.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n="error"===e,i=this._events;if(void 0!==i)n=n&&void 0===i.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)z(a,this,t);else{var c=a.length,d=Y(a,c);for(r=0;r<c;++r)z(d[r],this,t)}return!0},V.prototype.addListener=function(e,t){return H(this,e,t,!1)},V.prototype.on=V.prototype.addListener,V.prototype.prependListener=function(e,t){return H(this,e,t,!0)},V.prototype.once=function(e,t){return G(t),this.on(e,J(this,e,t)),this},V.prototype.prependOnceListener=function(e,t){return G(t),this.prependListener(e,J(this,e,t)),this},V.prototype.removeListener=function(e,t){var r,n,i,s,o;if(G(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},V.prototype.off=V.prototype.removeListener,V.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},V.prototype.listeners=function(e){return K(this,e,!0)},V.prototype.rawListeners=function(e){return K(this,e,!1)},V.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Q.call(e,t)},V.prototype.listenerCount=Q,V.prototype.eventNames=function(){return this._eventsCount>0?L(this._events):[]};var Z=F.exports;Object.defineProperty(N,"__esModule",{value:!0}),N.EnhancedEventEmitter=void 0;const ee=Z,te=new M.Logger("EnhancedEventEmitter");class re extends ee.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(t){te.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,t);try{super.emit("listenererror",e,t)}catch(e){}return Boolean(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)}}N.EnhancedEventEmitter=re;var ne={};Object.defineProperty(ne,"__esModule",{value:!0}),ne.InvalidStateError=ne.UnsupportedError=void 0;class ie extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ie):this.stack=new Error(e).stack}}ne.UnsupportedError=ie;class se extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,se):this.stack=new Error(e).stack}}ne.InvalidStateError=se;var oe={};Object.defineProperty(oe,"__esModule",{value:!0}),oe.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},oe.generateRandomNumber=function(){return Math.round(1e7*Math.random())},oe.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const n of r){const r=t[n];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var ae={},ce={},de={},le=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(de,"__esModule",{value:!0}),de.Logger=void 0;const ue=le(v),pe="h264-profile-level-id";de.Logger=class{constructor(e){e?(this._debug=(0,ue.default)(`${pe}:${e}`),this._warn=(0,ue.default)(`${pe}:WARN:${e}`),this._error=(0,ue.default)(`${pe}:ERROR:${e}`)):(this._debug=(0,ue.default)(pe),this._warn=(0,ue.default)(`${pe}:WARN`),this._error=(0,ue.default)(`${pe}: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}},Object.defineProperty(ce,"__esModule",{value:!0}),ce.ProfileLevelId=ce.Level=ce.Profile=void 0,ce.parseProfileLevelId=Se,ce.profileLevelIdToString=Ce,ce.profileToString=function(e){switch(e){case fe.ConstrainedBaseline:return"ConstrainedBaseline";case fe.Baseline:return"Baseline";case fe.Main:return"Main";case fe.ConstrainedHigh:return"ConstrainedHigh";case fe.High:return"High";case fe.PredictiveHigh444:return"PredictiveHigh444";default:return void he.warn(`profileToString() | unrecognized profile ${e}`)}},ce.levelToString=function(e){switch(e){case me.L1_b:return"1b";case me.L1:return"1";case me.L1_1:return"1.1";case me.L1_2:return"1.2";case me.L1_3:return"1.3";case me.L2:return"2";case me.L2_1:return"2.1";case me.L2_2:return"2.2";case me.L3:return"3";case me.L3_1:return"3.1";case me.L3_2:return"3.2";case me.L4:return"4";case me.L4_1:return"4.1";case me.L4_2:return"4.2";case me.L5:return"5";case me.L5_1:return"5.1";case me.L5_2:return"5.2";default:return void he.warn(`levelToString() | unrecognized level ${e}`)}},ce.parseSdpProfileLevelId=ke,ce.isSameProfile=function(e={},t={}){const r=ke(e),n=ke(t);return Boolean(r&&n&&r.profile===n.profile)},ce.isSameProfileAndLevel=function(e={},t={}){const r=ke(e),n=ke(t);return Boolean(r&&n&&r.profile===n.profile&&r.level==n.level)},ce.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void he.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=ke(e),n=ke(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!n)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==n.profile)throw new TypeError("H264 Profile mismatch");const i=Pe(e)&&Pe(t),s=r.level,o=n.level,a=function(e,t){return function(e,t){if(e===me.L1_b)return t!==me.L1&&t!==me.L1_b;if(t===me.L1_b)return e!==me.L1;return e<t}(e,t)?e:t}(s,o),c=i?s:a;return he.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),Ce(new ge(r.profile,c))},ce.supportedLevel=function(e,t){for(let r=we.length-1;r>=0;--r){const n=we[r];if(256*n.max_macroblock_frame_size<=e&&n.max_macroblocks_per_second<=t*n.max_macroblock_frame_size)return he.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${n.level}]`),n.level}return void he.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const he=new de.Logger;var fe,me;!function(e){e[e.ConstrainedBaseline=1]="ConstrainedBaseline",e[e.Baseline=2]="Baseline",e[e.Main=3]="Main",e[e.ConstrainedHigh=4]="ConstrainedHigh",e[e.High=5]="High",e[e.PredictiveHigh444=6]="PredictiveHigh444"}(fe||(ce.Profile=fe={})),function(e){e[e.L1_b=0]="L1_b",e[e.L1=10]="L1",e[e.L1_1=11]="L1_1",e[e.L1_2=12]="L1_2",e[e.L1_3=13]="L1_3",e[e.L2=20]="L2",e[e.L2_1=21]="L2_1",e[e.L2_2=22]="L2_2",e[e.L3=30]="L3",e[e.L3_1=31]="L3_1",e[e.L3_2=32]="L3_2",e[e.L4=40]="L4",e[e.L4_1=41]="L4_1",e[e.L4_2=42]="L4_2",e[e.L5=50]="L5",e[e.L5_1=51]="L5_1",e[e.L5_2=52]="L5_2"}(me||(ce.Level=me={}));class ge{constructor(e,t){this.profile=e,this.level=t}}ce.ProfileLevelId=ge;const ve=new ge(fe.ConstrainedBaseline,me.L3_1);class be{constructor(e){this.mask=~Te("x",e),this.masked_value=Te("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class ye{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const _e=[new ye(66,new be("x1xx0000"),fe.ConstrainedBaseline),new ye(77,new be("1xxx0000"),fe.ConstrainedBaseline),new ye(88,new be("11xx0000"),fe.ConstrainedBaseline),new ye(66,new be("x0xx0000"),fe.Baseline),new ye(88,new be("10xx0000"),fe.Baseline),new ye(77,new be("0x0x0000"),fe.Main),new ye(100,new be("00000000"),fe.High),new ye(100,new be("00001100"),fe.ConstrainedHigh),new ye(244,new be("00000000"),fe.PredictiveHigh444)],we=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:me.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:me.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:me.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:me.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:me.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:me.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:me.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:me.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:me.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:me.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:me.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:me.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:me.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:me.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:me.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:me.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:me.L5_2}];function Se(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,n=t>>8&255,i=t>>16&255;let s;switch(r){case me.L1_1:s=16&n?me.L1_b:me.L1_1;break;case me.L1:case me.L1_2:case me.L1_3:case me.L2:case me.L2_1:case me.L2_2:case me.L3:case me.L3_1:case me.L3_2:case me.L4:case me.L4_1:case me.L4_2:case me.L5:case me.L5_1:case me.L5_2:s=r;break;default:return void he.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of _e)if(i===t.profile_idc&&t.profile_iop.isMatch(n))return he.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new ge(t.profile,s);he.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function Ce(e){if(e.level==me.L1_b)switch(e.profile){case fe.ConstrainedBaseline:return"42f00b";case fe.Baseline:return"42100b";case fe.Main:return"4d100b";default:return void he.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case fe.ConstrainedBaseline:t="42e0";break;case fe.Baseline:t="4200";break;case fe.Main:t="4d00";break;case fe.ConstrainedHigh:t="640c";break;case fe.High:t="6400";break;case fe.PredictiveHigh444:t="f400";break;default:return void he.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function ke(e={}){const t=e["profile-level-id"];return t?Se(t):ve}function Te(e,t){return Number(t[0]===e)<<7|Number(t[1]===e)<<6|Number(t[2]===e)<<5|Number(t[3]===e)<<4|Number(t[4]===e)<<3|Number(t[5]===e)<<2|Number(t[6]===e)<<1|Number(t[7]===e)}function Pe(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}Object.defineProperty(ae,"__esModule",{value:!0}),ae.validateAndNormalizeRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)Me(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)Ae(t)},ae.validateAndNormalizeRtpParameters=De,ae.validateAndNormalizeSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},ae.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},ae.getExtendedRtpCapabilities=function(e,t,r){const n={codecs:[],headerExtensions:[]};if(r)for(const r of e.codecs??[]){if(Be(r))continue;const e=(t.codecs??[]).find(e=>ze(e,r,{strict:!0,modify:!0}));if(!e)continue;const i={kind:r.kind,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,localPayloadType:r.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:e.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:r.parameters??{},remoteParameters:e.parameters??{},rtcpFeedback:Ve(r,e)};n.codecs.push(i)}else for(const r of t.codecs??[]){if(Be(r))continue;const t=(e.codecs??[]).find(e=>ze(e,r,{strict:!0,modify:!0}));if(!t)continue;const i={kind:t.kind,mimeType:t.mimeType,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:r.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters??{},remoteParameters:r.parameters??{},rtcpFeedback:Ve(t,r)};n.codecs.push(i)}for(const r of n.codecs){const n=e.codecs.find(e=>Be(e)&&e.parameters?.apt===r.localPayloadType),i=t.codecs.find(e=>Be(e)&&e.parameters?.apt===r.remotePayloadType);n&&i&&(r.localRtxPayloadType=n.preferredPayloadType,r.remoteRtxPayloadType=i.preferredPayloadType)}for(const r of t.headerExtensions){const t=e.headerExtensions.find(e=>Ue(e,r));if(!t)continue;const i={kind:r.kind,uri:r.uri,sendId:t.preferredId,recvId:r.preferredId,encrypt:t.preferredEncrypt??!1,direction:"sendrecv"};switch(r.direction){case"sendrecv":i.direction="sendrecv";break;case"recvonly":i.direction="sendonly";break;case"sendonly":i.direction="recvonly";break;case"inactive":i.direction="inactive"}n.headerExtensions.push(i)}return n},ae.getRecvRtpCapabilities=function(e){const t={codecs:[],headerExtensions:[]};for(const r of e.codecs){const e={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(e),!r.remoteRtxPayloadType)continue;const n={kind:r.kind,mimeType:`${r.kind}/rtx`,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(n)}for(const r of e.headerExtensions){if("sendrecv"!==r.direction&&"recvonly"!==r.direction)continue;const e={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt??!1,direction:r.direction};t.headerExtensions.push(e)}return t},ae.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},ae.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"goog-remb"!==e.type);else if(r.headerExtensions.some(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"transport-cc"!==e.type);else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"transport-cc"!==e.type&&"goog-remb"!==e.type);return r},ae.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(ze(e[n],t,{strict:!0})){r.push(e[n]),Be(e[n+1])&&r.push(e[n+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),Be(e[1])&&r.push(e[1]);return r},ae.generateProbatorRtpParameters=function(e){De(e=Ee.clone(e));const t={mid:Oe,codecs:[],headerExtensions:[],encodings:[{ssrc:xe}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=Ie,t.headerExtensions=e.headerExtensions,t},ae.canSend=function(e,t){return(t.codecs??[]).some(t=>t.kind===e)},ae.canReceive=function(e,t){if(De(e),0===e.codecs.length)return!1;const r=e.codecs[0];return(t.codecs??[]).some(e=>e.preferredPayloadType===r.payloadType)};const Re=ce,Ee=oe,Oe="probator",xe=1234,Ie=127;function De(e){if("object"!=typeof e)throw new TypeError("params is not an object");if(e.mid&&"string"!=typeof e.mid)throw new TypeError("params.mid is not a string");if(!Array.isArray(e.codecs))throw new TypeError("missing params.codecs");for(const t of e.codecs)Le(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("params.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)Ne(t);if(e.encodings&&!Array.isArray(e.encodings))throw new TypeError("params.encodings is not an array");e.encodings||(e.encodings=[]);for(const t of e.encodings)Fe(t);if(e.rtcp&&"object"!=typeof e.rtcp)throw new TypeError("params.rtcp is not an object");e.rtcp||(e.rtcp={}),function(e){if("object"!=typeof e)throw new TypeError("rtcp is not an object");if(e.cname&&"string"!=typeof e.cname)throw new TypeError("invalid rtcp.cname");e.reducedSize&&"boolean"==typeof e.reducedSize||(e.reducedSize=!0)}(e.rtcp)}function Me(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if(e.kind=r[1].toLowerCase(),"number"!=typeof e.preferredPayloadType)throw new TypeError("missing codec.preferredPayloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===e.kind?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)je(t)}function je(e){if("object"!=typeof e)throw new TypeError("fb is not an object");if(!e.type||"string"!=typeof e.type)throw new TypeError("missing fb.type");e.parameter&&"string"==typeof e.parameter||(e.parameter="")}function Ae(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if("audio"!==e.kind&&"video"!==e.kind)throw new TypeError("invalid ext.kind");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.preferredId)throw new TypeError("missing ext.preferredId");if(e.preferredEncrypt&&"boolean"!=typeof e.preferredEncrypt)throw new TypeError("invalid ext.preferredEncrypt");if(e.preferredEncrypt||(e.preferredEncrypt=!1),e.direction&&"string"!=typeof e.direction)throw new TypeError("invalid ext.direction");e.direction||(e.direction="sendrecv")}function Le(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if("number"!=typeof e.payloadType)throw new TypeError("missing codec.payloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===r[1].toLowerCase()?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)je(t)}function Ne(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.id)throw new TypeError("missing ext.id");if(e.encrypt&&"boolean"!=typeof e.encrypt)throw new TypeError("invalid ext.encrypt");e.encrypt||(e.encrypt=!1),e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError("invalid header extension parameter")}}function Fe(e){if("object"!=typeof e)throw new TypeError("encoding is not an object");if(e.ssrc&&"number"!=typeof e.ssrc)throw new TypeError("invalid encoding.ssrc");if(e.rid&&"string"!=typeof e.rid)throw new TypeError("invalid encoding.rid");if(e.rtx&&"object"!=typeof e.rtx)throw new TypeError("invalid encoding.rtx");if(e.rtx&&"number"!=typeof e.rtx.ssrc)throw new TypeError("missing encoding.rtx.ssrc");if(e.dtx&&"boolean"==typeof e.dtx||(e.dtx=!1),e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("invalid encoding.scalabilityMode")}function Be(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function ze(e,t,{strict:r=!1,modify:n=!1}={}){const i=e.mimeType.toLowerCase();if(i!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(i){case"video/h264":if(r){if((e.parameters["packetization-mode"]??0)!==(t.parameters["packetization-mode"]??0))return!1;if(!Re.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=Re.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}n&&(r?(e.parameters["profile-level-id"]=r,t.parameters["profile-level-id"]=r):(delete e.parameters["profile-level-id"],delete t.parameters["profile-level-id"]))}break;case"video/vp9":if(r){if((e.parameters["profile-id"]??0)!==(t.parameters["profile-id"]??0))return!1}}return!0}function Ue(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function Ve(e,t){const r=[];for(const n of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find(e=>e.type===n.type&&(e.parameter===n.parameter||!e.parameter&&!n.parameter));e&&r.push(e)}return r}var $e={},Ge={},qe={},He={};Object.defineProperty(He,"__esModule",{value:!0}),He.Logger=void 0;const We=v,Je="awaitqueue";He.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=We(`${Je}:${e}`),this._warn=We(`${Je}:WARN:${e}`),this._error=We(`${Je}:ERROR:${e}`)):(this._debug=We(Je),this._warn=We(`${Je}:WARN`),this._error=We(`${Je}: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}};var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.AwaitQueueRemovedTaskError=Ke.AwaitQueueStoppedError=void 0;class Qe extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Qe)}}Ke.AwaitQueueStoppedError=Qe;class Ye extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Ye)}}Ke.AwaitQueueRemovedTaskError=Ye,Object.defineProperty(qe,"__esModule",{value:!0}),qe.AwaitQueue=void 0;const Xe=Ke,Ze=new He.Logger("AwaitQueue");qe.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;stopping=!1;constructor(){Ze.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,Ze.debug(`push() [name:${t}]`),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise((r,n)=>{const i={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(i.completed)return;i.completed=!0,this.pendingTasks.delete(i.id),Ze.debug(`resolving task [name:${i.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!i.completed&&(i.completed=!0,this.pendingTasks.delete(i.id),Ze.debug(`rejecting task [name:${i.name}]: %s`,String(e)),n(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(i.id,i),1===this.pendingTasks.size&&this.execute(i)})}stop(){Ze.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Ze.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Xe.AwaitQueueStoppedError);this.stopping=!1}remove(e){Ze.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Xe.AwaitQueueRemovedTaskError):Ze.debug(`stop() | no task with given idx [taskIdx:${e}]`)}dump(){const e=Date.now();let 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(Ze.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=qe;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Ke;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(Ge);var et={};Object.defineProperty(et,"__esModule",{value:!0}),et.Producer=void 0;const tt=N,rt=ne,nt=new M.Logger("Producer");class it extends tt.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new tt.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),nt.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=n,this._kind=n.kind,this._rtpParameters=i,this._paused=!!o&&!n.enabled,this._maxSpatialLayer=void 0,this._stopTracks=s,this._disableTrackOnPause=o,this._zeroRtpOnPause=a,this._appData=c??{},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||(nt.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(nt.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new rt.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){nt.debug("pause()"),this._closed?nt.error("pause() | Producer closed"):(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(){nt.debug("resume()"),this._closed?nt.error("resume() | Producer closed"):(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(nt.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new rt.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new rt.InvalidStateError("track ended");e!==this._track?(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()):nt.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new rt.InvalidStateError("closed");if("video"!==this._kind)throw new rt.UnsupportedError("not a video Producer");if("number"!=typeof e)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 rt.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)})}onTrackEnded(){nt.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(e){}}}et.Producer=it;var st={};Object.defineProperty(st,"__esModule",{value:!0}),st.Consumer=void 0;const ot=N,at=ne,ct=new M.Logger("Consumer");class dt extends ot.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new ot.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:s,appData:o}){super(),ct.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=n,this._track=i,this._rtpParameters=s,this._paused=!i.enabled,this._appData=o??{},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||(ct.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(ct.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new at.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){ct.debug("pause()"),this._closed?ct.error("pause() | Consumer closed"):this._paused?ct.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){ct.debug("resume()"),this._closed?ct.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):ct.debug("resume() | Consumer is already resumed")}onTrackEnded(){ct.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(e){}}}st.Consumer=dt;var lt={};Object.defineProperty(lt,"__esModule",{value:!0}),lt.DataProducer=void 0;const ut=N,pt=ne,ht=new M.Logger("DataProducer");class ft extends ut.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new ut.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),ht.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=n??{},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||(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"))}send(e){if(ht.debug("send()"),this._closed)throw new pt.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(ht.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;const t=e.error??new Error("unknown DataChannel error");"sctp-failure"===e.error?.errorDetail?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",()=>{this._closed||ht.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}}lt.DataProducer=ft;var mt={};Object.defineProperty(mt,"__esModule",{value:!0}),mt.DataConsumer=void 0;const gt=N,vt=new M.Logger("DataConsumer");class bt extends gt.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new gt.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),vt.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=n,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||(vt.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(vt.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(vt.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;const t=e.error??new Error("unknown DataChannel error");"sctp-failure"===e.error?.errorDetail?vt.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):vt.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(vt.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)})}}mt.DataConsumer=bt,Object.defineProperty($e,"__esModule",{value:!0}),$e.Transport=void 0;const yt=Ge,_t=N,wt=ne,St=oe,Ct=ae,kt=et,Tt=st,Pt=lt,Rt=mt,Et=new M.Logger("Transport");class Ot{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}let xt=class extends _t.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 yt.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new _t.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d,handlerFactory:l,getSendExtendedRtpCapabilities:u,recvRtpCapabilities:p,canProduceByKind:h}){super(),Et.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=u,this._recvRtpCapabilities=p,this._canProduceByKind=h,this._maxSctpMessageSize=s?s.maxMessageSize:null;const f=St.clone(c)??{};delete f.iceServers,delete f.iceTransportPolicy,delete f.bundlePolicy,delete f.rtcpMuxPolicy,this._handler=l.factory({direction:e,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:f,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){Et.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(const e of this._producers.values())e.transportClosed();this._producers.clear();for(const e of this._consumers.values())e.transportClosed();this._consumers.clear();for(const e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(const 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 wt.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(Et.debug("restartIce()"),this._closed)throw new wt.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(Et.debug("updateIceServers()"),this._closed)throw new wt.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,encodings:t,codecOptions:r,codec:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,onRtpSender:a,appData:c={}}={}){if(Et.debug("produce() [track:%o]",e),this._closed)throw new wt.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new wt.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new wt.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new wt.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(c&&"object"!=typeof c)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push(async()=>{let d;if(t&&!Array.isArray(t))throw TypeError("encodings must be an array");t&&0===t.length?d=void 0:t&&(d=t.map(e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t}));const{localId:l,rtpParameters:u,rtpSender:p}=await this._handler.send({track:e,encodings:d,codecOptions:r,codec:n,onRtpSender:a});try{Ct.validateAndNormalizeRtpParameters(u);const{id:t}=await new Promise((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:u,appData:c},t,r)}),r=new kt.Producer({id:t,localId:l,rtpSender:p,track:e,rtpParameters:u,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,appData:c});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(l).catch(()=>{}),e}},"transport.produce()").catch(t=>{if(i)try{e.stop()}catch(e){}throw t})}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:s,appData:o={}}){if(Et.debug("consume()"),this._closed)throw new wt.InvalidStateError("closed");if("recv"!==this._direction)throw new wt.UnsupportedError("not a receiving Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing producerId");if("audio"!==r&&"video"!==r)throw new TypeError(`invalid kind '${r}'`);if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");const a=St.clone(n);if(!Ct.canReceive(a,this._recvRtpCapabilities))throw new wt.UnsupportedError("cannot consume this Producer");const c=new Ot({id:e,producerId:t,kind:r,rtpParameters:a,streamId:i,onRtpReceiver:s,appData:o});return this._pendingConsumerTasks.push(c),queueMicrotask(()=>{this._closed||!1===this._consumerCreationInProgress&&this.createPendingConsumers()}),c.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:n="",protocol:i="",appData:s={}}={}){if(Et.debug("produceData()"),this._closed)throw new wt.InvalidStateError("closed");if("send"!==this._direction)throw new wt.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new wt.UnsupportedError("SCTP not enabled by remote Transport");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("producedata"))throw new TypeError('no "producedata" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");return(t||r)&&(e=!1),this._awaitQueue.push(async()=>{const{dataChannel:o,sctpStreamParameters:a}=await this._handler.sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i});Ct.validateAndNormalizeSctpStreamParameters(a);const{id:c}=await new Promise((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:n,protocol:i,appData:s},e,t)}),d=new Pt.DataProducer({id:c,dataChannel:o,sctpStreamParameters:a,appData:s});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:n="",protocol:i="",appData:s={}}){if(Et.debug("consumeData()"),this._closed)throw new wt.InvalidStateError("closed");if("recv"!==this._direction)throw new wt.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new wt.UnsupportedError("SCTP not enabled by remote Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing dataProducerId");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");const o=St.clone(r);return Ct.validateAndNormalizeSctpStreamParameters(o),this._awaitQueue.push(async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:n,protocol:i}),a=new Rt.DataConsumer({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:o,appData:s});return this._dataConsumers.set(a.id,a),this.handleDataConsumer(a),this._observer.safeEmit("newdataconsumer",a),a},"transport.consumeData()")}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingConsumerTasks.length)return void Et.debug("createPendingConsumers() | there is no Consumer to be created");const e=[...this._pendingConsumerTasks];let t;this._pendingConsumerTasks=[];const r=[];for(const t of e){const{id:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o})}try{const n=await this._handler.receive(r);for(let r=0;r<n.length;++r){const i=e[r],s=n[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:l}=i.consumerOptions,{localId:u,rtpReceiver:p,track:h}=s,f=new Tt.Consumer({id:o,localId:u,producerId:a,rtpReceiver:p,track:h,rtpParameters:d,appData:l});this._consumers.set(f.id,f),this.handleConsumer(f),this._probatorConsumerCreated||t||"video"!==c||(t=f),this._observer.safeEmit("newconsumer",f),i.resolve(f)}}catch(t){for(const r of e)r.reject(t)}if(t)try{const e=Ct.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),Et.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){Et.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",e)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingPauseConsumers.size)return void Et.debug("pausePendingConsumers() | there is no Consumer to be paused");const e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{const t=e.map(e=>e.localId);await this._handler.pauseReceiving(t)}catch(e){Et.error("pausePendingConsumers() | failed to pause Consumers:",e)}},"transport.pausePendingConsumers").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingResumeConsumers.size)return void Et.debug("resumePendingConsumers() | there is no Consumer to be resumed");const e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{const t=e.map(e=>e.localId);await this._handler.resumeReceiving(t)}catch(e){Et.error("resumePendingConsumers() | failed to resume Consumers:",e)}},"transport.resumePendingConsumers").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingCloseConsumers.size)return void Et.debug("closePendingConsumers() | there is no Consumer to be closed");const e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(e=>e.localId))}catch(e){Et.error("closePendingConsumers() | failed to close Consumers:",e)}},"transport.closePendingConsumers").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){const e=this._handler;e.on("@connect",({dtlsParameters:e},t,r)=>{this._closed?r(new wt.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)}),e.on("@icegatheringstatechange",e=>{e!==this._iceGatheringState&&(Et.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))}),e.on("@icecandidateerror",e=>{Et.warn(`ICE candidate error [url:${e.url}, localAddress:${e.address}, localPort:${e.port}]: ${e.errorCode} "${e.errorText}"`),this.safeEmit("icecandidateerror",e)}),e.on("@connectionstatechange",e=>{e!==this._connectionState&&(Et.debug("connection state changed to %s",e),this._connectionState=e,this._closed||this.safeEmit("connectionstatechange",e))})}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(e=>Et.warn("producer.close() failed:%o",e))}),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,n)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(r).catch(n)}),e.on("@setmaxspatiallayer",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(r).catch(n)}),e.on("@setrtpencodingparameters",(t,r,n)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(r).catch(n)}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new wt.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),!1===this._consumerCloseInProgress&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||!1===this._consumerPauseInProgress&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()})}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new wt.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)})}};$e.Transport=xt;var It={},Dt={},Mt={},jt={exports:{}},At=jt.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"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(e){return null!=e.subtype?"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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"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"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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(e){return null!=e.maxMessageSize?"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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{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(At).forEach(function(e){At[e].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})});var Lt=jt.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=Lt,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach(function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(i))return r(c,o,i)}}),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var r,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}})})}}(Mt);var Nt=Lt,Ft=/%[sdv%]/g,Bt=function(e){var t=1,r=arguments,n=r.length;return e.replace(Ft,function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},zt=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return Bt.apply(null,n)},Ut=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Vt=["i","c","b","a"],$t=Mt,Gt=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var r=t.outerOrder||Ut,n=t.innerOrder||Vt,i=[];return r.forEach(function(t){Nt[t].forEach(function(r){r.name in e&&null!=e[r.name]?i.push(zt(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){i.push(zt(t,r,e))})})}),e.media.forEach(function(e){i.push(zt("m",Nt.m[0],e)),n.forEach(function(t){Nt[t].forEach(function(r){r.name in e&&null!=e[r.name]?i.push(zt(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){i.push(zt(t,r,e))})})})}),i.join("\r\n")+"\r\n"},qt=Lt;Dt.grammar=qt;var Ht=Dt.write=Gt,Wt=Dt.parse=$t.parse;Dt.parseParams=$t.parseParams,Dt.parseFmtpConfig=$t.parseFmtpConfig,Dt.parsePayloads=$t.parsePayloads,Dt.parseRemoteCandidates=$t.parseRemoteCandidates,Dt.parseImageAttributes=$t.parseImageAttributes,Dt.parseSimulcastStreamList=$t.parseSimulcastStreamList;var Jt={};Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.parse=function(e){const t=Kt.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const Kt=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var Qt={};Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=new Map;for(const n of e.media){const e=n.type;switch(e){case"audio":case"video":break;default:continue}for(const r of n.rtp){const n={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(n.preferredPayloadType,n)}for(const e of n.fmtp??[]){const r=Yt.parseParams(e.config),n=t.get(e.payload);n&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),n.parameters=r)}for(const r of n.rtcpFb??[]){const n={type:r.type,parameter:r.subtype};if(n.parameter||delete n.parameter,"*"!==r.payload){const e=t.get(Number(r.payload));if(!e)continue;e.rtcpFeedback.push(n)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(n)}for(const t of n.ext??[]){if(t["encrypt-uri"])continue;const n={kind:e,uri:t.uri,preferredId:t.value};r.set(n.preferredId,n)}}return{codecs:Array.from(t.values()),headerExtensions:Array.from(r.values())}},Qt.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,n=e.fingerprint;if(!r||!n){const t=(e.media??[]).find(e=>0!==e.port);t&&(r??=t.setup,n??=t.fingerprint)}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!n)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:n.type,value:n.hash}]}},Qt.getCname=function({offerMediaObject:e}){const t=(e.ssrcs??[]).find(e=>"cname"===e.attribute);if(!t)return"";return t.value},Qt.applyCodecParameters=function({offerRtpParameters:e,answerMediaObject:t}){for(const r of e.codecs){const e=r.mimeType.toLowerCase();if("audio/opus"!==e)continue;if(!(t.rtp??[]).find(e=>e.payload===r.payloadType))continue;t.fmtp=t.fmtp??[];let n=t.fmtp.find(e=>e.payload===r.payloadType);n||(n={payload:r.payloadType,config:""},t.fmtp.push(n));const i=Yt.parseParams(n.config);switch(e){case"audio/opus":{const e=r.parameters?.["sprop-stereo"];void 0!==e&&(i.stereo=Number(e)?1:0);break}}n.config="";for(const e of Object.keys(i))n.config&&(n.config+=";"),n.config+=`${e}=${i[e]}`}};const Yt=Dt;var Xt={};Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.getRtpEncodings=function({offerMediaObject:e}){const t=new Set;for(const r of e.ssrcs??[]){const e=r.id;e&&t.add(e)}if(0===t.size)throw new Error("no a=ssrc lines found");const r=new Map;for(const n of e.ssrcGroups??[]){if("FID"!==n.semantics)continue;const e=n.ssrcs.split(/\s+/),i=Number(e[0]),s=Number(e[1]);t.has(i)&&(t.delete(i),t.delete(s),r.set(i,s))}for(const e of t)r.set(e,void 0);const n=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},Xt.addLegacySimulcast=function({offerMediaObject:e,numStreams:t}){if(t<=1)throw new TypeError("numStreams must be greater than 1");const r=(e.ssrcs??[]).find(e=>"msid"===e.attribute);if(!r)throw new Error("a=ssrc line with msid information not found");const[n,i]=r.value.split(" "),s=Number(r.id);let o;(e.ssrcGroups??[]).some(e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===s&&(o=Number(t[1]),!0)});const a=(e.ssrcs??[]).find(e=>"cname"===e.attribute);if(!a)throw new Error("a=ssrc line with cname information not found");const c=a.value,d=[],l=[];for(let e=0;e<t;++e)d.push(s+e),o&&l.push(o+e);e.ssrcGroups=[],e.ssrcs=[],e.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(const t of d)e.ssrcs.push({id:t,attribute:"cname",value:c}),e.ssrcs.push({id:t,attribute:"msid",value:`${n} ${i}`});for(let t=0;t<l.length;++t){const r=d[t],s=l[t];e.ssrcs.push({id:s,attribute:"cname",value:c}),e.ssrcs.push({id:s,attribute:"msid",value:`${n} ${i}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var Zt={};Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.addNackSupportForOpus=function(e){for(const t of e.codecs??[])"audio/opus"!==t.mimeType.toLowerCase()&&"audio/multiopus"!==t.mimeType.toLowerCase()||t.rtcpFeedback?.some(e=>"nack"===e.type&&!e.parameter)||(t.rtcpFeedback||(t.rtcpFeedback=[]),t.rtcpFeedback.push({type:"nack"}))};var er={},tr={};Object.defineProperty(tr,"__esModule",{value:!0}),tr.OfferMediaSection=tr.AnswerMediaSection=tr.MediaSection=void 0;const rr=Dt,nr=oe;class ir{_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(const e of t){const t={foundation:e.foundation,component:1,ip:e.address??e.ip,port:e.port,priority:e.priority,transport:e.protocol,type:e.type};e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}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 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause(),delete this._mediaObject.ext,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}close(){this.disable(),this._mediaObject.port=0}}tr.MediaSection=ir;tr.AnswerMediaSection=class extends ir{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,offerMediaObject:s,offerRtpParameters:o,answerRtpParameters:a,codecOptions:c}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s.mid),this._mediaObject.type=s.type,this._mediaObject.protocol=s.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),s.type){case"audio":case"video":this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(const e of a.codecs){const t={payload:e.payloadType,codec:sr(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=nr.clone(e.parameters)??{};let n=nr.clone(e.rtcpFeedback)??[];if(c){const{opusStereo:t,opusFec:i,opusDtx:s,opusMaxPlaybackRate:a,opusMaxAverageBitrate:d,opusPtime:l,opusNack:u,videoGoogleStartBitrate:p,videoGoogleMaxBitrate:h,videoGoogleMinBitrate:f}=c,m=o.codecs.find(t=>t.payloadType===e.payloadType);switch(e.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":void 0!==t&&(m.parameters["sprop-stereo"]=t?1:0,r.stereo=t?1:0),void 0!==i&&(m.parameters.useinbandfec=i?1:0,r.useinbandfec=i?1:0),void 0!==s&&(m.parameters.usedtx=s?1:0,r.usedtx=s?1:0),void 0!==a&&(r.maxplaybackrate=a),void 0!==d&&(r.maxaveragebitrate=d),void 0!==l&&(m.parameters.ptime=l,r.ptime=l),u||(m.rtcpFeedback=m.rtcpFeedback.filter(e=>"nack"!==e.type||e.parameter),n=n.filter(e=>"nack"!==e.type||e.parameter));break;case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":void 0!==p&&(r["x-google-start-bitrate"]=p),void 0!==h&&(r["x-google-max-bitrate"]=h),void 0!==f&&(r["x-google-min-bitrate"]=f)}}const i={payload:e.payloadType,config:""};for(const e of Object.keys(r))i.config&&(i.config+=";"),i.config+=`${e}=${r[e]}`;i.config&&this._mediaObject.fmtp.push(i);for(const t of n)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=a.codecs.map(e=>e.payloadType).join(" "),this._mediaObject.ext=[];for(const e of a.headerExtensions){(s.ext??[]).some(t=>t.uri===e.uri)&&this._mediaObject.ext.push({uri:e.uri,value:e.id})}if("extmap-allow-mixed"===s.extmapAllowMixed&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),s.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:s.simulcast.list1},this._mediaObject.rids=[];for(const e of s.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}else if(s.simulcast_03){this._mediaObject.simulcast_03={value:s.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(const e of s.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break;case"application":"number"==typeof s.sctpPort?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):s.sctpmap&&(this._mediaObject.payloads=String(n.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize})}}setDtlsRole(e){switch(e){case"client":this._mediaObject.setup="active";break;case"server":this._mediaObject.setup="passive";break;case"auto":this._mediaObject.setup="actpass"}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;const t={};for(const r of e)r.rid&&(t[r.rid]=r);const r=this._mediaObject.simulcast.list1,n=rr.parseSimulcastStreamList(r);for(const e of n)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=n.map(e=>e.map(e=>`${e.paused?"~":""}${e.scid}`).join(",")).join(";")}};function sr(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}tr.OfferMediaSection=class extends ir{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,mid:s,kind:o,offerRtpParameters:a,streamId:c,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r}),this._mediaObject.mid=String(s),this._mediaObject.type=o,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},this._mediaObject.protocol=n?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",o){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=`${c??"-"} ${d}`;for(const e of a.codecs){const t={payload:e.payloadType,codec:sr(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r={payload:e.payloadType,config:""};for(const t of Object.keys(e.parameters??{}))r.config&&(r.config+=";"),r.config+=`${t}=${e.parameters[t]}`;r.config&&this._mediaObject.fmtp.push(r);for(const t of e.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=a.codecs.map(e=>e.payloadType).join(" "),this._mediaObject.ext=[];for(const e of a.headerExtensions)this._mediaObject.ext.push({uri:e.uri,value:e.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";const e=a.encodings[0],t=e.ssrc,r=e.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],t&&a.rtcp.cname&&this._mediaObject.ssrcs.push({id:t,attribute:"cname",value:a.rtcp.cname}),r&&(a.rtcp.cname&&this._mediaObject.ssrcs.push({id:r,attribute:"cname",value:a.rtcp.cname}),t&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${t} ${r}`}));break}case"application":this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}},Object.defineProperty(er,"__esModule",{value:!0}),er.RemoteSdp=void 0;const or=Dt,ar=tr,cr=["av1","h264"],dr=new M.Logger("RemoteSdp");er.RemoteSdp=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:"mediasoup-client"},name:"-",timing:{start:0,stop:0},media:[]},e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){dr.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(const t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){dr.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){dr.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){const 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:n,codecOptions:i}){const s=new ar.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i}),o=s.getObject();o.rtp.find(e=>cr.includes(e.codec.toLowerCase()))||(o.ext=o.ext?.filter(e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"!==e.uri)),t?this._replaceMediaSection(s,t):this._midToIndex.has(s.mid)?this._replaceMediaSection(s):this._addMediaSection(s)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}){this.setSessionExtmapAllowMixed();const s=new ar.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i}),o=this._mediaSections.find(e=>e.closed);o?this._replaceMediaSection(s,o.mid):this._addMediaSection(s)}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){const t=this._findMediaSection(e);return e===this._firstMid?(dr.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){const r=this._findMediaSection(e);r.muxSimulcastStreams(t),this._replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){const t=new ar.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this._addMediaSection(t)}receiveSctpAssociation(){const e=new ar.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++,or.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("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this._regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}_findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)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(" "))}},Object.defineProperty(It,"__esModule",{value:!0}),It.Chrome111=void 0;const lr=Dt,ur=N,pr=ae,hr=ne,fr=Jt,mr=Qt,gr=Xt,vr=Zt,br=er,yr=new M.Logger("Chrome111"),_r="Chrome111",wr={OS:1024,MIS:1024};class Sr extends ur.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:_r,factory:e=>new Sr(e),getNativeRtpCapabilities:async()=>{yr.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video",{sendEncodings:[{scalabilityMode:"L3T3"}]});const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=lr.parse(t.sdp);return Sr.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(yr.debug("getNativeSctpCapabilities()"),{numStreams:wr})}}static getLocalRtpCapabilities(e){const t=mr.extractRtpCapabilities({sdpObject:e});return pr.validateAndNormalizeRtpCapabilities(t),vr.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),yr.debug("constructor()"),this._direction=e,this._remoteSdp=new br.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(yr.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return _r}close(){if(yr.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}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(),yr.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),yr.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});yr.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();yr.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){if(this.assertNotClosed(),this.assertSendDirection(),yr.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1){let e=1;for(const r of t){const t=r.scalabilityMode?(0,fr.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`})}const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(o.sender);const a=await this._pc.createOffer();let c=lr.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=Sr.getLocalRtpCapabilities(c),l=this._getSendExtendedRtpCapabilities(d),u=pr.getSendingRtpParameters(e.kind,l);u.codecs=pr.reduceCodecs(u.codecs,n);const p=pr.getSendingRemoteRtpParameters(e.kind,l);p.codecs=pr.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c}),yr.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const h=o.mid;u.mid=h,c=lr.parse(this._pc.localDescription.sdp);const f=c.media[s.idx];if(u.rtcp.cname=mr.getCname({offerMediaObject:f}),t)if(1===t.length){const e=gr.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),u.encodings=e}else u.encodings=t;else u.encodings=gr.getRtpEncodings({offerMediaObject:f});this._remoteSdp.send({offerMediaObject:f,reuseMid:s.reuseMid,offerRtpParameters:u,answerRtpParameters:p,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return yr.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(h,o),{localId:h,rtpParameters:u,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),yr.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();yr.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),yr.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();yr.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),yr.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();yr.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?yr.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):yr.debug("replaceTrack() [localId:%s, no track]",e);const 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(),yr.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();yr.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),yr.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();yr.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};yr.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%wr.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=lr.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),yr.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};yr.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;yr.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=lr.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find(e=>String(e.mid)===i);mr.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:lr.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),yr.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){yr.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();yr.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){yr.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();yr.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){yr.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();yr.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};yr.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};yr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=lr.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}yr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=lr.parse(this._pc.localDescription.sdp));const r=mr.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new hr.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}It.Chrome111=Sr;var Cr={};Object.defineProperty(Cr,"__esModule",{value:!0}),Cr.Chrome74=void 0;const kr=Dt,Tr=N,Pr=ae,Rr=ne,Er=Jt,Or=Qt,xr=Xt,Ir=Zt,Dr=er,Mr=new M.Logger("Chrome74"),jr="Chrome74",Ar={OS:1024,MIS:1024};class Lr extends Tr.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:jr,factory:e=>new Lr(e),getNativeRtpCapabilities:async()=>{Mr.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=kr.parse(t.sdp);return Lr.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(Mr.debug("getNativeSctpCapabilities()"),{numStreams:Ar})}}static getLocalRtpCapabilities(e){const t=Or.extractRtpCapabilities({sdpObject:e});return Pr.validateAndNormalizeRtpCapabilities(t),Ir.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Mr.debug("constructor()"),this._direction=e,this._remoteSdp=new Dr.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Mr.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return jr}close(){if(Mr.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}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(),Mr.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Mr.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Mr.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Mr.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n}){this.assertNotClosed(),this.assertSendDirection(),Mr.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const i=this._remoteSdp.getNextMediaSectionIdx(),s=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let o=await this._pc.createOffer(),a=kr.parse(o.sdp);a.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const c=Lr.getLocalRtpCapabilities(a),d=this._getSendExtendedRtpCapabilities(c),l=Pr.getSendingRtpParameters(e.kind,d);l.codecs=Pr.reduceCodecs(l.codecs,n);const u=Pr.getSendingRemoteRtpParameters(e.kind,d);u.codecs=Pr.reduceCodecs(u.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:a});let p=!1;const h=(0,Er.parse)((t??[{}])[0].scalabilityMode);let f;t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===l.codecs[0].mimeType.toLowerCase()&&(Mr.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,a=kr.parse(o.sdp),f=a.media[i.idx],xr.addLegacySimulcast({offerMediaObject:f,numStreams:h.spatialLayers}),o={type:"offer",sdp:kr.write(a)}),Mr.debug("send() | calling pc.setLocalDescription() [offer:%o]",o),await this._pc.setLocalDescription(o);const m=s.mid;if(l.mid=m,a=kr.parse(this._pc.localDescription.sdp),f=a.media[i.idx],l.rtcp.cname=Or.getCname({offerMediaObject:f}),t)if(1===t.length){let e=xr.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),p&&(e=[e[0]]),l.encodings=e}else l.encodings=t;else l.encodings=xr.getRtpEncodings({offerMediaObject:f});if(l.encodings.length>1&&("video/vp8"===l.codecs[0].mimeType.toLowerCase()||"video/h264"===l.codecs[0].mimeType.toLowerCase()))for(const e of l.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,reuseMid:i.reuseMid,offerRtpParameters:l,answerRtpParameters:u,codecOptions:r});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return Mr.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(m,s),{localId:m,rtpParameters:l,rtpSender:s.sender}}async stopSending(e){if(this.assertSendDirection(),Mr.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Mr.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Mr.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Mr.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Mr.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Mr.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Mr.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Mr.debug("replaceTrack() [localId:%s, no track]",e);const 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(),Mr.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Mr.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Mr.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Mr.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Mr.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ar.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=kr.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Mr.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Mr.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;Mr.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=kr.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find(e=>String(e.mid)===i);Or.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:kr.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Mr.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Mr.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mr.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Mr.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mr.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Mr.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mr.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Mr.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Mr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=kr.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Mr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=kr.parse(this._pc.localDescription.sdp));const r=Or.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new Rr.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Cr.Chrome74=Lr;var Nr={};Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.Firefox120=void 0;const Fr=Dt,Br=N,zr=ne,Ur=ae,Vr=Jt,$r=Qt,Gr=Xt,qr=er,Hr=new M.Logger("Firefox120"),Wr="Firefox120",Jr={OS:16,MIS:2048};class Kr extends Br.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Wr,factory:e=>new Kr(e),getNativeRtpCapabilities:async()=>{Hr.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});const t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"}),e.addTransceiver(r,{direction:"sendrecv",sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const n=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}e=void 0;const i=Fr.parse(n.sdp);return Kr.getLocalRtpCapabilities(i)}catch(n){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e?.close()}catch(e){}throw e=void 0,n}},getNativeSctpCapabilities:async()=>(Hr.debug("getNativeSctpCapabilities()"),{numStreams:Jr})}}static getLocalRtpCapabilities(e){const t=$r.extractRtpCapabilities({sdpObject:e});return Ur.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),Hr.debug("constructor()"),this._direction=e,this._remoteSdp=new qr.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(Hr.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Wr}close(){if(Hr.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}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 zr.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Hr.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Hr.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Hr.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),Hr.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const s=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(s.sender);const o=await this._pc.createOffer();let a=Fr.parse(o.sdp);a.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const c=Kr.getLocalRtpCapabilities(a),d=this._getSendExtendedRtpCapabilities(c),l=Ur.getSendingRtpParameters(e.kind,d);l.codecs=Ur.reduceCodecs(l.codecs,n);const u=Ur.getSendingRemoteRtpParameters(e.kind,d);u.codecs=Ur.reduceCodecs(u.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:a});const p=(0,Vr.parse)((t??[{}])[0].scalabilityMode);Hr.debug("send() | calling pc.setLocalDescription() [offer:%o]",o),await this._pc.setLocalDescription(o);const h=s.mid;l.mid=h,a=Fr.parse(this._pc.localDescription.sdp);const f=a.media[a.media.length-1];if(l.rtcp.cname=$r.getCname({offerMediaObject:f}),t)if(1===t.length){const e=Gr.getRtpEncodings({offerMediaObject:f});Object.assign(e[0],t[0]),l.encodings=e}else l.encodings=t;else l.encodings=Gr.getRtpEncodings({offerMediaObject:f});if(l.encodings.length>1&&("video/vp8"===l.codecs[0].mimeType.toLowerCase()||"video/h264"===l.codecs[0].mimeType.toLowerCase()))for(const e of l.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:f,offerRtpParameters:l,answerRtpParameters:u,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Hr.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(h,s),{localId:h,rtpParameters:l,rtpSender:s.sender}}async stopSending(e){if(this.assertSendDirection(),Hr.debug("stopSending() [localId:%s]",e),this._closed)return;const 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);const r=await this._pc.createOffer();Hr.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Hr.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Hr.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Hr.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Hr.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Hr.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Hr.debug("replaceTrack() [localId:%s, no track]",e);const 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(),Hr.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Hr.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Hr.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Hr.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Hr.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Jr.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Fr.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Hr.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Hr.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;Hr.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Fr.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,o=r.get(e),a=s.media.find(e=>String(e.mid)===o);$r.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:Fr.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Hr.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Hr.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hr.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hr.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hr.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Hr.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Hr.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Hr.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Hr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Fr.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Hr.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Fr.parse(this._pc.localDescription.sdp));const r=$r.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new zr.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Nr.Firefox120=Kr;var Qr={};Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.Safari12=void 0;const Yr=Dt,Xr=N,Zr=ae,en=ne,tn=Jt,rn=er,nn=Qt,sn=Xt,on=Zt,an=new M.Logger("Safari12"),cn="Safari12",dn={OS:1024,MIS:1024};class ln extends Xr.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:cn,factory:e=>new ln(e),getNativeRtpCapabilities:async()=>{an.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=Yr.parse(t.sdp);return ln.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(an.debug("getNativeSctpCapabilities()"),{numStreams:dn})}}static getLocalRtpCapabilities(e){const t=nn.extractRtpCapabilities({sdpObject:e});return Zr.validateAndNormalizeRtpCapabilities(t),on.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),an.debug("constructor()"),this._direction=e,this._remoteSdp=new rn.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",e=>{this.emit("@icecandidateerror",e)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(an.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return cn}close(){if(an.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch(e){}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(),an.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),an.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});an.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();an.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),an.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});i&&i(o.sender);let a=await this._pc.createOffer(),c=Yr.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=ln.getLocalRtpCapabilities(c),l=this._getSendExtendedRtpCapabilities(d),u=Zr.getSendingRtpParameters(e.kind,l);u.codecs=Zr.reduceCodecs(u.codecs,n);const p=Zr.getSendingRemoteRtpParameters(e.kind,l);let h;p.codecs=Zr.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c});const f=(0,tn.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(an.debug("send() | enabling legacy simulcast"),c=Yr.parse(a.sdp),h=c.media[s.idx],sn.addLegacySimulcast({offerMediaObject:h,numStreams:t.length}),a={type:"offer",sdp:Yr.write(c)}),an.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const m=o.mid;if(u.mid=m,c=Yr.parse(this._pc.localDescription.sdp),h=c.media[s.idx],u.rtcp.cname=nn.getCname({offerMediaObject:h}),u.encodings=sn.getRtpEncodings({offerMediaObject:h}),t)for(let e=0;e<u.encodings.length;++e)t[e]&&Object.assign(u.encodings[e],t[e]);if(u.encodings.length>1&&("video/vp8"===u.codecs[0].mimeType.toLowerCase()||"video/h264"===u.codecs[0].mimeType.toLowerCase()))for(const e of u.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${f.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:h,reuseMid:s.reuseMid,offerRtpParameters:u,answerRtpParameters:p,codecOptions:r});const g={type:"answer",sdp:this._remoteSdp.getSdp()};return an.debug("send() | calling pc.setRemoteDescription() [answer:%o]",g),await this._pc.setRemoteDescription(g),this._mapMidTransceiver.set(m,o),{localId:m,rtpParameters:u,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;an.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();an.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),an.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();an.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),an.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();an.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?an.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):an.debug("replaceTrack() [localId:%s, no track]",e);const 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(),an.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();an.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),an.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();an.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};an.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%dn.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Yr.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),an.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};an.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;an.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Yr.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find(e=>String(e.mid)===i);nn.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Yr.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),an.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){an.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();an.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){an.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();an.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){an.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();an.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};an.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};an.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Yr.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}an.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Yr.parse(this._pc.localDescription.sdp));const r=nn.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new en.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Qr.Safari12=ln;var un={};Object.defineProperty(un,"__esModule",{value:!0}),un.ReactNative106=void 0;const pn=Dt,hn=N,fn=ae,mn=ne,gn=Jt,vn=er,bn=Qt,yn=Xt,_n=Zt,wn=new M.Logger("ReactNative106"),Sn="ReactNative106",Cn={OS:1024,MIS:1024};class kn extends hn.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:Sn,factory:e=>new kn(e),getNativeRtpCapabilities:async()=>{wn.debug("getNativeRtpCapabilities()");let e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}e=void 0;const r=pn.parse(t.sdp);return kn.getLocalRtpCapabilities(r)}catch(t){try{e?.close()}catch(e){}throw e=void 0,t}},getNativeSctpCapabilities:async()=>(wn.debug("getNativeSctpCapabilities()"),{numStreams:Cn})}}static getLocalRtpCapabilities(e){const t=bn.extractRtpCapabilities({sdpObject:e});return fn.validateAndNormalizeRtpCapabilities(t),_n.addNackSupportForOpus(t),t}constructor({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,getSendExtendedRtpCapabilities:c}){super(),wn.debug("constructor()"),this._direction=e,this._remoteSdp=new vn.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._getSendExtendedRtpCapabilities=c,n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(wn.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return Sn}close(){if(wn.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch(e){}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(),wn.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),wn.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});wn.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();wn.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),wn.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const s=this._remoteSdp.getNextMediaSectionIdx(),o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(o.sender);let a=await this._pc.createOffer(),c=pn.parse(a.sdp);c.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();const d=kn.getLocalRtpCapabilities(c),l=this._getSendExtendedRtpCapabilities(d),u=fn.getSendingRtpParameters(e.kind,l);u.codecs=fn.reduceCodecs(u.codecs,n);const p=fn.getSendingRemoteRtpParameters(e.kind,l);p.codecs=fn.reduceCodecs(p.codecs,n),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:c});let h=!1;const f=(0,gn.parse)((t??[{}])[0].scalabilityMode);let m;t&&1===t.length&&f.spatialLayers>1&&"video/vp9"===u.codecs[0].mimeType.toLowerCase()&&(wn.debug("send() | enabling legacy simulcast for VP9 SVC"),h=!0,c=pn.parse(a.sdp),m=c.media[s.idx],yn.addLegacySimulcast({offerMediaObject:m,numStreams:f.spatialLayers}),a={type:"offer",sdp:pn.write(c)}),wn.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);let g=o.mid??void 0;if(g||wn.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),u.mid=g,c=pn.parse(this._pc.localDescription.sdp),m=c.media[s.idx],u.rtcp.cname=bn.getCname({offerMediaObject:m}),t)if(1===t.length){let e=yn.getRtpEncodings({offerMediaObject:m});Object.assign(e[0],t[0]),h&&(e=[e[0]]),u.encodings=e}else u.encodings=t;else u.encodings=yn.getRtpEncodings({offerMediaObject:m});if(u.encodings.length>1&&("video/vp8"===u.codecs[0].mimeType.toLowerCase()||"video/h264"===u.codecs[0].mimeType.toLowerCase()))for(const e of u.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${f.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:m,reuseMid:s.reuseMid,offerRtpParameters:u,answerRtpParameters:p,codecOptions:r});const v={type:"answer",sdp:this._remoteSdp.getSdp()};return wn.debug("send() | calling pc.setRemoteDescription() [answer:%o]",v),await this._pc.setRemoteDescription(v),g||(g=o.mid,u.mid=g),this._mapMidTransceiver.set(g,o),{localId:g,rtpParameters:u,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;wn.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();wn.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),wn.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();wn.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),wn.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();wn.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?wn.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):wn.debug("replaceTrack() [localId:%s, no track]",e);const 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(),wn.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();wn.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),wn.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach((e,r)=>{n.encodings[r]={...e,...t}}),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();wn.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};wn.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Cn.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=pn.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),wn.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};wn.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:n,rtpParameters:i,streamId:s}=t;wn.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=pn.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find(e=>String(e.mid)===i);bn.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:pn.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),wn.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===i);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){wn.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wn.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){wn.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wn.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){wn.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();wn.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};wn.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};wn.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=pn.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}wn.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=pn.parse(this._pc.localDescription.sdp));const r=bn.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),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")}};assertNotClosed(){if(this._closed)throw new mn.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}un.ReactNative106=kn,Object.defineProperty(y,"__esModule",{value:!0}),y.Device=void 0,y.detectDevice=Nn,y.detectDeviceAsync=Fn;const Tn=P,Pn=N,Rn=ne,En=oe,On=ae,xn=$e,In=It,Dn=Cr,Mn=Nr,jn=Qr,An=un,Ln=new M.Logger("Device");function Nn(e){Ln.debug("detectDevice() [userAgent:%s]",e),e||"object"!=typeof navigator||(e=navigator.userAgent);return zn(new Tn.default(e))}async function Fn(e){Ln.debug("detectDeviceAsync() [userAgent:%s]",e),e||"object"!=typeof navigator||(e=navigator.userAgent);return zn(new Tn.default(e))}class Bn{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new Pn.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(Ln.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&!(e=await Fn()))throw new Rn.UnsupportedError("device not supported");return new Bn({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(Ln.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)Ln.debug("constructor() | handler given: %s",e);else{if(!(e=Nn()))throw new Rn.UnsupportedError("device not supported");Ln.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=In.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=Dn.Chrome74.createFactory();break;case"Firefox120":this._handlerFactory=Mn.Firefox120.createFactory();break;case"Safari12":this._handlerFactory=jn.Safari12.createFactory();break;case"ReactNative106":this._handlerFactory=An.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(){if(!this._loaded)throw new Rn.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Rn.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(Ln.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new Rn.InvalidStateError("already loaded");const r=En.clone(e);On.validateAndNormalizeRtpCapabilities(r);const{getNativeRtpCapabilities:n,getNativeSctpCapabilities:i}=this._handlerFactory,s=En.clone(await n());On.validateAndNormalizeRtpCapabilities(s),Ln.debug("load() | got native RTP capabilities:%o",s),this._getSendExtendedRtpCapabilities=e=>En.clone(On.getExtendedRtpCapabilities(e,r,t));const o=On.getExtendedRtpCapabilities(s,r,!1);this._recvRtpCapabilities=On.getRecvRtpCapabilities(o),On.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities),Ln.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._canProduceByKind.audio=On.canSend("audio",this._recvRtpCapabilities),this._canProduceByKind.video=On.canSend("video",this._recvRtpCapabilities),this._sctpCapabilities=await i(),On.validateSctpCapabilities(this._sctpCapabilities),Ln.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),Ln.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(!this._loaded)throw new Rn.InvalidStateError("not loaded");if("audio"!==e&&"video"!==e)throw new TypeError(`invalid kind "${e}"`);return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c}){return Ln.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c}){return Ln.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,appData:c})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d}){if(!this._loaded)throw new Rn.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(n))throw new TypeError("missing iceCandidates");if("object"!=typeof i)throw new TypeError("missing dtlsParameters");if(s&&"object"!=typeof s)throw new TypeError("wrong sctpParameters");if(d&&"object"!=typeof d)throw new TypeError("if given, appData must be an object");const l=new xn.Transport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:d,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",l),l}}function zn(e){if("object"==typeof navigator&&"ReactNative"===navigator.product)return Ln.debug("detectDeviceImpl() | React-Native detected"),"undefined"==typeof RTCPeerConnection||"undefined"==typeof RTCRtpTransceiver?void Ln.warn("detectDeviceImpl() | unsupported react-native-webrtc without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?"):"ReactNative106";{const t=e.parseUserAgent(),r=/^\d+/.exec(t?.shortVersion??"0"),n=parseInt(r?.[0]??"0",10),i=t.platform===Tn.KnownPlatforms.iphone||t.platform===Tn.KnownPlatforms.ipad||t.platform===Tn.KnownPlatforms.mac&&(t.isMobile||t.isTablet||"object"==typeof navigator&&navigator?.maxTouchPoints>=2),s=t.isChrome,o=t.isFireFox,a=t.isSafari,c=t.isEdge,d=t.isDesktop&&t.name===Tn.KnownBrowsers.electron,l={browserMajorVersion:n,isIOS:i,isChrome:s,isFirefox:o,isSafari:a,isElectron:d};if(Ln.debug("detectDeviceImpl() | detected browser [userAgent:%s, parsed:%o, result:%o]",t.userAgent,t,l),(s||c)&&!i&&n>=111)return"Chrome111";if(s&&!i&&n>=74||c&&!i&&n>=88)return"Chrome74";if(d)return"Chrome111";if(o&&!i&&n>=120)return"Firefox120";if(a&&n>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(i&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";{const r=e.userAgent?.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(r){return Number(r[1])>=111?"Chrome111":"Chrome74"}return void Ln.warn("detectDeviceImpl() | browser not supported [userAgent:%s, parsed:%o, result:%o]",t.userAgent,t,l)}}}y.Device=Bn;var Un={},Vn={},$n={},Gn={};Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.default="ffffffff-ffff-ffff-ffff-ffffffffffff";var qn={};Object.defineProperty(qn,"__esModule",{value:!0}),qn.default="00000000-0000-0000-0000-000000000000";var Hn={},Wn={},Jn={};Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,Object.defineProperty(Wn,"__esModule",{value:!0});const Kn=Jn;Wn.default=function(e){return"string"==typeof e&&Kn.default.test(e)},Object.defineProperty(Hn,"__esModule",{value:!0});const Qn=Wn;Hn.default=function(e){if(!(0,Qn.default)(e))throw TypeError("Invalid UUID");let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)};var Yn={};Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.unsafeStringify=void 0;const Xn=Wn,Zn=[];for(let BE=0;BE<256;++BE)Zn.push((BE+256).toString(16).slice(1));function ei(e,t=0){return(Zn[e[t+0]]+Zn[e[t+1]]+Zn[e[t+2]]+Zn[e[t+3]]+"-"+Zn[e[t+4]]+Zn[e[t+5]]+"-"+Zn[e[t+6]]+Zn[e[t+7]]+"-"+Zn[e[t+8]]+Zn[e[t+9]]+"-"+Zn[e[t+10]]+Zn[e[t+11]]+Zn[e[t+12]]+Zn[e[t+13]]+Zn[e[t+14]]+Zn[e[t+15]]).toLowerCase()}Yn.unsafeStringify=ei,Yn.default=function(e,t=0){const r=ei(e,t);if(!(0,Xn.default)(r))throw TypeError("Stringified UUID is invalid");return r};var ti={},ri={};let ni;Object.defineProperty(ri,"__esModule",{value:!0});const ii=new Uint8Array(16);ri.default=function(){if(!ni){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ni=crypto.getRandomValues.bind(crypto)}return ni(ii)},Object.defineProperty(ti,"__esModule",{value:!0}),ti.updateV1State=void 0;const si=ri,oi=Yn,ai={};function ci(e,t,r){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=r.slice(10,16),e.node[0]|=1,e.clockseq=16383&(r[8]<<8|r[9])),e.msecs=t,e}function di(e,t,r,n,i,s,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(s){if(o<0||o+16>s.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`)}else s=new Uint8Array(16),o=0;t??=Date.now(),r??=0,n??=16383&(e[8]<<8|e[9]),i??=e.slice(10,16);const a=(1e4*(268435455&(t+=122192928e5))+r)%4294967296;s[o++]=a>>>24&255,s[o++]=a>>>16&255,s[o++]=a>>>8&255,s[o++]=255&a;const c=t/4294967296*1e4&268435455;s[o++]=c>>>8&255,s[o++]=255&c,s[o++]=c>>>24&15|16,s[o++]=c>>>16&255,s[o++]=n>>>8|128,s[o++]=255&n;for(let e=0;e<6;++e)s[o++]=i[e];return s}ti.updateV1State=ci,ti.default=function(e,t,r){let n;const i=e?._v6??!1;if(e){const t=Object.keys(e);1===t.length&&"_v6"===t[0]&&(e=void 0)}if(e)n=di(e.random??e.rng?.()??(0,si.default)(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{const e=Date.now(),s=(0,si.default)();ci(ai,e,s),n=di(s,ai.msecs,ai.nsecs,i?void 0:ai.clockseq,i?void 0:ai.node,t,r)}return t??(0,oi.unsafeStringify)(n)};var li={};Object.defineProperty(li,"__esModule",{value:!0});const ui=Hn,pi=Yn;li.default=function(e){const t=function(e){return Uint8Array.of((15&e[6])<<4|e[7]>>4&15,(15&e[7])<<4|(240&e[4])>>4,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,(15&e[1])<<4|(240&e[2])>>4,96|15&e[2],e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,ui.default)(e):e);return"string"==typeof e?(0,pi.unsafeStringify)(t):t};var hi={},fi={};function mi(e){return 14+(e+64>>>9<<4)+1}function gi(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function vi(e,t,r,n,i,s){return gi((o=gi(gi(t,e),gi(n,s)))<<(a=i)|o>>>32-a,r);var o,a}function bi(e,t,r,n,i,s,o){return vi(t&r|~t&n,e,t,i,s,o)}function yi(e,t,r,n,i,s,o){return vi(t&n|r&~n,e,t,i,s,o)}function _i(e,t,r,n,i,s,o){return vi(t^r^n,e,t,i,s,o)}function wi(e,t,r,n,i,s,o){return vi(r^(t|~n),e,t,i,s,o)}Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=function(e){const t=function(e){if(0===e.length)return new Uint32Array;const t=new Uint32Array(mi(8*e.length)).fill(0);for(let r=0;r<e.length;r++)t[r>>2]|=(255&e[r])<<r%4*8;return t}(e),r=function(e,t){const r=new Uint32Array(mi(t)).fill(0);r.set(e),r[t>>5]|=128<<t%32,r[r.length-1]=t,e=r;let n=1732584193,i=-271733879,s=-1732584194,o=271733878;for(let t=0;t<e.length;t+=16){const r=n,a=i,c=s,d=o;n=bi(n,i,s,o,e[t],7,-680876936),o=bi(o,n,i,s,e[t+1],12,-389564586),s=bi(s,o,n,i,e[t+2],17,606105819),i=bi(i,s,o,n,e[t+3],22,-1044525330),n=bi(n,i,s,o,e[t+4],7,-176418897),o=bi(o,n,i,s,e[t+5],12,1200080426),s=bi(s,o,n,i,e[t+6],17,-1473231341),i=bi(i,s,o,n,e[t+7],22,-45705983),n=bi(n,i,s,o,e[t+8],7,1770035416),o=bi(o,n,i,s,e[t+9],12,-1958414417),s=bi(s,o,n,i,e[t+10],17,-42063),i=bi(i,s,o,n,e[t+11],22,-1990404162),n=bi(n,i,s,o,e[t+12],7,1804603682),o=bi(o,n,i,s,e[t+13],12,-40341101),s=bi(s,o,n,i,e[t+14],17,-1502002290),i=bi(i,s,o,n,e[t+15],22,1236535329),n=yi(n,i,s,o,e[t+1],5,-165796510),o=yi(o,n,i,s,e[t+6],9,-1069501632),s=yi(s,o,n,i,e[t+11],14,643717713),i=yi(i,s,o,n,e[t],20,-373897302),n=yi(n,i,s,o,e[t+5],5,-701558691),o=yi(o,n,i,s,e[t+10],9,38016083),s=yi(s,o,n,i,e[t+15],14,-660478335),i=yi(i,s,o,n,e[t+4],20,-405537848),n=yi(n,i,s,o,e[t+9],5,568446438),o=yi(o,n,i,s,e[t+14],9,-1019803690),s=yi(s,o,n,i,e[t+3],14,-187363961),i=yi(i,s,o,n,e[t+8],20,1163531501),n=yi(n,i,s,o,e[t+13],5,-1444681467),o=yi(o,n,i,s,e[t+2],9,-51403784),s=yi(s,o,n,i,e[t+7],14,1735328473),i=yi(i,s,o,n,e[t+12],20,-1926607734),n=_i(n,i,s,o,e[t+5],4,-378558),o=_i(o,n,i,s,e[t+8],11,-2022574463),s=_i(s,o,n,i,e[t+11],16,1839030562),i=_i(i,s,o,n,e[t+14],23,-35309556),n=_i(n,i,s,o,e[t+1],4,-1530992060),o=_i(o,n,i,s,e[t+4],11,1272893353),s=_i(s,o,n,i,e[t+7],16,-155497632),i=_i(i,s,o,n,e[t+10],23,-1094730640),n=_i(n,i,s,o,e[t+13],4,681279174),o=_i(o,n,i,s,e[t],11,-358537222),s=_i(s,o,n,i,e[t+3],16,-722521979),i=_i(i,s,o,n,e[t+6],23,76029189),n=_i(n,i,s,o,e[t+9],4,-640364487),o=_i(o,n,i,s,e[t+12],11,-421815835),s=_i(s,o,n,i,e[t+15],16,530742520),i=_i(i,s,o,n,e[t+2],23,-995338651),n=wi(n,i,s,o,e[t],6,-198630844),o=wi(o,n,i,s,e[t+7],10,1126891415),s=wi(s,o,n,i,e[t+14],15,-1416354905),i=wi(i,s,o,n,e[t+5],21,-57434055),n=wi(n,i,s,o,e[t+12],6,1700485571),o=wi(o,n,i,s,e[t+3],10,-1894986606),s=wi(s,o,n,i,e[t+10],15,-1051523),i=wi(i,s,o,n,e[t+1],21,-2054922799),n=wi(n,i,s,o,e[t+8],6,1873313359),o=wi(o,n,i,s,e[t+15],10,-30611744),s=wi(s,o,n,i,e[t+6],15,-1560198380),i=wi(i,s,o,n,e[t+13],21,1309151649),n=wi(n,i,s,o,e[t+4],6,-145523070),o=wi(o,n,i,s,e[t+11],10,-1120210379),s=wi(s,o,n,i,e[t+2],15,718787259),i=wi(i,s,o,n,e[t+9],21,-343485551),n=gi(n,r),i=gi(i,a),s=gi(s,c),o=gi(o,d)}return Uint32Array.of(n,i,s,o)}(t,8*e.length);return function(e){const t=new Uint8Array(4*e.length);for(let r=0;r<4*e.length;r++)t[r]=e[r>>2]>>>r%4*8&255;return t}(r)};var Si={};Object.defineProperty(Si,"__esModule",{value:!0}),Si.URL=Si.DNS=Si.stringToBytes=void 0;const Ci=Hn,ki=Yn;function Ti(e){e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t}Si.stringToBytes=Ti,Si.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Si.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",Si.default=function(e,t,r,n,i,s){const o="string"==typeof r?Ti(r):r,a="string"==typeof n?(0,Ci.default)(n):n;if("string"==typeof n&&(n=(0,Ci.default)(n)),16!==n?.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(a),c.set(o,a.length),c=t(c),c[6]=15&c[6]|e,c[8]=63&c[8]|128,i){s=s||0;for(let e=0;e<16;++e)i[s+e]=c[e];return i}return(0,ki.unsafeStringify)(c)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=fi,r=Si;var n=Si;function i(e,n,i,s){return(0,r.default)(48,t.default,e,n,i,s)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=r.DNS,i.URL=r.URL,e.default=i}(hi);var Pi={},Ri={};Object.defineProperty(Ri,"__esModule",{value:!0});const Ei="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);Ri.default={randomUUID:Ei},Object.defineProperty(Pi,"__esModule",{value:!0});const Oi=Ri,xi=ri,Ii=Yn;Pi.default=function(e,t,r){if(Oi.default.randomUUID&&!t&&!e)return Oi.default.randomUUID();const n=(e=e||{}).random??e.rng?.()??(0,xi.default)();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=n[e];return t}return(0,Ii.unsafeStringify)(n)};var Di={},Mi={};function ji(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function Ai(e,t){return e<<t|e>>>32-t}Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.default=function(e){const t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128;const i=(e=n).length/4+2,s=Math.ceil(i/16),o=new Array(s);for(let t=0;t<s;++t){const r=new Uint32Array(16);for(let n=0;n<16;++n)r[n]=e[64*t+4*n]<<24|e[64*t+4*n+1]<<16|e[64*t+4*n+2]<<8|e[64*t+4*n+3];o[t]=r}o[s-1][14]=8*(e.length-1)/Math.pow(2,32),o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<s;++e){const n=new Uint32Array(80);for(let t=0;t<16;++t)n[t]=o[e][t];for(let e=16;e<80;++e)n[e]=Ai(n[e-3]^n[e-8]^n[e-14]^n[e-16],1);let i=r[0],s=r[1],a=r[2],c=r[3],d=r[4];for(let e=0;e<80;++e){const r=Math.floor(e/20),o=Ai(i,5)+ji(r,s,a,c)+d+t[r]+n[e]>>>0;d=c,c=a,a=Ai(s,30)>>>0,s=i,i=o}r[0]=r[0]+i>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+a>>>0,r[3]=r[3]+c>>>0,r[4]=r[4]+d>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URL=e.DNS=void 0;const t=Mi,r=Si;var n=Si;function i(e,n,i,s){return(0,r.default)(80,t.default,e,n,i,s)}Object.defineProperty(e,"DNS",{enumerable:!0,get:function(){return n.DNS}}),Object.defineProperty(e,"URL",{enumerable:!0,get:function(){return n.URL}}),i.DNS=r.DNS,i.URL=r.URL,e.default=i}(Di);var Li={};Object.defineProperty(Li,"__esModule",{value:!0});const Ni=Yn,Fi=ti,Bi=li;Li.default=function(e,t,r){e??={},r??=0;let n=(0,Fi.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,Bi.default)(n),t){for(let e=0;e<16;e++)t[r+e]=n[e];return t}return(0,Ni.unsafeStringify)(n)};var zi={};Object.defineProperty(zi,"__esModule",{value:!0});const Ui=Hn,Vi=Yn;zi.default=function(e){const t=function(e){return Uint8Array.of((15&e[3])<<4|e[4]>>4&15,(15&e[4])<<4|(240&e[5])>>4,(15&e[5])<<4|15&e[6],e[7],(15&e[1])<<4|(240&e[2])>>4,(15&e[2])<<4|(240&e[3])>>4,16|(240&e[0])>>4,(15&e[0])<<4|(240&e[1])>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}("string"==typeof e?(0,Ui.default)(e):e);return"string"==typeof e?(0,Vi.unsafeStringify)(t):t};var $i={};Object.defineProperty($i,"__esModule",{value:!0}),$i.updateV7State=void 0;const Gi=ri,qi=Yn,Hi={};function Wi(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++),e}function Ji(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(n){if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else n=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=255&t,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|3&e[10],n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}$i.updateV7State=Wi,$i.default=function(e,t,r){let n;if(e)n=Ji(e.random??e.rng?.()??(0,Gi.default)(),e.msecs,e.seq,t,r);else{const e=Date.now(),i=(0,Gi.default)();Wi(Hi,e,i),n=Ji(i,Hi.msecs,Hi.seq,t,r)}return t??(0,qi.unsafeStringify)(n)};var Ki={};Object.defineProperty(Ki,"__esModule",{value:!0});const Qi=Wn;Ki.default=function(e){if(!(0,Qi.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.version=e.validate=e.v7=e.v6ToV1=e.v6=e.v5=e.v4=e.v3=e.v1ToV6=e.v1=e.stringify=e.parse=e.NIL=e.MAX=void 0;var t=Gn;Object.defineProperty(e,"MAX",{enumerable:!0,get:function(){return t.default}});var r=qn;Object.defineProperty(e,"NIL",{enumerable:!0,get:function(){return r.default}});var n=Hn;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return n.default}});var i=Yn;Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.default}});var s=ti;Object.defineProperty(e,"v1",{enumerable:!0,get:function(){return s.default}});var o=li;Object.defineProperty(e,"v1ToV6",{enumerable:!0,get:function(){return o.default}});var a=hi;Object.defineProperty(e,"v3",{enumerable:!0,get:function(){return a.default}});var c=Pi;Object.defineProperty(e,"v4",{enumerable:!0,get:function(){return c.default}});var d=Di;Object.defineProperty(e,"v5",{enumerable:!0,get:function(){return d.default}});var l=Li;Object.defineProperty(e,"v6",{enumerable:!0,get:function(){return l.default}});var u=zi;Object.defineProperty(e,"v6ToV1",{enumerable:!0,get:function(){return u.default}});var p=$i;Object.defineProperty(e,"v7",{enumerable:!0,get:function(){return p.default}});var h=Wn;Object.defineProperty(e,"validate",{enumerable:!0,get:function(){return h.default}});var f=Ki;Object.defineProperty(e,"version",{enumerable:!0,get:function(){return f.default}})}($n);var Yi={};Object.defineProperty(Yi,"__esModule",{value:!0}),Yi.FakeEventTarget=void 0;Yi.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]??=[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(e=>e.callback!==("function"==typeof t?t:t.handleEvent)))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout(()=>{throw e},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}};var Xi={};Object.defineProperty(Xi,"__esModule",{value:!0}),Xi.FakeEvent=void 0;Xi.FakeEvent=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){}};var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.FakeMediaStreamTrack=void 0;const es=$n,ts=Yi,rs=Xi,ns=Zi;class is extends ts.FakeEventTarget{#e;#t;#r;#n;#i;#s;#o;#a;#c;#d;#l;#u=null;#p=null;#h=null;#f=null;#m=null;constructor({kind:e,id:t,label:r,contentHint:n,enabled:i,muted:s,readyState:o,capabilities:a,constraints:c,settings:d,data:l}){super(),this.#e=t??(0,es.v4)(),this.#t=e,this.#r=r??"",this.#o=n??"",this.#i=i??!0,this.#s=s??!1,this.#n=o??"live",this.#a=a??{},this.#c=c??{},this.#d=d??{},this.#l=l??{}}get id(){return this.#e}get kind(){return this.#t}get label(){return this.#r}get contentHint(){return this.#o}set contentHint(e){this.#o=e}get enabled(){return this.#i}set enabled(e){const t=this.#i!==e;this.#i=e,t&&this.dispatchEvent(new rs.FakeEvent("enabledchange"))}get muted(){return this.#s}get readyState(){return this.#n}get data(){return this.#l}set data(e){this.#l=e}get onmute(){return this.#u}set onmute(e){this.#u&&this.removeEventListener("mute",this.#u),this.#u=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#p}set onunmute(e){this.#p&&this.removeEventListener("unmute",this.#p),this.#p=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#h}set onended(e){this.#h&&this.removeEventListener("ended",this.#h),this.#h=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#f}set onenabledchange(e){this.#f&&this.removeEventListener("enabledchange",this.#f),this.#f=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#m}set onstopped(e){this.#m&&this.removeEventListener("stopped",this.#m),this.#m=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(){"ended"!==this.#n&&(this.#n="ended",this.dispatchEvent(new rs.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new is({id:e??(0,es.v4)(),kind:this.#t,label:this.#r,contentHint:this.#o,enabled:this.#i,muted:this.#s,readyState:this.#n,capabilities:(0,ns.clone)(this.#a),constraints:(0,ns.clone)(this.#c),settings:(0,ns.clone)(this.#d),data:t??(0,ns.clone)(this.#l)})}getCapabilities(){return this.#a}getConstraints(){return this.#c}async applyConstraints(e={}){return this.#c=e,Promise.resolve()}getSettings(){return this.#d}remoteStop(){"ended"!==this.#n&&(this.#n="ended",this.dispatchEvent(new rs.FakeEvent("stopped")),this.dispatchEvent(new rs.FakeEvent("ended")))}remoteMute(){this.#s||(this.#s=!0,this.dispatchEvent(new rs.FakeEvent("mute")))}remoteUnmute(){this.#s&&(this.#s=!1,this.dispatchEvent(new rs.FakeEvent("unmute")))}}Vn.FakeMediaStreamTrack=is;var ss={};Object.defineProperty(ss,"__esModule",{value:!0}),ss.FakeEventTarget=void 0;ss.FakeEventTarget=class{listeners={};addEventListener(e,t,r){t&&(this.listeners[e]??=[],this.listeners[e].push({callback:"function"==typeof t?t:t.handleEvent,once:"object"==typeof r&&!0===r.once}))}removeEventListener(e,t,r){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(e=>e.callback!==("function"==typeof t?t:t.handleEvent)))}dispatchEvent(e){if(!e||"string"!=typeof e.type)throw new Error("invalid event object");const t=this.listeners[e.type];if(!t)return!0;for(const r of[...t]){try{r.callback.call(this,e)}catch(e){setTimeout(()=>{throw e},0)}r.once&&this.removeEventListener(e.type,r.callback)}return!e.defaultPrevented}},Object.defineProperty(Un,"__esModule",{value:!0}),Un.FakeHandler=void 0;const os=Vn,as=N,cs=oe,ds=ae,ls=ne,us=ss,ps=new M.Logger("FakeHandler"),hs="FakeHandler";class fs extends as.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${cs.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:hs,factory:t=>new fs(t,e),getNativeRtpCapabilities:async()=>(ps.debug("getNativeRtpCapabilities()"),fs.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(ps.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){const t=e.generateNativeRtpCapabilities();return ds.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),ps.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return hs}close(){ps.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(),ps.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),ps.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,encodings:t,codecOptions:r,codec:n}){this.assertNotClosed(),ps.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});const i=fs.getLocalRtpCapabilities(this._fakeParameters),s=this._getSendExtendedRtpCapabilities(i),o=ds.getSendingRtpParameters(e.kind,s);o.codecs=ds.reduceCodecs(o.codecs,n);const a=o.codecs.some(e=>/.+\/rtx$/i.test(e.mimeType));o.mid=`mid-${cs.generateRandomNumber()}`,t||(t=[{}]);for(const e of t)e.ssrc=cs.generateRandomNumber(),a&&(e.rtx={ssrc:cs.generateRandomNumber()});o.encodings=t,o.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const c=this._nextLocalId++;return this._tracks.set(c,e),{localId:String(c),rtpParameters:o}}async stopSending(e){if(ps.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?ps.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ps.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),ps.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),ps.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),ps.debug("sendDataChannel()");return{dataChannel:new ms({id:this._nextSctpStreamId++,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}),sctpStreamParameters:{streamId:this._nextSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r}}}async receive(e){this.assertNotClosed();const t=[];for(const r of e){const{trackId:e,kind:n}=r;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),ps.debug("receive() [trackId:%s, kind:%s]",e,n);const i=this._nextLocalId++,s=new os.FakeMediaStreamTrack({kind:n});this._tracks.set(i,s),t.push({localId:String(i),track:s})}return t}async stopReceiving(e){if(!this._closed)for(const t of e)ps.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}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),ps.debug("receiveDataChannel()");return{dataChannel:new ms({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:r})}}async setupTransport({localDtlsRole:e,localSdpObject:t}){const r=cs.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(r.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((e,t)=>this.emit("@connect",{dtlsParameters:r},e,t)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new ls.InvalidStateError("method called in a closed handler")}}Un.FakeHandler=fs;class ms extends us.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:n=null,label:i="",protocol:s=""}){super(),ps.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${r}, maxRetransmits:${n}, label:${i}, protocol:${s}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=r,this._maxRetransmits=n,this._label=i,this._protocol=s}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("open"!==this._readyState)throw new ls.InvalidStateError("not open")}}var gs={};Object.defineProperty(gs,"__esModule",{value:!0}),gs.generateRouterRtpCapabilities=function(){return vs.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"}]})},gs.generateNativeRtpCapabilities=function(){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}]}},gs.generateNativeSctpCapabilities=function(){return vs.deepFreeze({numStreams:{OS:2048,MIS:2048}})},gs.generateLocalDtlsParameters=function(){return vs.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"})},gs.generateTransportRemoteParameters=function(){return{id:bs(),iceParameters:vs.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:vs.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:vs.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:vs.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}},gs.generateProducerRemoteParameters=function(){return vs.deepFreeze({id:bs()})},gs.generateConsumerRemoteParameters=function({id:e,codecMimeType:t}={}){switch(t){case"audio/opus":return{id:e??bs(),producerId:bs(),kind:"audio",rtpParameters:vs.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:e??bs(),producerId:bs(),kind:"audio",rtpParameters:vs.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:e??bs(),producerId:bs(),kind:"video",rtpParameters:vs.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:e??bs(),producerId:bs(),kind:"video",rtpParameters:vs.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 '${t}'`)}},gs.generateDataProducerRemoteParameters=function(){return vs.deepFreeze({id:bs()})},gs.generateDataConsumerRemoteParameters=function({id:e}={}){return{id:e??bs(),dataProducerId:bs(),sctpStreamParameters:vs.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}};const vs=oe;function bs(){return String(vs.generateRandomNumber())}!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.debug=e.testFakeParameters=e.FakeHandler=e.enhancedEvents=e.ortc=e.parseScalabilityMode=e.detectDeviceAsync=e.detectDevice=e.Device=e.version=e.types=void 0;const t=v;e.debug=t.default,e.types=b,e.version="3.15.7";var r=y;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return r.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return r.detectDevice}}),Object.defineProperty(e,"detectDeviceAsync",{enumerable:!0,get:function(){return r.detectDeviceAsync}});var n=Jt;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return n.parse}}),e.ortc=ae,e.enhancedEvents=N;var i=Un;Object.defineProperty(e,"FakeHandler",{enumerable:!0,get:function(){return i.FakeHandler}}),e.testFakeParameters=gs}(h);let ys=!0,_s=!0;function ws(e,t,r){const n=e.match(t);return n&&n.length>=r&&parseFloat(n[r],10)}function Ss(e,t,r){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),i.apply(this,[e,s])};const s=n.removeEventListener;n.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const n=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Cs(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ys=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ks(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(_s=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Ts(){if("object"==typeof window){if(ys)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ps(e,t){_s&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Rs(e){return"[object Object]"===Object.prototype.toString.call(e)}function Es(e){return Rs(e)?Object.keys(e).reduce(function(t,r){const n=Rs(e[r]),i=n?Es(e[r]):e[r],s=n&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})},{}):e}function Os(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach(n=>{n.endsWith("Id")?Os(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach(t=>{Os(e,e.get(t),r)})}))}function xs(e,t,r){const n=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}),s.forEach(t=>{e.forEach(r=>{r.type===n&&r.trackId===t.id&&Os(e,r,i)})}),i}const Is=Ts;function Ds(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const n="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[i("min",r)]=n.ideal,t.optional.push(e),e={},e[i("max",r)]=n.ideal,t.optional.push(e)):(e[i("",r)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then(r=>{let o=(r=r.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),Is("chrome: "+JSON.stringify(e)),i(e)})}e.video=n(e.video)}return Is("chrome: "+JSON.stringify(e)),i(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,n){i(e,e=>{r.webkitGetUserMedia(e,t,e=>{n&&n(s(e))})})}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(s(e))))}}}function Ms(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function js(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.track.id):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.id):{track:r};const i=new Event("track");i.track=r,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Ss(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function As(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Ls(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>xs(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),Ss(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>xs(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,n;return this.getSenders().forEach(r=>{r.track===e&&(t?n=!0:t=r)}),this.getReceivers().forEach(t=>(t.track===e&&(r?n=!0:r=t),t.track===e)),n||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Ns(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(n)&&this._shimmedLocalStreams[r.id].push(n):this._shimmedLocalStreams[r.id]=[r,n],n};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{const t=this.getSenders().find(t=>t.track===e);if(t)throw new DOMException("Track already exists.","InvalidAccessError")});const t=this.getSenders();r.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function Fs(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Ns(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{const t=this.getSenders().find(t=>t.track===e);if(t)throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}n.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(i.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const i=this.getSenders().find(e=>e.track===t);if(i)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const n=new e.MediaStream([t]);this._streams[r.id]=n,this._reverseStreams[n.id]=r,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then(e=>s(this,e))}};e.RTCPeerConnection.prototype[t]=n[t]});const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(n.id,"g"),i.id)}),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(r=>{this._streams[r].getTracks().find(t=>e.track===t)&&(t=this._streams[r])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Bs(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]})}function zs(e,t){Ss(e,"negotiationneeded",e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e})}var Us=Object.freeze({__proto__:null,fixNegotiationNeeded:zs,shimAddTrackRemoveTrack:Fs,shimAddTrackRemoveTrackWithNative:Ns,shimGetSendersWithDtmf:As,shimGetUserMedia:Ds,shimMediaStream:Ms,shimOnTrack:js,shimPeerConnection:Bs,shimSenderReceiverGetStats:Ls});function Vs(e,t){const r=e&&e.navigator,n=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,n){Ps("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function $s(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Gs(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]});const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,s]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!i)try{e.forEach(e=>{e.type=r[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:r[t.type]||t.type}))})}return e}).then(i,s)}}function qs(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Hs(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),Ss(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ws(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ps("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Js(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ks(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const r=e.length>0;r&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=t.apply(this,arguments);if(r){const{sender:t}=n,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(r).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function Qs(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Ys(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Xs(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Zs=Object.freeze({__proto__:null,shimAddTransceiver:Ks,shimCreateAnswer:Xs,shimCreateOffer:Ys,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})},shimGetParameters:Qs,shimGetUserMedia:Vs,shimOnTrack:$s,shimPeerConnection:Gs,shimRTCDataChannel:Js,shimReceiverGetStats:Hs,shimRemoveStream:Ws,shimSenderGetStats:qs});function eo(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(r=>t.call(this,r,e)),e.getVideoTracks().forEach(r=>t.call(this,r,e))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach(e=>{r.includes(e.track)&&this.removeTrack(e)})})}}function to(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)})}),t.apply(e,arguments)}}}function ro(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const n=i.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,r){const n=s.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,r){const n=o.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.addIceCandidate=a}function no(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(io(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,n){t.mediaDevices.getUserMedia(e).then(r,n)}.bind(t))}function io(e){return e&&void 0!==e.video?Object.assign({},e,{video:Es(e.video)}):e}function so(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let n=e.iceServers[r];void 0===n.urls&&n.url?(Ps("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function oo(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ao(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function co(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var lo=Object.freeze({__proto__:null,shimAudioContext:co,shimCallbacksAPI:ro,shimConstraints:io,shimCreateOfferLegacy:ao,shimGetUserMedia:no,shimLocalStreamsAPI:eo,shimRTCIceServerUrls:so,shimRemoteStreamsAPI:to,shimTrackEventTransceiver:oo}),uo={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter(e=>0===e.indexOf(r))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)r=n[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+r+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(r.attribute=e.substring(t+1,n),r.value=e.substring(n+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const n=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return n&&i?{usernameFragment:n.substring(12),password:i.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");r.profile=n[2];for(let i=3;i<n.length;i++){const s=n[i],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),i=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=i.length?t.parseFmtp(i[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{r.headerExtensions.push(t.parseExtmap(e))});const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach(e=>{i.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),r},t.writeRtpDescription=function(e,r){let n="";n+="m="+e+" ",n+=r.codecs.length>0?"9":"0",n+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=r.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)});let i=0;return r.codecs.forEach(e=>{e.maxptime>i&&(i=e.maxptime)}),i>0&&(n+="a=maxptime:"+i+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){const r=[],n=t.parseRtpParameters(e),i=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),i&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},r.push(t))}}),0===r.length&&a&&r.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,r.forEach(e=>{e.maxBitrate=l})),r},t.parseRtcpParameters=function(e){const r={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(r.cname=n.value,r.ssrc=n.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.length;const s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return r=n[0].substring(7).split(" "),{stream:r[0],track:r[1]};const i=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return i.length>0?(r=i[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let i;n.length>0&&(i=parseInt(n[0].substring(19),10)),isNaN(i)&&(i=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:r.fmt,maxMessageSize:i};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,n){let i;const s=void 0!==r?r:2;i=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+i+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(uo);var po=uo.exports,ho=c(po),fo=i({__proto__:null,default:ho},[po]);function mo(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const r=new t(e),n=ho.parseCandidate(e.candidate);for(const e in n)e in r||Object.defineProperty(r,e,{value:n[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Ss(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function go(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Ss(e,"icecandidate",e=>{if(e.candidate){const t=ho.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function vo(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=ho.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=ho.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),n=function(e,r){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const i=ho.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?n=parseInt(i[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(n=2147483637),n}(arguments[0],e);let i;i=0===r&&0===n?Number.POSITIVE_INFINITY:0===r||0===n?Math.max(r,n):Math.min(r,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>i}),this._sctp=s}return r.apply(this,arguments)}}function bo(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const n=arguments[0],i=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&i>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},Ss(e,"datachannel",e=>(t(e.channel,e.target),e))}function yo(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function _o(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function wo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function So(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>r.apply(this,[e]))})}var Co=Object.freeze({__proto__:null,removeExtmapAllowMixed:_o,shimAddIceCandidateNullOrEmpty:wo,shimConnectionState:yo,shimMaxMessageSize:vo,shimParameterlessSetLocalDescription:So,shimRTCIceCandidate:mo,shimRTCIceCandidateRelayProtocol:go,shimSendThrowTypeError:bo});const ko=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=Ts,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.userAgentData&&r.userAgentData.brands){const e=r.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(r.mozGetUserMedia)t.browser="firefox",t.version=parseInt(ws(r.userAgent,/Firefox\/(\d+)\./,1));else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(ws(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(ws(r.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=ws(r.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),i={browserDetails:n,commonShim:Co,extractVersion:ws,disableLog:Cs,disableWarnings:ks,sdp:fo};switch(n.browser){case"chrome":if(!Us||!Bs||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===n.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=Us,wo(e,n),So(e),Ds(e,n),Ms(e),Bs(e,n),js(e),Fs(e,n),As(e),Ls(e),zs(e,n),mo(e),go(e),yo(e),vo(e,n),bo(e),_o(e,n);break;case"firefox":if(!Zs||!Gs||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=Zs,wo(e,n),So(e),Vs(e,n),Gs(e,n),$s(e),Ws(e),qs(e),Hs(e),Js(e),Ks(e),Qs(e),Ys(e),Xs(e),mo(e),yo(e),vo(e,n),bo(e);break;case"safari":if(!lo||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=lo,wo(e,n),So(e),so(e),ao(e),ro(e),eo(e),to(e),oo(e),no(e),co(e),mo(e),go(e),vo(e,n),bo(e),_o(e,n);break;default:r("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});var To;function Po(){}function Ro(){Ro.init.call(this)}function Eo(e){return void 0===e._maxListeners?Ro.defaultMaxListeners:e._maxListeners}function Oo(e,t,r,n){var i,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new Po,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=Eo(e))&&i>0&&o.length>i){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function xo(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function Io(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Do(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}function Mo(e){return{id:e.id,tracks:e.getTracks().map(function(e){return{id:e.id,kind:e.kind,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}})}}Po.prototype=Object.create(null),Ro.EventEmitter=Ro,Ro.usingDomains=!1,Ro.prototype.domain=void 0,Ro.prototype._events=void 0,Ro.prototype._maxListeners=void 0,Ro.defaultMaxListeners=10,Ro.init=function(){this.domain=null,Ro.usingDomains&&(!To.active||this instanceof To.Domain||(this.domain=To.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Po,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Ro.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Ro.prototype.getMaxListeners=function(){return Eo(this)},Ro.prototype.emit=function(e){var t,r,n,i,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Do(e,n),s=0;s<n;++s)i[s].call(r)}(r,l,this);break;case 2:!function(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=Do(e,i),o=0;o<i;++o)s[o].call(r,n)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=Do(e,s),a=0;a<s;++a)o[a].call(r,n,i)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=Do(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];!function(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=Do(e,i),o=0;o<i;++o)s[o].apply(r,n)}(r,l,this,i)}return!0},Ro.prototype.addListener=function(e,t){return Oo(this,e,t,!1)},Ro.prototype.on=Ro.prototype.addListener,Ro.prototype.prependListener=function(e,t){return Oo(this,e,t,!0)},Ro.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,xo(this,e,t)),this},Ro.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,xo(this,e,t)),this},Ro.prototype.removeListener=function(e,t){var r,n,i,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0===--this._eventsCount?this._events=new Po:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new Po,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,o||t)}return this},Ro.prototype.off=function(e,t){return this.removeListener(e,t)},Ro.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Po,this._eventsCount=0):r[e]&&(0===--this._eventsCount?this._events=new Po:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new Po,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Ro.prototype.listeners=function(e){var t,r,n=this._events;return r=n&&(t=n[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[],r},Ro.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Io.call(e,t)},Ro.prototype.listenerCount=Io,Ro.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var jo=function(e,t,r){var n=0,i=!!window.mozRTCPeerConnection,s=!!window.RTCIceGatherer,o={};if(r.forEach(function(r){if(window[r+"RTCPeerConnection"]&&("webkit"!==r||!s)){var a=window[r+"RTCPeerConnection"],c=function(r,c){var d=new a(r,c),l="PC_"+n++;d.__rtcStatsId=l,r||(r={nullConfig:!0}),((r=JSON.parse(JSON.stringify(r)))&&r.iceServers||[]).forEach(function(e){delete e.credential}),r.browserType=i?"moz":s?"edge":"webkit",e("create",l,r),c&&e("constraints",l,c),d.addEventListener("icecandidate",function(t){e("onicecandidate",l,t.candidate)}),d.addEventListener("addstream",function(t){e("onaddstream",l,t.stream.id+" "+t.stream.getTracks().map(function(e){return e.kind+":"+e.id}))}),d.addEventListener("track",function(t){e("ontrack",l,t.track.kind+":"+t.track.id+" "+t.streams.map(function(e){return"stream:"+e.id}))}),d.addEventListener("removestream",function(t){e("onremovestream",l,t.stream.id+" "+t.stream.getTracks().map(function(e){return e.kind+":"+e.id}))}),d.addEventListener("signalingstatechange",function(){e("onsignalingstatechange",l,d.signalingState)}),d.addEventListener("iceconnectionstatechange",function(){e("oniceconnectionstatechange",l,d.iceConnectionState)}),d.addEventListener("icegatheringstatechange",function(){e("onicegatheringstatechange",l,d.iceGatheringState)}),d.addEventListener("connectionstatechange",function(){e("onconnectionstatechange",l,d.connectionState)}),d.addEventListener("negotiationneeded",function(){e("onnegotiationneeded",l,void 0)}),d.addEventListener("datachannel",function(t){e("ondatachannel",l,[t.channel.id,t.channel.label])});var u=function(){d.getStats(null).then(function(t){var r=function(e){if(!e.entries)return e;var t={};return e.forEach(function(e,r){t[r]=e}),t}(t),n=JSON.parse(JSON.stringify(r));e("getstats",l,function(e,t){t=JSON.parse(JSON.stringify(t)),Object.keys(t).forEach(function(r){var n=t[r];delete n.id,e[r]&&Object.keys(n).forEach(function(i){n[i]===e[r][i]&&delete t[r][i],(0===Object.keys(n).length||1===Object.keys(n).length&&n.timestamp)&&delete t[r]})});var r=-1/0;return Object.keys(t).forEach(function(e){var n=t[e];n.timestamp>r&&(r=n.timestamp)}),Object.keys(t).forEach(function(e){var n=t[e];n.timestamp===r&&(n.timestamp=0)}),t.timestamp=r,t}(o[l]||{},r)),o[l]=n})};if(!s&&t)var p=window.setInterval(function(){"closed"!==d.signalingState?u():window.clearInterval(p)},t);return s||d.addEventListener("connectionstatechange",function(){"connected"!==d.connectionState&&"failed"!==d.connectionState||u()}),d};["createDataChannel","close"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){return e(t,this.__rtcStatsId,arguments),r.apply(this,arguments)})}),["addStream","removeStream"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=arguments[0],i=n.getTracks().map(function(e){return e.kind+":"+e.id}).join(",");return e(t,this.__rtcStatsId,n.id+" "+i),r.apply(this,arguments)})}),["addTrack"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=arguments[0],i=[].slice.call(arguments,1);return e(t,this.__rtcStatsId,n.kind+":"+n.id+" "+(i.map(function(e){return"stream:"+e.id}).join(";")||"-")),r.apply(this,arguments)})}),["removeTrack"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=arguments[0].track;return e(t,this.__rtcStatsId,n?n.kind+":"+n.id:"null"),r.apply(this,arguments)})}),["createOffer","createAnswer"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n,i=this.__rtcStatsId,s=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?n=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(n=arguments[2]),e(t,this.__rtcStatsId,n),r.apply(this,n?[n]:void 0).then(function(r){if(e(t+"OnSuccess",i,r),!(s.length>0&&"function"==typeof s[0]))return r;s[0].apply(null,[r])},function(r){if(e(t+"OnFailure",i,r.toString()),!(s.length>1&&"function"==typeof s[1]))throw r;s[1].apply(null,[r])})})}),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=this.__rtcStatsId,i=arguments;return e(t,this.__rtcStatsId,i[0]),r.apply(this,[i[0]]).then(function(){e(t+"OnSuccess",n,void 0),i.length>=2&&"function"==typeof i[1]&&i[1].apply(null,[])},function(r){if(e(t+"OnFailure",n,r.toString()),!(i.length>=3&&"function"==typeof i[2]))throw r;i[2].apply(null,[r])})})}),a.generateCertificate&&Object.defineProperty(c,"generateCertificate",{get:function(){return arguments.length?a.generateCertificate.apply(null,arguments):a.generateCertificate}}),window[r+"RTCPeerConnection"]=c,window[r+"RTCPeerConnection"].prototype=a.prototype}}),r.forEach(function(t){var r=t+(t.length?"GetUserMedia":"getUserMedia");if(navigator[r]){var n=navigator[r].bind(navigator);navigator[r]=function(){e("getUserMedia",null,arguments[0]);var t=arguments[1],r=arguments[2];n(arguments[0],function(r){e("getUserMediaOnSuccess",null,Mo(r)),t&&t(r)},function(t){e("getUserMediaOnFailure",null,t.name),r&&r(t)})}.bind(navigator)}}),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var a=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(){return e("navigator.mediaDevices.getUserMedia",null,arguments[0]),a.apply(navigator.mediaDevices,arguments).then(function(t){return e("navigator.mediaDevices.getUserMediaOnSuccess",null,Mo(t)),t},function(t){return e("navigator.mediaDevices.getUserMediaOnFailure",null,t.name),Promise.reject(t)})}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var c=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getDisplayMedia=function(){return e("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),c.apply(navigator.mediaDevices,arguments).then(function(t){return e("navigator.mediaDevices.getDisplayMediaOnSuccess",null,Mo(t)),t},function(t){return e("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)})}.bind(navigator.mediaDevices)}return{resetDelta(){o={}}}},Ao=c(jo);let Lo;const No=new Uint8Array(16);function Fo(){if(!Lo&&(Lo="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Lo))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lo(No)}const Bo=[];for(let zE=0;zE<256;++zE)Bo.push((zE+256).toString(16).slice(1));var zo={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Uo(e,t,r){if(zo.randomUUID&&!e)return zo.randomUUID();const n=(e=e||{}).random||(e.rng||Fo)();return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(e,t=0){return Bo[e[t+0]]+Bo[e[t+1]]+Bo[e[t+2]]+Bo[e[t+3]]+"-"+Bo[e[t+4]]+Bo[e[t+5]]+"-"+Bo[e[t+6]]+Bo[e[t+7]]+"-"+Bo[e[t+8]]+Bo[e[t+9]]+"-"+Bo[e[t+10]]+Bo[e[t+11]]+Bo[e[t+12]]+Bo[e[t+13]]+Bo[e[t+14]]+Bo[e[t+15]]}(n)}const Vo=Object.create(null);Vo.open="0",Vo.close="1",Vo.ping="2",Vo.pong="3",Vo.message="4",Vo.upgrade="5",Vo.noop="6";const $o=Object.create(null);Object.keys(Vo).forEach(e=>{$o[Vo[e]]=e});const Go={type:"error",data:"parser error"},qo="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Ho="function"==typeof ArrayBuffer,Wo=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Jo=({type:e,data:t},r,n)=>qo&&t instanceof Blob?r?n(t):Ko(t,n):Ho&&(t instanceof ArrayBuffer||Wo(t))?r?n(t):Ko(new Blob([t]),n):n(Vo[e]+(t||"")),Ko=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Qo(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Yo;const Xo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Zo="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let UE=0;UE<64;UE++)Zo[Xo.charCodeAt(UE)]=UE;const ea="function"==typeof ArrayBuffer,ta=(e,t)=>{if("string"!=typeof e)return{type:"message",data:na(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:ra(e.substring(1),t)};return $o[r]?e.length>1?{type:$o[r],data:e.substring(1)}:{type:$o[r]}:Go},ra=(e,t)=>{if(ea){const r=(e=>{let t,r,n,i,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=Zo[e.charCodeAt(t)],n=Zo[e.charCodeAt(t+1)],i=Zo[e.charCodeAt(t+2)],s=Zo[e.charCodeAt(t+3)],l[c++]=r<<2|n>>4,l[c++]=(15&n)<<4|i>>2,l[c++]=(3&i)<<6|63&s;return d})(e);return na(r,t)}return{base64:!0,data:e}},na=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,ia=String.fromCharCode(30);function sa(){return new TransformStream({transform(e,t){!function(e,t){qo&&e.data instanceof Blob?e.data.arrayBuffer().then(Qo).then(t):Ho&&(e.data instanceof ArrayBuffer||Wo(e.data))?t(Qo(e.data)):Jo(e,!1,e=>{Yo||(Yo=new TextEncoder),t(Yo.encode(e))})}(e,r=>{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(r)})}})}let oa;function aa(e){return e.reduce((e,t)=>e+t.length,0)}function ca(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function da(e){if(e)return function(e){for(var t in da.prototype)e[t]=da.prototype[t];return e}(e)}da.prototype.on=da.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},da.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},da.prototype.off=da.prototype.removeListener=da.prototype.removeAllListeners=da.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},da.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},da.prototype.emitReserved=da.prototype.emit,da.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},da.prototype.hasListeners=function(e){return!!this.listeners(e).length};const la="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function ua(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const pa=la.setTimeout,ha=la.clearTimeout;function fa(e,t){t.useNativeTimers?(e.setTimeoutFn=pa.bind(la),e.clearTimeoutFn=ha.bind(la)):(e.setTimeoutFn=la.setTimeout.bind(la),e.clearTimeoutFn=la.clearTimeout.bind(la))}function ma(e){return"string"==typeof e?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(e):Math.ceil(1.33*(e.byteLength||e.size))}class ga extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class va extends da{constructor(e){super(),this.writable=!1,fa(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new ga(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=ta(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const ba="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),ya={};let _a,wa=0,Sa=0;function Ca(e){let t="";do{t=ba[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function ka(){const e=Ca(+new Date);return e!==_a?(wa=0,_a=e):e+"."+Ca(wa++)}for(;Sa<64;Sa++)ya[ba[Sa]]=Sa;let Ta=!1;try{Ta="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(VE){}const Pa=Ta;function Ra(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Pa))return new XMLHttpRequest}catch(e){}if(!t)try{return new(la[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Ea(){}const Oa=null!=new Ra({xdomain:!1}).responseType;let xa=class e extends da{constructor(e,t){super(),fa(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var t;const r=ua(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this.opts.xd;const n=this.xhr=new Ra(r);try{n.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(t=this.opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(n)),4===n.readyState&&(200===n.status||1223===n.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof n.status?n.status:0)},0))},n.send(this.data)}catch(e){return void this.setTimeoutFn(()=>{this.onError(e)},0)}"undefined"!=typeof document&&(this.index=e.requestsCount++,e.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Ea,t)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete e.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}};if(xa.requestsCount=0,xa.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Ia);else if("function"==typeof addEventListener){addEventListener("onpagehide"in la?"pagehide":"unload",Ia,!1)}function Ia(){for(let e in xa.requests)xa.requests.hasOwnProperty(e)&&xa.requests[e].abort()}const Da="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Ma=la.WebSocket||la.MozWebSocket,ja="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const Aa={websocket:class extends va{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=ja?{}:ua(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=ja?new Ma(e,t,r):t?new Ma(e,t):new Ma(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;Jo(r,this.supportsBinary,e=>{try{this.ws.send(e)}catch(e){}n&&Da(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ka()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Ma}},webtransport:class extends va{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const t=function(e,t){oa||(oa=new TextDecoder);const r=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===n){if(aa(r)<1)break;const e=ca(r,1);s=!(128&~e[0]),i=127&e[0],n=i<126?3:126===i?1:2}else if(1===n){if(aa(r)<2)break;const e=ca(r,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(aa(r)<8)break;const e=ca(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(Go);break}i=s*Math.pow(2,32)+t.getUint32(4),n=3}else{if(aa(r)<i)break;const e=ca(r,i);a.enqueue(ta(s?e:oa.decode(e),t)),n=0}if(0===i||i>e){a.enqueue(Go);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=sa();n.readable.pipeTo(e.writable),this.writer=n.writable.getWriter();const i=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;this.writer.write(r).then(()=>{n&&Da(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends va{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=Oa&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(ia),n=[];for(let e=0;e<r.length;e++){const i=ta(r[e],t);if(n.push(i),"error"===i.type)break}return n})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach((e,s)=>{Jo(e,!1,e=>{n[s]=e,++i===r&&t(n.join(ia))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=ka()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new xa(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}},La=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Na=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Fa(e){if(e.length>2e3)throw"URI too long";const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=La.exec(e||""),s={},o=14;for(;o--;)s[Na[o]]=i[o]||"";return-1!=r&&-1!=n&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(r[t]=n)}),r}(0,s.query),s}let Ba=class e extends da{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Fa(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Fa(t.host).host),fa(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new Aa[e](r)}open(){let t;if(this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(e){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",e=>this.onClose("transport close",e))}probe(t){let r=this.createTransport(t),n=!1;e.priorWebsocketSuccess=!1;const i=()=>{n||(r.send([{type:"ping",data:"probe"}]),r.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;e.priorWebsocketSuccess="websocket"===r.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(l(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=r.name,this.emitReserved("upgradeError",e)}}))};function s(){n||(n=!0,l(),r.close(),r=null)}const o=e=>{const t=new Error("probe error: "+e);t.transport=r.name,s(),this.emitReserved("upgradeError",t)};function a(){o("transport closed")}function c(){o("socket closed")}function d(e){r&&e.name!==r.name&&s()}const l=()=>{r.removeListener("open",i),r.removeListener("error",o),r.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};r.once("open",i),r.once("error",o),r.once("close",a),this.once("close",c),this.once("upgrading",d),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||r.open()},200):r.open()}onOpen(){if(this.readyState="open",e.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const r=this.writeBuffer[t].data;if(r&&(e+=ma(r)),t>0&&e>this.maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}onError(t){e.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}};Ba.protocol=4;const za="function"==typeof ArrayBuffer,Ua=Object.prototype.toString,Va="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Ua.call(Blob),$a="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Ua.call(File);function Ga(e){return za&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Va&&e instanceof Blob||$a&&e instanceof File}function qa(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(qa(e[t]))return!0;return!1}if(Ga(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return qa(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&qa(e[t]))return!0;return!1}function Ha(e){const t=[],r=e.data,n=e;return n.data=Wa(r,t),n.attachments=t.length,{packet:n,buffers:t}}function Wa(e,t){if(!e)return e;if(Ga(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=Wa(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=Wa(e[n],t));return r}return e}function Ja(e,t){return e.data=Ka(e.data,t),delete e.attachments,e}function Ka(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=Ka(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Ka(e[r],t));return e}const Qa=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Ya;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Ya||(Ya={}));function Xa(e){return"[object Object]"===Object.prototype.toString.call(e)}class Za extends da{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Ya.BINARY_EVENT;r||t.type===Ya.BINARY_ACK?(t.type=r?Ya.EVENT:Ya.ACK,this.reconstructor=new ec(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Ga(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Ya[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Ya.BINARY_EVENT||r.type===Ya.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Za.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Ya.CONNECT:return Xa(t);case Ya.DISCONNECT:return void 0===t;case Ya.CONNECT_ERROR:return"string"==typeof t||Xa(t);case Ya.EVENT:case Ya.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Qa.indexOf(t[0]));case Ya.ACK:case Ya.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ec{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Ja(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var tc=Object.freeze({__proto__:null,Decoder:Za,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Ya.EVENT&&e.type!==Ya.ACK||!qa(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Ya.EVENT?Ya.BINARY_EVENT:Ya.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Ya.BINARY_EVENT&&e.type!==Ya.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Ha(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}},get PacketType(){return Ya},protocol:5});function rc(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const nc=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ic extends da{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[rc(e,"open",this.onopen.bind(this)),rc(e,"packet",this.onpacket.bind(this)),rc(e,"error",this.onerror.bind(this)),rc(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(nc.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Ya.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise((n,i)=>{t.push((e,t)=>r?e?i(e):n(t):n(e)),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ya.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ya.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ya.EVENT:case Ya.BINARY_EVENT:this.onevent(e);break;case Ya.ACK:case Ya.BINARY_ACK:this.onack(e);break;case Ya.DISCONNECT:this.ondisconnect();break;case Ya.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,t.packet({type:Ya.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ya.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function sc(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}sc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+r:e-r}return 0|Math.min(e,this.max)},sc.prototype.reset=function(){this.attempts=0},sc.prototype.setMin=function(e){this.ms=e},sc.prototype.setMax=function(e){this.max=e},sc.prototype.setJitter=function(e){this.jitter=e};class oc extends da{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,fa(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new sc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||tc;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Ba(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=rc(t,"open",function(){r.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=rc(t,"error",i);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{n(),i(new Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(n),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(rc(e,"ping",this.onping.bind(this)),rc(e,"data",this.ondata.bind(this)),rc(e,"error",this.onerror.bind(this)),rc(e,"close",this.onclose.bind(this)),rc(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Da(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new ic(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const ac={};function cc(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=Fa(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,s=r.path,o=ac[i]&&s in ac[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new oc(n,t):(ac[i]||(ac[i]=new oc(n,t)),a=ac[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(cc,{Manager:oc,Socket:ic,io:cc,connect:cc});var dc={},lc={},uc={};Object.defineProperty(uc,"__esModule",{value:!0}),uc.isCorrect=uc.isInSubnet=void 0,uc.isInSubnet=function(e){return!(this.subnetMask<e.subnetMask)&&this.mask(e.subnetMask)===e.mask()},uc.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}};var pc={};Object.defineProperty(pc,"__esModule",{value:!0}),pc.RE_SUBNET_STRING=pc.RE_ADDRESS=pc.GROUPS=pc.BITS=void 0,pc.BITS=32,pc.GROUPS=4,pc.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,pc.RE_SUBNET_STRING=/\/\d{1,2}$/;var hc={};Object.defineProperty(hc,"__esModule",{value:!0}),hc.AddressError=void 0;class fc extends Error{constructor(e,t){super(e),this.name="AddressError",null!==t&&(this.parseMessage=t)}}hc.AddressError=fc;var mc,gc={exports:{}};mc=gc,function(){var e;function t(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function r(){return new t(null)}var n="undefined"!=typeof navigator;n&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,r,n,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],d=this[e++]>>15,l=a*c+d*o;i=((c=o*c+((32767&l)<<15)+r[n]+(1073741823&i))>>>30)+(l>>>15)+a*d+(i>>>30),r[n++]=1073741823&c}return i},e=30):n&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this[e++]+r[n]+i;i=Math.floor(o/67108864),r[n++]=67108863&o}return i},e=26):(t.prototype.am=function(e,t,r,n,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],d=this[e++]>>14,l=a*c+d*o;i=((c=o*c+((16383&l)<<14)+r[n]+i)>>28)+(l>>14)+a*d,r[n++]=268435455&c}return i},e=28),t.prototype.DB=e,t.prototype.DM=(1<<e)-1,t.prototype.DV=1<<e,t.prototype.FV=Math.pow(2,52),t.prototype.F1=52-e,t.prototype.F2=2*e-52;var i,s,o=new Array;for(i="0".charCodeAt(0),s=0;s<=9;++s)o[i++]=s;for(i="a".charCodeAt(0),s=10;s<36;++s)o[i++]=s;for(i="A".charCodeAt(0),s=10;s<36;++s)o[i++]=s;function a(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function c(e,t){var r=o[e.charCodeAt(t)];return null==r?-1:r}function d(e){var t=r();return t.fromInt(e),t}function l(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function u(e){this.m=e}function p(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function h(e,t){return e&t}function f(e,t){return e|t}function m(e,t){return e^t}function g(e,t){return e&~t}function v(e){if(0==e)return-1;var t=0;return 65535&e||(e>>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function b(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function y(){}function _(e){return e}function w(e){this.r2=r(),this.q3=r(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}u.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},u.prototype.revert=function(e){return e},u.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},u.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},u.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},p.prototype.convert=function(e){var n=r();return e.abs().dlShiftTo(this.m.t,n),n.divRemTo(this.m,null,n),e.s<0&&n.compareTo(t.ZERO)>0&&this.m.subTo(n,n),n},p.prototype.revert=function(e){var t=r();return e.copyTo(t),this.reduce(t),t},p.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e[t],n=r*this.mpl+((r*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,n,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},p.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},p.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},t.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},t.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},t.prototype.fromString=function(e,r){var n;if(16==r)n=4;else if(8==r)n=3;else if(256==r)n=8;else if(2==r)n=1;else if(32==r)n=5;else{if(4!=r)return void this.fromRadix(e,r);n=2}this.t=0,this.s=0;for(var i=e.length,s=!1,o=0;--i>=0;){var a=8==n?255&e[i]:c(e,i);a<0?"-"==e.charAt(i)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+n>this.DB?(this[this.t-1]|=(a&(1<<this.DB-o)-1)<<o,this[this.t++]=a>>this.DB-o):this[this.t-1]|=a<<o,(o+=n)>=this.DB&&(o-=this.DB))}8==n&&128&e[0]&&(this.s=-1,o>0&&(this[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),s&&t.ZERO.subTo(this,this)},t.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},t.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s},t.prototype.drShiftTo=function(e,t){for(var r=e;r<this.t;++r)t[r-e]=this[r];t.t=Math.max(this.t-e,0),t.s=this.s},t.prototype.lShiftTo=function(e,t){var r,n=e%this.DB,i=this.DB-n,s=(1<<i)-1,o=Math.floor(e/this.DB),a=this.s<<n&this.DM;for(r=this.t-1;r>=0;--r)t[r+o+1]=this[r]>>i|a,a=(this[r]&s)<<n;for(r=o-1;r>=0;--r)t[r]=0;t[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},t.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,s=(1<<n)-1;t[0]=this[r]>>n;for(var o=r+1;o<this.t;++o)t[o-r-1]|=(this[o]&s)<<i,t[o-r]=this[o]>>n;n>0&&(t[this.t-r-1]|=(this.s&s)<<i),t.t=this.t-r,t.clamp()}},t.prototype.subTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]-e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e[r],t[r++]=n&this.DM,n>>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t[r++]=this.DV+n:n>0&&(t[r++]=n),t.t=r,t.clamp()},t.prototype.multiplyTo=function(e,r){var n=this.abs(),i=e.abs(),s=n.t;for(r.t=s+i.t;--s>=0;)r[s]=0;for(s=0;s<i.t;++s)r[s+n.t]=n.am(0,i[s],r,s,0,n.t);r.s=0,r.clamp(),this.s!=e.s&&t.ZERO.subTo(r,r)},t.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e[r]=0;for(r=0;r<t.t-1;++r){var n=t.am(r,t[r],e,2*r,0,1);(e[r+t.t]+=t.am(r+1,2*t[r],e,2*r+1,n,t.t-r-1))>=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()},t.prototype.divRemTo=function(e,n,i){var s=e.abs();if(!(s.t<=0)){var o=this.abs();if(o.t<s.t)return null!=n&&n.fromInt(0),void(null!=i&&this.copyTo(i));null==i&&(i=r());var a=r(),c=this.s,d=e.s,u=this.DB-l(s[s.t-1]);u>0?(s.lShiftTo(u,a),o.lShiftTo(u,i)):(s.copyTo(a),o.copyTo(i));var p=a.t,h=a[p-1];if(0!=h){var f=h*(1<<this.F1)+(p>1?a[p-2]>>this.F2:0),m=this.FV/f,g=(1<<this.F1)/f,v=1<<this.F2,b=i.t,y=b-p,_=null==n?r():n;for(a.dlShiftTo(y,_),i.compareTo(_)>=0&&(i[i.t++]=1,i.subTo(_,i)),t.ONE.dlShiftTo(p,_),_.subTo(a,a);a.t<p;)a[a.t++]=0;for(;--y>=0;){var w=i[--b]==h?this.DM:Math.floor(i[b]*m+(i[b-1]+v)*g);if((i[b]+=a.am(0,w,i,y,0,p))<w)for(a.dlShiftTo(y,_),i.subTo(_,i);i[b]<--w;)i.subTo(_,i)}null!=n&&(i.drShiftTo(p,n),c!=d&&t.ZERO.subTo(n,n)),i.t=p,i.clamp(),u>0&&i.rShiftTo(u,i),c<0&&t.ZERO.subTo(i,i)}}},t.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},t.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},t.prototype.exp=function(e,n){if(e>4294967295||e<1)return t.ONE;var i=r(),s=r(),o=n.convert(this),a=l(e)-1;for(o.copyTo(i);--a>=0;)if(n.sqrTo(i,s),(e&1<<a)>0)n.mulTo(s,o,i);else{var c=i;i=s,s=c}return n.revert(i)},t.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<<t)-1,i=!1,s="",o=this.t,c=this.DB-o*this.DB%t;if(o-- >0)for(c<this.DB&&(r=this[o]>>c)>0&&(i=!0,s=a(r));o>=0;)c<t?(r=(this[o]&(1<<c)-1)<<t-c,r|=this[--o]>>(c+=this.DB-t)):(r=this[o]>>(c-=t)&n,c<=0&&(c+=this.DB,--o)),r>0&&(i=!0),i&&(s+=a(r));return i?s:"0"},t.prototype.negate=function(){var e=r();return t.ZERO.subTo(this,e),e},t.prototype.abs=function(){return this.s<0?this.negate():this},t.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0},t.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+l(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var n=r();return this.abs().divRemTo(e,null,n),this.s<0&&n.compareTo(t.ZERO)>0&&e.subTo(n,n),n},t.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new u(t):new p(t),this.exp(e,r)},t.ZERO=d(0),t.ONE=d(1),y.prototype.convert=_,y.prototype.revert=_,y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},y.prototype.sqrTo=function(e,t){e.squareTo(t)},w.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=r();return e.copyTo(t),this.reduce(t),t},w.prototype.revert=function(e){return e},w.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},w.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},w.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var S,C,k,T=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],P=(1<<26)/T[T.length-1];function R(){var e;e=(new Date).getTime(),C[k++]^=255&e,C[k++]^=e>>8&255,C[k++]^=e>>16&255,C[k++]^=e>>24&255,k>=j&&(k-=j)}if(t.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},t.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),n=Math.pow(e,t),i=d(n),s=r(),o=r(),a="";for(this.divRemTo(i,s,o);s.signum()>0;)a=(n+o.intValue()).toString(e).substr(1)+a,s.divRemTo(i,s,o);return o.intValue().toString(e)+a},t.prototype.fromRadix=function(e,r){this.fromInt(0),null==r&&(r=10);for(var n=this.chunkSize(r),i=Math.pow(r,n),s=!1,o=0,a=0,d=0;d<e.length;++d){var l=c(e,d);l<0?"-"==e.charAt(d)&&0==this.signum()&&(s=!0):(a=r*a+l,++o>=n&&(this.dMultiply(i),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(r,o)),this.dAddOffset(a,0)),s&&t.ZERO.subTo(this,this)},t.prototype.fromNumber=function(e,r,n){if("number"==typeof r)if(e<2)this.fromInt(1);else for(this.fromNumber(e,n),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),f,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(r);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(t.ONE.shiftLeft(e-1),this);else{var i=new Array,s=7&e;i.length=1+(e>>3),r.nextBytes(i),s>0?i[0]&=(1<<s)-1:i[0]=0,this.fromString(i,256)}},t.prototype.bitwiseTo=function(e,t,r){var n,i,s=Math.min(e.t,this.t);for(n=0;n<s;++n)r[n]=t(this[n],e[n]);if(e.t<this.t){for(i=e.s&this.DM,n=s;n<this.t;++n)r[n]=t(this[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=s;n<e.t;++n)r[n]=t(i,e[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},t.prototype.changeBit=function(e,r){var n=t.ONE.shiftLeft(e);return this.bitwiseTo(n,r,n),n},t.prototype.addTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]+e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e[r],t[r++]=n&this.DM,n>>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t[r++]=n:n<-1&&(t[r++]=this.DV+n),t.t=r,t.clamp()},t.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},t.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},t.prototype.multiplyLowerTo=function(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i<n;++i)r[i+this.t]=this.am(0,e[i],r,i,0,this.t);for(n=Math.min(e.t,t);i<n;++i)this.am(0,e[i],r,i,0,t-i);r.clamp()},t.prototype.multiplyUpperTo=function(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r[this.t+n-t]=this.am(t-n,e[n],r,0,0,this.t+n-t);r.clamp(),r.drShiftTo(1,r)},t.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this[n])%e;return r},t.prototype.millerRabin=function(e){var n=this.subtract(t.ONE),i=n.getLowestSetBit();if(i<=0)return!1;var s=n.shiftRight(i);(e=e+1>>1)>T.length&&(e=T.length);for(var o=r(),a=0;a<e;++a){o.fromInt(T[Math.floor(Math.random()*T.length)]);var c=o.modPow(s,this);if(0!=c.compareTo(t.ONE)&&0!=c.compareTo(n)){for(var d=1;d++<i&&0!=c.compareTo(n);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(n))return!1}}return!0},t.prototype.clone=function(){var e=r();return this.copyTo(e),e},t.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},t.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},t.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},t.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},t.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n<this.DB&&(r=this[e]>>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<<this.DB-n);e>=0;)n<8?(r=(this[e]&(1<<n)-1)<<8-n,r|=this[--e]>>(n+=this.DB-8)):(r=this[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),128&r&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t},t.prototype.equals=function(e){return 0==this.compareTo(e)},t.prototype.min=function(e){return this.compareTo(e)<0?this:e},t.prototype.max=function(e){return this.compareTo(e)>0?this:e},t.prototype.and=function(e){var t=r();return this.bitwiseTo(e,h,t),t},t.prototype.or=function(e){var t=r();return this.bitwiseTo(e,f,t),t},t.prototype.xor=function(e){var t=r();return this.bitwiseTo(e,m,t),t},t.prototype.andNot=function(e){var t=r();return this.bitwiseTo(e,g,t),t},t.prototype.not=function(){for(var e=r(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},t.prototype.shiftLeft=function(e){var t=r();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},t.prototype.shiftRight=function(e){var t=r();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},t.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+v(this[e]);return this.s<0?this.t*this.DB:-1},t.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=b(this[r]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:!!(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,f)},t.prototype.clearBit=function(e){return this.changeBit(e,g)},t.prototype.flipBit=function(e){return this.changeBit(e,m)},t.prototype.add=function(e){var t=r();return this.addTo(e,t),t},t.prototype.subtract=function(e){var t=r();return this.subTo(e,t),t},t.prototype.multiply=function(e){var t=r();return this.multiplyTo(e,t),t},t.prototype.divide=function(e){var t=r();return this.divRemTo(e,t,null),t},t.prototype.remainder=function(e){var t=r();return this.divRemTo(e,null,t),t},t.prototype.divideAndRemainder=function(e){var t=r(),n=r();return this.divRemTo(e,t,n),new Array(t,n)},t.prototype.modPow=function(e,t){var n,i,s=e.bitLength(),o=d(1);if(s<=0)return o;n=s<18?1:s<48?3:s<144?4:s<768?5:6,i=s<8?new u(t):t.isEven()?new w(t):new p(t);var a=new Array,c=3,h=n-1,f=(1<<n)-1;if(a[1]=i.convert(this),n>1){var m=r();for(i.sqrTo(a[1],m);c<=f;)a[c]=r(),i.mulTo(m,a[c-2],a[c]),c+=2}var g,v,b=e.t-1,y=!0,_=r();for(s=l(e[b])-1;b>=0;){for(s>=h?g=e[b]>>s-h&f:(g=(e[b]&(1<<s+1)-1)<<h-s,b>0&&(g|=e[b-1]>>this.DB+s-h)),c=n;!(1&g);)g>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),y)a[g].copyTo(o),y=!1;else{for(;c>1;)i.sqrTo(o,_),i.sqrTo(_,o),c-=2;c>0?i.sqrTo(o,_):(v=o,o=_,_=v),i.mulTo(_,a[g],o)}for(;b>=0&&!(e[b]&1<<s);)i.sqrTo(o,_),v=o,o=_,_=v,--s<0&&(s=this.DB-1,--b)}return i.revert(o)},t.prototype.modInverse=function(e){var r=e.isEven();if(this.isEven()&&r||0==e.signum())return t.ZERO;for(var n=e.clone(),i=this.clone(),s=d(1),o=d(0),a=d(0),c=d(1);0!=n.signum();){for(;n.isEven();)n.rShiftTo(1,n),r?(s.isEven()&&o.isEven()||(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;i.isEven();)i.rShiftTo(1,i),r?(a.isEven()&&c.isEven()||(a.addTo(this,a),c.subTo(e,c)),a.rShiftTo(1,a)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);n.compareTo(i)>=0?(n.subTo(i,n),r&&s.subTo(a,s),o.subTo(c,o)):(i.subTo(n,i),r&&a.subTo(s,a),c.subTo(o,c))}return 0!=i.compareTo(t.ONE)?t.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},t.prototype.pow=function(e){return this.exp(e,new y)},t.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var n=t;t=r,r=n}var i=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(i<s&&(s=i),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},t.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=T[T.length-1]){for(t=0;t<T.length;++t)if(r[0]==T[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<T.length;){for(var n=T[t],i=t+1;i<T.length&&n<P;)n*=T[i++];for(n=r.modInt(n);t<i;)if(n%T[t++]==0)return!1}return r.millerRabin(e)},t.prototype.square=function(){var e=r();return this.squareTo(e),e},t.prototype.Barrett=w,null==C){var E;if(C=new Array,k=0,"undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var O=new Uint8Array(32);for(window.crypto.getRandomValues(O),E=0;E<32;++E)C[k++]=O[E]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5"){var x=window.crypto.random(32);for(E=0;E<x.length;++E)C[k++]=255&x.charCodeAt(E)}for(;k<j;)E=Math.floor(65536*Math.random()),C[k++]=E>>>8,C[k++]=255&E;k=0,R()}function I(){if(null==S){for(R(),(S=new M).init(C),k=0;k<C.length;++k)C[k]=0;k=0}return S.next()}function D(){}function M(){this.i=0,this.j=0,this.S=new Array}D.prototype.nextBytes=function(e){var t;for(t=0;t<e.length;++t)e[t]=I()},M.prototype.init=function(e){var t,r,n;for(t=0;t<256;++t)this.S[t]=t;for(r=0,t=0;t<256;++t)r=r+this.S[t]+e[t%e.length]&255,n=this.S[t],this.S[t]=this.S[r],this.S[r]=n;this.i=0,this.j=0},M.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]};var j=256;mc.exports={default:t,BigInteger:t,SecureRandom:D}}.call(a);var vc=gc.exports,bc={};!function(e){!function(){var t={not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function r(e){return function(e,n){var i,s,o,a,c,d,l,u,p,h=1,f=e.length,m="";for(s=0;s<f;s++)if("string"==typeof e[s])m+=e[s];else if("object"==typeof e[s]){if((a=e[s]).keys)for(i=n[h],o=0;o<a.keys.length;o++){if(null==i)throw new Error(r('[sprintf] Cannot access property "%s" of undefined value "%s"',a.keys[o],a.keys[o-1]));i=i[a.keys[o]]}else i=a.param_no?n[a.param_no]:n[h++];if(t.not_type.test(a.type)&&t.not_primitive.test(a.type)&&i instanceof Function&&(i=i()),t.numeric_arg.test(a.type)&&"number"!=typeof i&&isNaN(i))throw new TypeError(r("[sprintf] expecting number but found %T",i));switch(t.number.test(a.type)&&(u=i>=0),a.type){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,a.width?parseInt(a.width):0);break;case"e":i=a.precision?parseFloat(i).toExponential(a.precision):parseFloat(i).toExponential();break;case"f":i=a.precision?parseFloat(i).toFixed(a.precision):parseFloat(i);break;case"g":i=a.precision?String(Number(i.toPrecision(a.precision))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=a.precision?i.substring(0,a.precision):i;break;case"t":i=String(!!i),i=a.precision?i.substring(0,a.precision):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=a.precision?i.substring(0,a.precision):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=a.precision?i.substring(0,a.precision):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(a.type)?m+=i:(!t.number.test(a.type)||u&&!a.sign?p="":(p=u?"+":"-",i=i.toString().replace(t.sign,"")),d=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(p+i).length,c=a.width&&l>0?d.repeat(l):"",m+=a.align?p+i+c:"0"===d?p+c+i:c+p+i)}return m}(function(e){if(i[e])return i[e];var r,n=e,s=[],o=0;for(;n;){if(null!==(r=t.text.exec(n)))s.push(r[0]);else if(null!==(r=t.modulo.exec(n)))s.push("%");else{if(null===(r=t.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var a=[],c=r[2],d=[];if(null===(d=t.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a.push(d[1]);""!==(c=c.substring(d[0].length));)if(null!==(d=t.key_access.exec(c)))a.push(d[1]);else{if(null===(d=t.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");a.push(d[1])}r[2]=a}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");s.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}n=n.substring(r[0].length)}return i[e]=s}(e),arguments)}function n(e,t){return r.apply(null,[e].concat(t||[]))}var i=Object.create(null);e.sprintf=r,e.vsprintf=n,"undefined"!=typeof window&&(window.sprintf=r,window.vsprintf=n)}()}(bc);var yc=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),_c=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),wc=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&yc(t,e,r);return _c(t,e),t};Object.defineProperty(lc,"__esModule",{value:!0}),lc.Address4=void 0;const Sc=wc(uc),Cc=wc(pc),kc=hc,Tc=vc,Pc=bc;class Rc{constructor(e){this.groups=Cc.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=Sc.isCorrect(Cc.BITS),this.isInSubnet=Sc.isInSubnet,this.address=e;const t=Cc.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>Cc.BITS)throw new kc.AddressError("Invalid subnet mask.");e=e.replace(Cc.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new Rc(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(Cc.RE_ADDRESS))throw new kc.AddressError("Invalid IPv4 address.");return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromHex(e){const t=e.replace(/:/g,"").padStart(8,"0"),r=[];let n;for(n=0;n<8;n+=2){const e=t.slice(n,n+2);r.push(parseInt(e,16))}return new Rc(r.join("."))}static fromInteger(e){return Rc.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new Rc(t)}toHex(){return this.parsedAddress.map(e=>(0,Pc.sprintf)("%02x",parseInt(e,10))).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){const e=[];let t;for(t=0;t<Cc.GROUPS;t+=2){const r=(0,Pc.sprintf)("%02x%02x",parseInt(this.parsedAddress[t],10),parseInt(this.parsedAddress[t+1],10));e.push((0,Pc.sprintf)("%x",parseInt(r,16)))}return e.join(":")}bigInteger(){return new Tc.BigInteger(this.parsedAddress.map(e=>(0,Pc.sprintf)("%02x",parseInt(e,10))).join(""),16)}_startAddress(){return new Tc.BigInteger(this.mask()+"0".repeat(Cc.BITS-this.subnetMask),2)}startAddress(){return Rc.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Tc.BigInteger("1");return Rc.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Tc.BigInteger(this.mask()+"1".repeat(Cc.BITS-this.subnetMask),2)}endAddress(){return Rc.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Tc.BigInteger("1");return Rc.fromBigInteger(this._endAddress().subtract(e))}static fromBigInteger(e){return Rc.fromInteger(parseInt(e.toString(),10))}mask(e){return void 0===e&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||(e={});const t=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?t:(0,Pc.sprintf)("%s.in-addr.arpa.",t)}isMulticast(){return this.isInSubnet(new Rc("224.0.0.0/4"))}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Cc.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(Cc.RE_ADDRESS,(0,Pc.sprintf)('<span class="hover-group group-v4 group-6">%s</span>.<span class="hover-group group-v4 group-7">%s</span>',e.slice(0,2).join("."),e.slice(2,4).join(".")))}}lc.Address4=Rc;var Ec={},Oc={};Object.defineProperty(Oc,"__esModule",{value:!0}),Oc.RE_URL_WITH_PORT=Oc.RE_URL=Oc.RE_ZONE_STRING=Oc.RE_SUBNET_STRING=Oc.RE_BAD_ADDRESS=Oc.RE_BAD_CHARACTERS=Oc.TYPES=Oc.SCOPES=Oc.GROUPS=Oc.BITS=void 0,Oc.BITS=128,Oc.GROUPS=8,Oc.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},Oc.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"},Oc.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,Oc.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,Oc.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,Oc.RE_ZONE_STRING=/%.*$/,Oc.RE_URL=new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/),Oc.RE_URL_WITH_PORT=new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);var xc={};Object.defineProperty(xc,"__esModule",{value:!0}),xc.simpleGroup=xc.spanLeadingZeroes=xc.spanAll=xc.spanAllZeroes=void 0;const Ic=bc;function Dc(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function Mc(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}xc.spanAllZeroes=Dc,xc.spanAll=function(e,t=0){return e.split("").map((e,r)=>(0,Ic.sprintf)('<span class="digit value-%s position-%d">%s</span>',e,r+t,Dc(e))).join("")},xc.spanLeadingZeroes=function(e){return e.split(":").map(e=>Mc(e)).join(":")},xc.simpleGroup=function(e,t=0){return e.split(":").map((e,r)=>/group-v4/.test(e)?e:(0,Ic.sprintf)('<span class="hover-group group-%d">%s</span>',r+t,Mc(e)))};var jc={},Ac=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Lc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Nc=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&Ac(t,e,r);return Lc(t,e),t};Object.defineProperty(jc,"__esModule",{value:!0}),jc.possibleElisions=jc.simpleRegularExpression=jc.ADDRESS_BOUNDARY=jc.padGroup=jc.groupPossibilities=void 0;const Fc=Nc(Oc),Bc=bc;function zc(e){return(0,Bc.sprintf)("(%s)",e.join("|"))}function Uc(e){return e.length<4?(0,Bc.sprintf)("0{0,%d}%s",4-e.length,e):e}jc.groupPossibilities=zc,jc.padGroup=Uc,jc.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]",jc.simpleRegularExpression=function(e){const t=[];e.forEach((e,r)=>{0===parseInt(e,16)&&t.push(r)});const r=t.map(t=>e.map((e,r)=>{if(r===t){const t=0===r||r===Fc.GROUPS-1?":":"";return zc([Uc(e),t])}return Uc(e)}).join(":"));return r.push(e.map(Uc).join(":")),zc(r)},jc.possibleElisions=function(e,t,r){const n=t?"":":",i=r?"":":",s=[];t||r||s.push("::"),t&&r&&s.push(""),(r&&!t||!r&&t)&&s.push(":"),s.push((0,Bc.sprintf)("%s(:0{1,4}){1,%d}",n,e-1)),s.push((0,Bc.sprintf)("(0{1,4}:){1,%d}%s",e-1,i)),s.push((0,Bc.sprintf)("(0{1,4}:){%d}0{1,4}",e-1));for(let t=1;t<e-1;t++)for(let r=1;r<e-t;r++)s.push((0,Bc.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}",r,e-r-t-1));return zc(s)};var Vc=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),$c=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Gc=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&Vc(t,e,r);return $c(t,e),t};Object.defineProperty(Ec,"__esModule",{value:!0}),Ec.Address6=void 0;const qc=Gc(uc),Hc=Gc(pc),Wc=Gc(Oc),Jc=Gc(xc),Kc=lc,Qc=jc,Yc=hc,Xc=vc,Zc=bc;function ed(e){if(!e)throw new Error("Assertion failed.")}function td(e){return e=(e=e.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2')).replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2')}function rd(e){return(0,Zc.sprintf)("%04x",parseInt(e,16))}function nd(e){return 255&e}class id{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=qc.isInSubnet,this.isCorrect=qc.isCorrect(Wc.BITS),this.groups=void 0===t?Wc.GROUPS:t,this.address=e;const r=Wc.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>Wc.BITS)throw new Yc.AddressError("Invalid subnet mask.");e=e.replace(Wc.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new Yc.AddressError("Invalid subnet mask.");const n=Wc.RE_ZONE_STRING.exec(e);n&&(this.zone=n[0],e=e.replace(Wc.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new id(e),!0}catch(e){return!1}}static fromBigInteger(e){const t=e.toString(16).padStart(32,"0"),r=[];let n;for(n=0;n<Wc.GROUPS;n++)r.push(t.slice(4*n,4*(n+1)));return new id(r.join(":"))}static fromURL(e){let t,r,n=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=Wc.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],n=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=Wc.RE_URL.exec(e),null===r)return{error:"failed to parse address from URL",address:null,port:null};t=r[1]}else t=e;return n?(n=parseInt(n,10),(n<0||n>65536)&&(n=null)):n=null,{address:new id(t),port:n}}static fromAddress4(e){const t=new Kc.Address4(e),r=Wc.BITS-(Hc.BITS-t.subnetMask);return new id(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new Yc.AddressError("Invalid 'ip6.arpa' form.");const r=t.split(".").reverse();for(let e=7;e>0;e--){const t=4*e;r.splice(t,0,":")}return t=r.join(""),new id(t)}microsoftTranscription(){return(0,Zc.sprintf)("%s.ipv6-literal.net",this.correctForm().replace(/:/g,"-"))}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=Wc.BITS-this.subnetMask-Math.abs(e-Wc.BITS);return t<0?"0":function(e){const t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,"$1,$2");return e}(new Xc.BigInteger("2",10).pow(t).toString(10))}_startAddress(){return new Xc.BigInteger(this.mask()+"0".repeat(Wc.BITS-this.subnetMask),2)}startAddress(){return id.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Xc.BigInteger("1");return id.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Xc.BigInteger(this.mask()+"1".repeat(Wc.BITS-this.subnetMask),2)}endAddress(){return id.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Xc.BigInteger("1");return id.fromBigInteger(this._endAddress().subtract(e))}getScope(){let e=Wc.SCOPES[this.getBits(12,16).intValue()];return"Global unicast"===this.getType()&&"Link local"!==e&&(e="Global"),e||"Unknown"}getType(){for(const e of Object.keys(Wc.TYPES))if(this.isInSubnet(new id(e)))return Wc.TYPES[e];return"Global unicast"}getBits(e,t){return new Xc.BigInteger(this.getBitsBase2(e,t),2)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){const r=t-e;if(r%4!=0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,t).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,Wc.BITS)}reverseForm(e){e||(e={});const t=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,t).reverse().join(".");return t>0?e.omitSuffix?r:(0,Zc.sprintf)("%s.ip6.arpa.",r):e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const n=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&n.push([e-r,e-1]),r=0)}r>1&&n.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const i=n.map(e=>e[1]-e[0]+1);if(n.length>0){const e=i.indexOf(Math.max(...i));t=function(e,t){const r=[],n=[];let i;for(i=0;i<e.length;i++)i<t[0]?r.push(e[i]):i>t[1]&&n.push(e[i]);return r.concat(["compact"]).concat(n)}(this.parsedAddress,n[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)"compact"!==t[e]&&(t[e]=parseInt(t[e],16).toString(16));let s=t.join(":");return s=s.replace(/^compact$/,"::"),s=s.replace(/^compact|compact$/,":"),s=s.replace(/compact/,""),s}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Wc.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(Hc.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new Kc.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new Yc.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(Hc.RE_ADDRESS,this.address4.parsedAddress.map(td).join(".")));this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(":")}return e}parse(e){const t=(e=this.parse4in6(e)).match(Wc.RE_BAD_CHARACTERS);if(t)throw new Yc.AddressError((0,Zc.sprintf)("Bad character%s detected in address: %s",t.length>1?"s":"",t.join("")),e.replace(Wc.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(Wc.RE_BAD_ADDRESS);if(r)throw new Yc.AddressError((0,Zc.sprintf)("Address failed regex: %s",r.join("")),e.replace(Wc.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let n=[];const i=e.split("::");if(2===i.length){let e=i[0].split(":"),t=i[1].split(":");1===e.length&&""===e[0]&&(e=[]),1===t.length&&""===t[0]&&(t=[]);const r=this.groups-(e.length+t.length);if(!r)throw new Yc.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,n=n.concat(e);for(let e=0;e<r;e++)n.push("0");n=n.concat(t)}else{if(1!==i.length)throw new Yc.AddressError("Too many :: groups found");n=e.split(":"),this.elidedGroups=0}if(n=n.map(e=>(0,Zc.sprintf)("%x",parseInt(e,16))),n.length!==this.groups)throw new Yc.AddressError("Incorrect number of groups found");return n}canonicalForm(){return this.parsedAddress.map(rd).join(":")}decimal(){return this.parsedAddress.map(e=>(0,Zc.sprintf)("%05d",parseInt(e,16))).join(":")}bigInteger(){return new Xc.BigInteger(this.parsedAddress.map(rd).join(""),16)}to4(){const e=this.binaryZeroPad().split("");return Kc.Address4.fromHex(new Xc.BigInteger(e.slice(96,128).join(""),2).toString(16))}to4in6(){const e=this.to4(),t=new id(this.parsedAddress.slice(0,6).join(":"),6).correctForm();let r="";return/:$/.test(t)||(r=":"),t+r+e.address}inspectTeredo(){const e=this.getBitsBase16(0,32),t=this.getBits(80,96).xor(new Xc.BigInteger("ffff",16)).toString(),r=Kc.Address4.fromHex(this.getBitsBase16(32,64)),n=Kc.Address4.fromHex(this.getBits(96,128).xor(new Xc.BigInteger("ffffffff",16)).toString(16)),i=this.getBits(64,80),s=this.getBitsBase2(64,80),o=i.testBit(15),a=i.testBit(14),c=i.testBit(8),d=i.testBit(9),l=new Xc.BigInteger(s.slice(2,6)+s.slice(8,16),2).toString(10);return{prefix:(0,Zc.sprintf)("%s:%s",e.slice(0,4),e.slice(4,8)),server4:r.address,client4:n.address,flags:s,coneNat:o,microsoft:{reserved:a,universalLocal:d,groupIndividual:c,nonce:l},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=Kc.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:(0,Zc.sprintf)("%s",e.slice(0,4)),gateway:t.address}}to6to4(){if(!this.is4())return null;const e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new id(e)}toByteArray(){const e=this.bigInteger().toByteArray();return 17===e.length&&0===e[0]?e.slice(1):e}toUnsignedByteArray(){return this.toByteArray().map(nd)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(nd))}static fromUnsignedByteArray(e){const t=new Xc.BigInteger("256",10);let r=new Xc.BigInteger("0",10),n=new Xc.BigInteger("1",10);for(let i=e.length-1;i>=0;i--)r=r.add(n.multiply(new Xc.BigInteger(e[i].toString(10),10))),n=n.multiply(t);return id.fromBigInteger(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return"1111111010000000000000000000000000000000000000000000000000000000"===this.getBitsBase2(0,64)}isMulticast(){return"Multicast"===this.getType()}is4(){return this.v4}isTeredo(){return this.isInSubnet(new id("2001::/32"))}is6to4(){return this.isInSubnet(new id("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":(0,Zc.sprintf)(":%s",e),(0,Zc.sprintf)("http://[%s]%s/",this.correctForm(),e)}link(e){e||(e={}),void 0===e.className&&(e.className=""),void 0===e.prefix&&(e.prefix="/#address="),void 0===e.v4&&(e.v4=!1);let t=this.correctForm;return e.v4&&(t=this.to4in6),e.className?(0,Zc.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>',e.prefix,t.call(this),e.className):(0,Zc.sprintf)('<a href="%1$s%2$s">%2$s</a>',e.prefix,t.call(this))}group(){if(0===this.elidedGroups)return Jc.simpleGroup(this.address).join(":");ed("number"==typeof this.elidedGroups),ed("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...Jc.simpleGroup(t)):e.push("");const n=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)n.push((0,Zc.sprintf)("group-%d",e));return e.push((0,Zc.sprintf)('<span class="%s"></span>',n.join(" "))),r.length?e.push(...Jc.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(ed(this.address4 instanceof Kc.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new id(this.correctForm());if(0===r.elidedGroups)t.push((0,Qc.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===Wc.GROUPS)t.push((0,Qc.possibleElisions)(Wc.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,Qc.simpleRegularExpression)(e[0].split(":"))),ed("number"==typeof r.elidedGroups),t.push((0,Qc.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,Qc.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",Qc.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",Qc.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}Ec.Address6=id,function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&t(n,e,i);return r(n,e),n};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;const i=lc;Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});const s=Ec;Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return s.Address6}});const o=hc;Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}});const c=n(xc);e.v6={helpers:c}}(dc);var sd={exports:{}};!function(e){(function(){var t,r,n,i,s,o,a,c;r={},null!==e&&e.exports?e.exports=r:this.ipaddr=r,a=function(e,t,r,n){var i,s;if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;n>0;){if((s=r-n)<0&&(s=0),e[i]>>s!==t[i]>>s)return!1;n-=r,i+=1}return!0},r.subnetMatch=function(e,t,r){var n,i,s,o,a;for(s in null==r&&(r="unicast"),t)for(!(o=t[s])[0]||o[0]instanceof Array||(o=[o]),n=0,i=o.length;n<i;n++)if(a=o[n],e.kind()===a[0].kind()&&e.match.apply(e,a))return s;return r},r.IPv4=function(){function e(e){var t,r,n;if(4!==e.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(t=0,r=e.length;t<r;t++)if(!(0<=(n=e[t])&&n<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=e}return e.prototype.kind=function(){return"ipv4"},e.prototype.toString=function(){return this.octets.join(".")},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv4"!==e.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,e.octets,8,t)},e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.toIPv4MappedAddress=function(){return r.IPv6.parse("::ffff:"+this.toString())},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,n,i,s,o;for(o={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},e=0,i=!1,t=r=3;r>=0;t=r+=-1){if(!((n=this.octets[t])in o))return null;if(s=o[n],i&&0!==s)return null;8!==s&&(i=!0),e+=s}return 32-e},e}(),n="(0?\\d+|0x[a-f0-9]+)",i={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},r.IPv4.parser=function(e){var t,r,n,s,o;if(r=function(e){return"0"===e[0]&&"x"!==e[1]?parseInt(e,8):parseInt(e)},t=e.match(i.fourOctet))return function(){var e,i,s,o;for(o=[],e=0,i=(s=t.slice(1,6)).length;e<i;e++)n=s[e],o.push(r(n));return o}();if(t=e.match(i.longValue)){if((o=r(t[1]))>4294967295||o<0)throw new Error("ipaddr: address outside defined range");return function(){var e,t;for(t=[],s=e=0;e<=24;s=e+=8)t.push(o>>s&255);return t}().reverse()}return null},r.IPv6=function(){function e(e,t){var r,n,i,s,o,a;if(16===e.length)for(this.parts=[],r=n=0;n<=14;r=n+=2)this.parts.push(e[r]<<8|e[r+1]);else{if(8!==e.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=e}for(i=0,s=(a=this.parts).length;i<s;i++)if(!(0<=(o=a[i])&&o<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return e.prototype.kind=function(){return"ipv6"},e.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},e.prototype.toRFC5952String=function(){var e,t,r,n,i;for(n=/((^|:)(0(:|$)){2,})/g,i=this.toNormalizedString(),e=0,t=-1;r=n.exec(i);)r[0].length>t&&(e=r.index,t=r[0].length);return t<0?i:i.substring(0,e)+"::"+i.substring(e+t)},e.prototype.toByteArray=function(){var e,t,r,n,i;for(e=[],t=0,r=(i=this.parts).length;t<r;t++)n=i[t],e.push(n>>8),e.push(255&n);return e},e.prototype.toNormalizedString=function(){var e,t,r;return e=function(){var e,r,n,i;for(i=[],e=0,r=(n=this.parts).length;e<r;e++)t=n[e],i.push(t.toString(16));return i}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.toFixedLengthString=function(){var e,t,r;return e=function(){var e,r,n,i;for(i=[],e=0,r=(n=this.parts).length;e<r;e++)t=n[e],i.push(t.toString(16).padStart(4,"0"));return i}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv6"!==e.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,e.parts,16,t)},e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],reserved:[[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},e.prototype.toIPv4Address=function(){var e,t,n;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=(n=this.parts.slice(-2))[0],t=n[1],new r.IPv4([e>>8,255&e,t>>8,255&t])},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,n,i,s,o;for(o={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},e=0,i=!1,t=r=7;r>=0;t=r+=-1){if(!((n=this.parts[t])in o))return null;if(s=o[n],i&&0!==s)return null;16!==s&&(i=!0),e+=s}return 128-e},e}(),s="(?:[0-9a-f]+::?)+",c="%[0-9a-z]{1,}",o={zoneIndex:new RegExp(c,"i"),native:new RegExp("^(::)?("+s+")?([0-9a-f]+)?(::)?("+c+")?$","i"),transitional:new RegExp("^((?:"+s+")|(?:::)(?:"+s+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"("+c+")?$","i")},t=function(e,t){var r,n,i,s,a,c;if(e.indexOf("::")!==e.lastIndexOf("::"))return null;for((c=(e.match(o.zoneIndex)||[])[0])&&(c=c.substring(1),e=e.replace(/%.+$/,"")),r=0,n=-1;(n=e.indexOf(":",n+1))>=0;)r++;if("::"===e.substr(0,2)&&r--,"::"===e.substr(-2,2)&&r--,r>t)return null;for(a=t-r,s=":";a--;)s+="0:";return":"===(e=e.replace("::",s))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){var t,r,n,s;for(s=[],t=0,r=(n=e.split(":")).length;t<r;t++)i=n[t],s.push(parseInt(i,16));return s}(),zoneId:c}},r.IPv6.parser=function(e){var r,n,i,s,a,c,d;if(o.native.test(e))return t(e,8);if((s=e.match(o.transitional))&&(d=s[6]||"",(r=t(s[1].slice(0,-1)+d,6)).parts)){for(n=0,i=(c=[parseInt(s[2]),parseInt(s[3]),parseInt(s[4]),parseInt(s[5])]).length;n<i;n++)if(!(0<=(a=c[n])&&a<=255))return null;return r.parts.push(c[0]<<8|c[1]),r.parts.push(c[2]<<8|c[3]),{parts:r.parts,zoneId:r.zoneId}}return null},r.IPv4.isIPv4=r.IPv6.isIPv6=function(e){return null!==this.parser(e)},r.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(e){return!1}},r.IPv4.isValidFourPartDecimal=function(e){return!(!r.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},r.IPv6.isValid=function(e){var t;if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{return new this((t=this.parser(e)).parts,t.zoneId),!0}catch(e){return!1}},r.IPv4.parse=function(e){var t;if(null===(t=this.parser(e)))throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},r.IPv6.parse=function(e){var t;if(null===(t=this.parser(e)).parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(t.parts,t.zoneId)},r.IPv4.parseCIDR=function(e){var t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=32)return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},r.IPv4.subnetMaskFromPrefixLength=function(e){var t,r,n;if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(n=[0,0,0,0],r=0,t=Math.floor(e/8);r<t;)n[r]=255,r++;return t<4&&(n[t]=Math.pow(2,e%8)-1<<8-e%8),new this(n)},r.IPv4.broadcastAddressFromCIDR=function(e){var t,r,n,i,s;try{for(n=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)|255^parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv4.networkAddressFromCIDR=function(e){var t,r,n,i,s;try{for(n=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv6.parseCIDR=function(e){var t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=128)return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},r.isValid=function(e){return r.IPv6.isValid(e)||r.IPv4.isValid(e)},r.parse=function(e){if(r.IPv6.isValid(e))return r.IPv6.parse(e);if(r.IPv4.isValid(e))return r.IPv4.parse(e);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},r.parseCIDR=function(e){try{return r.IPv6.parseCIDR(e)}catch(t){try{return r.IPv4.parseCIDR(e)}catch(e){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},r.fromByteArray=function(e){var t;if(4===(t=e.length))return new r.IPv4(e);if(16===t)return new r.IPv6(e);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},r.process=function(e){var t;return"ipv6"===(t=this.parse(e)).kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(a)}(sd);var od=sd.exports,ad=function(e,t){if("string"==typeof t)return cd(e,t);if("object"==typeof t){for(var r=!1,n=0;n<t.length;n++)if(cd(e,t[n])){r=!0;break}return r}};function cd(e,t){try{var r=od.process(e);if(-1===t.indexOf("/")){var n=od.process(t);return"ipv6"===r.kind()&&"ipv6"===n.kind()?r.toNormalizedString()===n.toNormalizedString():r.toString()==n.toString()}var i=od.parseCIDR(t);return r.match(i)}catch(e){return!1}}var dd=ad,ld=/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,ud=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.2.0/24","192.168.0.0/16","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","224.0.0.0/3"],pd=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];for(var hd=function(e){var t=[],r={originalIp:e,boiledIp:!1,isValid:!1,isBogon:!1,isApipa:!1,isMulticast:!1,isRfc1918:!1,isPublicIp:!1};if(ld.test(e)){r.isValid=!0;for(var n=e.split("."),i=0;i<4;i++)t.push(parseInt(n[i],10));r.boiledIp=t.join("."),dd(r.boiledIp,ud)&&(r.isBogon=!0),dd(r.boiledIp,"169.254.0.0/16")&&(r.isApipa=!0),dd(r.boiledIp,"224.0.0.0/4")&&(r.isMulticast=!0),dd(r.boiledIp,pd)?r.isRfc1918=!0:!1===r.isBogon&&(r.isPublicIp=!0)}return r},fd=c(hd),md={exports:{}},gd=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vd=[],bd=0;bd<256;bd++)vd[bd]=(bd+256).toString(16).substr(1);md.exports=function(e,t){var r;if(Buffer.isBuffer(e))r=function(e){var t=0,r=vd;return r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]}(e);else{if("[object String]"!==Object.prototype.toString.call(e))return!1;r=e}if(r=r.toLowerCase(),!gd.test(r))return!1;if(void 0===t)t=yd(r);else if(yd(r)!==t)return!1;switch(t){case 1:case 2:return!0;case 3:case 4:case 5:return-1!==["8","9","a","b"].indexOf(r.charAt(19));default:throw new Error("Invalid version provided.")}};var yd=md.exports.version=function(e){return 0|e.charAt(14)},_d=c(md.exports);class wd extends Error{constructor(e){super(e.message),this.name="AssertionError",this.code="ERR_ASSERTION",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,Error.captureStackTrace&&Error.captureStackTrace(this,e.stackStartFn)}}function Sd(e){if(e.message instanceof Error)throw e.message;throw new wd(e)}function Cd(...e){!function(e,t,r,n){if(!r){let i=!1;if(0===t)i=!0,n="No value argument passed to `assert.ok()`";else if(n instanceof Error)throw n;const s=new wd({actual:r,expected:!0,message:n,operator:"==",stackStartFn:e});throw s.generatedMessage=i,s}}(Cd,e.length,...e)}const kd={fail:e=>{Sd({actual:"fail()",expected:"fail() should not be called",message:e,operator:"fail",stackStartFn:kd.fail})},ok:Cd};function Td(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r(function(t){t(e)})}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())})}kd.notEqual=function e(t,r,n){if(arguments.length<2)throw new Error("'actual' and 'expected' arguments are required");t==r&&Sd({actual:t,expected:r,message:n,operator:"!=",stackStartFn:e})},kd.ok=Cd,"function"==typeof SuppressedError&&SuppressedError;const Pd="[a-fA-F\\d:]",Rd=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${Pd})|(?<=${Pd})(?=\\s|$))`:"",Ed="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Od="[a-fA-F\\d]{1,4}",xd=`\n(?:\n(?:${Od}:){7}(?:${Od}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${Od}:){6}(?:${Ed}|:${Od}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${Od}:){5}(?::${Ed}|(?::${Od}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${Od}:){4}(?:(?::${Od}){0,1}:${Ed}|(?::${Od}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${Od}:){3}(?:(?::${Od}){0,2}:${Ed}|(?::${Od}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${Od}:){2}(?:(?::${Od}){0,3}:${Ed}|(?::${Od}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${Od}:){1}(?:(?::${Od}){0,4}:${Ed}|(?::${Od}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${Od}){0,5}:${Ed}|(?::${Od}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Id=new RegExp(`(?:^${Ed}$)|(?:^${xd}$)`),Dd=new RegExp(`^${Ed}$`),Md=new RegExp(`^${xd}$`),jd=e=>e&&e.exact?Id:new RegExp(`(?:${Rd(e)}${Ed}${Rd(e)})|(?:${Rd(e)}${xd}${Rd(e)})`,"g");jd.v4=e=>e&&e.exact?Dd:new RegExp(`${Rd(e)}${Ed}${Rd(e)}`,"g"),jd.v6=e=>e&&e.exact?Md:new RegExp(`${Rd(e)}${xd}${Rd(e)}`,"g");const Ad=new URLSearchParams(window.location.search).has("debug");class Ld{constructor(){this._isEnabled=!1,this._isEnabled=Ad}isEnabled(){return this._isEnabled}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}info(...e){if(this._isEnabled)return console.info(...e)}warn(...e){if(this._isEnabled)return console.warn(...e)}error(...e){if(this._isEnabled)return console.error(...e)}withDebugLogger(e){return this._debugger=e,this}debug(...e){if(!this._isEnabled||!this._debugger)return;const t=[];e.forEach(e=>{if("function"==typeof e){const r=e();t.push(r)}else t.push(e)}),this._debugger.print(...t)}}const Nd={codecOptions:{opusDtx:!0,opusFec:!0},encodings:[{dtx:!0}]},Fd={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:4,maxBitrate:15e4},{scaleResolutionDownBy:2,maxBitrate:5e5},{scaleResolutionDownBy:1,maxBitrate:1e6}]},Bd={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:2,maxBitrate:15e4},{scaleResolutionDownBy:1,maxBitrate:5e5}]},zd={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2",maxBitrate:1e6}]},Ud={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2",maxBitrate:5e5}]},Vd={encodings:[{}]},$d={encodings:[{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},Gd={encodings:[{scaleResolutionDownBy:4,dtx:!0,maxBitrate:15e4},{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},qd=(e,t,r,n=!1)=>{var i;const{lowDataModeEnabled:s,simulcastScreenshareOn:o,vp9On:a}=r;if("audio"===e)return Nd;const c="chrome"===(null===(i=ko.browserDetails)||void 0===i?void 0:i.browser)&&a;return t?Wd({areTooManyAlreadyPresenting:n,simulcastScreenshareOn:o}):Hd({lowBandwidth:s,isVp9Available:c})},Hd=({lowBandwidth:e,isVp9Available:t})=>e?t?Ud:Bd:t?zd:Fd,Wd=({areTooManyAlreadyPresenting:e,simulcastScreenshareOn:t})=>e?Gd:t?$d:Vd;var Jd;!function(e){e.H264="video/h264",e.VP9="video/vp9"}(Jd||(Jd={}));function Kd(e,t){const r=e.find(({mimeType:e})=>e.toLowerCase()===t);return r?[...e].sort((e,n)=>{var i;return e.mimeType.toLowerCase()===t?-1:"video/rtx"===e.mimeType.toLowerCase()&&(null===(i=e.parameters)||void 0===i?void 0:i.apt)===r.preferredPayloadType?n.mimeType.toLowerCase()===t?1:-1:0}):e}function Qd(e){return Td(this,void 0,void 0,function*(){const t=yield Promise.all(e.map(({mimeType:e})=>function(e){return Td(this,void 0,void 0,function*(){const{powerEfficient:t}=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{width:1280,height:720,bitrate:2580,framerate:24,contentType:e}});return t})}(e).then(t=>[e,t]))),r=Object.fromEntries(t),n=e.sort((e,t)=>{const n=r[e.mimeType];return n===r[t.mimeType]?0:n?-1:1});return n})}function Yd(e,t){return Td(this,void 0,void 0,function*(){let r=function(e,t){const r=e.map(({mimeType:e})=>e).filter((e,t,r)=>r.indexOf(e)===t),n=function(e,{av1On:t}){return e.unshift("video/vp9"),t&&e.unshift("video/av1"),e}(r,t);return e.sort((e,t)=>{const r=n.indexOf(e.mimeType.toLowerCase()),i=n.indexOf(t.mimeType.toLowerCase());return(r>=0?r:Number.MAX_VALUE)-(i>=0?i:Number.MAX_VALUE)})}(e,t);return r=yield Qd(e),r})}ko.default;const Xd={id:Uo(),connectionNumber:0},Zd=()=>{};let el=Zd;const tl=function(e,t=console){const r=[];let n,i,s,o,a,c,d,l,u,p,h,f,m=0,g=!1,v=0;const b={connected:!1,attemptedConnectedAtLeastOnce:!1,trace:(...e)=>{if(e.push(Date.now()),"customEvent"===e[0]&&"roomSessionId"===e[2].type){const t=c&&c[2].value.roomSessionId,r=e[2].value.roomSessionId;c=e,g&&r&&r!==t&&(null==n||n.close()),r&&(g=!0)}else"customEvent"===e[0]&&"clientId"===e[2].type?s=e:"customEvent"===e[0]&&"organizationId"===e[2].type?i=e:"customEvent"===e[0]&&"displayName"===e[2].type?o=e:"customEvent"===e[0]&&"userRole"===e[2].type?a=e:"customEvent"===e[0]&&"deviceId"===e[2].type?l=e:"customEvent"===e[0]&&"roomProduct"===e[2].type?u=e:"customEvent"===e[0]&&"roomMode"===e[2].type?p=e:"customEvent"===e[0]&&"sfuServer"===e[2].type?h=e:"customEvent"===e[0]&&"featureFlags"===e[2].type&&(f=e);(null==n?void 0:n.readyState)===WebSocket.OPEN?(m=0,n.send(JSON.stringify(e))):"getstats"===e[0]?v<20&&(v++,r.push(e)):"customEvent"===e[0]&&"insightsStats"===e[2].type||r.push(e),(null==n?void 0:n.readyState)===WebSocket.CLOSED&&d&&setTimeout(()=>{n.readyState===WebSocket.CLOSED&&d&&b.connect()},1e3*m)},close:()=>{d=!1,null==n||n.close()},connect:()=>{d=!0,m+=1,null==n||n.close(),b.connected=!0,b.attemptedConnectedAtLeastOnce=!0,n=new WebSocket(e+window.location.pathname,"1.0"),n.onerror=e=>{b.connected=!1,t.warn("[RTCSTATS] WebSocket error",e)},n.onclose=e=>{b.connected=!1,t.info(`[RTCSTATS] Closed ${e.code}`),el()},n.onopen=()=>{for(Xd.connectionNumber++,n.send(JSON.stringify(["clientInfo",null,Xd])),i&&n.send(JSON.stringify(i)),s&&n.send(JSON.stringify(s)),c&&n.send(JSON.stringify(c)),o&&n.send(JSON.stringify(o)),a&&n.send(JSON.stringify(a)),l&&n.send(JSON.stringify(l)),p&&n.send(JSON.stringify(p)),u&&n.send(JSON.stringify(u)),h&&n.send(JSON.stringify(h)),f&&n.send(JSON.stringify(f));r.length;)n.send(JSON.stringify(r.shift()));v=0}}};return b}("wss://rtcstats.srv.whereby.com"),rl=Ao(tl.trace,1e4,[""]);el=(null==rl?void 0:rl.resetDelta)||Zd;const nl={sendEvent:(e,t)=>{tl.trace("customEvent",null,{type:e,value:t})},sendAudioMuted:e=>{nl.sendEvent("audio_muted",{muted:e})},sendVideoMuted:e=>{nl.sendEvent("video_muted",{muted:e})},server:tl};let il=[],sl=0;const ol=new WeakMap,al=e=>{il=il.filter(t=>t!==e)};if(window.RTCPeerConnection){const $E=window.RTCPeerConnection;function GE(e){const t=new $E(e);il.push(t),ol.set(t,{index:sl++});const r=()=>{"closed"===t.connectionState&&(al(t),t.removeEventListener("connectionstatechange",r))};return t.addEventListener("connectionstatechange",r),t}GE.prototype=$E.prototype,window.RTCPeerConnection=GE}const cl=new WeakMap;const dl=(e=cl)=>Promise.all(il.map(t=>Td(void 0,void 0,void 0,function*(){let r=e.get(t);r||(r={ssrcToTrackId:{}},e.set(t,r));try{const e=yield t.getStats();let n=null;if(e.forEach(t=>{if(!("inbound-rtp"!==t.type&&"outbound-rtp"!==t.type||t.trackIdentifier||r.ssrcToTrackId[t.ssrc])){if(t.mediaSourceId){const n=e.get(t.mediaSourceId);n&&n.trackIdentifier&&(r.ssrcToTrackId[t.ssrc]=n.trackIdentifier)}if(!r.ssrcToTrackId[t.ssrc]&&t.trackId){const n=e.get(t.trackId);n&&n.trackIdentifier&&(r.ssrcToTrackId[t.ssrc]=n.trackIdentifier)}r.ssrcToTrackId[t.ssrc]||(n||(n=[]),n.push(t.ssrc))}}),n){const e=[...t.getSenders(),...t.getReceivers()];(yield Promise.all(e.map(e=>e.getStats()))).forEach((t,n)=>{t.forEach(t=>{"inbound-rtp"!==t.type&&"outbound-rtp"!==t.type||(r.ssrcToTrackId[t.ssrc]=e[n].track.id)})}),n.forEach(e=>{r.ssrcToTrackId[e]||(r.ssrcToTrackId[e]="?"+e)})}return[t,e,r]}catch(e){return nl.sendEvent("trackSsrcLookupFailed",{name:null==e?void 0:e.name,cause:null==e?void 0:e.cause,message:null==e?void 0:e.message}),[t,[],r]}}))),ll={id:"unknown",clientId:"unknown",audio:{enabled:!1,track:void 0},video:{enabled:!1,track:void 0},isAudioOnlyModeEnabled:!1,isLocalClient:!0,isPresentation:!1};function ul(e,t,r){return Td(this,arguments,void 0,function*(e,{logger:t,interval:r},n){const i=ul.bind(null,e,{interval:r,logger:t});try{const a=e.getClients(),c=a.find(e=>e.isLocalClient&&!e.isPresentation)||ll;let d=e.statsByView[c.id];d||(d={tracks:{},candidatePairs:{},pressure:null},e.statsByView[c.id]=d),d.pressure=e.lastPressureObserverRecord;if(Date.now()-e.lastUpdateTime<400)return n?e.statsByView:(e.subscriptions.forEach(t=>{var r;return null===(r=t.onUpdatedStats)||void 0===r?void 0:r.call(t,e.statsByView,a)}),void(e.nextTimeout=setTimeout(i,r)));if(e.lastUpdateTime=Date.now(),(yield dl()).forEach(([n,i,s])=>{const o=(e=>{var t;return null===(t=ol.get(e))||void 0===t?void 0:t.index})(n);void 0===o&&t.warn("Could not find index for PeerConnection"),"closed"===n.connectionState&&(i=new Map,al(n)),s.previousSSRCs=s.currentSSRCs||{},s.currentSSRCs={},i.forEach(t=>{var n,l;if("candidate-pair"===t.type&&/inprogress|succeeded/.test(t.state)){const a=null===(n=s._oldReport)||void 0===n?void 0:n.get(t.id),c=a?t.timestamp-a.timestamp:r,l=o+":"+t.id;let u=d.candidatePairs[l];u||(u={startTime:e.lastUpdateTime,id:l},d.candidatePairs[l]=u),function(e,t,r,n,i){const s=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0),o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.bitrateIn=8e3*s/n,e.bitrateOut=8e3*o/n,e.state=t.state,e.roundTripTime=t.currentRoundTripTime,e.requestsSent=t.requestsSent,e.responsesReceived=t.responsesReceived,e.requestsReceived=t.requestsReceived,e.responsesSent=t.responsesSent,e.availableOutgoingBitrate=t.availableOutgoingBitrate,e.availableIncomingBitrate=t.availableIncomingBitrate;const a=i.get(t.remoteCandidateId),c=i.get(t.localCandidateId);e.usingTurn=!1,c&&/relay/i.test(c.candidateType||"")&&(e.usingTurn=!0,e.turnProtocol=c.relayProtocol),a&&c&&(e.localEp=`${c.protocol}:${c.address||c.ip}:${c.port} ${c.candidateType} (${c.networkType})`,e.remoteEp=`${a.protocol}:${a.address||a.ip}:${a.port} ${a.candidateType}`)}(u,t,a,c,i),u.lastRtcStatsTime=e.lastUpdateTime}if("inbound-rtp"===t.type||"outbound-rtp"===t.type){const n=t.mediaType||t.kind,d=t.ssrc;let u=t.trackIdentifier||s.ssrcToTrackId[d],p=null===(l=s._oldReport)||void 0===l?void 0:l.get(t.id);if(p&&p.mediaSourceId!==t.mediaSourceId){const e=i.get(t.mediaSourceId);e&&e.trackIdentifier&&(u=e.trackIdentifier,s.ssrcToTrackId[d]=u)}const h=a.find(e=>{var t;return(null===(t=e[n].track)||void 0===t?void 0:t.id)===u})||c,f=h[n].track;if(!t.trackIdentifier&&s.ssrcToTrackId[d]&&(null==f?void 0:f.id)&&f.id!==s.ssrcToTrackId[d]&&(u=f.id,s.ssrcToTrackId[d]=f.id),s.currentSSRCs[d]=h.id,p){const e=i.get(t.transportId),r=s._oldReport.get(p.transportId);(r&&(null==e?void 0:e.selectedCandidatePairId)!==r.selectedCandidatePairId||t.bytesReceived<p.bytesReceived||t.bytesSent<p.bytesSent)&&(p=null)}const m=p?t.timestamp-p.timestamp:r,g=((e,t,r,n,i,s)=>{let o=e[n];o||(o={candidatePairs:{},tracks:{},startTime:t,updated:t},e[n]=o),o.updated=t;let a=o.tracks[i];a||(a={ssrcs:{},startTime:t,updated:t},o.tracks[i]=a),a.updated=t;let c=a.ssrcs[s];return c||(c={startTime:t,updated:t,pcIndex:r},a.ssrcs[s]=c),c.updated=t,c})(e.statsByView,e.lastUpdateTime,o,h.id,u,d);!function(e,t,r,n,i){if(e.codec)return;e.kind=t.kind||t.mediaType,e.ssrc=t.ssrc,e.direction="inbound-rtp"===t.type?"in":"out";const s=t.codecId&&i.get(t.codecId);e.codec=s&&[s.mimeType,s.channels&&`${s.channels}ch`,s.clockRate,s.payloadType,t.encoderImplementation||t.decoderImplementation,s.sdpFmtpLine].filter(Boolean).join(" "),e.mid=t.mid,e.rid=t.rid}(g,t,0,0,i),function(e,t,r,n,i){const s=(t.nackCount||0)-((null==r?void 0:r.nackCount)||0);if(e.nackCount=(e.nackCount||0)+s,e.nackRate=1e3*s/n,"in"===e.direction){const i=t.packetsReceived-((null==r?void 0:r.packetsReceived)||0);e.packetCount=(e.packetCount||0)+i,e.packetRate=1e3*i/n;const s=t.packetsLost-((null==r?void 0:r.packetsLost)||0);e.packetLossCount=(e.packetLossCount||0)+s,e.packetLossRate=1e3*s/n,e.lossRatio=s/(s+i)*1e3/n;const o=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesReceived&&(a=t.headerBytesReceived-((null==r?void 0:r.headerBytesReceived)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;if(e.bitrate=8e3*c/n,e.mediaRatio=o/c,"audio"===t.kind){const n=(t.fecBytesReceived||0)-((null==r?void 0:r.fecBytesReceived)||0);e.fecRatio=n/o}const d=(t.jitterBufferDelay||0)-((null==r?void 0:r.jitterBufferDelay)||0),l=(t.jitterBufferEmittedCount||0)-((null==r?void 0:r.jitterBufferEmittedCount)||0);e.jitter=l?d/l:0}else{const s=t.packetsSent-((null==r?void 0:r.packetsSent)||0);e.packetCount=(e.packetCount||0)+s,e.packetRate=1e3*s/n;const o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesSent&&(a=t.headerBytesSent-((null==r?void 0:r.headerBytesSent)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;e.bitrate=8e3*c/n,e.mediaRatio=o/c;const d=t.totalPacketSendDelay-((null==r?void 0:r.totalPacketSendDelay)||0);e.sendDelay=d/s;const l=t.retransmittedPacketsSent-((null==r?void 0:r.retransmittedPacketsSent)||0);if(e.retransRatio=l/s*1e3/n,t.remoteId){const r=i.get(t.remoteId);r&&(e.roundTripTime=r.roundTripTime||0,e.jitter=r.jitter||0,e.fractionLost=r.fractionLost||0)}}}(g,t,p,m,i),"video"===n&&function(e,t,r,n,i){e.width=t.frameWidth,e.height=t.frameHeight,e.qualityLimitationReason=t.qualityLimitationReason||"";const s=t.pliCount-((null==r?void 0:r.pliCount)||0);e.pliCount=(e.pliCount||0)+s,e.pliRate=1e3*s/n;const o=t.firCount-((null==r?void 0:r.firCount)||0);if(e.firCount=(e.firCount||0)+o,e.firRate=1e3*o/n,"in"===e.direction){const i=t.keyFramesDecoded-((null==r?void 0:r.keyFramesDecoded)||0);e.kfCount=(e.kfCount||0)+i,e.kfRate=1e3*i/n;const s=t.framesDecoded-((null==r?void 0:r.framesDecoded)||0);e.frameCount=(e.frameCount||0)+s;const o=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=o/s,e.fps=1e3*s/n}else{const s=t.keyFramesEncoded-((null==r?void 0:r.keyFramesEncoded)||0);e.kfCount=(e.kfCount||0)+s,e.kfRate=1e3*s/n;const o=t.framesEncoded-((null==r?void 0:r.framesEncoded)||0);e.frameCount=(e.frameCount||0)+o;const a=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=a/o,e.fps=1e3*o/n;const c=t.totalEncodeTime-((null==r?void 0:r.totalEncodeTime)||0);if(e.encodeTime=c/o,t.mediaSourceId){const r=i.get(t.mediaSourceId);r&&(e.sourceWidth=r.width||0,e.sourceHeight=r.height||0,e.sourceFps=r.framesPerSecond||0)}}}(g,t,p,m,i),"audio"===n&&function(e,t,r){const n=t.packetsDiscarded-((null==r?void 0:r.packetsDiscarded)||0);if(e.packetsDiscarded=(e.packetsDiscarded||0)+n,"in"===e.direction){const n=t.totalAudioEnergy-((null==r?void 0:r.totalAudioEnergy)||0),i=t.totalSamplesDuration-((null==r?void 0:r.totalSamplesDuration)||0);e.audioLevel=Math.sqrt(n/i);const s=t.totalSamplesReceived||0,o=t.concealmentEvents||0,a=s-((null==r?void 0:r.totalSamplesReceived)||0),c=t.concealedSamples||0,d=c-((null==r?void 0:r.concealedSamples)||0),l=(t.silentConcealedSamples||0)-((null==r?void 0:r.silentConcealedSamples)||0),u=(t.insertedSamplesForDeceleration||0)-((null==r?void 0:r.insertedSamplesForDeceleration)||0),p=(t.removedSamplesForAcceleration||0)-((null==r?void 0:r.removedSamplesForAcceleration)||0);e.audioSamples=s,e.audioConcealmentEvents=o,e.audioConcealedSamples=c,e.audioConcealment=d?d/a:0,e.audioSilentConcealment=l?l/a:0,e.audioAcceleration=p?p/a:0,e.audioDeceleration=u?u/a:0}}(g,t,p)}}),s._oldReport=i,Object.keys(s.previousSSRCs).filter(e=>!s.currentSSRCs[e]).forEach(t=>{const r=s.previousSSRCs[t];if(r){const n=e.statsByView[r];n&&Object.values(n.tracks).forEach(e=>{e.ssrcs[t]&&delete e.ssrcs[t]})}})}),s=e.statsByView,o=e.lastUpdateTime,Object.entries(s).forEach(([e,t])=>{void 0!==t.updated&&t.updated<o?delete s[e]:Object.entries(t.tracks).forEach(([e,r])=>{r.updated<o?delete t.tracks[e]:Object.entries(r.ssrcs).forEach(([e,t])=>{t.updated<o&&delete r.ssrcs[e]})})}),Object.entries((null==d?void 0:d.candidatePairs)||{}).forEach(([t,r])=>{const n=r.lastRtcStatsTime===e.lastUpdateTime;r.active=n,n||(r.state="old/inactive",r.inactiveFromTime?e.lastUpdateTime-r.inactiveFromTime>4e3&&delete d.candidatePairs[t]:r.inactiveFromTime=e.lastUpdateTime)}),n)return e.statsByView;e.subscriptions.forEach(t=>{var r;return null===(r=t.onUpdatedStats)||void 0===r?void 0:r.call(t,e.statsByView,a)})}catch(r){t.warn(r),e.numFailedStatsReports++,nl.sendEvent("collectStatsFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message})}var s,o;e.nextTimeout=setTimeout(i,r)})}const pl={};function hl(e,t=pl,r=window.document){e.forEach(({hostnamePattern:e,token:n})=>{const i=`${e}-${n}`;if(!t[i]&&e.test(r.location.hostname)){const e=r.createElement("meta");e.httpEquiv="origin-trial",e.content=n,r.head.append(e),t[i]=!0}})}const fl={sampleRate:1,originTrials:[{hostnamePattern:/hereby\.dev/,token:"AkSNPHJw6EK08X0QU7kORnK9NABzRLAC7dqfXOwk5JwFAQG4Ey7WxLXxsnhieCgC1QHUdevE2EFICy7uBGDANwUAAABqeyJvcmlnaW4iOiJodHRwczovL2hlcmVieS5kZXY6NDQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="},{hostnamePattern:/whereby\.com/,token:"Asc2wu8KpSx648i932NICteQDFcB05yl2QUUSHD7AQo8JGP2Fp6FF91TvYVJBsKGzLMH349rysPw5q9tqPC/PAUAAABqeyJvcmlnaW4iOiJodHRwczovL3doZXJlYnkuY29tOjQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="}]};const ml={currentMonitor:null,getClients:()=>[],lastUpdateTime:0,statsByView:{},subscriptions:[],numFailedStatsReports:0},gl={interval:2e3,logger:new Ld},vl=()=>{var e;return null===(e=ml.currentMonitor)||void 0===e?void 0:e.getUpdatedStats()};function bl(e,{interval:t,logger:r}){const n=ul.bind(null,e,{interval:t,logger:r});let i;try{i=function(e,{sampleRate:t,originTrials:r}=fl,n=globalThis.window){let i;if(hl(r),"PressureObserver"in n)return i=new n.PressureObserver(e,{sampleRate:t}),i.observe("cpu",{sampleInterval:1e3*t}),{stop:()=>{i.unobserve("cpu")}}}(t=>e.lastPressureObserverRecord=t.pop())}catch(e){r.warn("Failed to observe CPU pressure",e)}return setTimeout(n,t),{getUpdatedStats:()=>n(!0),stop:()=>{clearTimeout(e.nextTimeout),null==i||i.stop()}}}const yl="fetch_mediaserver_config",_l="start_screenshare",wl="stop_screenshare",Sl="audio_enabled",Cl="client_left",kl="mediaserver_config",Tl="new_client",Pl="screenshare_started",Rl="screenshare_stopped",El="room_joined",Ol="video_enabled",xl="ice_candidate",Il="ice_endofcandidates",Dl="ready_to_receive_offer",Ml="sdp_answer",jl="sdp_offer",Al="pending_client_left",Ll="media_quality_changed",Nl=new Ld;class Fl extends Ro{constructor(e){super(),this.reconnectThresholdInMs=0,this._socket=e,this._clients={},this._signalDisconnectTime=void 0,this.rtcManager=void 0,this.metrics={roomJoinedLate:0,pendingClientCanceled:0,evaluationFailed:0,roomJoined:0},e.on("disconnect",()=>{this._signalDisconnectTime=Date.now()}),e.on(El,e=>this._onRoomJoined(e)),e.on(Tl,e=>this._onNewClient(e)),e.on(Cl,e=>this._onClientLeft(e)),e.on(Al,e=>this._onPendingClientLeft(e)),e.on(Sl,e=>this._onAudioEnabled(e)),e.on(Ol,e=>this._onVideoEnabled(e)),e.on(Pl,e=>this._onScreenshareChanged(e,!0)),e.on(Rl,e=>this._onScreenshareChanged(e,!1))}_onRoomJoined(e){return Td(this,void 0,void 0,function*(){var t;if(this.reconnectThresholdInMs=.8*(e.disconnectTimeout||0),null==e?void 0:e.error)return void this.emit(El,e);if(!e.selfId)return void this.emit(El,e);const r=null===(t=e.room.clients.find(t=>e.selfId===t.id))||void 0===t?void 0:t.deviceId;if(!r)return void this.emit(El,e);if(!this._signalDisconnectTime)return this._resetClientState(e),e.room.clients=e.room.clients.filter(e=>!(e.deviceId===r&&e.isPendingToLeave)),void this.emit(El,e);const n=.8*e.disconnectTimeout;if(Date.now()-this._signalDisconnectTime>n)return this._resetClientState(e),this.emit(El,e),void this.metrics.roomJoinedLate++;e.room.clients=e.room.clients.filter(e=>!(e.deviceId===r&&e.isPendingToLeave));const i=yield vl();e.room.clients.forEach(t=>{var r;try{if(t.id===e.selfId)return;if(!this._clients[t.id])return void this._addClientToState(t);if(!(null===(r=this.rtcManager)||void 0===r?void 0:r.hasClient(t.id)))return;if(this._hasClientStateChanged({clientId:t.id,webcam:t.isVideoEnabled,mic:t.isAudioEnabled,screenShare:t.streams.length>1}))return;if(this._wasClientSendingMedia(t.id)&&!this._isClientMediaActive(i,t.id))return;t.mergeWithOldClientState=!0}catch(e){Nl.error("Failed to evaluate if we should merge client state %o",e),this.metrics.evaluationFailed++}}),e.room.clients.forEach(e=>{e.isPendingToLeave&&this._onPendingClientLeft({clientId:e.id})}),this.metrics.roomJoined++,this.emit(El,e)})}_onClientLeft(e){var t;const{clientId:r}=e,n=this._clients[r];n&&(clearTimeout(n.timeout),delete this._clients[r]),null===(t=this.rtcManager)||void 0===t||t.disconnect(r,null,e.eventClaim),this.emit(Cl,e)}_onPendingClientLeft(e){const{clientId:t}=e,r=this._clients[t];r?r.isPendingToLeave||(r.isPendingToLeave=!0,this._wasClientSendingMedia(t)&&(r.checkActiveMediaAttempts=0,this._abortIfNotActive(e))):Nl.warn(`client ${t} not found`)}_onNewClient(e){const{client:{id:t,deviceId:r}}=e,n=this._clients[t];if(n&&n.isPendingToLeave)return clearTimeout(n.timeoutHandler),n.isPendingToLeave=!1,void this.metrics.pendingClientCanceled++;this._getPendingClientsByDeviceId(r).forEach(e=>{clearTimeout(e.timeoutHandler),e.isPendingToLeave=void 0,this.emit(Cl,{clientId:e.clientId})}),this._addClientToState(e.client),this.emit(Tl,e)}_abortIfNotActive(e){return Td(this,void 0,void 0,function*(){const{clientId:t}=e;let r=this._clients[t];if(!(null==r?void 0:r.isPendingToLeave))return;if(r.checkActiveMediaAttempts++,r.checkActiveMediaAttempts>3)return;(yield this._checkIsActive(t))?r.timeoutHandler=setTimeout(()=>this._abortIfNotActive(e),500):(r=this._clients[t],(null==r?void 0:r.isPendingToLeave)&&(clearTimeout(r.timeoutHandler),delete this._clients[t],this.emit(Cl,e)))})}_checkIsActive(e){return Td(this,void 0,void 0,function*(){const t=yield vl();return this._isClientMediaActive(t,e)})}_isClientMediaActive(e,t){const r=null==e?void 0:e[t];let n=!1;return r&&Object.entries(r.tracks).forEach(([e,t])=>{"probator"!==e&&Object.values(t.ssrcs).forEach(e=>{(e.bitrate||0)>0&&(n=!0)})}),n}_onAudioEnabled(e){const{clientId:t,isAudioEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isAudioEnabled:r})}_onVideoEnabled(e){const{clientId:t,isVideoEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isVideoEnabled:r})}_onScreenshareChanged(e,t){const{clientId:r}=e;this._clients[r]=Object.assign(Object.assign({},this._clients[r]||{}),{isScreenshareEnabled:t})}_hasClientStateChanged({clientId:e,webcam:t,mic:r,screenShare:n}){const i=this._clients[e];if(!i)throw new Error(`Client ${e} not found in ReconnectManager state`);return t!==i.isVideoEnabled||(r!==i.isAudioEnabled||n!==i.isScreenshareEnabled)}_addClientToState(e){this._clients[e.id]=Object.assign(Object.assign({},this._clients[e.id]||{}),{isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled,isScreenshareEnabled:e.streams.length>1,deviceId:e.deviceId,isPendingToLeave:e.isPendingToLeave,clientId:e.id})}_wasClientSendingMedia(e){const t=this._clients[e];if(!t)throw new Error(`Client ${e} not found in ReconnectManager state`);return t.isAudioEnabled||t.isVideoEnabled||t.isScreenshareEnabled}_getPendingClientsByDeviceId(e){return Object.values(this._clients).filter(t=>t.deviceId===e&&t.isPendingToLeave)}_resetClientState(e){this._clients={},e.room.clients.forEach(t=>{t.id!==e.selfId&&this._addClientToState(t)})}}var Bl;const zl=null!==(Bl=ko.default)&&void 0!==Bl?Bl:ko;class Ul{constructor(e,t,r=!1){this._wasConnectedUsingWebsocket=!1,this._reconnectManager=null,this._socket=cc(e,Object.assign({path:"/protocol/socket.io/v4",randomizationFactor:.5,reconnectionDelay:250,reconnectionDelayMax:5e3,timeout:5e3,transports:["websocket"],withCredentials:!0},t)),this.joinRoomFinished=!1,this._socket.io.on("reconnect",()=>{this._socket.sendBuffer=[]}),this._socket.io.on("reconnect_attempt",()=>{var e;this._wasConnectedUsingWebsocket?(this._socket.io.opts.transports=["websocket"],"safari"!==(null===(e=zl.browserDetails)||void 0===e?void 0:e.browser)&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["websocket","polling"]}),r&&(this._reconnectManager=new Fl(this._socket)),this._socket.on("room_joined",e=>{const{error:t}=e;t||(this.joinRoomFinished=!0)}),this._socket.on("connect",()=>{"websocket"===this.getTransport()&&(this._wasConnectedUsingWebsocket=!0,this.noopKeepaliveInterval||(this.noopKeepaliveInterval=setInterval(()=>{try{this._socket.connected&&this._socket.io.engine.sendPacket("noop")}catch(e){}},2e3)))}),this._socket.on("disconnect",()=>{this.joinRoomFinished=!1,this.disconnectTimestamp=Date.now(),this.noopKeepaliveInterval&&(clearInterval(this.noopKeepaliveInterval),this.noopKeepaliveInterval=null)})}setRtcManager(e){this._reconnectManager&&(this._reconnectManager.rtcManager=e)}connect(){this.isConnected()||this.isConnecting()||this._socket.open()}disconnect(){this._socket.disconnect()}emit(e,...t){this._socket.emit.apply(this._socket,arguments)}getTransport(){var e,t,r,n;return null===(n=null===(r=null===(t=null===(e=this._socket)||void 0===e?void 0:e.io)||void 0===t?void 0:t.engine)||void 0===r?void 0:r.transport)||void 0===n?void 0:n.name}getManager(){return this._socket.io}isConnecting(){return this._socket&&this._socket.connecting}isConnected(){return this._socket&&this._socket.connected}on(e,t){const r=[El,Cl,Tl];return this._reconnectManager&&r.includes(e)?this._interceptEvent(e,t):(this._socket.on(e,t),()=>{this._socket.off(e,t)})}onEngineEvent(e,t){var r;return null===(r=this._socket.io)||void 0===r||r.on(e,t),()=>{var r;null===(r=this._socket.io)||void 0===r||r.off(e,t)}}once(e,t){this._socket.once(e,t)}off(e,t){this._socket.off(e,t)}_interceptEvent(e,t){return this._reconnectManager&&this._reconnectManager.on(e,t),()=>{this._reconnectManager&&this._reconnectManager.removeListener(e,t)}}getGlitchFreeMetrics(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.metrics}getReconnectThreshold(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.reconnectThresholdInMs}}const Vl=(e,t)=>{if(!t.useOnlyTURN)return;e.iceTransportPolicy="relay";const r={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[t.useOnlyTURN];r&&(e.iceServers=e.iceServers.filter(e=>e.url&&e.url.match(r)||e.urls&&(e.urls=(e.urls.some?e.urls:[e.urls]).filter(e=>e.match(r)),e.urls.length>0)?e:void 0))},$l=(e,t)=>{if(t&&e){const r=t,n=r.indexOf(":")>0?"":":443",i=":"+r+n;return e.map(e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,i)),t.urls&&(t.urls=t.urls.map(e=>e.replace(/:[^?]*/,i))),t})}return e},Gl=[{pattern:/^(?:([^.]+)[.])?(server:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?(localhost:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?((\d+[.]){3}:?\d*)$/,separator:"."},{pattern:/^(?:([^.]+)-)?(ip-[^.]*[.](?:hereby[.]dev|rfc1918[.]disappear[.]at)(?::\d+|))$/,separator:"-"},{pattern:/^(?:([^.]+)[.])?((:?[^.]+[.]){1,}[^.]+)$/,separator:"."}];function ql({host:e="whereby.com",protocol:t="https:"}={}){let r="",n=e,i=".";for(const{separator:t,pattern:s}of Gl){const o=s.exec(e);if(o){r=o[1]||"",n=o[2],i=t;break}}const s=r?`${r}${i}${n}`:n;return{domain:n,domainWithSeparator:`${i}${n}`,organizationDomain:s,organization:`${t}//${s}`,service:`${t}//${n}`,subdomain:r}}ql(window&&window.location);const Hl=new Ld,Wl={print:(...e)=>console.debug(e[0],...e.slice(1))};Hl.withDebugLogger(Wl);var Jl,Kl;const Ql=null!==(Jl=ko.default)&&void 0!==Jl?Jl:ko,Yl=new Ld,Xl=null===(Kl=Ql.browserDetails)||void 0===Kl?void 0:Kl.browser,Zl=Ql.browserDetails.version;function eu(e,t){let r=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),n=t.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/);r||(r=e.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/),n=t.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/));for(let e=1;e<r.length;e++)t=t.replace(new RegExp(n[e],"g"),r[e]);return t}function tu(e){return"firefox"!==Xl?e:ho.splitLines(e.trim()).map(e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e).join("\r\n")+"\r\n"}function ru(e){return function(e,t,r=!1,n=!1){var i,s;try{const o=Wt(e);if((null===(i=null==o?void 0:o.ext)||void 0===i?void 0:i.length)&&o.ext.length>0)return e;if((null==o?void 0:o.media.length)<1)return e;const a=null==o?void 0:o.media.flatMap(e=>e.ext||[]),c=(null===(s=a.find(e=>e.uri===t))||void 0===s?void 0:s.value)||[...new Set([0,15,...a.map(e=>e.value)])].sort((e,t)=>e-t).find((e,t,r)=>e+1!==r[t+1])+1;return o.media.forEach(e=>{var i;(r&&"audio"===e.type||n&&"video"===e.type)&&((null===(i=e.ext)||void 0===i?void 0:i.find(e=>e.uri===t))||(Array.isArray(e.ext)?e.ext.push({value:c,uri:t}):e.ext=[{value:c,uri:t}]))}),Ht(o)}catch(e){console.error("Error during addAbsCaptureTimeExtMap: ",e)}return e}(e,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",!0,!0)}function nu(e,t,r=console){const n=e.getSenders().find(e=>e.track&&"video"===e.track.kind);if(!n)return Promise.resolve();const i=n.getParameters();return i.encodings&&0===i.encodings.length?Promise.resolve():(i.encodings||(i.encodings=[{}]),0===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,n.setParameters(i).catch(e=>{r.error("setParameters err: ",e)}))}var iu;const su=null!==(iu=ko.default)&&void 0!==iu?iu:ko,ou=new Ld;class au{constructor({peerConnectionId:e,bandwidth:t,deprioritizeH264Encoding:r}){this.peerConnectionId=e,this.relayCandidateSeen=!1,this.serverReflexiveCandidateSeen=!1,this.publicHostCandidateSeen=!1,this.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this.pc=null,this.wasEverConnected=!1,this.connectionStatus=null,this.stats={totalSent:0,totalRecv:0},this.bandwidth=t||0,this.pending=[],this.isOperationPending=!1,this.streamIds=[],this.streams=[],this.earlyIceCandidates=[],this.afterConnected=new Promise(e=>{this.registerConnected=e}),this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._deprioritizeH264Encoding=r}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:r,shouldAddLocalVideo:n}){return this.peerConnectionConfig=r,this.shouldAddLocalVideo=n,this.clientId=e,this.pc=new RTCPeerConnection(r),this.signalingState=this.pc.signalingState,this.pc.addEventListener("signalingstatechange",()=>{if(this.signalingState!==this.pc.signalingState&&(this.signalingState=this.pc.signalingState,"stable"===this.pc.signalingState)){this.isOperationPending=!1;const e=this.pending.shift();e&&e.apply()}}),this.pc}addStream(e){this.streamIds.push(e.id),this.streams.push(e),RTCPeerConnection.prototype.addTrack?(e.getAudioTracks().forEach(t=>{this.pc.addTrack(t,e)}),e.getVideoTracks().forEach(t=>{this.pc.addTrack(t,e)})):this.pc.addStream(e)}addTrack(e,t){t||(t=this.streams[0]),null==t||t.addTrack(e),this.pc.addTrack(e,t)}removeTrack(e){this.streams[0].removeTrack(e);const t=this.pc.getSenders().find(t=>t.track===e);t&&this.pc.removeTrack(t)}removeStream(e){for(let t=0;t<this.streamIds.length;t++)this.streamIds[t]===e.id&&(this.streamIds.splice(t,1),this.streams.splice(t,1));this.pc&&(this.pc.removeTrack?e.getTracks().forEach(e=>{const t=this.pc.getSenders().find(t=>t.track===e);t&&this.pc.removeTrack(t)}):this.pc.removeStream&&this.pc.removeStream(e))}_setRemoteDescription(e){return this._deprioritizeH264Encoding&&(e.sdp=function(e){return ho.splitSections(e).map(e=>{if("video"!==ho.getKind(e))return e;const t=ho.matchPrefix(e,"a=rtpmap:").map(e=>ho.parseRtpMap(e)).filter(e=>/h264/i.test(e.name)).map(e=>""+e.payloadType);if(!t.length)return e;const r=ho.matchPrefix(e,"m=video")[0],n=/(\s\d+)+$/i.exec(r),i=n?n[0]:"",s=[...i.split(" ").filter(e=>e&&!t.includes(e)),...t].join(" "),o=r.replace(i," "+s);return e.replace(r,o)}).join("")}(e.sdp)),this.srdComplete=this.pc.setRemoteDescription(e),this.srdComplete.then(()=>{this.earlyIceCandidates.forEach(e=>this.pc.addIceCandidate(e)),this.earlyIceCandidates=[]})}handleOffer(e){if(!this.canModifyPeerConnection())return new Promise(t=>{this.pending.push(()=>this.handleOffer(e).then(t))});this.isOperationPending=!0;let t=e.sdp;t=function(e){return"safari"!==Xl&&("firefox"!==Xl||Zl&&Zl>=63||60===Zl)?e:ho.splitLines(e.trim()).filter(e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==ho.parseExtmap(e).uri).join("\r\n")+"\r\n"}(t),t=tu(t);const r={type:e.type,sdp:t};let n;return this._setRemoteDescription(r).then(()=>this.pc.createAnswer()).then(e=>(n=e,this.pc.setLocalDescription(e))).then(()=>nu(this.pc,this.bandwidth)).then(()=>n)}handleAnswer(e){const t=tu(e.sdp),r={type:e.type,sdp:t};return this._setRemoteDescription(r).then(()=>nu(this.pc,this.bandwidth),e=>{ou.warn("Could not set remote description from remote answer: ",e)})}addIceCandidate(e){this.srdComplete?this.srdComplete.then(()=>{var t;"closed"!==this.pc.signalingState&&("safari"===(null===(t=su.browserDetails)||void 0===t?void 0:t.browser)&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch(t=>{ou.warn("Failed to add ICE candidate ('%s'): %s",e?e.candidate:null,t)}))}):this.earlyIceCandidates.push(e)}canModifyPeerConnection(){return"stable"===this.pc.signalingState&&!this.isOperationPending}close(){const e=this.pc;if(e){e.oniceconnectionstatechange=null,e.onicecandidate=null,e.ontrack=null;try{e.close()}catch(e){ou.warn("failures during close of session",e)}}}hasConnectedPeerConnection(){return this.pc&&"connected"===this.pc.connectionState}replaceTrack(e,t){const r=this.pc;if(!r)return!1;const n=r.getSenders();if(e||(e=(n.find(e=>e.track&&e.track.kind===t.kind)||{}).track),window.RTCRtpSender&&window.RTCRtpSender.prototype.replaceTrack){if(e){const r=()=>{for(let r=0;r<n.length;r++){const i=n[r].track;if((null==i?void 0:i.id)===t.id)return Promise.resolve(t);if((null==i?void 0:i.id)===e.id)return n[r].replaceTrack(t)}return null};let i=r();if(i)return i;let s=null,o=null;i=new Promise((e,t)=>{s=e,o=t});let a=0,c=setInterval(()=>Td(this,void 0,void 0,function*(){const e=r();if(!e)return void(3<++a&&(clearInterval(c),c=null,o("No sender track to replace")));clearInterval(c),c=null;const t=yield e;s(t)}),1e3);return i}const i=this.streams.find(e=>e.getTracks().find(e=>e.id===t.id))||this.streams[0];return i?r.addTrack(t,i):Promise.reject(new Error("replaceTrack: No stream?"))}if(!this.canModifyPeerConnection())return void this.pending.push(()=>{this.replaceTrack(e,t)});this.isOperationPending=!0;const i=r.onnegotiationneeded;return r.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout(()=>{r.onnegotiationneeded=i},0),"offer"===r.localDescription.type?r.createOffer().then(e=>(e.sdp=eu(r.localDescription.sdp,e.sdp),r.setLocalDescription(e))).then(()=>this._setRemoteDescription(r.remoteDescription)):this._setRemoteDescription(r.remoteDescription).then(()=>r.createAnswer()).then(e=>(e.sdp=eu(r.localDescription.sdp,e.sdp),r.setLocalDescription(e)))}changeBandwidth(e){e!==this.bandwidth&&(this.canModifyPeerConnection()?(this.bandwidth=e,this.pc.localDescription&&""!==this.pc.localDescription.type&&nu(this.pc,this.bandwidth)):this.pending.push(()=>this.changeBandwidth(e)))}setAudioOnly(e,t=[]){this.pc.getTransceivers().filter(e=>{var r,n,i,s,o,a;return"recvonly"!==(null==e?void 0:e.direction)&&"video"===(null===(n=null===(r=null==e?void 0:e.receiver)||void 0===r?void 0:r.track)||void 0===n?void 0:n.kind)&&!t.includes(null===(s=null===(i=null==e?void 0:e.receiver)||void 0===i?void 0:i.track)||void 0===s?void 0:s.id)&&!t.includes(null===(a=null===(o=null==e?void 0:e.sender)||void 0===o?void 0:o.track)||void 0===a?void 0:a.id)}).forEach(t=>{t.direction=e?"sendonly":"sendrecv"})}}const cu=400;var du;const lu=null!==(du=ko.default)&&void 0!==du?du:ko;const uu="client_connection_status_changed",pu="stream_added",hu="rtc_manager_created",fu="rtc_manager_destroyed",mu="local_stream_track_added",gu="local_stream_track_removed",vu="connecting",bu="connection_failed",yu="connection_successful",_u="connection_disconnected",wu="camera",Su="screen_share";var Cu,ku,Tu,Pu="connection_blocked_by_network",Ru="ice_ipv6_seen",Eu="ice_mdns_seen",Ou="ice_no_public_ip_gathered",xu="ice_no_public_ip_gathered_3sec",Iu="ice_restart",Du="microphone_not_working",Mu="microphone_stopped_working",ju="camera_stopped_working",Au="new_pc",Lu="sfu_connection_open",Nu="sfu_connection_closed",Fu="sfu_connection_info",Bu="dominant_speaker",zu="pc_sld_failure",Uu="pc_on_answer_failure",Vu="pc_on_offer_failure";const $u=null!==(Cu=ko.default)&&void 0!==Cu?Cu:ko,Gu=new Ld,qu=class{constructor(e,t){this.id=""+e,this.type=t,this.isEnabled=!0,this.hasSupportForAutoSuperSize=!1,this.isAudioEnabled=!0,this.isVideoEnabled=!0,this.status=vu,this.stream=null,this.streamId=null}setup(e){return this.stream=e,this.streamId=e.id,this.setVideoEnabled(this.isVideoEnabled&&e.getVideoTracks().length>0),this.setAudioEnabled(this.isAudioEnabled&&e.getAudioTracks().length>0),this}setStatus(e){return this.status=e,this}setVideoEnabled(e){this.isVideoEnabled=e,this.stream&&this.stream.getVideoTracks().forEach(t=>{t.enabled=e})}setAudioEnabled(e){this.isAudioEnabled=e,this.stream&&this.stream.getAudioTracks().forEach(t=>{t.enabled=e})}static getCameraId(){return"0"}static getTypeFromId(e){return"0"===""+e?wu:Su}}.getCameraId(),Hu=null===(ku=$u.browserDetails)||void 0===ku?void 0:ku.browser,Wu=$u.browserDetails.version;"firefox"===Hu&&$u.browserShim&&"shimGetDisplayMedia"in $u.browserShim&&(null===(Tu=$u.browserShim)||void 0===Tu||Tu.shimGetDisplayMedia(window,"screen"));let Ju=!1;"chrome"===Hu&&window.document.addEventListener("beforeunload",()=>{Ju=!0});class Ku{constructor({selfId:e,room:t,emitter:r,serverSocket:n,webrtcProvider:i,features:s}){const{name:o,session:a,iceServers:c,turnServers:d,sfuServer:l,mediaserverConfigTtlSeconds:u}=t;this._selfId=e,this._roomName=o,this._roomSessionId=a&&a.id,this.peerConnections={},this.localStreams={},this.enabledLocalStreamIds=[],this._screenshareVideoTrackIds=[],this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction=null,this._emitter=r,this._serverSocket=n,this._webrtcProvider=i,this._features=s||{},this._isAudioOnlyMode=!1,this._closed=!1,this.skipEmittingServerMessageCount=0,this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._audioTrackOnEnded=()=>{nl.sendEvent("audio_ended",{unloading:Ju}),this._emit(Mu,{})},this._videoTrackOnEnded=()=>{nl.sendEvent("video_ended",{unloading:Ju}),this._emit(ju,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:u}),this.totalSessionsCreated=0}numberOfPeerconnections(){return Object.keys(this.peerConnections).length}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._roomName===t&&r===!!this._sfuServer}supportsScreenShareAudio(){return!0}addNewStream(e,t,r,n,i=[]){if(t!==this.localStreams[e]){if(this._addLocalStream(e,t),e===qu){this._addStreamToPeerConnections(t);const e=t.getAudioTracks()[0],r=t.getVideoTracks()[0];if(e){e.effectTrack||this._monitorAudioTrack(e);const t=i.find(e=>"audio"===e.kind);t&&this._monitorAudioTrack(t)}if(r){r.effectTrack||this._monitorVideoTrack(r);const e=i.find(e=>"video"===e.kind);e&&this._monitorVideoTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const n=e=>{const{enable:t,track:r}=e.detail;this._handleStopOrResumeVideo({enable:t,track:r})};return t.addEventListener("stopresumevideo",n),void(this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",n)})}this._screenshareVideoTrackIds.push(t.getVideoTracks()[0].id),this._shareScreen(e,t)}}replaceTrack(e,t){return"audio"!==t.kind||t.effectTrack||this._monitorAudioTrack(t),"video"!==t.kind||t.effectTrack||this._monitorVideoTrack(t),this._replaceTrackToPeerConnections(e,t)}close(){this._closed=!0,this.disconnectAll()}disconnectAll(){Object.keys(this.peerConnections).forEach(e=>{this.disconnect(e)}),this.peerConnections={},this._socketListenerDeregisterFunctions.forEach(e=>{e()}),this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null)}fixChromeAudio(e){if("chrome"!==Hu)return;const t=this._getLocalCameraStream(),r=t.getAudioTracks()[0];return r&&"ended"===r.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then(e=>{const n=e.getAudioTracks()[0];return n.enabled=r.enabled,t.removeTrack(r),t.addTrack(n),this.replaceTrack(r,n)}):void 0}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on(kl,e=>{e.error?Gu.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)}),this._serverSocket.on(Dl,e=>{this._connect(e.clientId)}),this._serverSocket.on(xl,e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):Gu.warn("No RTCPeerConnection on ICE_CANDIDATE",e)}),this._serverSocket.on(Il,e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):Gu.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)}),this._serverSocket.on(jl,e=>{var t,r;const n=this._getSession(e.clientId);if(!n)return void Gu.warn("No RTCPeerConnection on SDP_OFFER",e);const i=this._transformIncomingSdp(e.message,n.pc);null===(r=(t=n.handleOffer(i).then(t=>{this._emitServerEvent(Ml,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})})).catch)||void 0===r||r.call(t,e=>{this._emit(Vu,e)})}),this._serverSocket.on(Ml,e=>{var t,r;const n=this._getSession(e.clientId);if(!n)return void Gu.warn("No RTCPeerConnection on SDP_ANSWER",e);const i=this._transformIncomingSdp(e.message,n.pc);null===(r=null===(t=n.handleAnswer(i))||void 0===t?void 0:t.catch)||void 0===r||r.call(t,e=>{this._emit(Uu,e)})}),this._serverSocket.on(El,e=>{var t,r;if(null==e?void 0:e.error)return;if(null!==(r=null===(t=null==e?void 0:e.room)||void 0===t?void 0:t.sfuServer)&&void 0!==r&&r||!this._wasScreenSharing)return;const n=Object.keys(this.localStreams).find(e=>e!==qu);if(!n)return;const i=this.localStreams[n];if(!i)return void Gu.warn("screenshare stream %s not found",n);const s=i.getAudioTracks().length>0;this._emitServerEvent(_l,{streamId:n,hasAudioTrack:s})})]}sendAudioMutedStats(e){nl.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){nl.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){nl.sendEvent(e,t)}rtcStatsConnect(){nl.server.connected||nl.server.connect()}rtcStatsDisconnect(){nl.server.close()}rtcStatsReconnect(){!nl.server.connected&&nl.server.attemptedConnectedAtLeastOnce&&nl.server.connect()}setAudioOnly(e){this._isAudioOnlyMode=e,this._forEachPeerConnection(e=>{e.hasConnectedPeerConnection()&&this._withForcedRenegotiation(e,()=>e.setAudioOnly(this._isAudioOnlyMode,this._screenshareVideoTrackIds))})}setRemoteScreenshareVideoTrackIds(e=[]){const t=this._getFirstLocalNonCameraStream();this._screenshareVideoTrackIds=[...(null==t?void 0:t.track)?[t.track.id]:[],...e]}setRoomSessionId(e){this._roomSessionId=e}_setConnectionStatus(e,t,r){const n=e.connectionStatus;n!==t&&e.peerConnectionId!==this._selfId&&(n===_u&&t===vu||(e.connectionStatus=t,setTimeout(()=>{this._emit(uu,{streamIds:e.streamIds,clientId:r,status:t,previous:n})},0)))}_setJitterBufferTarget(e){try{e.getReceivers().forEach(e=>{e.jitterBufferTarget=cu,e.playoutDelayHint=.4})}catch(e){Gu.error("Error during setting jitter buffer target:",e)}}_emitServerEvent(e,t){this._closed?Gu.warn("RtcManager closed. Will not send event",e,t):this._features.awaitJoinRoomFinished&&!this._serverSocket.joinRoomFinished?(nl.sendEvent("skip_emitting_server_message",{eventName:e}),this.skipEmittingServerMessageCount++):this._serverSocket.emit(e,t)}_emit(e,t){this._emitter.emit(e,t)}_addEnabledLocalStreamId(e){this.enabledLocalStreamIds.push(e)}_deleteEnabledLocalStreamId(e){const t=this.enabledLocalStreamIds.indexOf(e);-1!==t&&this.enabledLocalStreamIds.splice(t,1)}_getSession(e){return e in this.peerConnections?this.peerConnections[e]:null}_getOrCreateSession(e,t){let r=this.peerConnections[e];if(void 0===r){const n="safari"===Hu&&Wu&&Wu>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=r=new au({peerConnectionId:e,bandwidth:t,deprioritizeH264Encoding:n}),this.totalSessionsCreated++}return r}_getLocalCameraStream(){return this.localStreams[qu]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter(e=>e!==qu)}_isScreensharingLocally(){return this._getNonLocalCameraStreamIds().length>0}_getFirstLocalNonCameraStream(){const e=this._getNonLocalCameraStreamIds();return 0===e.length?null:this.localStreams[e[0]]}_transformIncomingSdp(e,t){return{type:e.type,sdp:e.sdpU}}_transformOutgoingSdp(e){return{type:e.type,sdpU:e.sdp}}_createSession({clientId:e,initialBandwidth:t,isOfferer:r,peerConnectionId:n,shouldAddLocalVideo:i}){if(!n)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const s=this._getOrCreateSession(n,t),o={optional:[]};"chrome"===Hu&&o.optional.push({googCpuOveruseDetection:!0}),o.optional.push({rtcStatsRoomSessionId:this._roomSessionId}),o.optional.push({rtcStatsClientId:this._selfId}),o.optional.push({rtcStatsPeerId:n}),o.optional.push({rtcStatsConferenceId:this._roomName});const a={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};var c,d;a.iceServers=$l(a.iceServers,this._features.turnServerOverrideHost),c=a,(d=this._features).addGoogleStunServers&&(c.iceServers=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun2.l.google.com:19302"},...c.iceServers]),d.addCloudflareStunServers&&(c.iceServers=[{urls:"stun:stun.cloudflare.com:3478"},{urls:"stun:stun.cloudflare.com:53"},...c.iceServers]),Vl(a,this._features),"chrome"===Hu&&(a.sdpSemantics="unified-plan");const l=s.setAndGetPeerConnection({constraints:o,peerConnectionConfig:a,shouldAddLocalVideo:i,clientId:e});setTimeout(()=>this._emit(Au),0),l.ontrack=t=>{const r=t.streams[0];"default"===r.id&&0===r.getAudioTracks().length||-1===s.streamIds.indexOf(r.id)&&(s.streamIds.push(r.id),this._emit(pu,{clientId:e,stream:r}),s.connectionStatus===yu&&setTimeout(()=>{this._emit(uu,{streamIds:s.streamIds,clientId:e,status:s.connectionStatus,previous:vu})},0))},l.oniceconnectionstatechange=()=>{let t;const r=s.connectionStatus;switch(l.iceConnectionState){case"checking":t=vu;break;case"connected":case"completed":t=yu,s.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach(e=>{"function"==typeof e&&e()}),this._pendingActionsForConnectedPeerConnections=[]),!s.wasEverConnected&&(l.iceConnectionState.match(/connected|completed/)||"chrome"===Hu&&l.localDescription&&"answer"===l.localDescription.type)&&(s.wasEverConnected=!0),this._isAudioOnlyMode&&s.setAudioOnly(!0,this._screenshareVideoTrackIds),s.registerConnected();break;case"disconnected":t=_u,setTimeout(()=>{"disconnected"===l.iceConnectionState&&this._maybeRestartIce(e,s)},2e3);break;case"failed":t=bu,r!==t&&this._maybeRestartIce(e,s),null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(Pu);break;default:return}this._setConnectionStatus(s,t,e)},l.onconnectionstate=()=>{switch(l.connectionState){case"connected":setTimeout(()=>{(function(e){var t,r;if("chrome"!==(null===(t=lu.browserDetails)||void 0===t?void 0:t.browser)||(null===(r=lu.browserDetails)||void 0===r?void 0:r.browser)<58||"closed"===e.signalingState)return Promise.resolve(!1);const n=e.getSenders().some(e=>e.track&&"audio"===e.track.kind),i=e.getReceivers().some(e=>e.track&&"audio"===e.track.kind);return e.getStats(null).then(e=>{let t=!1;return e.forEach(e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!n?"inbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!i||0===e.bytesReceived&&(t="inbound"):0===e.bytesSent&&(t="outbound")}),t})})(s.pc).then(t=>{!1!==t&&this._emit(Du,{failureDirection:t,clientId:e})})},3e3),s.registerConnected();break;case"failed":const t=bu;null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(Pu),this._setConnectionStatus(s,t,e)}};const u=this.localStreams[qu];return i&&u&&s.addStream(u),i&&Object.keys(this.localStreams).forEach(e=>{if(e===qu)return;const t=this.localStreams[e];r?s.addStream(t):s.afterConnected.then(()=>{this._emitServerEvent(_l,{receiverId:s.clientId,streamId:t.id,hasAudioTrack:!!t.getAudioTracks().length}),this._withForcedRenegotiation(s,()=>s.addStream(t))})}),s}_cleanup(e){const t=this._getSession(e);t?(t.close(),delete this.peerConnections[e]):Gu.warn("No RTCPeerConnection in RTCManager.disconnect()",e)}_forEachPeerConnection(e){Object.values(this.peerConnections).forEach(t=>{e(t)})}_addStreamToPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.addStream(e))})}_addTrackToPeerConnections(e,t){this._forEachPeerConnection(r=>{this._withForcedRenegotiation(r,()=>r.addTrack(e,t))})}_replaceTrackToPeerConnections(e,t){const r=[];return this._forEachPeerConnection(n=>{if(!n.hasConnectedPeerConnection()){Gu.info("Session doesn't have a connected PeerConnection, adding pending action!");const i=this._pendingActionsForConnectedPeerConnections;if(!i)return void Gu.warn("No pending action is created to replace track, because the pending actions array is null");const s=new Promise((r,s)=>{i.push(()=>{const i=n.replaceTrack(e,t);if(!i)return Gu.error("replaceTrack returned false!"),void s("ReplaceTrack returned false");i.then(e=>r(e)).catch(e=>s(e))})});return void r.push(s)}const i=n.replaceTrack(e,t);i?r.push(i):Gu.error("replaceTrack returned false!")}),Promise.all(r)}_removeStreamFromPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.removeStream(e))})}_removeTrackFromPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.removeTrack(e))})}_addLocalStream(e,t){this._addEnabledLocalStreamId(e),this.localStreams[e]=t}_removeLocalStream(e){delete this.localStreams[e],this._deleteEnabledLocalStreamId(e)}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,mediaserverConfigTtlSeconds:n}){this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._mediaserverConfigTtlSeconds=n,this._clearMediaServersRefresh(),n&&(this._fetchMediaServersTimer=setTimeout(()=>this._emitServerEvent(yl),1e3*n))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_connect(e){try{this.rtcStatsReconnect()}catch(e){}let t=this._getSession(e),r=t&&t.bandwidth||0;return t?(Gu.warn("Replacing peer session",e),this._cleanup(e)):r=this._changeBandwidthForAllClients(!0),t=this._createP2pSession({clientId:e,initialBandwidth:r,shouldAddLocalVideo:!0,isOfferer:!0}),this._negotiatePeerConnection(e,t),Promise.resolve(t)}_maybeRestartIce(e,t){const r=t.pc;"disconnected"!==r.iceConnectionState&&"failed"!==r.iceConnectionState||"offer"===r.localDescription.type&&(t.wasEverConnected=!1,t.relayCandidateSeen=!1,t.serverReflexiveCandidateSeen=!1,t.publicHostCandidateSeen=!1,t.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this._emit(Iu),this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_setCodecPreferences(e){return Td(this,void 0,void 0,function*(){const{p2pAv1On:t,redOn:r}=this._features;try{const n=e.getTransceivers().filter(e=>{var t,r;return"audio"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)});n.forEach(e=>{if(void 0===RTCRtpSender.getCapabilities)return;const t=RTCRtpSender.getCapabilities("audio");for(let e=0;e<t.codecs.length;e++)if(r&&"audio/red"===t.codecs[e].mimeType.toLowerCase()){t.codecs.unshift(t.codecs.splice(e,1)[0]);break}void 0!==e.setCodecPreferences&&e.setCodecPreferences(t.codecs)});const i=e.getTransceivers().filter(e=>{var t,r;return"video"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)});yield Promise.all(i.map(e=>Td(this,void 0,void 0,function*(){if(void 0===RTCRtpReceiver.getCapabilities)return;if(void 0===e.setCodecPreferences)return;const r=RTCRtpReceiver.getCapabilities("video");r.codecs=yield Yd(r.codecs,{av1On:t}),e.setCodecPreferences(r.codecs)})))}catch(e){Gu.error("Error during setting setCodecPreferences:",e)}})}_negotiatePeerConnection(e,t,r){if(!t)return void Gu.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const n=t.pc;if(!t.canModifyPeerConnection())return void t.pending.push(()=>{this._negotiatePeerConnection(e,t,r)});t.isOperationPending=!0;const{redOn:i,rtpAbsCaptureTimeOn:s,cleanSdpOn:o}=this._features;this._setCodecPreferences(n).then(()=>n.createOffer(r||this.offerOptions).then(t=>{s&&(t.sdp=ru(t.sdp)),"firefox"===Hu&&(t.sdp=function(e,t){var r,n;try{const i=Wt(e);if(Array.isArray(null==i?void 0:i.media)){const e=i.media.find(e=>"audio"===e.type);if(Array.isArray(null==e?void 0:e.rtp)){const n=e.rtp;for(let i=0;i<n.length;i++)if(t&&"red"===n[i].codec){const t=null===(r=e.payloads)||void 0===r?void 0:r.split(" "),s=null==t?void 0:t.indexOf(""+n[i].payload);s&&-1!==s&&s>=0&&(null==t||t.unshift(t.splice(s,1)[0]),e.payloads=null==t?void 0:t.join(" "))}}const s=i.media.find(e=>"video"===e.type);if(Array.isArray(null==s?void 0:s.rtp)){const e=s.rtp;for(let t=0;t<e.length;t++)if("VP9"===e[t].codec){const r=null===(n=s.payloads)||void 0===n?void 0:n.split(" "),i=null==r?void 0:r.indexOf(""+e[t].payload);i&&-1!==i&&i>=0&&(null==r||r.unshift(r.splice(i,1)[0]),s.payloads=null==r?void 0:r.join(" "))}}}return Ht(i)}catch(e){Yl.error("setCodecPreferenceSDP error:",e)}}(t.sdp,i)),o&&(t.sdp=function(e){try{const t=Wt(e);return t.media.forEach(e=>{const t={};e.payloads&&(e.payloads=(""+e.payloads).split(" ").filter(e=>!t[e]&&(t[e]=!0)).join(" "));const r={};e.rtp=e.rtp.filter(e=>!e.payload||t[e.payload]&&!r[e.payload]&&(r[e.payload]=!0));const n={};e.fmtp&&(e.fmtp=e.fmtp.filter(e=>!e.payload||t[e.payload]&&!n[e.payload]&&(n[e.payload]=!0)));const i={};e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter(e=>!e.payload||t[e.payload]&&!i[e.payload+e.type+e.subtype]&&(i[e.payload+e.type+e.subtype]=!0)))}),Ht(t)}catch(e){}return e}(t.sdp)),n.setLocalDescription(t).catch(e=>{throw Gu.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e),this._emit(zu,e),e}).then(()=>{this._emitServerEvent(jl,{receiverId:e,message:this._transformOutgoingSdp(t)})})}).catch(e=>{Gu.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))}_withForcedRenegotiation(e,t){const r=e.pc,n=r.onnegotationneeded;r.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout(()=>r.onnegotiationneeded=n,0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);const r=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:0,2:384,3:256,4:192,5:128,6:128,7:64}[t];return void 0===r?0:(this._forEachPeerConnection(e=>{e.changeBandwidth(r)}),r)}_createP2pSession({clientId:e,initialBandwidth:t,shouldAddLocalVideo:r=!1,isOfferer:n=!1}){const i=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:r,isOfferer:n}),s=i.pc;this._features.increaseIncomingMediaBufferOn&&this._setJitterBufferTarget(s);const o=this.localStreams[qu];return r&&o&&!o.getVideoTracks().length&&this._stoppedVideoTrack&&s.addTrack(this._stoppedVideoTrack,o),s.onicegatheringstatechange=e=>{switch(e.target.iceGatheringState){case"gathering":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=setTimeout(()=>{i.publicHostCandidateSeen||i.relayCandidateSeen||i.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState&&"completed"===s.iceConnectionState||this._emit(xu)},3e3);break;case"complete":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=void 0}},s.onicecandidate=t=>{var r,n;if(t.candidate){switch(null===(r=t.candidate)||void 0===r?void 0:r.type){case"host":const e=null===(n=null==t?void 0:t.candidate)||void 0===n?void 0:n.address;try{if(jd.v4({exact:!0}).test(e)){fd(e).isPublicIp&&(i.publicHostCandidateSeen=!0)}else if(jd.v6({exact:!0}).test(e.replace(/^\[(.*)\]/,"$1"))){const t=new dc.Address6(e.replace(/^\[(.*)\]/,"$1"));i.ipv6HostCandidateSeen=!0,"Global"===t.getScope()&&(i.publicHostCandidateSeen=!0),t.isTeredo()&&(i.ipv6HostCandidateTeredoSeen=!0),t.is6to4()&&(i.ipv6HostCandidate6to4Seen=!0)}else{const t=e.replace(/.local/,"");t&&_d(t,4)&&(i.mdnsHostCandidateSeen=!0)}}catch(e){Gu.info("Error during parsing candidates! Error: ",{error:e})}break;case"srflx":i.serverReflexiveCandidateSeen||(i.serverReflexiveCandidateSeen=!0);break;case"relay":case"relayed":i.relayCandidateSeen||(i.relayCandidateSeen=!0)}this._emitServerEvent(xl,{receiverId:e,message:t.candidate})}else this._emitServerEvent(Il,{receiverId:e}),i.publicHostCandidateSeen||i.relayCandidateSeen||i.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState||"completed"===s.iceConnectionState||this._emit(Ou),i.ipv6HostCandidateSeen&&this._emit(Ru,{teredoSeen:i.ipv6HostCandidateTeredoSeen,sixtofourSeen:i.ipv6HostCandidate6to4Seen}),i.mdnsHostCandidateSeen&&this._emit(Eu)},s.onnegotiationneeded=()=>{"new"!==s.iceConnectionState&&i.connectionStatus&&this._negotiatePeerConnection(e,i)},i}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:r}){let n=this._getSession(t);if(n&&e!==t)return n;let i=n&&n.bandwidth||0;return n?(Gu.warn("Replacing peer session",t),this._cleanup(t)):i=this._changeBandwidthForAllClients(!0),n=this._createP2pSession({clientId:t,initialBandwidth:i,shouldAddLocalVideo:!!r,isOfferer:!1}),this._emitServerEvent(Dl,{receiverId:t}),n}disconnect(e){this._cleanup(e),this._changeBandwidthForAllClients(!1);0===this.numberOfPeerconnections()&&setTimeout(()=>{0===this.numberOfPeerconnections()&&this.rtcStatsDisconnect()},6e4)}updateStreamResolution(){}stopOrResumeAudio(){}_handleStopOrResumeVideo({enable:e,track:t}){e?this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,t),delete this._stoppedVideoTrack):this._addTrackToPeerConnections(t):this._stoppedVideoTrack=t}stopOrResumeVideo(e,t){var r;if(["chrome","safari"].includes(Hu))if(!1===t){const n="ended"===(null===(r=e.getVideoTracks().find(e=>!e.enabled))||void 0===r?void 0:r.readyState)?0:5e3;setTimeout(()=>{e.getVideoTracks().forEach(r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emit(gu,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))})},n)}else if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;if(!r)return;navigator.mediaDevices.getUserMedia({video:r}).then(r=>{const n=r.getVideoTracks()[0];e.addTrack(n),this._monitorVideoTrack(n),this._emit(mu,{streamId:e.id,tracks:[n],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:n})})}}_shareScreen(e,t){this._emitServerEvent(_l,{streamId:e,hasAudioTrack:!!t.getAudioTracks().length}),this._wasScreenSharing=!0,this._addStreamToPeerConnections(t)}removeStream(e,t,r){this._removeLocalStream(e),this._removeStreamFromPeerConnections(t),this._wasScreenSharing=!1,this._emitServerEvent(wl,{streamId:e,requestedByClientId:r})}hasClient(e){return Object.keys(this.peerConnections).includes(e)}}var Qu=Object.freeze({__proto__:null,KalmanFilter:class{constructor({R:e=.01,Q:t=2,A:r=1.1,B:n=1,C:i=1.2}={R:.01,Q:2,A:1.1,B:1,C:1.2}){this.R=e,this.Q=t,this.A=r,this.C=i,this.B=n,this.cov=NaN,this.x=NaN}filter(e,t=0){if(isNaN(this.x))this.x=1/this.C*e,this.cov=1/this.C*this.Q*(1/this.C);else{const r=this.predict(t),n=this.uncertainty(),i=n*this.C*(1/(this.C*n*this.C+this.Q));this.x=r+i*(e-this.C*r),this.cov=n-i*this.C*n}return this.x}predict(e=0){return this.A*this.x+this.B*e}uncertainty(){return this.A*this.cov*this.A+this.R}lastMeasurement(){return this.x}setMeasurementNoise(e){this.Q=e}setProcessNoise(e){this.R=e}},calculateStd:e=>{const t=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,r)=>e.concat(Math.pow(r-t,2)),[]).reduce((e,t)=>e+t,0)/e.length},createACFCalculator:()=>{let e=-1,t=0,r=0;return n=>{const i=n.reduce((e,t)=>e+t,0)/n.length;if(e=e<0?i:.95*e+.05*i,++r<2)return t=i,0;const s=(i-e)*(t-e);return t=i,s}},standardDeviation:e=>{const t=e.reduce((e,t)=>e+t,0)/e.length;return{mean:t,SD:Math.sqrt(e.reduce((e,r)=>e+Math.pow(r-t,2),0)/e.length)}},variance:(e,t=!1)=>{const r=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,t)=>e.concat(Math.pow(t-r,2)),[]).reduce((e,t)=>e+t,0)/(e.length-(t?0:1))}});const Yu={minDecibels:-80,maxDecibels:-10,smoothingTimeConstant:.8,aggSize:1,sampleRate:10,reportRate:2,bins:32,bands:[[0,1,2,3],[4,5,6,7]],separateTrack:{autoGainControl:!1,noiseSupression:!1},binFormula:"bin",scoreFormula:"300 * bands[1].avg / Math.max(bands[1].avg + bands[0].avg, 0.01)",outFormula:"score"},Xu=new Ld;const Zu=new Ld,ep=Object.freeze({ok:"ok",warning:"warning",critical:"critical"});class tp extends Ro{constructor(){super(),this._clients={},this._producers={},this._startMonitor()}close(){clearInterval(this._intervalHandle),delete this._intervalHandle,this._producers={},this._clients={}}_startMonitor(){this._intervalHandle=setInterval(()=>{Object.entries(this._producers).forEach(([e,t])=>{this._evaluateClient(e,t)})},600)}_evaluateClient(e,t){this._clients[e]||(this._clients[e]={audio:{currentQuality:ep.ok,trend:[]},video:{currentQuality:ep.ok,trend:[]}}),this._evaluateProducer(e,Object.values(t).filter(e=>"audio"===e.kind),"audio"),this._evaluateProducer(e,Object.values(t).filter(e=>"video"===e.kind),"video")}_evaluateProducer(e,t,r){if(0===t.length)return;const n=t.reduce((e,t)=>e+t.score,0)/t.length,i=this._evaluateScore(n);this._updateTrend(i,this._clients[e][r])&&this.emit(Ll,{clientId:e,kind:r,quality:i})}_updateTrend(e,t){return t.trend.push(e),t.trend.length>3&&t.trend.shift(),!(e===t.currentQuality||!t.trend.every(e=>e!==t.currentQuality))&&(t.currentQuality=e,!0)}addProducer(e,t){e&&t&&"string"==typeof e&&"string"==typeof t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Zu.warn("Missing clientId or producerId")}removeProducer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addConsumer(e,t){e&&t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Zu.warn("Missing clientId or consumerId")}removeConsumer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addProducerScore(e,t,r,n){Array.isArray(n)&&0!==n.length&&!n.some(e=>!e||!e.hasOwnProperty("score")||"number"!=typeof e.score||isNaN(e.score))?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(n.map(e=>e.score))}:Zu.warn("Unexpected producer score format")}addConsumerScore(e,t,r,n){n&&n.hasOwnProperty("producerScores")&&Array.isArray(n.producerScores)?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(n.producerScores)}:Zu.warn("Unexpected consumer score format")}_evaluateScore(e){return e<=9&&e>7?ep.warning:e<=7&&e>0?ep.critical:ep.ok}_calcAvgProducerScore(e){try{if(!Array.isArray(e)||0===e.length)return 0;let t=0,r=0;return e.forEach(e=>{e>0&&(t+=e,r++)}),0===t||0===r?0:t/r}catch(e){return Zu.error(e),0}}}class rp{static parse(e){let t;try{t=JSON.parse(e)}catch(e){return}if("object"==typeof t&&!Array.isArray(t))return t.request?rp._handleRequest(t):t.response?rp._handleResponse(t):t.message?rp._handleMessage(t):void 0}static _handleRequest(e){const t={request:!0};if("string"==typeof e.method&&"number"==typeof e.id)return t.id=e.id,t.method=e.method,t.data=e.data||{},t}static _handleResponse(e){const t={response:!0};if("number"==typeof e.id)return t.id=e.id,e.ok?(t.ok=!0,t.data=e.data||{}):(t.ok=!1,t.errorCode=e.errorCode,t.errorReason=e.errorReason),t}static _handleMessage(e){const t={message:!0};if("string"==typeof e.method)return t.method=e.method,t.data=e.data||{},t}static createRequest(e,t){return{request:!0,id:Math.round(1e7*Math.random()),method:e,data:t||{}}}static createSuccessResponse(e,t){return{response:!0,id:e.id,ok:!0,data:t||{}}}static createErrorResponse(e,t,r){return{response:!0,id:e.id,errorCode:t,errorReason:r}}static createMessage(e,t){return{message:!0,method:e,data:t||{}}}}const np=new Ld;class ip extends Ro{constructor(e,t="whereby-sfu#v4"){super(),this.socket=null,this.wsUrl=e,this.protocol=t,this.sents=new Map,this._setupSocket()}_setupSocket(){this.socket=new WebSocket(this.wsUrl,this.protocol),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onclose=this._onClose.bind(this),this.socket.onerror=this._onError.bind(this)}_tearDown(){null!==this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket=null,this.sents.forEach(e=>e.close()),this.emit("close"))}close(){var e;null===(e=this.socket)||void 0===e||e.close()}_onOpen(){np.info("Connected"),this.emit("open")}_onMessage(e){const t=rp.parse(e.data);np.info("Received message",t),(null==t?void 0:t.response)?this._handleResponse(t):(null==t?void 0:t.message)&&this.emit("message",t)}_onClose(){np.info("Disconnected"),this._tearDown()}_onError(e){np.info("Error",e)}_handleResponse(e){const t=this.sents.get(e.id);if(e.ok)t.resolve(e.data);else{const r=new Error(e.errorReason);t.reject(r)}}send(e){try{this.socket&&this.socket.send(JSON.stringify(e))}catch(e){}}message(e,t={}){const r=rp.createMessage(e,t);this.send(r)}request(e,t={},r=1500*(15+.1*this.sents.size)){const n=rp.createRequest(e,t);return this.send(n),new Promise((e,t)=>{const i={id:n.id,method:n.method,resolve:t=>{this.sents.delete(n.id)&&(clearTimeout(i.timer),e(t))},reject:e=>{this.sents.delete(n.id)&&(clearTimeout(i.timer),t(e))},timer:setTimeout(()=>{this.sents.delete(n.id)&&t(new Error("request timeout"))},r),close:()=>{clearTimeout(i.timer),t(new Error("transport closed"))}};this.sents.set(n.id,i)})}}function sp(e){let t,r,n,i,s=[];const o=e=>{s=function(e){return"string"==typeof e?e.split(",").filter(Boolean).map(e=>{const[t,r]=/\|/.test(e)?e.split("|"):["",e];return{host:r,dc:t}}):e.filter(e=>e.host).map(e=>({host:e.host,dc:e.dc||""}))}(e)};let a=!1,c=!1;const d=()=>{if(a)return void(c=!0);a=!0,c=!1;let o=s;if(t){const e=Date.now();e-3e3>(r||0)&&((!i||(n||0)>i)&&e-3e3>(n||0))||(o=[{host:t.host,dc:t.dc}])}const l={};let u=0;o.forEach(({dc:e})=>{void 0===l[e]&&(l[e]=u++)});let p=0;const h={};let f,m=o.length,g=!1,v=!1;const b=i,y=()=>{var t;m--,0!==m||g||(a=!1,c?setTimeout(d,0):null===(t=e.onFailed)||void 0===t||t.call(e))},_=[];o.forEach(({host:n,dc:s},d)=>{if(d>0){p+=500;const e=(h[s]||0)+2e3;p=Math.max(p,e)}h[s]=p,_.push(setTimeout(()=>{var u;if(_.shift(),v)return;if(b!==i)return y(),void _.forEach(e=>{clearTimeout(e),y()});const p=new ip((null===(u=e.getUrlForHost)||void 0===u?void 0:u.call(e,n))||n);let h=!1;p.on("open",()=>{setTimeout(()=>{var r;if(!h)if(f||v)p.close();else{f=p,v=!0;const i=[...new Set(o.slice(0,d).filter(e=>e.host!==n).map(e=>e.host))],u=[...new Set(o.slice(0,d).filter(e=>e.dc!==s).map(e=>e.dc))];t=t?Object.assign(Object.assign({},t),{host:n,dc:s,failedHosts:[...new Set([...i,...t.failedHosts])].filter(e=>e!==n&&!t.usedHosts.includes(e)),failedDCs:[...new Set([...u,...t.failedDCs])].filter(e=>e!==s&&!t.usedDCs.includes(e)),usedHosts:[...new Set([...t.usedHosts,n])],usedDCs:[...new Set([...t.usedDCs,s])],numConnections:t.numConnections+1}):{host:n,dc:s,initialHost:n,initialDC:s,initialHostIndex:d,initialDCIndex:l[s],failedHosts:i,failedDCs:u,usedHosts:[n],usedDCs:[s],numConnections:1,numUsedDCs:1,numUsedHosts:1,numFailedDCs:0,numFailedHosts:0},t.numUsedDCs=t.usedDCs.length,t.numUsedHosts=t.usedHosts.length,t.numFailedDCs=t.failedDCs.length,t.numFailedHosts=t.failedHosts.length,c=!1,a=!1,null===(r=e.onConnected)||void 0===r||r.call(e,p,t)}},100)}),p.on("close",()=>{var t;h=!0,p===f&&(f=void 0,r=Date.now(),g=!0,null===(t=e.onDisconnected)||void 0===t||t.call(e)),y()})},p))})};o(e.initialHostList);return{connect:d,updateHostList:o,networkIsUp:()=>{n=Math.max(Date.now(),n||0)},networkIsPossiblyDown:()=>{i=Date.now()}}}var op;const ap=null!==(op=ko.default)&&void 0!==op?op:ko,cp=new Ld,dp=ap.browserDetails.browser;let lp=!1;const up=Uo(),pp=Uo();"chrome"===dp&&window.document.addEventListener("beforeunload",()=>lp=!0);class hp{constructor({selfId:e,room:t,emitter:r,serverSocket:n,webrtcProvider:i,features:s,eventClaim:o}){const{session:a,iceServers:c,turnServers:d,sfuServer:l,sfuServers:u,mediaserverConfigTtlSeconds:p}=t;this._selfId=e,this._room=t,this._roomSessionId=null==a?void 0:a.id,this._emitter=r,this._serverSocket=n,this._webrtcProvider=i,this._features=s||{},this._eventClaim=o,this._vegaConnection=null,this._micAnalyser=null,this._micAnalyserDebugger=null,this._mediasoupDeviceInitializedAsync=(e=>Td(void 0,void 0,void 0,function*(){if(e.isNodeSdk)return new h.Device({handlerName:"Safari12"});let t=(yield h.detectDeviceAsync())||(/applecoremedia|applewebkit|safari/i.test(navigator.userAgent)?"Safari12":void 0);return/iphone|ipad/i.test(navigator.userAgent)&&(t="Safari12"),t||(t="Chrome111"),new h.Device({handlerName:t})}))(s),this._routerRtpCapabilities=null,this._sendTransport=null,this._receiveTransport=null,this._clientStates=new Map,this._streamIdToVideoConsumerId=new Map,this._streamIdToVideoResolution=new Map,this._consumers=new Map,this._dataConsumers=new Map,this._localStreamDeregisterFunction=null,this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._micProducer=null,this._micProducerPromise=null,this._micPaused=!1,this._micScoreProducer=null,this._micScoreProducerPromise=null,this._webcamProducer=null,this._webcamProducerPromise=null,this._webcamPaused=!1,this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._sndTransportIceRestartPromise=null,this._rcvTransportIceRestartPromise=null,this._colocation=null,this._stopCameraTimeout=null,this._audioTrackOnEnded=()=>{nl.sendEvent("audio_ended",{unloading:lp}),this._emitToPWA(Mu,{})},this._videoTrackOnEnded=()=>{nl.sendEvent("video_ended",{unloading:lp}),this._emitToPWA(ju,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,sfuServers:u,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:p}),this._socketListenerDeregisterFunctions=[],this._reconnect=!0,this._reconnectTimeOut=null,this._isConnectingOrConnected=!1,this._qualityMonitor=new tp,this._qualityMonitor.on(Ll,e=>{this._emitToPWA(Ll,e)}),this._networkIsDetectedUpBySignal=!1,this._cpuOveruseDetected=!1}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,sfuServers:n,mediaserverConfigTtlSeconds:i}){var s,o,a;this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._sfuServers=n,!n&&(null==r?void 0:r.fallbackServers)&&(this._sfuServers=r.fallbackServers.map(e=>({host:e.host||e.fqdn,dc:e.dc}))),this._mediaserverConfigTtlSeconds=i,null===(s=this._vegaConnectionManager)||void 0===s||s.updateHostList(this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||r.url);const c={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};c.iceServers=$l(c.iceServers,this._features.turnServerOverrideHost),null===(o=this._sendTransport)||void 0===o||o.updateIceServers(c),null===(a=this._receiveTransport)||void 0===a||a.updateIceServers(c),this._clearMediaServersRefresh(),i&&(this._fetchMediaServersTimer=setTimeout(()=>this._emitToSignal(yl),1e3*i))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_onNetworkIsDetectedUpBySignal(){var e;this._networkIsDetectedUpBySignal||(this._networkIsDetectedUpBySignal=!0,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsUp())}_onNetworkIsDetectedPossiblyDownBySignal(){var e;this._networkIsDetectedUpBySignal&&(this._networkIsDetectedUpBySignal=!1,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsPossiblyDown())}setupSocketListeners(){this._socketListenerDeregisterFunctions.push(()=>this._clearMediaServersRefresh(),this._serverSocket.on(kl,e=>{e.error?cp.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)}),this._serverSocket.on(El,e=>{(null==e?void 0:e.error)||(this._screenVideoTrack&&this._emitScreenshareStarted(),this._reconnect&&this._connect())}),this._serverSocket.on("connect",()=>this._onNetworkIsDetectedUpBySignal()),this._serverSocket.onEngineEvent("packet",()=>this._onNetworkIsDetectedUpBySignal()),this._serverSocket.on("disconnect",()=>this._onNetworkIsDetectedPossiblyDownBySignal())),this._connect()}_emitScreenshareStarted(){this._emitToSignal(_l,{streamId:pp,hasAudioTrack:Boolean(this._screenAudioTrack)})}_connect(){if(!this._isConnectingOrConnected){if(!this._serverSocket.isConnected()){const e=this._serverSocket.getReconnectThreshold();if(!e)return;if(Date.now()>(this._serverSocket.disconnectTimestamp||0)+e)return}if(this._reconnectTimeOut&&clearTimeout(this._reconnectTimeOut),!this._vegaConnectionManager){const e=this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||this._sfuServer.url;this._vegaConnectionManager=sp({initialHostList:e,getUrlForHost:e=>{const t=new URLSearchParams(Object.assign({clientId:this._selfId,organizationId:this._room.organizationId,roomName:this._room.name,eventClaim:this._room.isClaimed?this._eventClaim:null,lowBw:"true"},Object.keys(this._features||{}).filter(e=>this._features[e]&&/^sfu/.test(e)).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:this._features[t]}),{})));return`wss://${e}?${t.toString()}`},onConnected:(e,t)=>{this._vegaConnection=e,this._vegaConnection.on("message",e=>this._onMessage(e)),this._emitToPWA(Fu,t),this._join()},onDisconnected:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()},onFailed:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()}})}this._vegaConnectionManager.connect(),this._isConnectingOrConnected=!0}}_onClose(){var e,t;cp.info("_onClose()"),null===(e=this._sendTransport)||void 0===e||e.close(),null===(t=this._receiveTransport)||void 0===t||t.close(),this._sendTransport=null,this._receiveTransport=null,this._streamIdToVideoConsumerId.clear(),this._streamIdToVideoResolution.clear(),this._reconnect&&(this._reconnectTimeOut=setTimeout(()=>this._connect(),1e3)),this._qualityMonitor.close(),this._emitToPWA(Nu)}_join(){return Td(this,void 0,void 0,function*(){var e,t;cp.info("join()"),this._emitToPWA(Lu);try{const{routerRtpCapabilities:r}=yield this._vegaConnection.request("getCapabilities");if(!this._routerRtpCapabilities){const t=((e,t)=>{var r;const{vp9On:n,h264On:i}=t,s="chrome"===(null===(r=ko.browserDetails)||void 0===r?void 0:r.browser);if(!(null==e?void 0:e.codecs))return e;if(n&&s){const t=Kd(e.codecs,Jd.VP9);return Object.assign(Object.assign({},e),{codecs:t})}if(i){const t=Kd(e.codecs,Jd.H264);return Object.assign(Object.assign({},e),{codecs:t})}return e})(r,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}));this._routerRtpCapabilities=t,yield null===(e=yield this._mediasoupDeviceInitializedAsync)||void 0===e?void 0:e.load({routerRtpCapabilities:t})}this._vegaConnection.message("setCapabilities",{rtpCapabilities:null===(t=yield this._mediasoupDeviceInitializedAsync)||void 0===t?void 0:t.rtpCapabilities}),this._colocation&&this._vegaConnection.message("setColocation",{colocation:this._colocation}),yield Promise.all([this._createTransport(!0),this._createTransport(!1)]);const n=[];!this._micTrack||this._micProducer||this._micProducerPromise||n.push(this._internalSendMic()),!this._webcamTrack||this._webcamProducer||this._webcamProducerPromise||n.push(this._internalSendWebcam()),!this._screenVideoTrack||this._screenVideoProducer||this._screenVideoProducerPromise||n.push(this._internalSendScreenVideo()),!this._screenAudioTrack||this._screenAudioProducer||this._screenAudioProducerPromise||n.push(this._internalSendScreenAudio()),yield Promise.all(n)}catch(e){cp.error("_join() [error:%o]",e)}})}_createTransport(e){return Td(this,void 0,void 0,function*(){var t;const r=e?"createSendTransport":"createRecvTransport",n=yield this._vegaConnection.request("createTransport",{producing:e,consuming:!e,enableTcp:!0,enableUdp:!0,preferUdp:!0,sctpParameters:{enableSctp:!0,numSctpStreams:{OS:1024,MIS:1024},maxSctpMessageSize:262144,sctpSendBufferSize:262144}});n.iceServers=$l(this._features.turnServersOn?this._turnServers:this._iceServers,this._features.turnServerOverrideHost),Vl(n,this._features);const i=null===(t=yield this._mediasoupDeviceInitializedAsync)||void 0===t?void 0:t[r](n),s=t=>Td(this,void 0,void 0,function*(){if(cp.info(`Transport ConnectionStateChanged ${t}`),"disconnected"===t||"failed"===t)if(e){if(this._sndTransportIceRestartPromise)return;this._sndTransportIceRestartPromise=this._restartIce(i).finally(()=>{this._sndTransportIceRestartPromise=null})}else{if(this._rcvTransportIceRestartPromise)return;this._rcvTransportIceRestartPromise=this._restartIce(i).finally(()=>{this._rcvTransportIceRestartPromise=null})}});null==i||i.on("connect",({dtlsParameters:e},t)=>{var r;null===(r=this._vegaConnection)||void 0===r||r.message("connectTransport",{transportId:i.id,dtlsParameters:e}),t()}).on("connectionstatechange",s),null==i||i.observer.once("close",()=>{i.removeListener("connectionstatechange",s)}),e?(null==i||i.on("produce",(e,t,r)=>Td(this,[e,t,r],void 0,function*({kind:e,rtpParameters:t,appData:r},n,s){var o;try{const{paused:s}=r,{id:a}=yield null===(o=this._vegaConnection)||void 0===o?void 0:o.request("produce",{transportId:i.id,kind:e,rtpParameters:t,paused:s,appData:r});n({id:a})}catch(e){s(e)}})),null==i||i.on("producedata",(e,t,r)=>Td(this,[e,t,r],void 0,function*({appData:e,sctpStreamParameters:t},r,n){var s;try{const{id:n}=yield null===(s=this._vegaConnection)||void 0===s?void 0:s.request("produceData",{transportId:i.id,sctpStreamParameters:t,appData:e});r({id:n})}catch(e){n(e)}})),this._sendTransport=i):this._receiveTransport=i})}_restartIce(e){return Td(this,arguments,void 0,function*(e,t=0){if(!e||!("closed"in e)||!("connectionState"in e))return void cp.info("_restartIce: No transport or property closed or connectionState!");if(e.closed)return void cp.info("_restartIce: Transport is closed!");if("disconnected"!==e.connectionState&&"failed"!==e.connectionState)return void cp.info("_restartIce: Connection is healthy ICE restart no loneger needed!");const{iceRestartStarted:r}=e.appData,n=Date.now();if(Number.isFinite(r)&&n-r<3500)return;if(e.appData.iceRestartStarted=n,5<=t)return void cp.info("_restartIce: Reached restart ICE maximum retry count!");if(!this._vegaConnection)return void cp.info("_restartIce: Connection is undefined");const{iceParameters:i}=yield this._vegaConnection.request("restartIce",{transportId:e.id});cp.info("_restartIce: ICE restart iceParameters received from SFU: ",i);const s=yield e.restartIce({iceParameters:i}).then(()=>null).catch(e=>e);if(s)switch(cp.error(`_restartIce: ICE restart failed: ${s}`),s.message){case"missing transportId":case"no such transport":break;default:yield new Promise(e=>{setTimeout(()=>{e(void 0)},Math.min(3500*Math.pow(2,t),6e4))}),yield this._restartIce(e,t+1)}else yield new Promise(e=>{setTimeout(()=>{e(void 0)},6e4*Math.min(8,t+1))}),"failed"!==e.connectionState&&"disconnected"!==e.connectionState||(yield this._restartIce(e,t+1))})}_internalSendMic(){return Td(this,void 0,void 0,function*(){cp.info("_internalSendMic()"),this._micProducerPromise=(()=>Td(this,void 0,void 0,function*(){try{if(!this._micTrack||!this._sendTransport||this._micProducer)return void(this._micProducerPromise=null);const e=this._micPaused,t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._micTrack,disableTrackOnPause:!1,stopTracks:!1},qd("audio",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:up,sourceClientId:this._selfId,screenShare:!1,source:"mic",paused:e}}));e?t.pause():t.resume(),this._micProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",()=>{var e;cp.info('micProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._micProducer=null,this._micProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)}),this._micTrack!==this._micProducer.track&&(yield this._replaceMicTrack()),this._micPaused!==this._micProducer.paused&&this._pauseResumeMic()}catch(e){cp.error("micProducer failed:%o",e)}finally{this._micProducerPromise=null,this._micTrack||(this._stopProducer(this._micProducer),this._micProducer=null)}}))()})}_internalSetupMicScore(){return Td(this,void 0,void 0,function*(){cp.info("_internalSetupMicScore()"),this._micScoreProducerPromise=(()=>Td(this,void 0,void 0,function*(){try{if(!this._micProducer||!this._colocation||this._micScoreProducer)return void(this._micScoreProducerPromise=null);const e=yield this._sendTransport.produceData({ordered:!1,maxPacketLifeTime:3e3,label:"micscore",appData:{producerId:this._micProducer.id,clientId:this._selfId}});this._micScoreProducer=e,e.observer.once("close",()=>{var t;cp.info('micScoreProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeDataProducers",{dataProducerIds:[e.id]})),this._micScoreProducer=null,this._micScoreProducerPromise=null})}catch(e){cp.error("micScoreProducer failed:%o",e)}finally{this._micScoreProducerPromise=null,this._micProducer&&this._colocation||this._stopMicScoreProducer()}}))()})}_stopMicScoreProducer(){this._stopProducer(this._micScoreProducer),this._micScoreProducer=null}_replaceMicTrack(){return Td(this,void 0,void 0,function*(){var e;cp.info("_replaceMicTrack()"),this._micTrack&&this._micProducer&&!this._micProducer.closed&&this._micProducer.track!==this._micTrack&&(yield this._micProducer.replaceTrack({track:this._micTrack}),null===(e=this._micAnalyser)||void 0===e||e.setTrack(this._micTrack),yield this._replaceMicTrack())})}_pauseResumeMic(){var e,t;cp.info("_pauseResumeMic()"),this._micProducer&&!this._micProducer.closed&&this._micPaused!==this._micProducer.paused&&(this._micPaused?(this._micProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._micProducer.id]})):(this._micProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._micProducer.id]})),this._pauseResumeMic())}_sendMic(e){return Td(this,void 0,void 0,function*(){return cp.info("_sendMic() [track:%o]",e),this._micTrack=e,this._micProducer?yield this._replaceMicTrack():this._micProducerPromise?void 0:this._sendTransport?yield this._internalSendMic():void 0})}_sendMicScore(e){if(!isNaN(e)&&isFinite(e))if(this._micScoreProducer){if(this._micScoreProducer.closed)return void this._stopMicScoreProducer();try{this._micScoreProducer.send(JSON.stringify({score:e}))}catch(e){cp.error("_sendMicScore failed [error:%o]",e)}}else!this._micScoreProducerPromise&&this._micProducer&&this._colocation&&0!==e&&this._internalSetupMicScore()}_syncResourceUsage(){var e;if(this._webcamProducer){const t=!this._cpuOveruseDetected,r=this._webcamProducer.rtpParameters;if(3===(null===(e=null==r?void 0:r.encodings)||void 0===e?void 0:e.length)){const e=t?2:1;this._webcamProducer.maxSpatialLayer!==e&&(this._webcamProducer.setMaxSpatialLayer(e),nl.sendEvent("simulcast_layer_activation_changed",{layerIndex:2,active:t}))}}}_internalSendWebcam(){return Td(this,void 0,void 0,function*(){var e;cp.info("_internalSendWebcam()"),!this._sendTransport||this._webcamProducer||this._webcamProducerPromise||"live"!==(null===(e=this._webcamTrack)||void 0===e?void 0:e.readyState)||(this._webcamProducerPromise=(()=>Td(this,void 0,void 0,function*(){var e;try{const t=this._webcamPaused,r=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._webcamTrack,disableTrackOnPause:!1,stopTracks:!1},qd("video",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:up,sourceClientId:this._selfId,screenShare:!1,source:"webcam",paused:t}}));t?r.pause():r.resume();const n=this._features.producerCpuOveruseWatchOn?function({producer:e,onOveruse:t}){var r;const n=null===(r=e.rtpParameters)||void 0===r?void 0:r.encodings;let i=null;if(3===(null==n?void 0:n.length)){const{ssrc:r,rid:s}=n[0];let o=0,a=0;const c=2;i=setInterval(()=>Td(this,void 0,void 0,function*(){(yield e.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(r&&e.ssrc===r||s&&e.rid===s)&&(o&&e.frameHeight&&e.frameHeight<o?(a++,a>=c&&t()):a=0,o=Math.max(o,e.frameHeight||0))})}),2e3)}return()=>{i&&clearInterval(i)}}({producer:r,onOveruse:()=>{nl.sendEvent("producer_cpuoveruse_detected",{}),n(),this._cpuOveruseDetected=!0,this._syncResourceUsage()}}):()=>{};this._webcamProducer=r,this._qualityMonitor.addProducer(this._selfId,r.id),r.observer.once("close",()=>{var e;cp.info('webcamProducer "close" event'),r.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[r.id]})),n(),this._webcamProducer=null,this._webcamProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,r.id)}),this._webcamTrack&&this._webcamTrack!==(null===(e=this._webcamProducer)||void 0===e?void 0:e.track)&&(this._webcamProducerPromise=null,this._replaceWebcamTrack()),this._webcamPaused!==this._webcamProducer.paused&&this._pauseResumeWebcam()}catch(e){cp.error("webcamProducer failed:%o",e)}finally{this._webcamProducerPromise=null,this._webcamTrack||(this._stopProducer(this._webcamProducer),this._webcamProducer=null)}}))())})}_replaceWebcamTrack(){return Td(this,void 0,void 0,function*(){cp.info("_replaceWebcamTrack()"),this._sendTransport&&this._webcamTrack&&!this._webcamProducerPromise&&(this._webcamProducer||!this._webcamTrack.enabled?this._webcamProducer.track!==this._webcamTrack&&(yield this._webcamProducer.replaceTrack({track:this._webcamTrack}),yield this._replaceWebcamTrack()):yield this._internalSendWebcam())})}_pauseResumeWebcam(){var e,t;cp.info("_pauseResumeWebcam()"),this._webcamProducer&&!this._webcamProducer.closed&&this._webcamPaused!==this._webcamProducer.paused&&(this._webcamPaused?(this._webcamProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._webcamProducer.id]})):(this._webcamProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._webcamProducer.id]})),this._pauseResumeWebcam())}_sendWebcam(e){return Td(this,void 0,void 0,function*(){return cp.info("_sendWebcam() [track:%o]",e),this._webcamTrack=e,this._webcamProducer?yield this._replaceWebcamTrack():this._webcamProducerPromise?void 0:this._sendTransport?yield this._internalSendWebcam():void 0})}_internalSendScreenVideo(){return Td(this,void 0,void 0,function*(){cp.info("_internalSendScreenVideo()"),this._screenVideoProducerPromise=(()=>Td(this,void 0,void 0,function*(){var e,t;try{if(!this._screenVideoTrack||!this._sendTransport||this._screenVideoProducer)return void(this._screenVideoProducerPromise=null);const r=this._features.sfuVp9On?null===(t=null===(e=this._routerRtpCapabilities)||void 0===e?void 0:e.codecs)||void 0===t?void 0:t.find(e=>e.mimeType.match(/vp8/i)):void 0,n=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenVideoTrack,disableTrackOnPause:!1,stopTracks:!1,codec:r},qd("video",!0,Object.assign(Object.assign({},this._features),{vp9On:!1}),this._getAreTooManyAlreadyPresenting())),{appData:{streamId:pp,sourceClientId:this._selfId,screenShare:!0,source:"screenvideo",paused:!1}}));this._screenVideoProducer=n,this._qualityMonitor.addProducer(this._selfId,n.id),n.observer.once("close",()=>{var e;cp.info('screenVideoProducer "close" event'),n.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[n.id]})),this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,n.id)}),this._screenVideoTrack!==this._screenVideoProducer.track&&(yield this._replaceScreenVideoTrack())}catch(e){cp.error("screenVideoProducer failed:%o",e)}finally{this._screenVideoProducerPromise=null,this._screenVideoTrack||(yield this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null)}}))()})}_replaceScreenVideoTrack(){return Td(this,void 0,void 0,function*(){cp.info("_replaceScreenVideoTrack()"),this._screenVideoTrack&&this._screenVideoProducer&&!this._screenVideoProducer.closed&&this._screenVideoProducer.track!==this._screenVideoTrack&&(yield this._screenVideoProducer.replaceTrack({track:this._screenVideoTrack}),yield this._replaceScreenVideoTrack())})}_sendScreenVideo(e){return Td(this,void 0,void 0,function*(){return cp.info("_sendScreenVideo() [track:%o]",e),this._screenVideoTrack=e,this._screenVideoProducer?yield this._replaceScreenVideoTrack():this._screenVideoProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenVideo():void 0})}_internalSendScreenAudio(){return Td(this,void 0,void 0,function*(){cp.info("_internalSendScreenAudio()"),this._screenAudioProducerPromise=(()=>Td(this,void 0,void 0,function*(){try{if(!this._screenAudioTrack||!this._sendTransport||this._screenAudioProducer)return void(this._screenAudioProducerPromise=null);const e=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenAudioTrack,disableTrackOnPause:!1,stopTracks:!1},qd("audio",!0,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:pp,sourceClientId:this._selfId,screenShare:!0,source:"screenaudio",paused:!1}}));this._screenAudioProducer=e,this._qualityMonitor.addProducer(this._selfId,e.id),e.observer.once("close",()=>{var t;cp.info('screenAudioProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeProducers",{producerIds:[e.id]})),this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,e.id)}),this._screenAudioTrack!==this._screenAudioProducer.track&&(yield this._replaceScreenAudioTrack())}catch(e){cp.error("screenAudioProducer failed:%o",e)}finally{this._screenAudioProducerPromise=null,this._screenAudioTrack||(yield this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null)}}))()})}_replaceScreenAudioTrack(){return Td(this,void 0,void 0,function*(){cp.info("_replaceScreenAudioTrack()"),this._screenAudioTrack&&this._screenAudioProducer&&!this._screenAudioProducer.closed&&this._screenAudioProducer.track!==this._screenAudioTrack&&(yield this._screenAudioProducer.replaceTrack({track:this._screenAudioTrack}),yield this._replaceScreenAudioTrack())})}_sendScreenAudio(e){return Td(this,void 0,void 0,function*(){return cp.info("_sendScreenAudio() [track:%o]",e),this._screenAudioTrack=e,this._screenAudioProducer?yield this._replaceScreenAudioTrack():this._screenAudioProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenAudio():void 0})}_stopProducer(e){cp.info("_stopProducer()"),e&&!e.closed&&(e.appData.localClosed=!0,e.close())}_getAreTooManyAlreadyPresenting(){return[...this._clientStates.values()].filter(e=>e.hasAcceptedScreenStream&&e.screenStream).length>=3}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._room.name===t&&Boolean(r)}setEventClaim(e){var t;this._eventClaim=e,null===(t=this._vegaConnection)||void 0===t||t.message("eventClaim",{eventClaim:e})}setColocation(e){var t;this._colocation=e,null===(t=this._vegaConnection)||void 0===t||t.message("setColocation",{colocation:e}),e||!this._micScoreProducer||this._micScoreProducerPromise||this._stopMicScoreProducer(),this._syncMicAnalyser(),nl.sendEvent("colocation_changed",{colocation:e})}setAudioOnly(e){var t;null===(t=this._vegaConnection)||void 0===t||t.message(e?"enableAudioOnly":"disableAudioOnly")}setRemoteScreenshareVideoTrackIds(){}setRoomSessionId(e){this._roomSessionId=e}disconnect(e,t,r){var n;cp.info("disconnect() [clientIdOrStreamId:%s, eventClaim:%s]",e,r);const i=this._clientStates.get(e);i&&(i.hasAcceptedWebcamStream=!1,i.hasAcceptedScreenStream=!1,this._syncIncomingStreamsWithPWA(e)),r&&(this._eventClaim=r,null===(n=this._vegaConnection)||void 0===n||n.message("eventClaim",{eventClaim:r}))}replaceTrack(e,t){"audio"===t.kind&&(t.effectTrack||this._monitorAudioTrack(t),this._micTrack=t,this._replaceMicTrack()),"video"===t.kind&&(t.effectTrack||this._monitorVideoTrack(t),this._webcamTrack=t,this._replaceWebcamTrack())}removeStream(e,t,r){cp.info("removeStream() [streamId:%s, requestedByClientId:%s]",e,r),this._emitToSignal(wl,{streamId:pp,requestedByClientId:r}),this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._screenVideoTrack=null,this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null,this._screenAudioTrack=null}_onMicAnalyserScoreUpdated(e){var t,r;null===(r=null===(t=this._micAnalyserDebugger)||void 0===t?void 0:t.onScoreUpdated)||void 0===r||r.call(t,e),this._sendMicScore(this._micPaused?0:e.out)}addNewStream(e,t,r,n,i=[]){if("0"===e){this._micPaused=r,this._webcamPaused=n;const e=t.getVideoTracks()[0],s=t.getAudioTracks()[0];if(e){this._sendWebcam(e),e.effectTrack||this._monitorVideoTrack(e);const t=i.find(e=>"video"===e.kind);t&&this._monitorVideoTrack(t)}if(s){this._sendMic(s),this._syncMicAnalyser(),s.effectTrack||this._monitorAudioTrack(s);const e=i.find(e=>"audio"===e.kind);e&&this._monitorAudioTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const o=e=>{const{enable:t,track:r}=e.detail;this._webcamPaused=!t,this._pauseResumeWebcam(),this._handleStopOrResumeVideo({enable:t,track:r})};t.addEventListener("stopresumevideo",o),this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",o)}}else{const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];e&&this._sendScreenVideo(e),r&&this._sendScreenAudio(r),this._emitScreenshareStarted()}}_syncMicAnalyser(){if(!this._micTrack||!this._colocation||this._micAnalyser)return this._micAnalyser&&!this._colocation?(this._micAnalyser.close(),void(this._micAnalyser=null)):void 0;this._micAnalyser=function({micTrack:e,params:t,onScoreUpdated:r}){const n=new AudioContext;let i=null,s=null,o=null,a=!1;const c=e=>Td(this,void 0,void 0,function*(){if(o&&a&&o.stop(),a=!1,e&&t.separateTrack)try{const r=yield navigator.mediaDevices.getUserMedia({audio:Object.assign({deviceId:null==o?void 0:o.getSettings().deviceId},t.separateTrack),video:!1});e=r.getAudioTracks()[0],a=!0}catch(e){Xu.warn("unable to fetch new track for colocation speaker analysis, using current",e)}if(o=e,s&&(s.disconnect(),s=null),e){const t=new MediaStream([e]);s=n.createMediaStreamSource(t),s.connect(i)}});let d;const l=e=>{if(clearInterval(d),t=Object.assign(Object.assign({},Yu),e),!i||i.fftSize!==2*t.bins){let e=null;i&&(e=o,c(null)),i=n.createAnalyser(),i.fftSize=2*t.bins,e&&c(e)}const s=new Uint8Array(i.frequencyBinCount),a=[];i.minDecibels=t.minDecibels,i.maxDecibels=t.maxDecibels,i.smoothingTimeConstant=t.smoothingTimeConstant;const l=t.initScript&&new Function("f","setTrack","lastTrack",t.initScript.join("\n")),u=t.scoreScript&&new Function("bins","g","f",t.scoreScript.join("\n")),p=t.scoreFormula&&new Function("bands",`return ${t.scoreFormula}`),h=t.outFormula&&new Function("score","avg","max","scores",`return ${t.outFormula}`),f=t.binFormula&&new Function("bin","index",`return ${t.binFormula}`);let m=0;const g=l&&l(Qu,c,o);d=setInterval(()=>{i.getByteFrequencyData(s);let e=0;if(p){const r=t.bands.map(e=>{const t=e.map(e=>f(s[e]/255,e));return{avg:t.reduce((e,t)=>e+t,0)/e.length,min:t.reduce((e,t)=>Math.min(e,t/255),Number.MAX_VALUE),max:t.reduce((e,t)=>Math.max(e,t/255),0)}});e=p(r)||0}else u&&(e=u(s,g,Qu),isNaN(e)&&(e=0));if(a.push(e),a.length>t.aggSize&&a.shift(),m++,m>=t.reportRate){m=0;const t=a.reduce((e,t)=>Math.max(e,t),0),n=a.reduce((e,t)=>e+t,0)/a.length,i=h(e,n,t,a);r({bins:s,score:e,max:t,avg:n,out:i})}},1e3/t.sampleRate)};return l(t),c(e),{setParams:l,setTrack:c,close(){c(null),clearInterval(d),n.close()}}}({micTrack:this._micTrack,onScoreUpdated:this._onMicAnalyserScoreUpdated.bind(this)})}stopOrResumeAudio(e,t){cp.info("stopOrResumeAudio() [enabled:%s]",t),this._micPaused=!t,this._pauseResumeMic()}_handleStopOrResumeVideo({enable:e,track:t}){e?this._sendWebcam(t):this._webcamProducer&&!this._webcamProducer.closed&&this._webcamProducer.track===t&&(this._stopProducer(this._webcamProducer),this._webcamProducer=null,this._webcamTrack=null)}stopOrResumeVideo(e,t){var r;if(cp.info("stopOrResumeVideo() [enable:%s]",t),this._webcamPaused=!t,this._pauseResumeWebcam(),["chrome","safari"].includes(dp))if(t){if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;navigator.mediaDevices.getUserMedia({video:r}).then(r=>{const n=r.getVideoTracks()[0];e.addTrack(n),this._monitorVideoTrack(n),this._emitToPWA(mu,{streamId:e.id,tracks:[n],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:n})})}}else{clearTimeout(this._stopCameraTimeout);const n="ended"===(null===(r=e.getVideoTracks().find(e=>!e.enabled))||void 0===r?void 0:r.readyState)?0:5e3;this._stopCameraTimeout=setTimeout(()=>{e.getVideoTracks().forEach(r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emitToPWA(gu,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))})},n)}}supportsScreenShareAudio(){return!0}acceptNewStream({streamId:e,clientId:t}){cp.info("acceptNewStream()",{streamId:e,clientId:t});const r=this._getOrCreateClientState(t);e!==t?(r.hasAcceptedScreenStream=!0,r.hasEmittedScreenStream=!1):(r.hasAcceptedWebcamStream=!0,r.hasEmittedWebcamStream=!1),this._syncIncomingStreamsWithPWA(t)}updateStreamResolution(e,t,{width:r,height:n}){var i,s;cp.info("updateStreamResolution()",{streamId:e,width:r,height:n});const o=this._streamIdToVideoConsumerId.get(e),a=this._consumers.get(o);if(!a)return void this._streamIdToVideoResolution.set(e,{width:r,height:n});const c=function(e){let t=0;return e.forEach(e=>{var r,n;e._closed||e._paused||"webcam"!==(null===(r=e._appData)||void 0===r?void 0:r.source)&&"screenvideo"!==(null===(n=e._appData)||void 0===n?void 0:n.source)||t++}),t}(this._consumers),d=function(e){var t,r,n;return/T3/.test((null===(n=null===(r=null===(t=e._rtpParameters)||void 0===t?void 0:t.encodings)||void 0===r?void 0:r[0])||void 0===n?void 0:n.scalabilityMode)||"")?3:2}(a),{spatialLayer:l,temporalLayer:u}=function({width:e,height:t},{numberOfActiveVideos:r,numberOfTemporalLayers:n,uncappedSingleRemoteVideoOn:i}){const s=Math.max(e,t);let o=s>=480?s>=960?2:1:0,a=n-1;return s<100&&(a=Math.max(n-2,0)),r>8&&0===o&&(a=Math.max(n-2,0)),r<4&&s>300&&0===o&&(o=1),i&&1===r&&(o=2,a=n-1),{spatialLayer:o,temporalLayer:a}}({width:r,height:n},{numberOfActiveVideos:c,numberOfTemporalLayers:d,uncappedSingleRemoteVideoOn:null===(i=this._features)||void 0===i?void 0:i.uncappedSingleRemoteVideoOn});a.appData.spatialLayer===l&&a.appData.temporalLayer===u||(a.appData.spatialLayer=l,a.appData.temporalLayer=u,null===(s=this._vegaConnection)||void 0===s||s.message("setConsumersPreferredLayers",{consumerIds:[o],spatialLayer:l,temporalLayer:u}))}close(){this.disconnectAll()}disconnectAll(){var e,t,r,n;this._reconnect=!1,this._reconnectTimeOut&&(clearTimeout(this._reconnectTimeOut),this._reconnectTimeOut=null),this._socketListenerDeregisterFunctions.forEach(e=>{e()}),this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null),this._socketListenerDeregisterFunctions=[],null===(e=this._vegaConnection)||void 0===e||e.removeAllListeners(),null===(t=this._vegaConnection)||void 0===t||t.close(),null===(r=this._sendTransport)||void 0===r||r.close(),null===(n=this._receiveTransport)||void 0===n||n.close(),this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._streamIdToVideoConsumerId.clear(),this._mediasoupDeviceInitializedAsync=Promise.resolve(null)}sendAudioMutedStats(e){nl.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){nl.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){nl.sendEvent(e,t)}rtcStatsConnect(){nl.server.connected||nl.server.connect()}rtcStatsDisconnect(){nl.server.close()}rtcStatsReconnect(){!nl.server.connected&&nl.server.attemptedConnectedAtLeastOnce&&nl.server.connect()}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_onMessage(e){return Td(this,void 0,void 0,function*(){const{method:t,data:r}=e;return Promise.resolve().then(()=>{switch(t){case"consumerReady":return this._onConsumerReady(r);case"consumerClosed":return this._onConsumerClosed(r);case"consumerPaused":return this._onConsumerPaused(r);case"consumerResumed":return this._onConsumerResumed(r);case"dataConsumerReady":return this._onDataConsumerReady(r);case"dataConsumerClosed":return this._onDataConsumerClosed(r);case"dominantSpeaker":return this._onDominantSpeaker(r);case"consumerScore":return this._onConsumerScore(r);case"producerScore":return this._onProducerScore(r);default:return void cp.info(`unknown message method "${t}"`)}}).catch(e=>{cp.error('"message" failed [error:%o]',e)})})}_onConsumerReady(e){return Td(this,void 0,void 0,function*(){cp.info("_onConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consume(e);if(t.pause(),t.appData.localPaused=!0,t.appData.spatialLayer=2,this._consumers.set(t.id,t),this._qualityMonitor.addConsumer(t.appData.sourceClientId,t.id),t.observer.once("close",()=>{this._consumers.delete(t.id),this._qualityMonitor.removeConsumer(t.appData.sourceClientId,t.id),this._consumerClosedCleanup(t)}),this._features.increaseIncomingMediaBufferOn&&t.rtpReceiver)try{t.rtpReceiver.jitterBufferTarget=cu,t.rtpReceiver.playoutDelayHint=.4}catch(e){cp.error("Error during setting jitter buffer target:",e)}const{sourceClientId:r,screenShare:n,streamId:i}=t.appData,s=this._getOrCreateClientState(r);n?(s.hasEmittedScreenStream=!1,s.screenShareStreamId=i):(s.hasEmittedWebcamStream=!1,s.camStreamId=i);let o=n?s.screenStream:s.webcamStream;o&&o.inboundId===i||(o=new MediaStream,o.inboundId=i,n?s.screenStream=o:s.webcamStream=o),"video"===t.kind&&this._streamIdToVideoConsumerId.set(o.id,t.id),o.addTrack(t.track),this._syncIncomingStreamsWithPWA(r);const a=this._streamIdToVideoResolution.get(o.id);a&&(this.updateStreamResolution(o.id,null,a),this._streamIdToVideoResolution.delete(o.id))})}_onConsumerClosed(e){return Td(this,arguments,void 0,function*({consumerId:e,reason:t}){var r;cp.info("_onConsumerClosed()",{consumerId:e,reason:t}),null===(r=this._consumers.get(e))||void 0===r||r.close()})}_onConsumerPaused({consumerId:e}){cp.info("_onConsumerPaused()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!0,t.pause())}_onConsumerResumed({consumerId:e}){cp.info("_onConsumerResumed()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!1,t.appData.localPaused||t.resume())}_onConsumerScore({consumerId:e,kind:t,score:r}){cp.info("_onConsumerScore()",{consumerId:e,kind:t,score:r});const{appData:{sourceClientId:n}}=this._consumers.get(e)||{appData:{}};n&&this._qualityMonitor.addConsumerScore(n,e,t,r)}_onProducerScore({producerId:e,kind:t,score:r}){cp.info("_onProducerScore()",{producerId:e,kind:t,score:r}),[this._micProducer,this._webcamProducer,this._screenVideoProducer,this._screenAudioProducer].forEach(n=>{(null==n?void 0:n.id)===e&&this._qualityMonitor.addProducerScore(this._selfId,e,t,r)})}_onDataConsumerReady(e){return Td(this,void 0,void 0,function*(){cp.info("_onDataConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consumeData(e);this._dataConsumers.set(t.id,t),t.once("close",()=>{this._dataConsumers.delete(t.id)});const{clientId:r}=t.appData;t.on("message",e=>{var r;if(!this._micAnalyserDebugger)return;if("string"!=typeof e)return;const{score:n}=JSON.parse(e);n&&(null===(r=this._micAnalyserDebugger)||void 0===r||r.onConsumerScore(t.appData.clientId,n))}),this._syncIncomingStreamsWithPWA(r)})}_onDataConsumerClosed(e){return Td(this,arguments,void 0,function*({dataConsumerId:e,reason:t}){cp.info("_onDataConsumerClosed()",{dataConsumerId:e,reason:t});const r=this._dataConsumers.get(e);null==r||r.close()})}_onDominantSpeaker({consumerId:e}){const t=this._consumers.get(e);if(!t)return;const{sourceClientId:r}=t.appData;this._emitToPWA(Bu,{clientId:r})}_consumerClosedCleanup(e){const{sourceClientId:t,screenShare:r}=e.appData,n=this._getOrCreateClientState(t),i=r?n.screenStream:n.webcamStream;i&&(i.removeTrack(e.track),0===i.getTracks().length&&(this._streamIdToVideoConsumerId.delete(i.id),this._streamIdToVideoResolution.delete(i.id),r?(n.screenStream=void 0,n.hasEmittedScreenStream=!1,n.screenShareStreamId=void 0):(n.hasEmittedWebcamStream=!1,n.camStreamId=void 0)))}_syncIncomingStreamsWithPWA(e){var t,r;const n=this._getOrCreateClientState(e),{webcamStream:i,screenStream:s,hasEmittedWebcamStream:o,hasEmittedScreenStream:a,hasAcceptedWebcamStream:c,hasAcceptedScreenStream:d,screenShareStreamId:l,camStreamId:u}=n,p=[],h=[];this._consumers.forEach(t=>{if(t.appData.sourceClientId!==e)return;const r=t.appData.screenShare?d:c;!t.appData.localPaused!==r&&(r?(t.appData.remotePaused||t.resume(),t.appData.localPaused=!1,h.push(t.id)):(t.pause(),t.appData.localPaused=!0,p.push(t.id)))}),p.length>0&&(null===(t=this._vegaConnection)||void 0===t||t.message("pauseConsumers",{consumerIds:p})),h.length>0&&(null===(r=this._vegaConnection)||void 0===r||r.message("resumeConsumers",{consumerIds:h})),i&&!o&&c&&(this._emitToPWA(pu,{clientId:e,stream:i,streamId:u,streamType:"webcam"}),n.hasEmittedWebcamStream=!0),s&&!a&&d&&(this._emitToPWA(pu,{clientId:e,stream:s,streamId:l,streamType:"screenshare"}),n.hasEmittedScreenStream=!0)}_getOrCreateClientState(e){let t=this._clientStates.get(e);return t||(t={hasAcceptedWebcamStream:!1,hasAcceptedScreenStream:!1,hasEmittedWebcamStream:!1,hasEmittedScreenStream:!1},this._clientStates.set(e,t)),t}_emitToPWA(e,t){this._emitter.emit(e,t)}_emitToSignal(e,t,r){this._serverSocket.emit(e,t,r)}shouldAcceptStreamsFromBothSides(){return!0}setMicAnalyserDebugger(e){this._micAnalyserDebugger=e}setMicAnalyserParams(e){var t;null===(t=this._micAnalyser)||void 0===t||t.setParams(e)}hasClient(e){return this._clientStates.has(e)}}class fp{constructor({emitter:e,serverSocket:t,webrtcProvider:r,features:n}){this.emitter=e,this.currentManager=null,t.on(El,({room:i,selfId:s,error:o,eventClaim:a})=>{if(o)return;const c={selfId:s,room:i,emitter:e,serverSocket:t,webrtcProvider:r,features:n,eventClaim:a},d=!!i.sfuServer;if(mp=d?"group":"normal",this.currentManager){if(this.currentManager.isInitializedWith({selfId:s,roomName:i.name,isSfu:d}))return void(this.currentManager.setEventClaim&&a&&this.currentManager.setEventClaim(a));this.currentManager.disconnectAll(),e.emit(fu)}let l=null;l=d?new hp(c):new Ku(c),l.rtcStatsConnect(),l.setupSocketListeners(),e.emit(hu,{rtcManager:l}),this.currentManager=l,t.setRtcManager(l)})}stopRtcManager(){this.currentManager&&(this.currentManager.disconnectAll(),this.emitter.emit(fu))}}let mp="";const gp=()=>mp,vp=new class{constructor(){this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD=.04,this.END_PACKET_LOSS_PERIOD_THRESHOLD=.005,this.INTERVAL_DIFF_THRESHOLD_MS=4e3,this.STALE_MEASUREMENT_TIMEOUT_MS=1e4,this.MINIMUM_INTERVAL_MS=3e4,this.ssrcsHistory=new Map,this.staleMeasurementTimeouts=new Map}addPacketLossMeasurement(e,t,r){this.handleStaleMeasurements(e);const n=t>this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD;let i=this.ssrcsHistory.get(e);if(!i)return i={id:e,hasActivePacketLoss:n,currPeriod:n?{begin:r}:void 0,hasPeriodicPacketLoss:!1},void this.ssrcsHistory.set(e,i);i.hasActivePacketLoss?t<this.END_PACKET_LOSS_PERIOD_THRESHOLD&&(this.endPacketLossPeriod(i,r),i.prevIntervalInMs&&i.prevIntervalInMs<this.MINIMUM_INTERVAL_MS&&this.ssrcsHistory.delete(e)):n&&(i.hasActivePacketLoss=!0,i.currPeriod={begin:r})}hasPeriodicPacketLoss(e,t){const r=this.ssrcsHistory.get(e);return r&&this.prevIntervalExceeded(r,t)?(this.ssrcsHistory.delete(r.id),!1):(null==r?void 0:r.hasPeriodicPacketLoss)||!1}prevIntervalExceeded(e,t){if(e.prevPeriod&&e.prevIntervalInMs){return t>this.calculatePeriodCenterTimestamp(e.prevPeriod)+e.prevIntervalInMs+this.INTERVAL_DIFF_THRESHOLD_MS}return!1}handleStaleMeasurements(e){const t=this.staleMeasurementTimeouts.get(e);t&&clearTimeout(t),this.staleMeasurementTimeouts.set(e,setTimeout(()=>{Hl.debug("handleStaleMeasurements() [measurements invalid for ssrc: %s]",e),this.ssrcsHistory.delete(e)},this.STALE_MEASUREMENT_TIMEOUT_MS))}endPacketLossPeriod(e,t){if(Hl.debug("endPacketLossPeriod() [ssrcId: %s, timestamp: %s]",e.id,t),!e.currPeriod)throw new Error("No packet loss period for "+e.id);e.prevPeriod?(e.currPeriod.end=t,this.addNewPacketLossInterval(e)):e.prevPeriod=Object.assign(Object.assign({},e.currPeriod),{end:t}),delete e.currPeriod,e.hasActivePacketLoss=!1}addNewPacketLossInterval(e){if(Hl.debug("addNewPacketLossInterval() [ssrcId: %s, prevIntervalInMs: %s]",e.id,e.prevIntervalInMs),!e.currPeriod||!e.prevPeriod)throw new Error("missing period timestamps");const t=this.calculatePeriodCenterTimestamp(e.prevPeriod),r=this.calculatePeriodCenterTimestamp(e.currPeriod)-t;if(e.prevIntervalInMs){const t=Math.abs(e.prevIntervalInMs-r);e.hasPeriodicPacketLoss=t<this.INTERVAL_DIFF_THRESHOLD_MS,Hl.debug("addNewPacketLossInterval() [hasPeriodicPacketLoss: %s, intervalDiffInMs: %s]",t<this.INTERVAL_DIFF_THRESHOLD_MS,t)}e.prevIntervalInMs=r,e.prevPeriod=e.currPeriod}calculatePeriodCenterTimestamp(e){if(!e.end)throw new Error("Missing period end timestamp");return e.begin+(e.end-e.begin)/2}},bp=[{id:"desync",enabled:({client:e,track:t,stats:r})=>!e.isLocalClient&&"audio"===(null==t?void 0:t.kind)&&"object"==typeof(null==r?void 0:r.tracks)&&Object.keys(r.tracks).length>1,check:({stats:e})=>{if(!e)return!1;const t={audio:0,video:0};Object.values(e.tracks).flatMap(e=>Object.values(e.ssrcs)).forEach(e=>{"audio"===e.kind&&e.jitter&&e.jitter>t.audio&&(t.audio=e.jitter),"video"===e.kind&&e.jitter&&e.jitter>t.video&&(t.video=e.jitter)});return Math.abs(1e3*t.audio-1e3*t.video)>500}},{id:"no-track",enabled:()=>!0,check:({client:e,clients:t,kind:r,track:n})=>{if(!n&&!e.isLocalClient&&"video"===r){const e=t.find(e=>e.isLocalClient);if(e)return!e.isAudioOnlyModeEnabled}return!n}},{id:"ended-track",enabled:({track:e})=>!!e,check:({track:e})=>"ended"===(null==e?void 0:e.readyState)},{id:"no-track-stats",enabled:({hasLiveTrack:e})=>e,check:({client:e,clients:t,kind:r,ssrcs:n})=>{if(0===n.length&&!e.isLocalClient&&"video"===r){const e=t.find(e=>e.isLocalClient);if(e)return!e.isAudioOnlyModeEnabled}return 0===n.length}},{id:"dry-track",enabled:({hasLiveTrack:e,ssrcs:t})=>!(!e||!t),check:({client:e,clients:t,ssrcs:r})=>{let n=!1;if(r.forEach(e=>{n=n||((null==e?void 0:e.bitrate)||0)>0}),!n&&e.isLocalClient){const e=t.filter(e=>!e.isLocalClient);if(e.length>0)return!e.every(e=>e.isAudioOnlyModeEnabled)}return!n}},{id:"denoiser-context-suspended",enabled:({client:e,kind:t})=>{var r,n;return!!e.isLocalClient&&"audio"===t&&!!(null===(n=null===(r=e.audio)||void 0===r?void 0:r.track)||void 0===n?void 0:n._denoiserCtx)},check:({track:e})=>{var t;return!(!e||!("_denoiserCtx"in e))&&"suspended"===(null===(t=e._denoiserCtx)||void 0===t?void 0:t.state)}},{id:"low-layer0-bitrate",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:n})=>e&&"video"===r&&!!t&&!!(null==t?void 0:t.height)&&!n.isPresentation,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&(((null==e?void 0:e.height)||0)<200&&e.bitrate<3e4)},{id:"quality-limitation-bw",enabled:({hasLiveTrack:e,stats:t,client:r,clients:n,kind:i})=>{if("normal"===gp()){if(n.filter(e=>!e.isLocalClient).some(e=>e.isAudioOnlyModeEnabled))return!1}return e&&!!r.isLocalClient&&"video"===i&&!!t},check:({stats:e})=>!!e&&!!Object.values(e.tracks).find(e=>Object.values(e.ssrcs).find(e=>"bandwidth"===e.qualityLimitationReason))},{id:"quality-limitation-cpu",enabled:({hasLiveTrack:e,stats:t,client:r,kind:n})=>e&&!!r.isLocalClient&&"video"===n&&!!t,check:({stats:e})=>!!e&&!!Object.values(e.tracks).find(e=>Object.values(e.ssrcs).find(e=>"cpu"===e.qualityLimitationReason))},{id:"high-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>2},{id:"extreme-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>5},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.1},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.1},{id:"fps-below-20",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:n})=>e&&!!t&&!!t.height&&"video"===r&&!n.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.height)||0)>180&&((null==e?void 0:e.fps)||0)<20},{id:"fps-below-10",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:n})=>e&&!!t&&!!t.height&&"video"===r&&!n.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.fps)||0)<10},{id:"bad-network",enabled:({hasLiveTrack:e,ssrcs:t})=>e&&t.length>0,check:({client:e,clients:t,kind:r,ssrcs:n})=>{if(!n.some(e=>((null==e?void 0:e.bitrate)||0)>0)&&e.isLocalClient&&"video"===r){const e=t.filter(e=>!e.isLocalClient);if(e.length>0)return!e.every(e=>e.isAudioOnlyModeEnabled)}const i=n[0];return!!i&&(0===i.bitrate||(i.lossRatio||0)>.03||(i.fractionLost||0)>.03||!e.isPresentation&&"video"===r&&!!(null==i?void 0:i.bitrate)&&i.bitrate<3e4||"in"===i.direction&&!!i.pliRate&&i.pliRate>2)}},{id:"periodic-packet-loss",enabled:({client:e,hasLiveTrack:t,ssrc0:r})=>!!e.isLocalClient&&t&&!!(null==r?void 0:r.ssrc)&&"out"===(null==r?void 0:r.direction)&&((null==r?void 0:r.bitrate)||0)>0,check:({ssrc0:e})=>!(!e||!e.ssrc)&&(vp.addPacketLossMeasurement(e.ssrc,e.fractionLost||0,Date.now()),vp.hasPeriodicPacketLoss(e.ssrc,Date.now()))},{id:"cpu-pressure-serious",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"serious"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"cpu-pressure-critical",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"critical"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"concealed",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===(null==e?void 0:e.direction)&&((null==e?void 0:e.audioLevel)||0)>=.001&&((null==e?void 0:e.audioConcealment)||0)>=.1},{id:"decelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&((null==e?void 0:e.audioDeceleration)||0)>=.1},{id:"accelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&(e.audioAcceleration||0)>=.1}];let yp=[],_p=null;const wp=[{id:"bitrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&!!t&&!!r,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+((null==t?void 0:t.bitrate)||0),0)},{id:"pixelrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:n})=>e&&"video"===n&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+(t.fps||0)*(t.width||0)*(t.height||0),0)},{id:"height",enabled:({hasLiveTrack:e,track:t,trackStats:r,ssrc0:n,kind:i})=>e&&"video"===i&&!!r&&!!t&&!!n&&!!n.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>Math.max(e,t.fps&&t.height||0),0)},{id:"layer0-height",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:n})=>e&&"video"===n&&!!t&&!!r&&!!r.height&&!!r.fps&&"out"===r.direction,value:({ssrc0:e})=>(null==e?void 0:e.height)||0},{id:"sourceHeight",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:n})=>e&&"video"===n&&!!t&&!!r&&!!r.sourceHeight&&"out"===r.direction,value:({ssrc0:e})=>(null==e?void 0:e.sourceHeight)||NaN},{id:"packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate,value:({ssrc0:e})=>("in"===(null==e?void 0:e.direction)?e.lossRatio:null==e?void 0:e.fractionLost)||0},{id:"jitter",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"in"===t.direction,value:({ssrc0:e})=>(null==e?void 0:e.jitter)||NaN},{id:"mos",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"out"===t.direction,value:({ssrc0:e})=>{const t=((null==e?void 0:e.roundTripTime)||0)+2*((null==e?void 0:e.jitter)||0)+10;let r=t<160?93.2-t/40:93.2-(t-120)/10;r-=2.5*(100*((null==e?void 0:e.fractionLost)||0));return 1+.035*r+7e-6*r*(r-60)*(100-r)}},{id:"rendered",value:()=>1},{id:"active",value:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&t&&r?1:0},{id:"cpu-pressure",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},value:({stats:e})=>{var t;return{nominal:.25,fair:.5,serious:.75,critical:1}[(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)||""]||0}},{id:"turn-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some(e=>e.usingTurn)?1:0},{id:"turn-tls-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some(e=>"tls"===e.turnProtocol)?1:0},{id:"concealment",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>(null==e?void 0:e.audioConcealment)||NaN},{id:"deceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>(null==e?void 0:e.audioDeceleration)||NaN},{id:"acceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>(null==e?void 0:e.audioAcceleration)||NaN},{id:"qpf",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:n})=>e&&"video"===n&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+(t.qpf||0),0)}];let Sp,Cp,kp;const Tp=()=>{Sp={},Cp={},kp={aggregated:{issues:Cp,metrics:Sp}}};function Pp(e,t){const{client:r,kind:n}=t;if(e.global&&"global"!==n)return!1;if(!e.global&&"global"===n)return!1;let i="global"===n;return("audio"===n&&r.audio.enabled||"video"===n&&r.video.enabled)&&(i=!0),i&&(!e.enabled||e.enabled(t))}function Rp(e,t){Object.values(Sp).forEach(e=>{e.curTicks=0,e.curSum=0,e.curMax=0,e.curMin=0,e.curAvg=0}),Object.values(Cp).forEach(e=>{e.curTicks=0,e.curRegistered=0,e.active=!1}),t.find(e=>!e.isLocalClient)&&(t.forEach(r=>{const n=e[r.id];["video","audio","global"].forEach(e=>{if("global"===e&&!r.isLocalClient)return;let i=kp[r.id];i||(i={issues:{},metrics:{}},kp[r.id]=i);const s="audio"===e||"video"===e?r[e].track:void 0,o=!!s&&"ended"!==s.readyState,a=s&&n&&n.tracks[s.id],c=a?Object.values(a.ssrcs).sort((e,t)=>(e.height||Number.MAX_SAFE_INTEGER)-(t.height||Number.MAX_SAFE_INTEGER)):[],d=c[0],l={client:r,clients:t,kind:e,track:s,trackStats:a,stats:n,hasLiveTrack:o,ssrc0:d,ssrcs:c,issues:i.issues,metrics:i.metrics},u="global"===e?"global":`${r.isLocalClient?"loc":"rem"}-${r.isPresentation?"pres":"cam"}-${e}`;wp.forEach(e=>{if(Pp(e,l)){const t=`${u}-${e.id}`;let r=i.metrics[t];const n=e.value(l);r||(r={ticks:0,sum:0,avg:0,min:n,max:n},i.metrics[t]=r),r.ticks++,r.sum+=n,r.min=Math.min(r.min,n),r.max=Math.max(r.max,n),r.avg=r.sum/r.ticks;let s=Sp[t];s||(s={ticks:0,sum:0,min:n,max:n,avg:0,curTicks:0,curMin:0,curMax:0,curAvg:0,curSum:0,totTicks:0,totMin:0,totMax:0,totAvg:0,totSum:0},Sp[t]=s),s.ticks++,s.sum+=n,s.min=Math.min(s.min,n),s.max=Math.max(s.max,n),s.avg=s.sum/s.ticks,0===s.curTicks?(s.curMax=n,s.curMin=n,s.curSum=n):(s.curMax=Math.max(s.curMax,n),s.curMin=Math.min(s.curMin,n),s.curSum+=n),s.curTicks++}}),bp.forEach(e=>{const t=`${u}-${e.id}`,r=Pp(e,l);let n=i.issues[t],s=Cp[t];if(r){n||(n={active:!1,ticks:0,registered:0,initial:0,periods:0,current:0,longest:0},i.issues[t]=n),n.ticks++,s||(s={active:!1,ticks:0,registered:0,initial:0,curTicks:0,curRegistered:0},Cp[t]=s),s.ticks++,s.curTicks++;e.check(l)?(n.registered++,n.current++,n.active||(n.active=!0,n.periods++),n.ticks===n.initial+1&&(n.initial++,s.initial++),n.current>n.longest&&(n.longest=n.current),s.active=!0,s.registered++,s.curRegistered++):(n.active=!1,n.current=0)}else n&&(n.active=!1,n.current=0)})})}),Object.values(Sp).forEach(e=>{e.curTicks&&(e.curAvg=e.curSum/e.curTicks,0===e.totTicks&&(e.totMin=e.curSum,e.totMax=e.curSum),e.totTicks++,e.totSum+=e.curSum,e.totMin=Math.min(e.totMin,e.curSum),e.totMax=Math.max(e.totMax,e.curSum),e.totAvg=e.totSum/e.totTicks)}),Object.values(Cp).forEach(e=>{e.curTicks}),yp.forEach(r=>{var n;return null===(n=r.onUpdatedIssues)||void 0===n?void 0:n.call(r,kp,e,t)}))}function Ep(e){return yp.push(e),_p||(_p=function(e,t=gl,r=ml){return r.subscriptions.push(e),r.currentMonitor||(r.currentMonitor=bl(r,t)),{stop(){var t;r.subscriptions=r.subscriptions.filter(t=>t!==e),r.subscriptions.length||(null===(t=r.currentMonitor)||void 0===t||t.stop(),r.currentMonitor=null)}}}({onUpdatedStats:Rp}).stop),{stop(){yp=yp.filter(t=>t!==e),yp.length||(null==_p||_p(),_p=null,Tp())}}}var Op,xp;Tp();const Ip="safari"===(null===(xp=(null!==(Op=ko.default)&&void 0!==Op?Op:ko).browserDetails)||void 0===xp?void 0:xp.browser);function Dp({disableAEC:e,disableAGC:t,hd:r,lax:n,lowDataMode:i,preferredDeviceIds:s,resolution:o,simulcast:a,widescreen:c}){var d,l;let u=480,p=240;r&&(u=n||Ip?720:{min:360,ideal:720}),a&&(!1===r?(u=360,p=270):p=360);const h={audio:Object.assign({},s.audioId&&{deviceId:s.audioId}),video:Object.assign(Object.assign({},s.videoId?{deviceId:s.videoId}:{facingMode:"user"}),{height:i?p:u,frameRate:i&&!a?15:24})};if(n)return(null===(d=h.audio)||void 0===d?void 0:d.deviceId)||(h.audio=!0),null===(l=h.video)||void 0===l||delete l.facingMode,h;if(o){const[e,t,r]=o.split(/[^\d]/g).map(e=>parseInt(e,10));e&&(h.video.width={exact:e}),t&&(h.video.height={exact:t}),r&&(h.video.frameRate={exact:r}),delete h.video.facingMode}else h.video.aspectRatio=c?16/9:4/3;return t&&(h.audio.autoGainControl=!1),e&&(h.audio.echoCancellation=!1),h}function Mp({devices:e,videoId:t,audioId:r,options:n,type:i="ideal"}){const s=e.filter(e=>"audioinput"===e.kind),o=e.filter(e=>"videoinput"===e.kind),a=!r||!s.some(e=>e.deviceId===r),c=!t||!o.some(e=>e.deviceId===t),d=Dp(Object.assign({preferredDeviceIds:{audioId:a?null:{[i]:r},videoId:c?null:{[i]:t}}},n));return!1!==r&&s.length||delete d.audio,!1!==t&&o.length||delete d.video,d}const jp=new Ld,Ap=/mobi/i.test(navigator.userAgent);class Lp extends Error{constructor(...e){super(...e),this.name="nodevices"}}function Np(e){return e.audio||e.video?navigator.mediaDevices.getUserMedia(e).catch(t=>{const r=`${t}, ${JSON.stringify(e,null,2)}`;throw jp.error(`getUserMedia ${r}`),t}):Promise.reject(new Lp("No provided devices"))}function Fp(e,t,r,n){var i,s,o;let a={deviceId:null};return t?(a.label=t.label,t.getSettings&&(a=Object.assign(Object.assign({},a),t.getSettings())),a.deviceId?a:(t.getCapabilities&&(a.deviceId=t.getCapabilities().deviceId),a.deviceId?a:(t.label&&r&&(a.deviceId=null===(s=r.find(r=>t.label===r.label&&r.kind===e))||void 0===s?void 0:s.deviceId),a.deviceId||(a.deviceId=null===(o=t.getConstraints())||void 0===o?void 0:o.deviceId,a.broken=1),a))):(n&&r&&(a.deviceId=null===(i=r.find(t=>t.deviceId===n&&t.kind===e))||void 0===i?void 0:i.deviceId),a)}function Bp(e,t){t&&"audio"!==t||e.getAudioTracks().forEach(e=>e.stop()),t&&"video"!==t||e.getVideoTracks().forEach(e=>e.stop())}function zp(e){return Td(this,arguments,void 0,function*(e,{replaceStream:t,fallback:r=!0}={}){var n;let i,s,o,a=null;const c=!1===e.audioId?"video":!1===e.videoId&&"audio",d=Ap||"video"!==c,l=Mp(e),u=(e,t)=>e?(e.details=Object.assign({constraints:l,constraint:e.constraint||(null==t?void 0:t.constraint),newConstraints:s,fallback:r,stopTracks:d},e!==i&&{error:String(i)}),e):new Error("Unknown error"),p=t=>Td(this,void 0,void 0,function*(){if(l.audio&&l.video){try{a=yield Np(Mp(Object.assign(Object.assign({},e),{audioId:!1})))}catch(e){"NotFoundError"!==(null==e?void 0:e.name)&&u(e,t)}try{a||(a=yield Np(Mp(Object.assign(Object.assign({},e),{videoId:!1}))))}catch(e){u(e,t)}}});d&&t&&Bp(t,c);try{a=yield Np(l)}catch(s){if(i=s,!r)throw u(s);if("OverconstrainedError"===(null==s?void 0:s.name)){o={deviceId:{videoId:null,audioId:null},width:{lax:!0},height:{lax:!0},"":{audioId:null,videoId:null,lax:!0}}[s.constraint||""]}else if("NotFoundError"===(null==s?void 0:s.name))yield p(s);else if("NotAllowedError"===(null==s?void 0:s.name)||"NotReadableError"===(null==s?void 0:s.name)||"AbortError"===(null==s?void 0:s.name)){if(t&&!d&&(Bp(t,c),o=e),"NotAllowedError"===(null==s?void 0:s.name))yield p(s);else if("NotAllowedError"!==s.name){try{a=yield Np(Mp(Object.assign(Object.assign({},e),{options:Object.assign(Object.assign({},e.options),{lax:!0})})))}catch(e){jp.warn("Tried getting stream again with laxer constraints, but failed: "+(""+e))}const t=(""+s).toLowerCase(),r={audio:"audioId",video:"videoId"}[(null===(n=/(video|audio)/.exec(t))||void 0===n?void 0:n[0])||c||""];if(!a&&r)try{a=yield Np(Mp(Object.assign(Object.assign({},e),{[r]:null})))}catch(e){jp.warn(`Re-tried ${r} with no constraints, but failed: ${""+e}`)}if(!a){const t=r?[r]:["videoId","audioId"];for(const r of t){try{a=yield Np(Mp(Object.assign(Object.assign({},e),{[r]:!1})))}catch(e){jp.warn(`Re-tried without ${r}, but failed: ${""+e}`)}if(a)break}}}}else s||(yield p(s))}if(o){const t=c?{audio:{videoId:!1},video:{audioId:!1}}[c]:{};s=Mp(Object.assign(Object.assign(Object.assign(Object.assign({},e),o),{options:Object.assign(Object.assign({},e.options),{lax:o.lax})}),t));try{a=yield Np(s)}catch(e){throw u(e,i)}}if(!a)throw u(i);let h;return t&&(d||Bp(t,c),h=function(e,t,r){const n=[];return r&&"audio"!==r||(n.push(...e.getAudioTracks()),t.getAudioTracks().forEach(t=>{t.replacement=!0,e.addTrack(t)})),r&&"video"!==r||(n.push(...e.getVideoTracks()),t.getVideoTracks().forEach(t=>{t.replacement=!0,e.addTrack(t)})),n.forEach(t=>{t.replaced=!0,e.removeTrack(t)}),n}(t,a,c),a=t),{error:i&&u(i),stream:a,replacedTracks:h}})}function Up({oldDevices:e,newDevices:t,currentAudioId:r,currentVideoId:n,currentSpeakerId:i}){const s=function(e,t){const[r,n]=[e,t].map(e=>e.filter(e=>e.kind&&e.deviceId).reduce((e,t)=>Object.assign(Object.assign({},e),{[t.kind]:Object.assign(Object.assign({},e[t.kind]),{[t.deviceId]:t})}),{})),i={};return e.forEach(e=>{e.kind&&e.deviceId&&(i[e.kind]||(i[e.kind]={added:{},removed:{},changed:{}}),n[e.kind]&&n[e.kind][e.deviceId]||(i[e.kind].removed[e.deviceId]=e))}),t.forEach(e=>{e.kind&&e.deviceId&&(i[e.kind]||(i[e.kind]={added:{},removed:{},changed:{}}),r[e.kind]&&r[e.kind][e.deviceId]?r[e.kind][e.deviceId].label&&r[e.kind][e.deviceId].label!==e.label&&(i[e.kind].changed[e.deviceId]=e):i[e.kind].added[e.deviceId]=e)}),i}(e,t),o={},a={},c={};return[["audioinput",r],["videoinput",n],["audiooutput",i]].forEach(([e,r])=>{const n=s[e];if(n){if(r){if(n.removed[r]&&(a[e]={deviceId:null},"audiooutput"===e)){const r=t.find(e=>"audiooutput"===e.kind);a[e]={deviceId:null==r?void 0:r.deviceId}}n.changed[r]&&(a[e]={deviceId:r})}if(Object.keys(n.added).length>0){const[t]=Object.keys(n.added).slice(0,1),r=n.added[t];c[e]={deviceId:r.deviceId,label:r.label,kind:r.kind}}if(Object.keys(n.removed).length>0){const[t]=Object.keys(n.removed).slice(0,1);o[e]=n.removed[t]}}}),{addedDevices:c,changedDevices:a,removedDevices:o}}var Vp;function $p(e,t){return function(){return e.apply(t,arguments)}}!function(e){e.rtc_manager_created="rtc_manager_created",e.stream_added="stream_added"}(Vp||(Vp={}));const{toString:Gp}=Object.prototype,{getPrototypeOf:qp}=Object,{iterator:Hp,toStringTag:Wp}=Symbol,Jp=(e=>t=>{const r=Gp.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Kp=e=>(e=e.toLowerCase(),t=>Jp(t)===e),Qp=e=>t=>typeof t===e,{isArray:Yp}=Array,Xp=Qp("undefined");function Zp(e){return null!==e&&!Xp(e)&&null!==e.constructor&&!Xp(e.constructor)&&rh(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const eh=Kp("ArrayBuffer");const th=Qp("string"),rh=Qp("function"),nh=Qp("number"),ih=e=>null!==e&&"object"==typeof e,sh=e=>{if("object"!==Jp(e))return!1;const t=qp(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Wp in e||Hp in e)},oh=Kp("Date"),ah=Kp("File"),ch=Kp("Blob"),dh=Kp("FileList"),lh=Kp("URLSearchParams"),[uh,ph,hh,fh]=["ReadableStream","Request","Response","Headers"].map(Kp);function mh(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),Yp(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(Zp(e))return;const i=r?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(n=0;n<s;n++)o=i[n],t.call(null,e[o],o,e)}}function gh(e,t){if(Zp(e))return null;t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const vh="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,bh=e=>!Xp(e)&&e!==vh;const yh=(_h="undefined"!=typeof Uint8Array&&qp(Uint8Array),e=>_h&&e instanceof _h);var _h;const wh=Kp("HTMLFormElement"),Sh=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Ch=Kp("RegExp"),kh=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};mh(r,(r,i)=>{let s;!1!==(s=t(r,i,e))&&(n[i]=s||r)}),Object.defineProperties(e,n)};const Th=Kp("AsyncFunction"),Ph=(Rh="function"==typeof setImmediate,Eh=rh(vh.postMessage),Rh?setImmediate:Eh?(Oh=`axios@${Math.random()}`,xh=[],vh.addEventListener("message",({source:e,data:t})=>{e===vh&&t===Oh&&xh.length&&xh.shift()()},!1),e=>{xh.push(e),vh.postMessage(Oh,"*")}):e=>setTimeout(e));var Rh,Eh,Oh,xh;const Ih="undefined"!=typeof queueMicrotask?queueMicrotask.bind(vh):"undefined"!=typeof process&&process.nextTick||Ph;var Dh={isArray:Yp,isArrayBuffer:eh,isBuffer:Zp,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||rh(e.append)&&("formdata"===(t=Jp(e))||"object"===t&&rh(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&eh(e.buffer),t},isString:th,isNumber:nh,isBoolean:e=>!0===e||!1===e,isObject:ih,isPlainObject:sh,isEmptyObject:e=>{if(!ih(e)||Zp(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:uh,isRequest:ph,isResponse:hh,isHeaders:fh,isUndefined:Xp,isDate:oh,isFile:ah,isBlob:ch,isRegExp:Ch,isFunction:rh,isStream:e=>ih(e)&&rh(e.pipe),isURLSearchParams:lh,isTypedArray:yh,isFileList:dh,forEach:mh,merge:function e(){const{caseless:t}=bh(this)&&this||{},r={},n=(n,i)=>{const s=t&&gh(r,i)||i;sh(r[s])&&sh(n)?r[s]=e(r[s],n):sh(n)?r[s]=e({},n):Yp(n)?r[s]=n.slice():r[s]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&mh(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(mh(t,(t,n)=>{r&&rh(t)?e[n]=$p(t,r):e[n]=t},{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&qp(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Jp,kindOfTest:Kp,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Yp(e))return e;let t=e.length;if(!nh(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Hp]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:wh,hasOwnProperty:Sh,hasOwnProp:Sh,reduceDescriptors:kh,freezeMethods:e=>{kh(e,(t,r)=>{if(rh(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];rh(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach(e=>{r[e]=!0})};return Yp(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:gh,global:vh,isContextDefined:bh,isSpecCompliantForm:function(e){return!!(e&&rh(e.append)&&"FormData"===e[Wp]&&e[Hp])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(ih(e)){if(t.indexOf(e)>=0)return;if(Zp(e))return e;if(!("toJSON"in e)){t[n]=e;const i=Yp(e)?[]:{};return mh(e,(e,t)=>{const s=r(e,n+1);!Xp(s)&&(i[t]=s)}),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn:Th,isThenable:e=>e&&(ih(e)||rh(e))&&rh(e.then)&&rh(e.catch),setImmediate:Ph,asap:Ih,isIterable:e=>null!=e&&rh(e[Hp])};function Mh(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}Dh.inherits(Mh,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Dh.toJSONObject(this.config),code:this.code,status:this.status}}});const jh=Mh.prototype,Ah={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Ah[e]={value:e}}),Object.defineProperties(Mh,Ah),Object.defineProperty(jh,"isAxiosError",{value:!0}),Mh.from=(e,t,r,n,i,s)=>{const o=Object.create(jh);return Dh.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Mh.call(o,e.message,t,r,n,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function Lh(e){return Dh.isPlainObject(e)||Dh.isArray(e)}function Nh(e){return Dh.endsWith(e,"[]")?e.slice(0,-2):e}function Fh(e,t,r){return e?e.concat(t).map(function(e,t){return e=Nh(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const Bh=Dh.toFlatObject(Dh,{},null,function(e){return/^is[A-Z]/.test(e)});function zh(e,t,r){if(!Dh.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=Dh.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!Dh.isUndefined(t[e])})).metaTokens,i=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&Dh.isSpecCompliantForm(t);if(!Dh.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Dh.isDate(e))return e.toISOString();if(Dh.isBoolean(e))return e.toString();if(!a&&Dh.isBlob(e))throw new Mh("Blob is not supported. Use a Buffer instead.");return Dh.isArrayBuffer(e)||Dh.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(Dh.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(Dh.isArray(e)&&function(e){return Dh.isArray(e)&&!e.some(Lh)}(e)||(Dh.isFileList(e)||Dh.endsWith(r,"[]"))&&(a=Dh.toArray(e)))return r=Nh(r),a.forEach(function(e,n){!Dh.isUndefined(e)&&null!==e&&t.append(!0===o?Fh([r],n,s):null===o?r:r+"[]",c(e))}),!1;return!!Lh(e)||(t.append(Fh(i,r,s),c(e)),!1)}const l=[],u=Object.assign(Bh,{defaultVisitor:d,convertValue:c,isVisitable:Lh});if(!Dh.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!Dh.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),Dh.forEach(r,function(r,s){!0===(!(Dh.isUndefined(r)||null===r)&&i.call(t,r,Dh.isString(s)?s.trim():s,n,u))&&e(r,n?n.concat(s):[s])}),l.pop()}}(e),t}function Uh(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Vh(e,t){this._pairs=[],e&&zh(e,this,t)}const $h=Vh.prototype;function Gh(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function qh(e,t,r){if(!t)return e;const n=r&&r.encode||Gh;Dh.isFunction(r)&&(r={serialize:r});const i=r&&r.serialize;let s;if(s=i?i(t,r):Dh.isURLSearchParams(t)?t.toString():new Vh(t,r).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}$h.append=function(e,t){this._pairs.push([e,t])},$h.toString=function(e){const t=e?function(t){return e.call(this,t,Uh)}:Uh;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Hh{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Dh.forEach(this.handlers,function(t){null!==t&&e(t)})}}var Wh={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Jh={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Vh,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const Kh="undefined"!=typeof window&&"undefined"!=typeof document,Qh="object"==typeof navigator&&navigator||void 0,Yh=Kh&&(!Qh||["ReactNative","NativeScript","NS"].indexOf(Qh.product)<0),Xh="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Zh=Kh&&window.location.href||"http://localhost";var ef={...Object.freeze({__proto__:null,hasBrowserEnv:Kh,hasStandardBrowserEnv:Yh,hasStandardBrowserWebWorkerEnv:Xh,navigator:Qh,origin:Zh}),...Jh};function tf(e){function t(e,r,n,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&Dh.isArray(n)?n.length:s,a)return Dh.hasOwnProp(n,s)?n[s]=[n[s],r]:n[s]=r,!o;n[s]&&Dh.isObject(n[s])||(n[s]=[]);return t(e,r,n[s],i)&&Dh.isArray(n[s])&&(n[s]=function(e){const t={},r=Object.keys(e);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],t[s]=e[s];return t}(n[s])),!o}if(Dh.isFormData(e)&&Dh.isFunction(e.entries)){const r={};return Dh.forEachEntry(e,(e,n)=>{t(function(e){return Dh.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),n,r,0)}),r}return null}const rf={transitional:Wh,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=Dh.isObject(e);i&&Dh.isHTMLForm(e)&&(e=new FormData(e));if(Dh.isFormData(e))return n?JSON.stringify(tf(e)):e;if(Dh.isArrayBuffer(e)||Dh.isBuffer(e)||Dh.isStream(e)||Dh.isFile(e)||Dh.isBlob(e)||Dh.isReadableStream(e))return e;if(Dh.isArrayBufferView(e))return e.buffer;if(Dh.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return zh(e,new ef.classes.URLSearchParams,{visitor:function(e,t,r,n){return ef.isNode&&Dh.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=Dh.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return zh(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),function(e,t,r){if(Dh.isString(e))try{return(t||JSON.parse)(e),Dh.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||rf.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(Dh.isResponse(e)||Dh.isReadableStream(e))return e;if(e&&Dh.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw Mh.from(e,Mh.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ef.classes.FormData,Blob:ef.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Dh.forEach(["delete","get","head","post","put","patch"],e=>{rf.headers[e]={}});const nf=Dh.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const sf=Symbol("internals");function of(e){return e&&String(e).trim().toLowerCase()}function af(e){return!1===e||null==e?e:Dh.isArray(e)?e.map(af):String(e)}function cf(e,t,r,n,i){return Dh.isFunction(n)?n.call(this,t,r):(i&&(t=r),Dh.isString(t)?Dh.isString(n)?-1!==t.indexOf(n):Dh.isRegExp(n)?n.test(t):void 0:void 0)}let df=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=of(t);if(!i)throw new Error("header name must be a non-empty string");const s=Dh.findKey(n,i);(!s||void 0===n[s]||!0===r||void 0===r&&!1!==n[s])&&(n[s||t]=af(e))}const s=(e,t)=>Dh.forEach(e,(e,r)=>i(e,r,t));if(Dh.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(Dh.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let r,n,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&nf[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t})(e),t);else if(Dh.isObject(e)&&Dh.isIterable(e)){let r,n,i={};for(const t of e){if(!Dh.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?Dh.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}s(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=of(e)){const r=Dh.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(Dh.isFunction(t))return t.call(this,e,r);if(Dh.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=of(e)){const r=Dh.findKey(this,e);return!(!r||void 0===this[r]||t&&!cf(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=of(e)){const i=Dh.findKey(r,e);!i||t&&!cf(0,r[i],i,t)||(delete r[i],n=!0)}}return Dh.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!cf(0,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return Dh.forEach(this,(n,i)=>{const s=Dh.findKey(r,i);if(s)return t[s]=af(n),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(i):String(i).trim();o!==i&&delete t[i],t[o]=af(n),r[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Dh.forEach(this,(r,n)=>{null!=r&&!1!==r&&(t[n]=e&&Dh.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[sf]=this[sf]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=of(e);t[n]||(!function(e,t){const r=Dh.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})})}(r,e),t[n]=!0)}return Dh.isArray(e)?e.forEach(n):n(e),this}};function lf(e,t){const r=this||rf,n=t||r,i=df.from(n.headers);let s=n.data;return Dh.forEach(e,function(e){s=e.call(r,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function uf(e){return!(!e||!e.__CANCEL__)}function pf(e,t,r){Mh.call(this,null==e?"canceled":e,Mh.ERR_CANCELED,t,r),this.name="CanceledError"}function hf(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new Mh("Request failed with status code "+r.status,[Mh.ERR_BAD_REQUEST,Mh.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}df.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Dh.reduceDescriptors(df.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),Dh.freezeMethods(df),Dh.inherits(pf,Mh,{__CANCEL__:!0});const ff=(e,t,r=3)=>{let n=0;const i=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];i||(i=c),r[s]=a,n[s]=c;let l=o,u=0;for(;l!==s;)u+=r[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let r,n,i=0,s=1e3/t;const o=(t,s=Date.now())=>{i=s,r=null,n&&(clearTimeout(n),n=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=s?o(e,t):(r=e,n||(n=setTimeout(()=>{n=null,o(r)},s-a)))},()=>r&&o(r)]}(r=>{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-n,c=i(a);n=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})},r)},mf=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},gf=e=>(...t)=>Dh.asap(()=>e(...t));var vf=ef.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,ef.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(ef.origin),ef.navigator&&/(msie|trident)/i.test(ef.navigator.userAgent)):()=>!0,bf=ef.hasStandardBrowserEnv?{write(e,t,r,n,i,s){const o=[e+"="+encodeURIComponent(t)];Dh.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Dh.isString(n)&&o.push("path="+n),Dh.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function yf(e,t,r){let n=!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const _f=e=>e instanceof df?{...e}:e;function wf(e,t){t=t||{};const r={};function n(e,t,r,n){return Dh.isPlainObject(e)&&Dh.isPlainObject(t)?Dh.merge.call({caseless:n},e,t):Dh.isPlainObject(t)?Dh.merge({},t):Dh.isArray(t)?t.slice():t}function i(e,t,r,i){return Dh.isUndefined(t)?Dh.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function s(e,t){if(!Dh.isUndefined(t))return n(void 0,t)}function o(e,t){return Dh.isUndefined(t)?Dh.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,s){return s in t?n(r,i):s in e?n(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>i(_f(e),_f(t),0,!0)};return Dh.forEach(Object.keys({...e,...t}),function(n){const s=c[n]||i,o=s(e[n],t[n],n);Dh.isUndefined(o)&&s!==a||(r[n]=o)}),r}var Sf=e=>{const t=wf({},e);let r,{data:n,withXSRFToken:i,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=df.from(a),t.url=qh(yf(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Dh.isFormData(n))if(ef.hasStandardBrowserEnv||ef.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(ef.hasStandardBrowserEnv&&(i&&Dh.isFunction(i)&&(i=i(t)),i||!1!==i&&vf(t.url))){const e=s&&o&&bf.read(o);e&&a.set(s,e)}return t};var Cf="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const n=Sf(e);let i=n.data;const s=df.from(n.headers).normalize();let o,a,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=n;function f(){d&&d(),l&&l(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let m=new XMLHttpRequest;function g(){if(!m)return;const n=df.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());hf(function(e){t(e),f()},function(e){r(e),f()},{data:u&&"text"!==u&&"json"!==u?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new Mh("Request aborted",Mh.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new Mh("Network Error",Mh.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||Wh;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new Mh(t,i.clarifyTimeoutError?Mh.ETIMEDOUT:Mh.ECONNABORTED,e,m)),m=null},void 0===i&&s.setContentType(null),"setRequestHeader"in m&&Dh.forEach(s.toJSON(),function(e,t){m.setRequestHeader(t,e)}),Dh.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),u&&"json"!==u&&(m.responseType=n.responseType),h&&([c,l]=ff(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,d]=ff(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(n.cancelToken||n.signal)&&(o=t=>{m&&(r(!t||t.type?new pf(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);v&&-1===ef.protocols.indexOf(v)?r(new Mh("Unsupported protocol "+v+":",Mh.ERR_BAD_REQUEST,e)):m.send(i||null)})};const kf=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof Mh?t:new pf(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,i(new Mh(`timeout ${t} of ms exceeded`,Mh.ETIMEDOUT))},t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:a}=n;return a.unsubscribe=()=>Dh.asap(o),a}},Tf=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,i=0;for(;i<r;)n=i+t,yield e.slice(i,n),i=n},Pf=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},Rf=(e,t,r,n)=>{const i=async function*(e,t){for await(const r of Pf(e))yield*Tf(r,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let s=n.byteLength;if(r){let e=o+=s;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},Ef="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Of=Ef&&"function"==typeof ReadableStream,xf=Ef&&("function"==typeof TextEncoder?(If=new TextEncoder,e=>If.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var If;const Df=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},Mf=Of&&Df(()=>{let e=!1;const t=new Request(ef.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),jf=Of&&Df(()=>Dh.isReadableStream(new Response("").body)),Af={stream:jf&&(e=>e.body)};var Lf;Ef&&(Lf=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Af[e]&&(Af[e]=Dh.isFunction(Lf[e])?t=>t[e]():(t,r)=>{throw new Mh(`Response type '${e}' is not supported`,Mh.ERR_NOT_SUPPORT,r)})}));const Nf=async(e,t)=>{const r=Dh.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(Dh.isBlob(e))return e.size;if(Dh.isSpecCompliantForm(e)){const t=new Request(ef.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Dh.isArrayBufferView(e)||Dh.isArrayBuffer(e)?e.byteLength:(Dh.isURLSearchParams(e)&&(e+=""),Dh.isString(e)?(await xf(e)).byteLength:void 0)})(t):r};var Ff=Ef&&(async e=>{let{url:t,method:r,data:n,signal:i,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=Sf(e);d=d?(d+"").toLowerCase():"text";let h,f=kf([i,s&&s.toAbortSignal()],o);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&Mf&&"get"!==r&&"head"!==r&&0!==(g=await Nf(l,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(Dh.isFormData(n)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=mf(g,ff(gf(c)));n=Rf(r.body,65536,e,t)}}Dh.isString(u)||(u=u?"include":"omit");const i="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:n,duplex:"half",credentials:i?u:void 0});let s=await fetch(h,p);const o=jf&&("stream"===d||"response"===d);if(jf&&(a||o&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=Dh.toFiniteNumber(s.headers.get("content-length")),[r,n]=a&&mf(t,ff(gf(a),!0))||[];s=new Response(Rf(s.body,65536,r,()=>{n&&n(),m&&m()}),e)}d=d||"text";let v=await Af[Dh.findKey(Af,d)||"text"](s,e);return!o&&m&&m(),await new Promise((t,r)=>{hf(t,r,{data:v,headers:df.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})})}catch(t){if(m&&m(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new Mh("Network Error",Mh.ERR_NETWORK,e,h),{cause:t.cause||t});throw Mh.from(t,t&&t.code,e,h)}});const Bf={http:null,xhr:Cf,fetch:Ff};Dh.forEach(Bf,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const zf=e=>`- ${e}`,Uf=e=>Dh.isFunction(e)||null===e||!1===e;var Vf=e=>{e=Dh.isArray(e)?e:[e];const{length:t}=e;let r,n;const i={};for(let s=0;s<t;s++){let t;if(r=e[s],n=r,!Uf(r)&&(n=Bf[(t=String(r)).toLowerCase()],void 0===n))throw new Mh(`Unknown adapter '${t}'`);if(n)break;i[t||"#"+s]=n}if(!n){const e=Object.entries(i).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new Mh("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(zf).join("\n"):" "+zf(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function $f(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new pf(null,e)}function Gf(e){$f(e),e.headers=df.from(e.headers),e.data=lf.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Vf(e.adapter||rf.adapter)(e).then(function(t){return $f(e),t.data=lf.call(e,e.transformResponse,t),t.headers=df.from(t.headers),t},function(t){return uf(t)||($f(e),t&&t.response&&(t.response.data=lf.call(e,e.transformResponse,t.response),t.response.headers=df.from(t.response.headers))),Promise.reject(t)})}const qf="1.11.0",Hf={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Hf[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Wf={};Hf.transitional=function(e,t,r){function n(e,t){return"[Axios v"+qf+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,s)=>{if(!1===e)throw new Mh(n(i," has been removed"+(t?" in "+t:"")),Mh.ERR_DEPRECATED);return t&&!Wf[i]&&(Wf[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,s)}},Hf.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var Jf={assertOptions:function(e,t,r){if("object"!=typeof e)throw new Mh("options must be an object",Mh.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const s=n[i],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new Mh("option "+s+" must be "+r,Mh.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new Mh("Unknown option "+s,Mh.ERR_BAD_OPTION)}},validators:Hf};const Kf=Jf.validators;let Qf=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Hh,response:new Hh}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=wf(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&Jf.assertOptions(r,{silentJSONParsing:Kf.transitional(Kf.boolean),forcedJSONParsing:Kf.transitional(Kf.boolean),clarifyTimeoutError:Kf.transitional(Kf.boolean)},!1),null!=n&&(Dh.isFunction(n)?t.paramsSerializer={serialize:n}:Jf.assertOptions(n,{encode:Kf.function,serialize:Kf.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Jf.assertOptions(t,{baseUrl:Kf.spelling("baseURL"),withXsrfToken:Kf.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&Dh.merge(i.common,i[t.method]);i&&Dh.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=df.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))});const c=[];let d;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let l,u=0;if(!a){const e=[Gf.bind(this),void 0];for(e.unshift(...o),e.push(...c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=Gf.call(this,p)}catch(e){return Promise.reject(e)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return qh(yf((e=wf(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};Dh.forEach(["delete","get","head","options"],function(e){Qf.prototype[e]=function(t,r){return this.request(wf(r||{},{method:e,url:t,data:(r||{}).data}))}}),Dh.forEach(["post","put","patch"],function(e){function t(t){return function(r,n,i){return this.request(wf(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Qf.prototype[e]=t(),Qf.prototype[e+"Form"]=t(!0)});const Yf={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Yf).forEach(([e,t])=>{Yf[t]=e});const Xf=function e(t){const r=new Qf(t),n=$p(Qf.prototype.request,r);return Dh.extend(n,Qf.prototype,r,{allOwnKeys:!0}),Dh.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(wf(t,r))},n}(rf);Xf.Axios=Qf,Xf.CanceledError=pf,Xf.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const n=new Promise(e=>{r.subscribe(e),t=e}).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e(function(e,n,i){r.reason||(r.reason=new pf(e,n,i),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},Xf.isCancel=uf,Xf.VERSION=qf,Xf.toFormData=zh,Xf.AxiosError=Mh,Xf.Cancel=Xf.CanceledError,Xf.all=function(e){return Promise.all(e)},Xf.spread=function(e){return function(t){return e.apply(null,t)}},Xf.isAxiosError=function(e){return Dh.isObject(e)&&!0===e.isAxiosError},Xf.mergeConfig=wf,Xf.AxiosHeaders=df,Xf.formToJSON=e=>tf(Dh.isHTMLForm(e)?new FormData(e):e),Xf.getAdapter=Vf,Xf.HttpStatusCode=Yf,Xf.default=Xf;const{Axios:Zf,AxiosError:em,CanceledError:tm,isCancel:rm,CancelToken:nm,VERSION:im,all:sm,Cancel:om,isAxiosError:am,spread:cm,toFormData:dm,AxiosHeaders:lm,HttpStatusCode:um,formToJSON:pm,getAdapter:hm,mergeConfig:fm}=Xf;var mm=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),gm=()=>Math.random().toString(36).substring(7).split("").join("."),vm={INIT:`@@redux/INIT${gm()}`,REPLACE:`@@redux/REPLACE${gm()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${gm()}`};function bm(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function ym(e){if(void 0===e)return"undefined";if(null===e)return"null";const t=typeof e;switch(t){case"boolean":case"string":case"number":case"symbol":case"function":return t}if(Array.isArray(e))return"array";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";const r=function(e){return"function"==typeof e.constructor?e.constructor.name:null}(e);switch(r){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return r}return Object.prototype.toString.call(e).slice(8,-1).toLowerCase().replace(/\s/g,"")}function _m(e){let t=typeof e;return t=ym(e),t}function wm(e,t,r){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${_m(e)}'`);if("function"==typeof t&&"function"==typeof r||"function"==typeof r&&"function"==typeof arguments[3])throw new Error("It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if("function"==typeof t&&void 0===r&&(r=t,t=void 0),void 0!==r){if("function"!=typeof r)throw new Error(`Expected the enhancer to be a function. Instead, received: '${_m(r)}'`);return r(wm)(e,t)}let n=e,i=t,s=new Map,o=s,a=0,c=!1;function d(){o===s&&(o=new Map,s.forEach((e,t)=>{o.set(t,e)}))}function l(){if(c)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return i}function u(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${_m(e)}'`);if(c)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");let t=!0;d();const r=a++;return o.set(r,e),function(){if(t){if(c)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");t=!1,d(),o.delete(r),s=null}}}function p(e){if(!bm(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${_m(e)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if("string"!=typeof e.type)throw new Error(`Action "type" property must be a string. Instead, the actual type was: '${_m(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,i=n(i,e)}finally{c=!1}return(s=o).forEach(e=>{e()}),e}p({type:vm.INIT});return{dispatch:p,subscribe:u,getState:l,replaceReducer:function(e){if("function"!=typeof e)throw new Error(`Expected the nextReducer to be a function. Instead, received: '${_m(e)}`);n=e,p({type:vm.REPLACE})},[mm]:function(){const e=u;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(`Expected the observer to be an object. Instead, received: '${_m(t)}'`);function r(){const e=t;e.next&&e.next(l())}r();return{unsubscribe:e(r)}},[mm](){return this}}}}}function Sm(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function Cm(e){const t=Object.keys(e),r={};for(let n=0;n<t.length;n++){const i=t[n];void 0===e[i]&&Sm(`No reducer provided for key "${i}"`),"function"==typeof e[i]&&(r[i]=e[i])}const n=Object.keys(r);let i,s;i={};try{!function(e){Object.keys(e).forEach(t=>{const r=e[t];if(void 0===r(void 0,{type:vm.INIT}))throw new Error(`The slice reducer for key "${t}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);if(void 0===r(void 0,{type:vm.PROBE_UNKNOWN_ACTION()}))throw new Error(`The slice reducer for key "${t}" returned undefined when probed with a random type. Don't try to handle '${vm.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`)})}(r)}catch(e){s=e}return function(e={},t){if(s)throw s;{const n=function(e,t,r,n){const i=Object.keys(t),s=r&&r.type===vm.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===i.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!bm(e))return`The ${s} has unexpected type of "${_m(e)}". Expected argument to be an object with the following keys: "${i.join('", "')}"`;const o=Object.keys(e).filter(e=>!t.hasOwnProperty(e)&&!n[e]);return o.forEach(e=>{n[e]=!0}),r&&r.type===vm.REPLACE?void 0:o.length>0?`Unexpected ${o.length>1?"keys":"key"} "${o.join('", "')}" found in ${s}. Expected to find one of the known reducer keys instead: "${i.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,r,t,i);n&&Sm(n)}let o=!1;const a={};for(let i=0;i<n.length;i++){const s=n[i],c=r[s],d=e[s],l=c(d,t);if(void 0===l){const e=t&&t.type;throw new Error(`When called with an action of type ${e?`"${String(e)}"`:"(unknown type)"}, the slice reducer for key "${s}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`)}a[s]=l,o=o||l!==d}return o=o||n.length!==Object.keys(e).length,o?a:e}}function km(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce((e,t)=>(...r)=>e(t(...r)))}function Tm(e){return bm(e)&&"type"in e&&"string"==typeof e.type}var Pm=Symbol.for("immer-nothing"),Rm=Symbol.for("immer-draftable"),Em=Symbol.for("immer-state"),Om=[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}];function xm(e,...t){{const r=Om[e],n="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${n}`)}}var Im=Object.getPrototypeOf;function Dm(e){return!!e&&!!e[Em]}function Mm(e){return!!e&&(Am(e)||Array.isArray(e)||!!e[Rm]||!!e.constructor?.[Rm]||zm(e)||Um(e))}var jm=Object.prototype.constructor.toString();function Am(e){if(!e||"object"!=typeof e)return!1;const t=Im(e);if(null===t)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===jm}function Lm(e,t){0===Nm(e)?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Nm(e){const t=e[Em];return t?t.type_:Array.isArray(e)?1:zm(e)?2:Um(e)?3:0}function Fm(e,t){return 2===Nm(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Bm(e,t,r){const n=Nm(e);2===n?e.set(t,r):3===n?e.add(r):e[t]=r}function zm(e){return e instanceof Map}function Um(e){return e instanceof Set}function Vm(e){return e.copy_||e.base_}function $m(e,t){if(zm(e))return new Map(e);if(Um(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=Am(e);if(!0===t||"class_only"===t&&!r){const t=Object.getOwnPropertyDescriptors(e);delete t[Em];let r=Reflect.ownKeys(t);for(let n=0;n<r.length;n++){const i=r[n],s=t[i];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(t[i]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[i]})}return Object.create(Im(e),t)}{const t=Im(e);if(null!==t&&r)return{...e};const n=Object.create(t);return Object.assign(n,e)}}function Gm(e,t=!1){return Hm(e)||Dm(e)||!Mm(e)||(Nm(e)>1&&(e.set=e.add=e.clear=e.delete=qm),Object.freeze(e),t&&Object.entries(e).forEach(([e,t])=>Gm(t,!0))),e}function qm(){xm(2)}function Hm(e){return Object.isFrozen(e)}var Wm,Jm={};function Km(e){const t=Jm[e];return t||xm(0,e),t}function Qm(){return Wm}function Ym(e,t){t&&(Km("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Xm(e){Zm(e),e.drafts_.forEach(tg),e.drafts_=null}function Zm(e){e===Wm&&(Wm=e.parent_)}function eg(e){return Wm={drafts_:[],parent_:Wm,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function tg(e){const t=e[Em];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function rg(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[Em].modified_&&(Xm(t),xm(4)),Mm(e)&&(e=ng(t,e),t.parent_||sg(t,e)),t.patches_&&Km("Patches").generateReplacementPatches_(r[Em].base_,e,t.patches_,t.inversePatches_)):e=ng(t,r,[]),Xm(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Pm?e:void 0}function ng(e,t,r){if(Hm(t))return t;const n=t[Em];if(!n)return Lm(t,(i,s)=>ig(e,n,t,i,s,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return sg(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const t=n.copy_;let i=t,s=!1;3===n.type_&&(i=new Set(t),t.clear(),s=!0),Lm(i,(i,o)=>ig(e,n,t,i,o,r,s)),sg(e,t,!1),r&&e.patches_&&Km("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function ig(e,t,r,n,i,s,o){if(i===r&&xm(5),Dm(i)){const o=ng(e,i,s&&t&&3!==t.type_&&!Fm(t.assigned_,n)?s.concat(n):void 0);if(Bm(r,n,o),!Dm(o))return;e.canAutoFreeze_=!1}else o&&r.add(i);if(Mm(i)&&!Hm(i)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;ng(e,i),t&&t.scope_.parent_||"symbol"==typeof n||!Object.prototype.propertyIsEnumerable.call(r,n)||sg(e,i)}}function sg(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Gm(t,r)}var og={get(e,t){if(t===Em)return e;const r=Vm(e);if(!Fm(r,t))return function(e,t,r){const n=dg(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}(e,r,t);const n=r[t];return e.finalized_||!Mm(n)?n:n===cg(e.base_,t)?(ug(e),e.copy_[t]=pg(n,e)):n},has:(e,t)=>t in Vm(e),ownKeys:e=>Reflect.ownKeys(Vm(e)),set(e,t,r){const n=dg(Vm(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const n=cg(Vm(e),t),o=n?.[Em];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((i=r)===(s=n)?0!==i||1/i==1/s:i!=i&&s!=s)&&(void 0!==r||Fm(e.base_,t)))return!0;ug(e),lg(e)}var i,s;return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==cg(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,ug(e),lg(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=Vm(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:r[t]}:n},defineProperty(){xm(11)},getPrototypeOf:e=>Im(e.base_),setPrototypeOf(){xm(12)}},ag={};function cg(e,t){const r=e[Em];return(r?Vm(r):e)[t]}function dg(e,t){if(!(t in e))return;let r=Im(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=Im(r)}}function lg(e){e.modified_||(e.modified_=!0,e.parent_&&lg(e.parent_))}function ug(e){e.copy_||(e.copy_=$m(e.base_,e.scope_.immer_.useStrictShallowCopy_))}Lm(og,(e,t)=>{ag[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),ag.deleteProperty=function(e,t){return isNaN(parseInt(t))&&xm(13),ag.set.call(this,e,t,void 0)},ag.set=function(e,t,r){return"length"!==t&&isNaN(parseInt(t))&&xm(14),og.set.call(this,e[0],t,r,e[0])};function pg(e,t){const r=zm(e)?Km("MapSet").proxyMap_(e,t):Um(e)?Km("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Qm(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=n,s=og;r&&(i=[n],s=ag);const{revoke:o,proxy:a}=Proxy.revocable(i,s);return n.draft_=a,n.revoke_=o,a}(e,t);return(t?t.scope_:Qm()).drafts_.push(r),r}function hg(e){if(!Mm(e)||Hm(e))return e;const t=e[Em];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=$m(e,t.scope_.immer_.useStrictShallowCopy_)}else r=$m(e,!0);return Lm(r,(e,t)=>{Bm(r,e,hg(t))}),t&&(t.finalized_=!1),r}var fg=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,r)=>{if("function"==typeof e&&"function"!=typeof t){const r=t;t=e;const n=this;return function(e=r,...i){return n.produce(e,e=>t.call(this,e,...i))}}let n;if("function"!=typeof t&&xm(6),void 0!==r&&"function"!=typeof r&&xm(7),Mm(e)){const i=eg(this),s=pg(e,void 0);let o=!0;try{n=t(s),o=!1}finally{o?Xm(i):Zm(i)}return Ym(i,r),rg(n,i)}if(!e||"object"!=typeof e){if(n=t(e),void 0===n&&(n=e),n===Pm&&(n=void 0),this.autoFreeze_&&Gm(n,!0),r){const t=[],i=[];Km("Patches").generateReplacementPatches_(e,n,t,i),r(t,i)}return n}xm(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,t=>e(t,...r));let r,n;const i=this.produce(e,t,(e,t)=>{r=e,n=t});return[i,r,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Mm(e)||xm(8),Dm(e)&&(e=function(e){Dm(e)||xm(10,e);return hg(e)}(e));const t=eg(this),r=pg(e,void 0);return r[Em].isManual_=!0,Zm(t),r}finishDraft(e,t){const r=e&&e[Em];r&&r.isManual_||xm(9);const{scope_:n}=r;return Ym(n,t),rg(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));const n=Km("Patches").applyPatches_;return Dm(e)?n(e,t):this.produce(e,e=>n(e,t))}},mg=fg.produce;fg.produceWithPatches.bind(fg),fg.setAutoFreeze.bind(fg),fg.setUseStrictShallowCopy.bind(fg),fg.applyPatches.bind(fg),fg.createDraft.bind(fg),fg.finishDraft.bind(fg);var gg=(e,t,r)=>{if(1===t.length&&t[0]===r){let t=!1;try{const r={};e(r)===r&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},vg=(e,t,r)=>{const{memoize:n,memoizeOptions:i}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,a=n(()=>({}),...i);if(!(a.apply(null,s)===a.apply(null,o))){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:r,firstInputs:s,secondInputs:o,stack:e})}},bg={inputStabilityCheck:"once",identityFunctionCheck:"once"};var yg=e=>Array.isArray(e)?e:[e];function _g(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const r=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${r}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function wg(e,t){const r=[],{length:n}=e;for(let i=0;i<n;i++)r.push(e[i].apply(null,t));return r}var Sg="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function Cg(){return{s:0,v:void 0,o:null,p:null}}function kg(e,t={}){let r={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:n}=t;let i,s=0;function o(){let t=r;const{length:o}=arguments;for(let e=0,r=o;e<r;e++){const r=arguments[e];if("function"==typeof r||"object"==typeof r&&null!==r){let e=t.o;null===e&&(t.o=e=new WeakMap);const n=e.get(r);void 0===n?(t=Cg(),e.set(r,t)):t=n}else{let e=t.p;null===e&&(t.p=e=new Map);const n=e.get(r);void 0===n?(t=Cg(),e.set(r,t)):t=n}}const a=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),s++,n){const e=i?.deref?.()??i;null!=e&&n(e,c)&&(c=e,0!==s&&s--);i="object"==typeof c&&null!==c||"function"==typeof c?new Sg(c):c}return a.s=1,a.v=c,c}return o.clearCache=()=>{r={s:0,v:void 0,o:null,p:null},o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function Tg(e,...t){const r="function"==typeof e?{memoize:e,memoizeOptions:t}:e,n=(...e)=>{let t,n=0,i=0,s={},o=e.pop();"object"==typeof o&&(s=o,o=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);const a={...r,...s},{memoize:c,memoizeOptions:d=[],argsMemoize:l=kg,argsMemoizeOptions:u=[],devModeChecks:p={}}=a,h=yg(d),f=yg(u),m=_g(e),g=c(function(){return n++,o.apply(null,arguments)},...h);let v=!0;const b=l(function(){i++;const e=wg(m,arguments);t=g.apply(null,e);{const{identityFunctionCheck:r,inputStabilityCheck:n}=((e,t)=>{const{identityFunctionCheck:r,inputStabilityCheck:n}={...bg,...t};return{identityFunctionCheck:{shouldRun:"always"===r||"once"===r&&e,run:gg},inputStabilityCheck:{shouldRun:"always"===n||"once"===n&&e,run:vg}}})(v,p);if(r.shouldRun&&r.run(o,e,t),n.shouldRun){const t=wg(m,arguments);n.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:h},arguments)}v&&(v=!1)}return t},...f);return Object.assign(b,{resultFunc:o,memoizedResultFunc:g,dependencies:m,dependencyRecomputations:()=>i,resetDependencyRecomputations:()=>{i=0},lastResult:()=>t,recomputations:()=>n,resetRecomputations:()=>{n=0},memoize:c,argsMemoize:l})};return Object.assign(n,{withTypes:()=>n}),n}var Pg=Tg(kg),Rg=Object.assign((e,t=Pg)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const r=Object.keys(e),n=t(r.map(t=>e[t]),(...e)=>e.reduce((e,t,n)=>(e[r[n]]=t,e),{}));return n},{withTypes:()=>Rg});function Eg(e){return({dispatch:t,getState:r})=>n=>i=>"function"==typeof i?i(t,r,e):n(i)}var Og=Eg(),xg=Eg,Ig="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?km:km.apply(null,arguments)},Dg=e=>e&&"function"==typeof e.match;function Mg(e,t){function r(...r){if(t){let n=t(...r);if(!n)throw new Error("prepareAction did not return an object");return{type:e,payload:n.payload,..."meta"in n&&{meta:n.meta},..."error"in n&&{error:n.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>Tm(t)&&t.type===e,r}function jg(e){return"function"==typeof e&&"type"in e&&Dg(e)}function Ag(e,t){let r=0;return{measureTime(e){const t=Date.now();try{return e()}finally{const e=Date.now();r+=e-t}},warnIfExceeded(){r>e&&console.warn(`${t} took ${r}ms, which is more than the warning threshold of ${e}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`)}}}var Lg=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Ng(e){return Mm(e)?mg(e,()=>{}):e}function Fg(e,t,r){return e.has(t)?e.get(t):e.set(t,r(t)).get(t)}function Bg(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function zg(e,t,r){const n=Ug(e,t,r);return{detectMutations:()=>Vg(e,t,n,r)}}function Ug(e,t=[],r,n="",i=new Set){const s={value:r};if(!e(r)&&!i.has(r)){i.add(r),s.children={};for(const i in r){const o=n?n+"."+i:i;t.length&&-1!==t.indexOf(o)||(s.children[i]=Ug(e,t,r[i],o))}}return s}function Vg(e,t=[],r,n,i=!1,s=""){const o=r?r.value:void 0,a=o===n;if(i&&!a&&!Number.isNaN(n))return{wasMutated:!0,path:s};if(e(o)||e(n))return{wasMutated:!1};const c={};for(let e in r.children)c[e]=!0;for(let e in n)c[e]=!0;const d=t.length>0;for(let i in c){const o=s?s+"."+i:i;if(d){if(t.some(e=>e instanceof RegExp?e.test(o):o===e))continue}const c=Vg(e,t,r.children[i],n[i],a,o);if(c.wasMutated)return c}return{wasMutated:!1}}function $g(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||bm(e)}function Gg(e,t="",r=$g,n,i=[],s){let o;if(!r(e))return{keyPath:t||"<root>",value:e};if("object"!=typeof e||null===e)return!1;if(s?.has(e))return!1;const a=null!=n?n(e):Object.entries(e),c=i.length>0;for(const[e,d]of a){const a=t?t+"."+e:e;if(c){if(i.some(e=>e instanceof RegExp?e.test(a):a===e))continue}if(!r(d))return{keyPath:a,value:d};if("object"==typeof d&&(o=Gg(d,a,r,n,i,s),o))return o}return s&&qg(e)&&s.add(e),!1}function qg(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!qg(t))return!1;return!0}function Hg(e){return"boolean"==typeof e}var Wg=()=>function(e){const{thunk:t=!0,immutableCheck:r=!0,serializableCheck:n=!0,actionCreatorCheck:i=!0}=e??{};let s=new Lg;if(t&&(Hg(t)?s.push(Og):s.push(xg(t.extraArgument))),r){let e={};Hg(r)||(e=r),s.unshift(function(e={}){{let t=function(e,t,n,i){return JSON.stringify(e,r(t,i),n)},r=function(e,t){let r=[],n=[];return t||(t=function(e,t){return r[0]===t?"[Circular ~]":"[Circular ~."+n.slice(0,r.indexOf(t)).join(".")+"]"}),function(i,s){if(r.length>0){var o=r.indexOf(this);~o?r.splice(o+1):r.push(this),~o?n.splice(o,1/0,i):n.push(i),~r.indexOf(s)&&(s=t.call(this,i,s))}else r.push(s);return null==e?s:e.call(this,i,s)}},{isImmutable:n=Bg,ignoredPaths:i,warnAfter:s=32}=e;const o=zg.bind(null,n,i);return({getState:e})=>{let r,n=e(),i=o(n);return a=>c=>{const d=Ag(s,"ImmutableStateInvariantMiddleware");d.measureTime(()=>{if(n=e(),r=i.detectMutations(),i=o(n),r.wasMutated)throw new Error(`A state mutation was detected between dispatches, in the path '${r.path||""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)});const l=a(c);return d.measureTime(()=>{if(n=e(),r=i.detectMutations(),i=o(n),r.wasMutated)throw new Error(`A state mutation was detected inside a dispatch, in the path: ${r.path||""}. Take a look at the reducer(s) handling the action ${t(c)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)}),d.warnIfExceeded(),l}}}}(e))}if(n){let e={};Hg(n)||(e=n),s.push(function(e={}){{const{isSerializable:t=$g,getEntries:r,ignoredActions:n=[],ignoredActionPaths:i=["meta.arg","meta.baseQueryMeta"],ignoredPaths:s=[],warnAfter:o=32,ignoreState:a=!1,ignoreActions:c=!1,disableCache:d=!1}=e,l=!d&&WeakSet?new WeakSet:void 0;return e=>d=>u=>{if(!Tm(u))return d(u);const p=d(u),h=Ag(o,"SerializableStateInvariantMiddleware");return c||n.length&&-1!==n.indexOf(u.type)||h.measureTime(()=>{const e=Gg(u,"",t,r,i,l);if(e){const{keyPath:t,value:r}=e;console.error(`A non-serializable value was detected in an action, in the path: \`${t}\`. Value:`,r,"\nTake a look at the logic that dispatched this action: ",u,"\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)","\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)")}}),a||(h.measureTime(()=>{const n=Gg(e.getState(),"",t,r,s,l);if(n){const{keyPath:e,value:t}=n;console.error(`A non-serializable value was detected in the state, in the path: \`${e}\`. Value:`,t,`\nTake a look at the reducer(s) handling this action type: ${u.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`)}}),h.warnIfExceeded()),p}}}(e))}if(i){let e={};Hg(i)||(e=i),s.unshift(function(e={}){const{isActionCreator:t=jg}=e;return()=>e=>r=>(t(r)&&console.warn(function(e){const t=e?`${e}`.split("/"):[],r=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \`dispatch(${r}())\` instead of \`dispatch(${r})\`. This is necessary even if the action has no payload.`}(r.type)),e(r))}(e))}return s},Jg=e=>t=>{setTimeout(t,e)},Kg=e=>function(t){const{autoBatch:r=!0}=t??{};let n=new Lg(e);return r&&n.push(((e={type:"raf"})=>t=>(...r)=>{const n=t(...r);let i=!0,s=!1,o=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?"undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:Jg(10):"callback"===e.type?e.queueNotification:Jg(e.timeout),d=()=>{o=!1,s&&(s=!1,a.forEach(e=>e()))};return Object.assign({},n,{subscribe(e){const t=n.subscribe(()=>i&&e());return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return i=!e?.meta?.RTK_autoBatch,s=!i,s&&(o||(o=!0,c(d))),n.dispatch(e)}finally{i=!0}}})})("object"==typeof r?r:void 0)),n};function Qg(e){const t=Wg(),{reducer:r,middleware:n,devTools:i=!0,duplicateMiddlewareCheck:s=!0,preloadedState:o,enhancers:a}=e||{};let c,d;if("function"==typeof r)c=r;else{if(!bm(r))throw new Error("`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");c=Cm(r)}if(n&&"function"!=typeof n)throw new Error("`middleware` field must be a callback");if("function"==typeof n){if(d=n(t),!Array.isArray(d))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else d=t();if(d.some(e=>"function"!=typeof e))throw new Error("each middleware provided to configureStore must be a function");if(s){let e=new Set;d.forEach(t=>{if(e.has(t))throw new Error("Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");e.add(t)})}let l=km;i&&(l=Ig({trace:!0,..."object"==typeof i&&i}));const u=function(...e){return t=>(r,n)=>{const i=t(r,n);let s=()=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")};const o={getState:i.getState,dispatch:(e,...t)=>s(e,...t)},a=e.map(e=>e(o));return s=km(...a)(i.dispatch),{...i,dispatch:s}}}(...d),p=Kg(u);if(a&&"function"!=typeof a)throw new Error("`enhancers` field must be a callback");let h="function"==typeof a?a(p):p();if(!Array.isArray(h))throw new Error("`enhancers` callback must return an array");if(h.some(e=>"function"!=typeof e))throw new Error("each enhancer provided to configureStore must be a function");d.length&&!h.includes(u)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return wm(c,o,l(...h))}function Yg(e){const t={},r=[];let n;const i={addCase(e,s){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(n)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");const o="string"==typeof e?e:e.type;if(!o)throw new Error("`builder.addCase` cannot be called with an empty action type");if(o in t)throw new Error(`\`builder.addCase\` cannot be called with two reducers for the same action type '${o}'`);return t[o]=s,i},addMatcher(e,t){if(n)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),i},addDefaultCase(e){if(n)throw new Error("`builder.addDefaultCase` can only be called once");return n=e,i}};return e(i),[t,r,n]}function Xg(...e){return t=>e.some(e=>((e,t)=>Dg(e)?e.match(t):e(t))(e,t))}var Zg=(e=21)=>{let t="",r=e;for(;r--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t},ev=["name","message","stack","code"],tv=class{constructor(e,t){this.payload=e,this.meta=t}_type},rv=class{constructor(e,t){this.payload=e,this.meta=t}_type},nv=e=>{if("object"==typeof e&&null!==e){const t={};for(const r of ev)"string"==typeof e[r]&&(t[r]=e[r]);return t}return{message:String(e)}},iv="External signal was aborted",sv=(()=>{function e(e,t,r){const n=Mg(e+"/fulfilled",(e,t,r,n)=>({payload:e,meta:{...n||{},arg:r,requestId:t,requestStatus:"fulfilled"}})),i=Mg(e+"/pending",(e,t,r)=>({payload:void 0,meta:{...r||{},arg:t,requestId:e,requestStatus:"pending"}})),s=Mg(e+"/rejected",(e,t,n,i,s)=>({payload:i,error:(r&&r.serializeError||nv)(e||"Rejected"),meta:{...s||{},arg:n,requestId:t,rejectedWithValue:!!i,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}}));return Object.assign(function(e,{signal:o}={}){return(a,c,d)=>{const l=r?.idGenerator?r.idGenerator(e):Zg(),u=new AbortController;let p,h;function f(e){h=e,u.abort()}o&&(o.aborted?f(iv):o.addEventListener("abort",()=>f(iv),{once:!0}));const m=async function(){let o;try{let s=r?.condition?.(e,{getState:c,extra:d});if(function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(s)&&(s=await s),!1===s||u.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise((e,t)=>{p=()=>{t({name:"AbortError",message:h||"Aborted"})},u.signal.addEventListener("abort",p)});a(i(l,e,r?.getPendingMeta?.({requestId:l,arg:e},{getState:c,extra:d}))),o=await Promise.race([m,Promise.resolve(t(e,{dispatch:a,getState:c,extra:d,requestId:l,signal:u.signal,abort:f,rejectWithValue:(e,t)=>new tv(e,t),fulfillWithValue:(e,t)=>new rv(e,t)})).then(t=>{if(t instanceof tv)throw t;return t instanceof rv?n(t.payload,l,e,t.meta):n(t,l,e)})])}catch(t){o=t instanceof tv?s(null,l,e,t.payload,t.meta):s(t,l,e)}finally{p&&u.signal.removeEventListener("abort",p)}return r&&!r.dispatchConditionRejection&&s.match(o)&&o.meta.condition||a(o),o}();return Object.assign(m,{abort:f,requestId:l,arg:e,unwrap:()=>m.then(ov)})}},{pending:i,rejected:s,fulfilled:n,settled:Xg(s,n),typePrefix:e})}return e.withTypes=()=>e,e})();function ov(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var av=Symbol.for("rtk-slice-createasyncthunk");function cv(e,t){return`${e}/${t}`}function dv({creators:e}={}){const t=e?.asyncThunk?.[av];return function(e){const{name:r,reducerPath:n=r}=e;if(!r)throw new Error("`name` is a required option for createSlice");const i=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},s=Object.keys(i),o={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},a={addCase(e,t){const r="string"==typeof e?e:e.type;if(!r)throw new Error("`context.addCase` cannot be called with an empty action type");if(r in o.sliceCaseReducersByType)throw new Error("`context.addCase` cannot be called with two reducers for the same action type: "+r);return o.sliceCaseReducersByType[r]=t,a},addMatcher:(e,t)=>(o.sliceMatchers.push({matcher:e,reducer:t}),a),exposeAction:(e,t)=>(o.actionCreators[e]=t,a),exposeCaseReducer:(e,t)=>(o.sliceCaseReducersByName[e]=t,a)};function c(){if("object"==typeof e.extraReducers)throw new Error("The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");const[t={},r=[],n]="function"==typeof e.extraReducers?Yg(e.extraReducers):[e.extraReducers],i={...t,...o.sliceCaseReducersByType};return function(e,t){if("object"==typeof t)throw new Error("The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");let r,[n,i,s]=Yg(t);if("function"==typeof e)r=()=>Ng(e());else{const t=Ng(e);r=()=>t}function o(e=r(),t){let o=[n[t.type],...i.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return 0===o.filter(e=>!!e).length&&(o=[s]),o.reduce((e,r)=>{if(r){if(Dm(e)){const n=r(e,t);return void 0===n?e:n}if(Mm(e))return mg(e,e=>r(e,t));{const n=r(e,t);if(void 0===n){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return n}}return e},e)}return o.getInitialState=r,o}(e.initialState,e=>{for(let t in i)e.addCase(t,i[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of r)e.addMatcher(t.matcher,t.reducer);n&&e.addDefaultCase(n)})}s.forEach(n=>{const s=i[n],o={reducerName:n,type:cv(r,n),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(s)?function({type:e,reducerName:t,createNotation:r},n,i){let s,o;if("reducer"in n){if(r&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(n))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");s=n.reducer,o=n.prepare}else s=n;i.addCase(e,s).exposeCaseReducer(t,s).exposeAction(t,o?Mg(e,o):Mg(e))}(o,s,a):function({type:e,reducerName:t},r,n,i){if(!i)throw new Error("Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");const{payloadCreator:s,fulfilled:o,pending:a,rejected:c,settled:d,options:l}=r,u=i(e,s,l);n.exposeAction(t,u),o&&n.addCase(u.fulfilled,o);a&&n.addCase(u.pending,a);c&&n.addCase(u.rejected,c);d&&n.addMatcher(u.settled,d);n.exposeCaseReducer(t,{fulfilled:o||pv,pending:a||pv,rejected:c||pv,settled:d||pv})}(o,s,a,t)});const d=e=>e,l=new Map,u=new WeakMap;let p;function h(e,t){return p||(p=c()),p(e,t)}function f(){return p||(p=c()),p.getInitialState()}function m(t,r=!1){function n(e){let i=e[t];if(void 0===i){if(!r)throw new Error("selectSlice returned undefined for an uninjected slice reducer");i=Fg(u,n,f)}return i}function i(t=d){const n=Fg(l,r,()=>new WeakMap);return Fg(n,t,()=>{const n={};for(const[i,s]of Object.entries(e.selectors??{}))n[i]=lv(s,t,()=>Fg(u,t,f),r);return n})}return{reducerPath:t,getSelectors:i,get selectors(){return i(n)},selectSlice:n}}const g={name:r,reducer:h,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:f,...m(n),injectInto(e,{reducerPath:t,...r}={}){const i=t??n;return e.inject({reducerPath:i,reducer:h},r),{...g,...m(i,!0)}}};return g}}function lv(e,t,r,n){function i(i,...s){let o=t(i);if(void 0===o){if(!n)throw new Error("selectState returned undefined for an uninjected slice reducer");o=r()}return e(o,...s)}return i.unwrapped=e,i}var uv=dv();function pv(){}var hv="listener",fv="completed",mv="cancelled",gv=`task-${mv}`,vv=`task-${fv}`,bv=`${hv}-${mv}`,yv=`${hv}-${fv}`,_v=class{constructor(e){this.code=e,this.message=`task ${mv} (reason: ${e})`}name="TaskAbortError";message},wv=(e,t)=>{if("function"!=typeof e)throw new TypeError(`${t} is not a function`)},Sv=()=>{},Cv=(e,t=Sv)=>(e.catch(t),e),kv=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Tv=(e,t)=>{const r=e.signal;r.aborted||("reason"in r||Object.defineProperty(r,"reason",{enumerable:!0,value:t,configurable:!0,writable:!0}),e.abort(t))},Pv=e=>{if(e.aborted){const{reason:t}=e;throw new _v(t)}};function Rv(e,t){let r=Sv;return new Promise((n,i)=>{const s=()=>i(new _v(e.reason));e.aborted?s():(r=kv(e,s),t.finally(()=>r()).then(n,i))}).finally(()=>{r=Sv})}var Ev=e=>t=>Cv(Rv(e,t).then(t=>(Pv(e),t))),Ov=e=>{const t=Ev(e);return e=>t(new Promise(t=>setTimeout(t,e)))},{assign:xv}=Object,Iv={},Dv="listenerMiddleware",Mv=(e,t)=>(r,n)=>{wv(r,"taskExecutor");const i=new AbortController;var s;s=i,kv(e,()=>Tv(s,e.reason));const o=(async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof _v?"cancelled":"rejected",error:e}}finally{t?.()}})(async()=>{Pv(e),Pv(i.signal);const t=await r({pause:Ev(i.signal),delay:Ov(i.signal),signal:i.signal});return Pv(i.signal),t},()=>Tv(i,vv));return n?.autoJoin&&t.push(o.catch(Sv)),{result:Ev(e)(o),cancel(){Tv(i,gv)}}},jv=(e,t)=>(r,n)=>Cv((async(r,n)=>{Pv(t);let i=()=>{};const s=[new Promise((t,n)=>{let s=e({predicate:r,effect:(e,r)=>{r.unsubscribe(),t([e,r.getState(),r.getOriginalState()])}});i=()=>{s(),n()}})];null!=n&&s.push(new Promise(e=>setTimeout(e,n,null)));try{const e=await Rv(t,Promise.race(s));return Pv(t),e}finally{i()}})(r,n)),Av=e=>{let{type:t,actionCreator:r,matcher:n,predicate:i,effect:s}=e;if(t)i=Mg(t).match;else if(r)t=r.type,i=r.match;else if(n)i=n;else if(!i)throw new Error("Creating or removing a listener requires one of the known fields for matching an action");return wv(s,"options.listener"),{predicate:i,type:t,effect:s}},Lv=xv(e=>{const{type:t,predicate:r,effect:n}=Av(e);return{id:Zg(),effect:n,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error("Unsubscribe not initialized")}}},{withTypes:()=>Lv}),Nv=(e,t)=>{const{type:r,effect:n,predicate:i}=Av(t);return Array.from(e.values()).find(e=>("string"==typeof r?e.type===r:e.predicate===i)&&e.effect===n)},Fv=e=>{e.pending.forEach(e=>{Tv(e,bv)})},Bv=(e,t,r)=>{try{e(t,r)}catch(e){setTimeout(()=>{throw e},0)}},zv=xv(Mg(`${Dv}/add`),{withTypes:()=>zv}),Uv=Mg(`${Dv}/removeAll`),Vv=xv(Mg(`${Dv}/remove`),{withTypes:()=>Vv}),$v=(...e)=>{console.error(`${Dv}/error`,...e)};let Gv,qv=class{constructor(e={}){this.data=void 0===e.data?{}:e.data,this.headers=e.headers||{},this.status=e.status||200,this.statusText=e.statusText||"OK",this.url=e.url||null}};function Hv(e,t){return kd.ok(e,`${t} is required`),e}function Wv(e,t){return kd.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function Jv(e,t){return kd.ok("number"==typeof e,`${t}<number> is required`),e}function Kv(e,t){return kd.ok("string"==typeof e,`${t}<string> is required`),e}function Qv(e,t,r){const n=r||t.name[0].toLowerCase()+t.name.substring(1);return kd.ok(e instanceof t,`${n}<${t.name}> is required`),e}function Yv(e,t){return kd.ok(Array.isArray(e),`${t}<array> is required`),e}function Xv(e,t){if(null==e||"object"!=typeof e||Array.isArray(e))throw new Error(`${t} must be a record. ${JSON.stringify(e)}`);return e}function Zv(e,t,r){Kv(t,"name"),function(e,t,r){Kv(r,"name");const n=`${r} must be null or of type ${t}`;kd.ok(null===e||typeof e===t,n)}(e,"string",t)}function eb({baseUrl:e,url:t}){return e?e+t:t}class tb{constructor({baseUrl:e}){Kv(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const r=Object.assign({},t,{url:e,baseURL:this._baseUrl});return Xf.request(r)}request(e,t){return Kv(e,"url"),kd.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),kd.ok(t,"options are required"),this._requestAxios(e,t).then(e=>{const{data:t,headers:r,status:n,statusText:i,config:s}=e,o=s&&s.url?eb({baseUrl:s.baseURL,url:s.url}):null;return new qv({data:t,headers:r,status:n,statusText:i,url:o})}).catch(e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:r,headers:n,status:i,statusText:s,config:o}=t,a=o&&o.url?eb({baseUrl:o.baseURL,url:o.url}):null;return Promise.reject(new qv({data:r,headers:n,status:i,statusText:s,url:a}))})}}class rb{constructor({httpClient:e}){kd.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){kd.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach(r=>{const n=e[r];t.append(r,n)}),t}request(e,t={}){const r=Object.assign(t.headers||{},{"Content-Type":void 0});return this._httpClient.request(e,Object.assign(t,{headers:r,transformRequest:rb.dataToFormData}))}}Gv="object"==typeof window?window.btoa||p:"object"==typeof global&&global.btoa||p;const nb=()=>Promise.resolve(null);class ib{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then(r=>{const n=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${Gv(t)}`}}return{}}(r),{"X-Appearin-Device-Platform":"web"}),i=Object.assign({},t,{headers:n});return this._httpClient.request(e,i)})}}class sb{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=nb}={}){this.authenticatedHttpClient=new ib({httpClient:new tb({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new rb({httpClient:this.authenticatedHttpClient})}request(e,t){return Kv(e,"url"),kd.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),kd.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return Kv(e,"url"),kd.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),kd.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function ob(e,t){return Kv(Xv(e,"data")[t],t)}const ab=(cb=ob,(e,t)=>{const r=Xv(e,"data")[t];return null==r?null:cb(e,t)});var cb;function db(e,t,r){return function(e,t){return Yv(Xv(e,"data")[t],t)}(e,t).map(e=>r(e))}class lb{constructor(e,t,r=void 0){this.credentials={uuid:e},this.hmac=t,this.userId=r}toJson(){return Object.assign({credentials:this.credentials,hmac:this.hmac},this.userId&&{userId:this.userId})}static fromJson(e){return new lb(ob(function(e,t){const r=Xv(e,"data")[t];return void 0===r?null:r}(e,"credentials"),"uuid"),ob(e,"hmac"),ab(e,"userId")||void 0)}}class ub{constructor({apiClient:e}){this._apiClient=e}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then(({data:e})=>lb.fromJson(e)).catch(e=>{if(e.response&&404===e.response.status)return null;throw e})}}class pb{constructor(e,t){this._key=e,this._chromeStorage=t}loadOrDefault(e){return new Promise(t=>{this._chromeStorage.get(this._key,r=>{t(r[this._key]||e)})})}save(e){return new Promise(t=>{this._chromeStorage.set({[this._key]:e},()=>{t()})})}}class hb{constructor(e,t){Hv(t,"localStorage"),this._key=Kv(e,"key"),this._localStorage=t}loadOrDefault(e){try{const t=this._localStorage.getItem(this._key);if(t)try{return Promise.resolve(JSON.parse(t))}catch(e){}return Promise.resolve(e)}catch(t){return console.warn("Error getting access to storage. Are cookies blocked?",t),Promise.resolve(e)}}save(e){try{return this._localStorage.setItem(this._key,JSON.stringify(e)),Promise.resolve()}catch(e){return console.warn("Error getting access to storage. Are cookies blocked?",e),Promise.reject(e)}}}let fb;try{fb=self.localStorage}catch(Op){fb={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var mb=fb;const gb="credentials_saved";class vb extends Ro{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=e,this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:r="localStorage"}){const n=new ub({apiClient:new sb({baseUrl:e})});let i=null;if("localStorage"===r)i=new hb(t,mb);else{if("chromeStorage"!==r)throw new Error(`Unknown store type: ${r}`);i=new pb(t,window.chrome.storage.local)}return new vb({deviceService:n,credentialsStore:i})}_fetchNewCredentialsFromApi(){const e=this._credentialsStore;return new Promise(t=>{const r=()=>{this._deviceService.getCredentials().then(r=>e.save(r?r.toJson():null).then(()=>t(r))).catch(()=>{setTimeout(r,2e3)})};r()})}getCurrentCredentials(){return this._credentialsStore.loadOrDefault(null).then(e=>e?lb.fromJson(e):null)}getCredentials(){return this.credentialsPromise||(this.credentialsPromise=this.getCurrentCredentials().then(e=>e||this._fetchNewCredentialsFromApi())),this.credentialsPromise}saveCredentials(e){return this.credentialsPromise=void 0,this._credentialsStore.save(e.toJson()).then(()=>(this.emit(gb,e),e))}setUserId(e){return this.getCurrentCredentials().then(t=>{t||console.error("Illegal state: no credentials to set user id for.");if(null===t||t.userId!==e)return this._credentialsStore.save(Object.assign({},null==t?void 0:t.toJson(),{userId:e}))}).then(()=>{})}}class bb{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:r,totalMinutesUsed:n}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=r,this.totalMinutesUsed=n}static fromJson(e){return new bb({isExhausted:Wv(e.isExhausted,"isExhausted"),renewsAt:new Date(Kv(e.renewsAt,"renewsAt")),totalMinutesLimit:Jv(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:Jv(e.totalMinutesUsed,"totalMinutesUsed")})}}class yb{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:r,isOnTrial:n,onTrialUntil:i,trialStatus:s}){this.basePlanId=e,this.isDeactivated=r,this.isOnTrial=n,this.onTrialUntil=i||null,this.trialStatus=s||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new yb({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:Wv(e.isDeactivated,"isDeactivated"),isOnTrial:Wv(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?bb.fromJson(e.embeddedFreeTierStatus):null})}}function _b(e){return null!=e}function wb(e={}){return{maxNumberOfInvitationsAndUsers:_b(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:_b(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:_b(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:_b(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:_b(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class Sb{constructor(e){this.logoImageUrl=null,this.roomBackgroundImageUrl=null,this.roomBackgroundThumbnailUrl=null,this.roomKnockPageBackgroundImageUrl=null,this.roomKnockPageBackgroundThumbnailUrl=null,this.preferences=null,this.onboardingSurvey=null,this.type=null,Qv(e,Object,"properties"),Kv(e.organizationId,"organizationId"),Kv(e.organizationName,"organizationName"),Kv(e.subdomain,"subdomain"),Qv(e.permissions,Object,"permissions"),Qv(e.limits,Object,"limits"),this.organizationId=e.organizationId,this.organizationName=e.organizationName,this.subdomain=e.subdomain,this.permissions=e.permissions,this.limits=e.limits,this.account=e.account?new yb(e.account):null,this.logoImageUrl=e.logoImageUrl,this.roomBackgroundImageUrl=e.roomBackgroundImageUrl,this.roomBackgroundThumbnailUrl=e.roomBackgroundThumbnailUrl,this.roomKnockPageBackgroundImageUrl=e.roomKnockPageBackgroundImageUrl,this.roomKnockPageBackgroundThumbnailUrl=e.roomKnockPageBackgroundThumbnailUrl,this.preferences=e.preferences,this.onboardingSurvey=e.onboardingSurvey,this.type=e.type}static fromJson(e){const t=Qv(e,Object,"data"),r=(null==t?void 0:t.preferences)||{},n=(null==t?void 0:t.onboardingSurvey)||null,i=Qv(t.permissions,Object,"permissions");return new Sb({organizationId:Kv(t.organizationId,"organizationId"),organizationName:Kv(t.organizationName,"organizationName"),subdomain:Kv(t.subdomain,"subdomain"),permissions:i,limits:wb(Qv(t.limits,Object,"limits")),account:t.account?yb.fromJson(t.account):null,logoImageUrl:"string"==typeof t.logoImageUrl?t.logoImageUrl:null,roomBackgroundImageUrl:"string"==typeof t.roomBackgroundImageUrl?t.roomBackgroundImageUrl:null,roomBackgroundThumbnailUrl:"string"==typeof t.roomBackgroundThumbnailUrl?t.roomBackgroundThumbnailUrl:null,roomKnockPageBackgroundImageUrl:"string"==typeof t.roomKnockPageBackgroundImageUrl?t.roomKnockPageBackgroundImageUrl:null,roomKnockPageBackgroundThumbnailUrl:"string"==typeof t.roomKnockPageBackgroundThumbnailUrl?t.roomKnockPageBackgroundThumbnailUrl:null,preferences:r,onboardingSurvey:n,type:"string"==typeof t.type?t.type:null})}}Sb.GLOBAL_ORGANIZATION_ID="1";class Cb{constructor({apiClient:e}){this._apiClient=e}createOrganization({organizationName:e,subdomain:t,owner:r}){const{displayName:n,consents:i}=r||{},s="email"in r?{value:r.email,verificationCode:Kv(r.verificationCode,"owner.verificationCode")}:null,o="idToken"in r?r.idToken:null;if(Kv(t,"subdomain"),Kv(e,"organizationName"),Kv(n,"owner.displayName"),kd.ok(s||o,"owner.email or owner.idToken is required"),i){Yv(i,"consents");for(const{consentRevisionId:e,action:t}of i)Kv(e,"consentRevisionId"),Zv(t,"action")}return this._apiClient.request("/organizations",{method:"POST",data:{organizationName:e,type:"private",subdomain:t,owner:Object.assign(Object.assign(Object.assign(Object.assign({},s&&{email:s}),o&&{idToken:o}),i&&{consents:i}),{displayName:n})}}).then(({data:e})=>ob(e,"organizationId"))}getOrganizationBySubdomain(e){return Kv(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then(({data:e})=>Sb.fromJson(e)).catch(e=>{if(e instanceof qv){if(404===e.status)return null;throw new Error(e.statusText)}throw e})}getOrganizationByOrganizationId(e){return Kv(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then(({data:e})=>Sb.fromJson(e)).catch(e=>{if(e instanceof qv){if(404===e.status)return null;throw new Error(e.statusText)}throw e})}getOrganizationsByContactPoint(e){const{code:t}=e,r="email"in e?e.email:null,n="phoneNumber"in e?e.phoneNumber:null;kd.ok((r||n)&&!(r&&n),"either email or phoneNumber is required"),Kv(t,"code");const i=r?{type:"email",value:r}:{type:"phoneNumber",value:n};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:i,code:t}}).then(({data:e})=>db(e,"organizations",e=>Sb.fromJson(e)))}getOrganizationsByIdToken({idToken:e}){return Kv(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then(({data:e})=>db(e,"organizations",e=>Sb.fromJson(Object.assign({permissions:{},limits:{}},Xv(e,"organization")))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then(({data:e})=>db(e,"organizations",e=>Sb.fromJson(Object.assign({permissions:{},limits:{}},Xv(e,"organization")))))}getSubdomainAvailability(e){return Kv(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then(({data:e})=>(Qv(e,Object,"data"),{status:ob(e,"status")}))}updatePreferences({organizationId:e,preferences:t}){return Hv(e,"organizationId"),Hv(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then(()=>{})}deleteOrganization({organizationId:e}){return Hv(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then(()=>{})}}class kb{constructor({organizationService:e,subdomain:t}){this._organizationService=e,this._subdomain=t,this._organizationPromise=null}initOrganization(){return this.fetchOrganization().then(()=>{})}fetchOrganization(){return this._organizationPromise||(this._organizationPromise=this._organizationService.getOrganizationBySubdomain(this._subdomain)),this._organizationPromise}}const Tb="https://api.whereby.dev";function Pb(e,{delay:t=500,edges:r}={}){let n,i=0;return(...s)=>{i+=1,r&&1===i&&e(...s),clearTimeout(n),n=setTimeout(()=>{(!r||i>1)&&e(...s),n=void 0,i=0},t)}}const Rb=((e={})=>{const t=new Map,{extra:r,onError:n=$v}=e;wv(n,"onError");const i=e=>(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&Fv(e)}))(Nv(t,e)??Lv(e));xv(i,{withTypes:()=>i});const s=e=>{const r=Nv(t,e);return r&&(r.unsubscribe(),e.cancelActive&&Fv(r)),!!r};xv(s,{withTypes:()=>s});const o=async(e,s,o,a)=>{const c=new AbortController,d=jv(i,c.signal),l=[];try{e.pending.add(c),await Promise.resolve(e.effect(s,xv({},o,{getOriginalState:a,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:Ov(c.signal),pause:Ev(c.signal),extra:r,signal:c.signal,fork:Mv(c.signal,l),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach((e,t,r)=>{e!==c&&(Tv(e,bv),r.delete(e))})},cancel:()=>{Tv(c,bv),e.pending.delete(c)},throwIfCancelled:()=>{Pv(c.signal)}})))}catch(e){e instanceof _v||Bv(n,e,{raisedBy:"effect"})}finally{await Promise.all(l),Tv(c,yv),e.pending.delete(c)}},a=(e=>()=>{e.forEach(Fv),e.clear()})(t);return{middleware:e=>r=>c=>{if(!Tm(c))return r(c);if(zv.match(c))return i(c.payload);if(Uv.match(c))return void a();if(Vv.match(c))return s(c.payload);let d=e.getState();const l=()=>{if(d===Iv)throw new Error(`${Dv}: getOriginalState can only be called synchronously`);return d};let u;try{if(u=r(c),t.size>0){const r=e.getState(),i=Array.from(t.values());for(const t of i){let i=!1;try{i=t.predicate(c,r,d)}catch(e){i=!1,Bv(n,e,{raisedBy:"predicate"})}i&&o(t,c,e,l)}}}finally{d=Iv}return u},startListening:i,stopListening:s,clearListeners:a}})(),Eb=Rb.startListening,Ob=(e,t)=>Eb({predicate:(t,r,n)=>{const i=e.map(e=>e(n)),s=e.map(e=>e(r));return i.some((e,t)=>e!==s[t])},effect:(r,{dispatch:n,getState:i,extra:s})=>{const o=e.map(e=>e(i()));t({dispatch:n,getState:i,extra:s},...o)}}),xb="1.2.9",Ib=uv({name:"app",initialState:{isNodeSdk:!1,isActive:!1,isDialIn:!1,isAssistant:!1,ignoreBreakoutGroups:!1,roomName:null,roomUrl:null,displayName:null,userAgent:`core:${xb}`,externalId:null},reducers:{doAppStart:(e,t)=>{const r=new URL(t.payload.roomUrl);return Object.assign(Object.assign(Object.assign({},e),t.payload),{roomName:r.pathname,initialConfig:Object.assign({},t.payload),isActive:!0,isAssistant:Boolean(t.payload.assistantKey)})},doAppStop:e=>Object.assign(Object.assign({},e),{isActive:!1})}}),{doAppStop:Db,doAppStart:Mb}=Ib.actions,jb=e=>e.app.isActive,Ab=e=>e.app.isDialIn,Lb=e=>e.app.roomName,Nb=e=>e.app.displayName,Fb=e=>e.app.userAgent,Bb=e=>e.app.externalId;function zb(e){return Mg(`signalConnection/event/${e}`)}const Ub={audioEnabled:zb("audioEnabled"),audioEnableRequested:zb("audioEnableRequested"),breakoutGroupJoined:zb("breakoutGroupJoined"),breakoutMoveToGroup:zb("breakoutMoveToGroup"),breakoutMoveToMain:zb("breakoutMoveToMain"),breakoutSessionUpdated:zb("breakoutSessionUpdated"),chatMessage:zb("chatMessage"),clientLeft:zb("clientLeft"),clientKicked:zb("clientKicked"),clientMetadataReceived:zb("clientMetadataReceived"),clientUnableToJoin:zb("clientUnableToJoin"),cloudRecordingStarted:zb("cloudRecordingStarted"),cloudRecordingStopped:zb("cloudRecordingStopped"),disconnect:zb("disconnect"),knockerLeft:zb("knockerLeft"),knockHandled:zb("knockHandled"),newClient:zb("newClient"),roomJoined:zb("roomJoined"),roomKnocked:zb("roomKnocked"),roomLeft:zb("roomLeft"),roomLocked:zb("roomLocked"),roomSessionEnded:zb("roomSessionEnded"),screenshareStarted:zb("screenshareStarted"),screenshareStopped:zb("screenshareStopped"),spotlightAdded:zb("spotlightAdded"),spotlightRemoved:zb("spotlightRemoved"),streamingStopped:zb("streamingStopped"),videoEnabled:zb("videoEnabled"),videoEnableRequested:zb("videoEnableRequested"),liveTranscriptionStarted:zb("liveTranscriptionStarted"),liveTranscriptionStopped:zb("liveTranscriptionStopped"),liveCaptionsStarted:zb("liveCaptionsStarted"),liveCaptionsStopped:zb("liveCaptionsStopped")},Vb={canLockRoom:["host"],canRequestAudioEnable:["host"],canRequestVideoEnable:["host"],canKickClient:["host"],canEndMeeting:["host"],canAskToSpeak:["host"],canSpotlight:["host"]},$b=uv({name:"authorization",initialState:{roomKey:null,assistantKey:null,roleName:"none"},reducers:{setRoomKey:(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload})},extraReducers:e=>{e.addCase(Mb,(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload.roomKey,assistantKey:t.payload.assistantKey})),e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r,selfId:n}=t.payload||{},i=null==r?void 0:r.clients.find(e=>e.id===n);return i?Object.assign(Object.assign({},e),{roleName:(null==i?void 0:i.role.roleName)||"none"}):e})}}),{setRoomKey:Gb}=$b.actions,qb=e=>e.authorization.roomKey,Hb=e=>e.authorization.roleName,Wb=Pg(Hb,e=>Vb.canLockRoom.includes(e)),Jb=Pg(Hb,e=>Vb.canRequestAudioEnable.includes(e)),Kb=Pg(Hb,e=>Vb.canRequestVideoEnable.includes(e)),Qb=Pg(Hb,e=>Vb.canKickClient.includes(e)),Yb=Pg(Hb,e=>Vb.canEndMeeting.includes(e)),Xb=Pg(Hb,e=>Vb.canAskToSpeak.includes(e)),Zb=Pg(Hb,e=>Vb.canSpotlight.includes(e));function ey(e,t){return sv(e,t)}function ty(e,t){return r=>(n,i,s)=>e(i())?t(r)(n,i,s):(console.warn("Not authorized to perform this action"),!1)}function ry(e){return t=>(r,n,i)=>"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):e(t)(r,n,i)}function ny(e,t){return ey(e,(e,r)=>{const{getState:n}=r;return"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),Promise.reject("Action cannot be performed outside of a connected room")):t(e,r)})}function iy(e,t){return r=>(n,i,s)=>"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):ty(e,t)(r)(n,i,s)}function sy(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}function oy(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r(function(t){t(e)})}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const ay=uv({name:"deviceCredentials",initialState:{isFetching:!1,data:null},reducers:{},extraReducers:e=>{e.addCase(cy.pending,e=>Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(cy.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload})),e.addCase(cy.rejected,e=>Object.assign(Object.assign({},e),{isFetching:!0}))}}),cy=ey("deviceCredentials/doGetDeviceCredentials",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{extra:t}){try{return yield t.services.credentialsService.getCredentials()}catch(e){console.error(e)}})),dy=e=>e.deviceCredentials,ly=e=>{var t,r;return null===(r=null===(t=e.deviceCredentials.data)||void 0===t?void 0:t.credentials)||void 0===r?void 0:r.uuid};Ob([Pg(jb,dy,(e,t)=>!(!e||t.isFetching||t.data))],({dispatch:e},t)=>{t&&e(cy())});const uy=uv({name:"signalConnection",initialState:{deviceIdentified:!1,isIdentifyingDevice:!1,status:"ready",socket:null},reducers:{socketConnecting:e=>Object.assign(Object.assign({},e),{status:"connecting"}),socketConnected:(e,t)=>Object.assign(Object.assign({},e),{socket:t.payload,status:"connected"}),socketDisconnected:e=>Object.assign(Object.assign({},e),{socket:null,deviceIdentified:!1,status:"disconnected"}),socketReconnecting:e=>Object.assign(Object.assign({},e),{status:"reconnecting"}),deviceIdentifying:e=>Object.assign(Object.assign({},e),{isIdentifyingDevice:!0}),deviceIdentified:e=>Object.assign(Object.assign({},e),{deviceIdentified:!0,isIdentifyingDevice:!1})},extraReducers:e=>{e.addCase(Ub.disconnect,e=>Object.assign(Object.assign({},e),{deviceIdentified:!1,status:"disconnected"}))}}),{deviceIdentifying:py,deviceIdentified:hy,socketConnected:fy,socketConnecting:my,socketDisconnected:gy,socketReconnecting:vy}=uy.actions,by=()=>(e,t)=>{if(ky(t()))return;e(my());const r=function(){const e=new URL("wss://signal.appearin.net").origin;return new Ul(e,{autoConnect:!1})}();r.on("connect",()=>e(fy(r))),r.on("device_identified",()=>e(hy())),r.getManager().on("reconnect",()=>e(vy())),function(e,t){e.on("room_joined",e=>t(Ub.roomJoined(e))),e.on("new_client",e=>t(Ub.newClient(e))),e.on("client_left",e=>t(Ub.clientLeft(e))),e.on("client_kicked",e=>t(Ub.clientKicked(e))),e.on("client_unable_to_join",e=>t(Ub.clientUnableToJoin(e))),e.on("audio_enabled",e=>t(Ub.audioEnabled(e))),e.on("video_enabled",e=>t(Ub.videoEnabled(e))),e.on("audio_enable_requested",e=>t(Ub.audioEnableRequested(e))),e.on("client_metadata_received",e=>t(Ub.clientMetadataReceived(e))),e.on("chat_message",e=>t(Ub.chatMessage(e))),e.on("disconnect",()=>t(Ub.disconnect())),e.on("room_knocked",e=>t(Ub.roomKnocked(e))),e.on("room_left",()=>t(Ub.roomLeft())),e.on("room_locked",e=>t(Ub.roomLocked(e))),e.on("room_session_ended",e=>t(Ub.roomSessionEnded(e))),e.on("knocker_left",e=>t(Ub.knockerLeft(e))),e.on("knock_handled",e=>t(Ub.knockHandled(e))),e.on("screenshare_started",e=>t(Ub.screenshareStarted(e))),e.on("screenshare_stopped",e=>t(Ub.screenshareStopped(e))),e.on("cloud_recording_started",e=>t(Ub.cloudRecordingStarted(e))),e.on("cloud_recording_stopped",()=>t(Ub.cloudRecordingStopped())),e.on("streaming_stopped",()=>t(Ub.streamingStopped())),e.on("spotlight_added",e=>t(Ub.spotlightAdded(e))),e.on("spotlight_removed",e=>t(Ub.spotlightRemoved(e))),e.on("live_transcription_started",e=>t(Ub.liveTranscriptionStarted(e))),e.on("live_transcription_stopped",e=>t(Ub.liveTranscriptionStopped(e))),e.on("live_captions_started",()=>t(Ub.liveCaptionsStarted())),e.on("live_captions_stopped",()=>t(Ub.liveCaptionsStopped())),e.on("video_enable_requested",e=>t(Ub.videoEnableRequested(e))),e.on("breakout_group_joined",e=>t(Ub.breakoutGroupJoined(e))),e.on("breakout_session_updated",e=>t(Ub.breakoutSessionUpdated(e))),e.on("breakout_move_to_group",()=>t(Ub.breakoutMoveToGroup())),e.on("breakout_move_to_main",()=>t(Ub.breakoutMoveToMain()))}(r,e),r.connect()},yy=({deviceCredentials:e})=>(t,r)=>{const n=r(),i=ky(n),s=Sy(n);i&&(s||(i.emit("identify_device",{deviceCredentials:e}),t(py())))},_y=()=>(e,t)=>{const r=t();if("connected"===Cy(r)){const t=wy(r).socket;null==t||t.disconnect(),e(gy())}},wy=e=>e.signalConnection,Sy=e=>e.signalConnection.deviceIdentified,Cy=e=>e.signalConnection.status,ky=e=>e.signalConnection.socket;Ob([Pg(jb,Cy,(e,t)=>!(!e||!["ready","reconnecting"].includes(t)))],({dispatch:e},t)=>{t&&e(by())});const Ty=Pg(dy,Cy,Sy,e=>e.signalConnection.isIdentifyingDevice,(e,t,r,n)=>!(!e.data||"connected"!==t||r||n));Ob([Ty,dy],({dispatch:e},t,r)=>{t&&r.data&&e(yy({deviceCredentials:r.data}))}),Eb({actionCreator:Ub.roomLeft,effect:(e,{dispatch:t})=>{t(_y())}}),Eb({actionCreator:Ub.clientKicked,effect:(e,{dispatch:t})=>{t(_y())}});const Py=uv({name:"localMedia",initialState:{busyDeviceIds:[],cameraEnabled:!1,currentSpeakerDeviceId:"default",devices:[],isSettingCameraDevice:!1,isSettingMicrophoneDevice:!1,isSettingSpeakerDevice:!1,isTogglingCamera:!1,lowDataMode:!1,microphoneEnabled:!1,status:"inactive",stream:void 0,isSwitchingStream:!1},reducers:{deviceBusy:(e,t)=>e.busyDeviceIds.includes(t.payload.deviceId)?e:Object.assign(Object.assign({},e),{busyDeviceIds:[...e.busyDeviceIds,t.payload.deviceId]}),toggleCameraEnabled(e,t){var r;return Object.assign(Object.assign({},e),{cameraEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.cameraEnabled})},setCurrentCameraDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentCameraDeviceId:t.payload.deviceId}),toggleMicrophoneEnabled(e,t){var r;return Object.assign(Object.assign({},e),{microphoneEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.microphoneEnabled})},setCurrentMicrophoneDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentMicrophoneDeviceId:t.payload.deviceId}),setCurrentSpeakerDeviceId(e,t){var r;return Object.assign(Object.assign({},e),{currentSpeakerDeviceId:null!==(r=t.payload.deviceId)&&void 0!==r?r:"default"})},toggleLowDataModeEnabled(e,t){var r;return Object.assign(Object.assign({},e),{lowDataMode:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.lowDataMode})},setDevices:(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}),setLocalMediaStream:(e,t)=>Object.assign(Object.assign({},e),{stream:t.payload.stream}),setLocalMediaOptions:(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.options}),localMediaStopped:e=>Object.assign(Object.assign({},e),{status:"stopped",stream:void 0}),localStreamMetadataUpdated(e,t){const{audio:r,video:n}=t.payload;return Object.assign(Object.assign({},e),{currentCameraDeviceId:n.deviceId,currentMicrophoneDeviceId:r.deviceId,busyDeviceIds:e.busyDeviceIds.filter(e=>e!==r.deviceId&&e!==n.deviceId)})}},extraReducers:e=>{e.addCase(Mb,(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.localMediaOptions})),e.addCase(Uy.pending,(e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:n,isSettingMicrophoneDevice:r})}),e.addCase(Uy.fulfilled,(e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!n&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice})}),e.addCase(Uy.rejected,(e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!n&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice,cameraDeviceError:n?t.error:e.cameraDeviceError,microphoneDeviceError:r?t.error:e.microphoneDeviceError})}),e.addCase(Fy.pending,e=>Object.assign(Object.assign({},e),{isTogglingCamera:!0})),e.addCase(Fy.fulfilled,e=>Object.assign(Object.assign({},e),{isTogglingCamera:!1})),e.addCase(Vy.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices})),e.addCase(Gy.pending,e=>Object.assign(Object.assign({},e),{status:"starting"})),e.addCase(Gy.fulfilled,(e,{payload:{stream:t,onDeviceChange:r}})=>{let n,i,s=!1,o=!1;const a=null==t?void 0:t.getAudioTracks()[0],c=null==t?void 0:t.getVideoTracks()[0];return a&&(i=a.getSettings().deviceId,o=a.enabled),c&&(s=c.enabled,n=c.getSettings().deviceId),Object.assign(Object.assign({},e),{stream:t,status:"started",currentCameraDeviceId:n,currentMicrophoneDeviceId:i,cameraEnabled:s,microphoneEnabled:o,onDeviceChange:r})}),e.addCase(Gy.rejected,(e,t)=>Object.assign(Object.assign({},e),{status:"error",startError:t.error})),e.addCase($y.pending,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!0})),e.addCase($y.fulfilled,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1})),e.addCase($y.rejected,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1}))}}),{deviceBusy:Ry,setCurrentCameraDeviceId:Ey,setCurrentMicrophoneDeviceId:Oy,setCurrentSpeakerDeviceId:xy,toggleCameraEnabled:Iy,toggleMicrophoneEnabled:Dy,toggleLowDataModeEnabled:My,setLocalMediaOptions:jy,setLocalMediaStream:Ay,localMediaStopped:Ly,localStreamMetadataUpdated:Ny}=Py.actions,Fy=ey("localMedia/doToggleCamera",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t,rejectWithValue:r}){const n=t(),i=r_(n);if(!i)return;let s=i.getVideoTracks()[0];const o=Ky(n);try{if(o)if(s)s.enabled=!0;else{const e=i_(n),t=Wy(n);yield zp(Object.assign(Object.assign({},e),{audioId:!1,videoId:t,type:"exact"}),{replaceStream:i}),s=i.getVideoTracks()[0]}else{if(!s)return;s.enabled=!1,s.stop(),i.removeTrack(s)}i.dispatchEvent(new CustomEvent("stopresumevideo",{detail:{track:s,enable:o}}))}catch(e){return r(e)}})),By=ey("localMedia/doToggleMicrophone",(e,{getState:t})=>{var r;const n=t(),i=r_(n);if(!i)return;const s=Qy(n),o=null===(r=i.getAudioTracks())||void 0===r?void 0:r[0];o&&(o.enabled=s)}),zy=()=>(e,t)=>{const r=t();if(!r_(r))return;const n=Wy(r),i=Jy(r);e($y({audioId:i,videoId:n}))},Uy=ey("localMedia/reactSetDevice",(e,t)=>oy(void 0,[e,t],void 0,function*({audio:e,video:t},{getState:r,rejectWithValue:n}){try{const n=r(),i=r_(n);if(!i)throw new Error("No stream");const s=!!e&&Jy(n),o=!!t&&Wy(n),a=i_(n),{replacedTracks:c}=yield zp(Object.assign(Object.assign({},a),{audioId:s,videoId:o,type:"exact"}),{replaceStream:i}),d=Qy(n);i.getAudioTracks().forEach(e=>e.enabled=d);const l=Ky(n);return i.getVideoTracks().forEach(e=>e.enabled=l),{replacedTracks:c}}catch(e){return n(e)}})),Vy=ey("localMedia/doUpdateDeviceList",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t,dispatch:r,rejectWithValue:n}){var i,s,o,a;const c=t();let d=[],l=[];const u=r_(c);try{d=yield navigator.mediaDevices.enumerateDevices(),l=Xy(c);if(!(u&&!n_(c)&&d&&l&&l.find(e=>e.deviceId)))return{devices:d};const{changedDevices:e,addedDevices:t}=Up({oldDevices:l,newDevices:d});let n=null===(i=e.audioinput)||void 0===i?void 0:i.deviceId,p=null===(s=e.videoinput)||void 0===s?void 0:s.deviceId;return void 0===n&&(n=null===(o=t.audioinput)||void 0===o?void 0:o.deviceId),void 0===p&&(p=null===(a=t.videoinput)||void 0===a?void 0:a.deviceId),void 0===n&&void 0===p||r($y({audioId:n,videoId:p})),{devices:d}}catch(e){return n(e)}})),$y=ey("localMedia/doSwitchLocalStream",(e,t)=>oy(void 0,[e,t],void 0,function*({audioId:e,videoId:t},{dispatch:r,getState:n,rejectWithValue:i}){const s=n(),o=r_(s),a=i_(s),c=!(!t||e)||!(t||!e);if(o)try{const{replacedTracks:n}=yield zp(Object.assign(Object.assign({},a),{audioId:void 0!==e&&e,videoId:void 0!==t&&t,type:"exact"}),{replaceStream:o}),i=e||t;return c&&i&&r(Ry({deviceId:i})),{replacedTracks:n}}catch(n){console.error(n);const s=e||t;return c&&s&&r(Ry({deviceId:s})),i(n)}})),Gy=ey("localMedia/doStartLocalMedia",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t,dispatch:r,rejectWithValue:n}){const i=Pb(()=>{r(Vy())},{delay:500});if(navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",i),"getTracks"in e)return Promise.resolve({stream:e,onDeviceChange:i});if(!e.audio&&!e.video)return{stream:void 0,onDeviceChange:i};r(jy({options:e}));try{yield r(Vy());const n=t(),s=i_(n),{stream:o}=yield zp(Object.assign(Object.assign({},s),{audioId:e.audio,videoId:e.video}));return{stream:o,onDeviceChange:i}}catch(e){return n(e)}})),qy=()=>(e,t)=>{const r=r_(t()),n=e_(t()).onDeviceChange;null==r||r.getTracks().forEach(e=>{e.stop()}),navigator.mediaDevices&&n&&navigator.mediaDevices.removeEventListener("devicechange",n),e(Ly())},Hy=e=>e.localMedia.busyDeviceIds,Wy=e=>e.localMedia.currentCameraDeviceId,Jy=e=>e.localMedia.currentMicrophoneDeviceId,Ky=e=>e.localMedia.cameraEnabled,Qy=e=>e.localMedia.microphoneEnabled,Yy=e=>e.localMedia.lowDataMode,Xy=e=>e.localMedia.devices,Zy=e=>e.localMedia.options;Pg(Zy,e=>!!e);const e_=e=>e.localMedia,t_=e=>e.localMedia.status,r_=e=>e.localMedia.stream,n_=e=>e.localMedia.isSwitchingStream,i_=Pg(Xy,Wy,Jy,Yy,(e,t,r,n)=>({devices:e,videoId:t,audioId:r,options:{disableAEC:!1,disableAGC:!1,hd:!0,lax:!1,lowDataMode:n,simulcast:!0,widescreen:!0}})),s_=Pg(t_,e=>"starting"===e),o_=Pg(Xy,Hy,(e,t)=>e.filter(e=>"videoinput"===e.kind).filter(e=>!t.includes(e.deviceId))),a_=Pg(Xy,Hy,(e,t)=>e.filter(e=>"audioinput"===e.kind).filter(e=>!t.includes(e.deviceId))),c_=Pg(Xy,e=>e.filter(e=>"audiooutput"===e.kind));Ob([Pg(jb,t_,Zy,(e,t,r)=>{if(e&&["inactive","stopped"].includes(t)&&r)return r})],({dispatch:e},t)=>{t&&e(Gy(t))});Ob([Pg(jb,t_,Zy,(e,t,r)=>!e&&"inactive"!==t&&!!r)],({dispatch:e},t)=>{t&&e(qy())}),Eb({predicate:(e,t,r)=>{const n=Qy(r),i=Qy(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(By())}}),Eb({predicate:(e,t,r)=>{const n=Yy(r),i=Yy(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(zy())}}),Eb({predicate:(e,t,r)=>{if(t.localMedia.isTogglingCamera)return!1;const n=Ky(r),i=Ky(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(Fy())}}),Eb({predicate:(e,t,r)=>{const n=Wy(r),i=Wy(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(Uy({audio:!1,video:!0}))}}),Eb({predicate:(e,t,r)=>{const n=Jy(r),i=Jy(t);return"started"===t_(r)&&n!==i},effect:(e,{dispatch:t})=>{t(Uy({audio:!0,video:!1}))}}),Eb({matcher:Xg(Gy.fulfilled,Vy.fulfilled,$y.fulfilled,$y.rejected),effect:(e,{dispatch:t,getState:r})=>{const n=r(),i=r_(n),s=Xy(n);if(!i)return;const o=function({audioTrack:e,videoTrack:t,devices:r,stoppedVideoTrack:n,lastAudioId:i,lastVideoId:s}){const o=e=>"live"===(null==e?void 0:e.readyState)?e:null;return t=o(t)||n,e=o(e),{video:Fp("videoinput",t,r,s),audio:Fp("audioinput",e,r,i)}}({audioTrack:i.getAudioTracks()[0],videoTrack:i.getVideoTracks()[0],devices:s});t(Ny(o))}}),Eb({actionCreator:Ub.audioEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Dy({enabled:!1}))}}),Eb({actionCreator:Ub.videoEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Iy({enabled:!1}))}}),Eb({actionCreator:Ub.breakoutSessionUpdated,effect:({payload:e},{dispatch:t})=>{var r;!1===(null===(r=e.initiatedBy)||void 0===r?void 0:r.active)&&t(Dy({enabled:!1}))}});const d_=["recorder","streamer"],l_=e=>e.localParticipant,u_=e=>e.localParticipant.id,p_=e=>e.localParticipant.displayName,h_=e=>e.localParticipant.stickyReaction,f_=Pg(l_,r_,(e,t)=>{const r={id:e.id,clientId:e.id,breakoutGroup:e.breakoutGroup,displayName:e.displayName,stream:t,isLocalClient:!0,isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled};return d_.includes(e.roleName)?null:r});function m_({assignments:e,groups:t,startedAt:r,initiatedBy:n,breakoutStartedAt:i,breakoutEndedAt:s,breakoutNotification:o,breakoutTimerDuration:a,autoMoveToGroup:c,moveToGroupGracePeriod:d,autoMoveToMain:l,moveToMainGracePeriod:u,enforceAssignment:p,breakoutTimerSetting:h}={}){return{assignments:e||null,groups:t||null,startedAt:r?new Date(r):null,initiatedBy:n,breakoutStartedAt:i||null,breakoutEndedAt:s||null,breakoutNotification:o||null,breakoutTimerDuration:a||1800,autoMoveToGroup:c||!1,moveToGroupGracePeriod:d||10,autoMoveToMain:l||!1,moveToMainGracePeriod:u||30,enforceAssignment:p||!1,breakoutTimerSetting:h||!1}}const g_=uv({name:"breakout",initialState:Object.assign(Object.assign({},m_()),{groupId:null}),reducers:{},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{breakout:r}=t.payload||{};return r?Object.assign(Object.assign({},e),m_(r)):e}),e.addCase(Ub.breakoutSessionUpdated,(e,t)=>Object.assign(Object.assign({},e),m_(t.payload))),e.addCase(Ub.breakoutGroupJoined,(e,t)=>{var r;return(null===(r=t.meta)||void 0===r?void 0:r.localParticipantId)!==t.payload.clientId?e:Object.assign(Object.assign({},e),{groupId:t.payload.group})})}}),v_=e=>(t,r)=>{const n=r(),{socket:i}=wy(n);null==i||i.emit("join_breakout_group",{group:e.group})},b_=e=>e.breakout,y_=e=>!!e.breakout.startedAt,__=e=>e.breakout.assignments,w_=Pg(b_,e=>e.localParticipant.breakoutGroup,(e,t)=>e.groupId||t||""),S_=Pg(b_,w_,(e,t)=>{var r;const n=null===(r=e.groups)||void 0===r?void 0:r[t];return n?{id:t,name:n}:null});Eb({actionCreator:Ub.breakoutMoveToGroup,effect:(e,{dispatch:t,getState:r})=>{const n=r(),i=l_(n).breakoutGroupAssigned;i&&t(v_({group:i}))}}),Eb({actionCreator:Ub.breakoutMoveToMain,effect:(e,{dispatch:t})=>{t(v_({group:""}))}}),Eb({actionCreator:Ub.breakoutSessionUpdated,effect:({payload:e},{dispatch:t,getState:r})=>{var n;const i=r(),s=b_(i).autoMoveToMain;!1===(null===(n=e.initiatedBy)||void 0===n?void 0:n.active)&&(s||t(v_({group:""})))}});const C_=uv({name:"chat",initialState:{chatMessages:[]},reducers:{},extraReducers(e){e.addCase(Ub.chatMessage,(e,t)=>{const r={senderId:t.payload.senderId,timestamp:t.payload.timestamp,text:t.payload.text};return Object.assign(Object.assign({},e),{chatMessages:[...e.chatMessages,r]})})}}),k_=ry(e=>(t,r)=>{const n=r(),i=wy(n).socket,s=w_(n);null==i||i.emit("chat_message",Object.assign(Object.assign({text:e.text},s&&{breakoutGroup:s}),e.isBroadcast&&{broadcast:!0}))}),T_=uv({name:"cloudRecording",initialState:{isInitiator:!1,isRecording:!1,error:null,startedAt:void 0},reducers:{recordingRequestStarted:e=>Object.assign(Object.assign({},e),{isInitiator:!0,status:"requested"})},extraReducers:e=>{e.addCase(Ub.cloudRecordingStopped,e=>Object.assign(Object.assign({},e),{isInitiator:!1,isRecording:!1,status:void 0})),e.addCase(Ub.cloudRecordingStarted,(e,t)=>{const{payload:r}=t;return r.error?Object.assign(Object.assign({},e),{isInitiator:!1,isRecording:!1,status:"error",error:r.error}):e}),e.addCase(Ub.newClient,(e,{payload:t})=>{var r;const{client:n}=t;return"recorder"===(null===(r=n.role)||void 0===r?void 0:r.roleName)?Object.assign(Object.assign({},e),{isRecording:!0,status:"recording",startedAt:n.startedCloudRecordingAt?new Date(n.startedCloudRecordingAt).getTime():(new Date).getTime()}):e})}}),{recordingRequestStarted:P_}=T_.actions,R_=ry(()=>(e,t)=>{const r=t(),n=wy(r).socket,i=O_(r);i&&["recording","requested"].includes(i)||(null==n||n.emit("start_recording",{recording:"cloud"}),e(P_()))}),E_=ry(()=>(e,t)=>{const r=t(),n=wy(r).socket;null==n||n.emit("stop_recording")}),O_=e=>e.cloudRecording.status,x_=e=>e.cloudRecording.isRecording,I_=e=>e.cloudRecording.isInitiator,D_=e=>e.roomConnection.status;function M_(e){return Mg(`rtcConnection/event/${e}`)}const j_={rtcManagerCreated:M_("rtcManagerCreated"),rtcManagerDestroyed:M_("rtcManagerDestroyed"),streamAdded:M_("streamAdded"),clientConnectionStatusChanged:M_("clientConnectionStatusChanged")};function A_(e,t=!1){const{streams:r,role:n,breakoutGroup:i}=e,s=sy(e,["streams","role","breakoutGroup"]);return Object.assign(Object.assign({},s),{stream:null,streams:r.map(e=>({id:e,state:t?"new_accept":"to_accept"})),isLocalParticipant:!1,roleName:(null==n?void 0:n.roleName)||"none",presentationStream:null,breakoutGroup:i||null,newJoiner:t})}function L_(e,t){const r=e.remoteParticipants.findIndex(e=>e.id===t);return{index:r,participant:e.remoteParticipants[r]}}function N_(e,t,r){const{participant:n,index:i}=L_(e,t);return n?Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.slice(0,i),Object.assign(Object.assign({},n),r),...e.remoteParticipants.slice(i+1)]}):(console.error(`Did not find client for update ${t}`),e)}function F_(e,t,r,n){const{participant:i}=L_(e,t);if(!i)return console.error(`No client ${t} found to update stream ${r} ${n}`),e;const s=i.streams.findIndex(e=>e.id===r),o=[...i.streams];return o[s]=Object.assign(Object.assign({},o[s]),{state:n}),N_(e,t,{streams:o})}function B_(e,t,r){const{participant:n}=L_(e,t);return!n||n.streams.find(e=>e.id===r)?(console.warn(`No participant ${t} or stream ${r} already exists`),e):N_(e,t,{streams:[...n.streams,{id:r,state:"to_accept"}]})}const z_=uv({name:"remoteParticipants",initialState:{remoteParticipants:[]},reducers:{streamStatusUpdated:(e,t)=>{let r=e;for(const{clientId:e,streamId:n,state:i}of t.payload)r=F_(r,e,n,i);return r},participantStreamAdded:(e,t)=>{const{clientId:r,stream:n}=t.payload;return N_(e,r,{stream:n})},participantStreamIdAdded:(e,t)=>{const{clientId:r,streamId:n}=t.payload;return B_(e,r,n)}},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r,selfId:n}=t.payload||{};return(null==r?void 0:r.clients)?Object.assign(Object.assign({},e),{remoteParticipants:r.clients.filter(e=>e.id!==n).map(e=>A_(e))}):e}),e.addCase(j_.streamAdded,(e,t)=>function(e,t){const{clientId:r,stream:n,streamType:i}=t;let{streamId:s}=t;const{participant:o}=L_(e,r);if(!o)return console.error(`Did not find client ${r} for adding stream`),e;const a=e.remoteParticipants;s||(s=n.id);const c=a.find(e=>e.id===r);if(!c)return e;const d=c.streams.find(e=>e.id===s);return c.stream&&(c.stream.id===s||c.stream.inboundId===s)||!c.stream&&"webcam"===i||!c.stream&&!i&&!d?N_(e,r,{stream:n}):N_(e,r,{presentationStream:n})}(e,t.payload)),e.addCase(Ub.newClient,(e,t)=>{const{client:r}=t.payload;return function(e,t){const{participant:r}=L_(e,t.id);return r?(console.warn(`Client already existing ${t.id}. Ignoring`),e):Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t]})}(e,A_(r,!0))}),e.addCase(Ub.clientLeft,(e,t)=>{const{clientId:r}=t.payload;return function(e,t){return Object.assign(Object.assign({},e),{remoteParticipants:e.remoteParticipants.filter(e=>e.id!==t)})}(e,r)}),e.addCase(Ub.audioEnabled,(e,t)=>{const{clientId:r,isAudioEnabled:n}=t.payload;return N_(e,r,{isAudioEnabled:n})}),e.addCase(Ub.videoEnabled,(e,t)=>{const{clientId:r,isVideoEnabled:n}=t.payload;return N_(e,r,{isVideoEnabled:n})}),e.addCase(Ub.clientMetadataReceived,(e,t)=>{const{error:r,payload:n}=t.payload;if(r||!n)return console.warn(r||"Client metadata error received"),e;const{clientId:i,displayName:s,stickyReaction:o}=n;return N_(e,i,{displayName:s,stickyReaction:o})}),e.addCase(Ub.breakoutGroupJoined,(e,t)=>{const{clientId:r,group:n}=t.payload;return N_(e,r,{breakoutGroup:n||null})}),e.addCase(Ub.screenshareStarted,(e,t)=>{const{clientId:r,streamId:n}=t.payload;return B_(e,r,n)}),e.addCase(Ub.screenshareStopped,(e,t)=>{const{clientId:r,streamId:n}=t.payload;return function(e,t,r){var n,i;const{participant:s}=L_(e,t);if(!s)return console.error(`No participant ${t} found to remove stream ${r}`),e;const o=s.stream&&s.stream.id,a=(null===(n=s.presentationStream)||void 0===n?void 0:n.inboundId)||(null===(i=s.presentationStream)||void 0===i?void 0:i.id),c=s.streams.findIndex(e=>e.id===r);return N_(e,t,Object.assign(Object.assign({streams:s.streams.filter((e,t)=>t!==c)},o===r&&{stream:null}),a===r&&{presentationStream:null}))}(e,r,n)})}}),{participantStreamAdded:U_,participantStreamIdAdded:V_,streamStatusUpdated:$_}=z_.actions,G_=iy(e=>Jb(e),e=>(t,r)=>{const n=r(),i=Xb(n);if(e.enable&&!i)return void console.warn("Not authorized to perform this action");const s=wy(n).socket;null==s||s.emit("request_audio_enable",e)}),q_=iy(e=>Kb(e),e=>(t,r)=>{const n=r(),i=wy(n).socket;null==i||i.emit("request_video_enable",e)}),H_=e=>e.remoteParticipants.remoteParticipants,W_=Pg(H_,e=>e.filter(e=>!d_.includes(e.roleName))),J_=Pg(H_,e=>e.length+1);Pg(W_,l_,(e,t)=>d_.includes(t.roleName)?e.length:e.length+1);const K_=uv({name:"localScreenshare",initialState:{status:"inactive",stream:null,error:null},reducers:{stopScreenshare:(e,t)=>Object.assign(Object.assign({},e),{status:"inactive",stream:null})},extraReducers:e=>{e.addCase(Y_.pending,e=>Object.assign(Object.assign({},e),{status:"starting"})),e.addCase(Y_.fulfilled,(e,{payload:{stream:t}})=>Object.assign(Object.assign({},e),{status:"active",stream:t})),e.addCase(Y_.rejected,(e,{payload:t})=>Object.assign(Object.assign({},e),{error:t,status:"inactive",stream:null}))}}),{stopScreenshare:Q_}=K_.actions,Y_=ny("localScreenshare/doStartScreenshare",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{dispatch:t,getState:r,rejectWithValue:n}){var i;try{const e=r(),n=Z_(e);if(n)return{stream:n};const s=yield navigator.mediaDevices.getDisplayMedia(),o=()=>{t(X_())};return"oninactive"in s?s.addEventListener("inactive",o):null===(i=s.getVideoTracks()[0])||void 0===i||i.addEventListener("ended",o),{stream:s}}catch(e){return n(e)}})),X_=ry(()=>(e,t)=>{const r=t(),n=Z_(r);n&&(n.getTracks().forEach(e=>e.stop()),e(Q_({stream:n})))}),Z_=e=>e.localScreenshare.stream;function ew(e){return"streamer"===e.roleName}function tw(e){return"recorder"===e.roleName}Eb({actionCreator:Ly,effect:(e,{getState:t})=>{const r=t(),n=Z_(r);n&&(null==n||n.getTracks().forEach(e=>{e.stop()}))}});const rw=uv({name:"room",initialState:{isLocked:!1},reducers:{},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return"room_locked"===t.payload.error?Object.assign(Object.assign({},e),{isLocked:Boolean(t.payload.isLocked)}):e;const{room:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r.isLocked)})}),e.addCase(Ub.roomLocked,(e,t)=>{const{isLocked:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r)})})}}),nw=ty(e=>Wb(e),e=>(t,r)=>{const n=r(),{socket:i}=wy(n);null==i||i.emit("set_lock",{locked:e.locked})}),iw=ty(e=>Qb(e),e=>(t,r)=>{const n=r(),{socket:i}=wy(n);null==i||i.emit("kick_client",{clientId:e.clientId,reasonId:"kick"})}),sw=ty(e=>Yb(e),e=>(t,r)=>{const n=r(),i=H_(n).map(e=>e.id);if(i.length){const{socket:e}=wy(n);null==e||e.emit("kick_client",{clientIds:i,reasonId:"end-meeting"})}e.stayBehind||t(Db())}),ow=Pg(Z_,l_,W_,(e,t,r)=>{const n=[];e&&n.push({id:e.id||"local-screenshare",participantId:"local",hasAudioTrack:e.getTracks().some(e=>"audio"===e.kind),breakoutGroup:t.breakoutGroup,stream:e,isLocal:!0});for(const e of r)e.presentationStream&&n.push({id:e.presentationStream.id||`pres-${e.id}`,participantId:e.id,hasAudioTrack:e.presentationStream.getTracks().some(e=>"audio"===e.kind),breakoutGroup:e.breakoutGroup,stream:e.presentationStream,isLocal:!1});return n}),aw=Pg(Z_,l_,W_,w_,__,(e,t,r,n,i)=>{const s=[];if(e){const r=!!e.getAudioTracks().length;s.push({clientId:t.id,displayName:"Your screenshare",id:"local-screenshare",isAudioEnabled:r,isLocalClient:!0,isPresentation:!0,isVideoEnabled:!0,stream:e,breakoutGroup:n||""})}for(const e of r){if(ew(e)||tw(e))continue;const{presentationStream:t}=e,r=sy(e,["presentationStream"]),n=e.displayName||"Guest",o=t&&t.active,a="pres-"+e.id,c=e.stream&&e.stream.active,d=e.isVideoEnabled;s.push(Object.assign(Object.assign(Object.assign({},r),{breakoutGroupAssigned:(null==i?void 0:i[e.deviceId])||"",clientId:e.id,displayName:n,hasActivePresentation:!!o}),e.isVideoEnabled?{isVideoEnabled:d}:{})),o&&s.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,stream:e.presentationStream,displayName:`Screenshare (${n})`,id:a,isPresentation:!0,isVideoEnabled:!0}),c&&{isRecording:null}))}return s}),cw=Pg(f_,aw,(e,t)=>[...e?[e]:[],...t]),dw=Pg(cw,y_,w_,(e,t,r)=>t&&r?e.filter(e=>e.isLocalClient||e.breakoutGroup===(r||"")||e.breakoutGroupAssigned&&e.breakoutGroupAssigned===r):e),lw=Pg(cw,y_,e=>e.breakout.groups,(e,t,r)=>{if(!t||!r)return[];return[{clients:e.filter(e=>!e.breakoutGroup||""===e.breakoutGroup),group:{id:"",name:""}},...Object.entries(r).map(([t,r])=>({clients:e.filter(e=>!e.isPresentation&&e.breakoutGroup===t),group:{id:t,name:r}}))]});function uw({isPresentation:e,stream:t}){var r,n;return e?null!==(n=null!==(r=null==t?void 0:t.outboundId)&&void 0!==r?r:null==t?void 0:t.inboundId)&&void 0!==n?n:null==t?void 0:t.id:"0"}function pw(e,t){const r=e.find(e=>e.clientId===t.clientId&&e.streamId===t.streamId);return r?e:e.concat(t)}const hw=uv({name:"spotlights",initialState:{sorted:[]},reducers:{addSpotlight(e,t){const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:pw(e.sorted,{clientId:r,streamId:n})})},removeSpotlight(e,t){const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>!(e.clientId===r&&e.streamId===n))})}},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{var r;if("error"in t.payload)return e;const{room:n}=t.payload||{};return n?Object.assign(Object.assign({},e),{sorted:null!==(r=n.spotlights)&&void 0!==r?r:e.sorted}):e}),e.addCase(Ub.spotlightAdded,(e,t)=>{const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:pw(e.sorted,{clientId:r,streamId:n})})}),e.addCase(Ub.spotlightRemoved,(e,t)=>{const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>!(e.clientId===r&&e.streamId===n))})}),e.addMatcher(Xg(Ub.clientKicked,Ub.clientLeft),(e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>e.clientId!==r)})})}}),{addSpotlight:fw,removeSpotlight:mw}=hw.actions,gw=ty(e=>Zb(e),({id:e})=>(t,r)=>{const n=r(),i=cw(n).find(t=>t.clientId===e);if(!i)return;const{socket:s}=wy(n),o=uw(i),a={clientId:i.id,streamId:null!=o?o:"0"};null==s||s.emit("add_spotlight",a)}),vw=ty(e=>Zb(e),({id:e})=>(t,r)=>{const n=r(),i=cw(n).find(t=>t.clientId===e);if(!i)return;const{socket:s}=wy(n),o=uw(i),a={clientId:i.id,streamId:null!=o?o:"0"};null==s||s.emit("remove_spotlight",a)}),bw=e=>e.spotlights.sorted;Pg(l_,bw,(e,t)=>function({spotlights:e,isPresentation:t,clientId:r,stream:n}){return!!e.find(e=>{const i=uw({isPresentation:t,stream:n});return e.clientId===r&&e.streamId===i})}({clientId:e.id,stream:e.stream,spotlights:t}));const yw=Pg(cw,bw,(e,t)=>function(e,t){return e.reduce((e,r)=>{const n=t.find(e=>r.clientId===e.clientId&&r.streamId===uw(e));return n&&!e.includes(n)&&e.push(n),e},[])}(t,e));Eb({actionCreator:Y_.fulfilled,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:n}=e,i=t(),s=l_(i);s&&r(fw({clientId:s.id,streamId:n.id}))}}),Eb({actionCreator:Q_,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:n}=e,i=t(),s=l_(i);s&&r(mw({clientId:s.id,streamId:n.id}))}});const _w=e=>({emit:(t,r)=>{"rtc_manager_created"===t?e(Aw(r)):"stream_added"===t?e(j_.streamAdded(r)):"rtc_manager_destroyed"===t?e(Rw()):"client_connection_status_changed"===t&&e(j_.clientConnectionStatusChanged(r))}}),ww={dispatcherCreated:!1,error:null,isCreatingDispatcher:!1,reportedStreamResolutions:{},rtcManager:null,rtcManagerDispatcher:null,rtcManagerInitialized:!1,status:"inactive",isAcceptingStreams:!1},Sw=uv({name:"rtcConnection",initialState:ww,reducers:{isAcceptingStreams:(e,t)=>Object.assign(Object.assign({},e),{isAcceptingStreams:t.payload}),resolutionReported:(e,t)=>{const{streamId:r,width:n,height:i}=t.payload;return Object.assign(Object.assign({},e),{reportedStreamResolutions:Object.assign(Object.assign({},e.reportedStreamResolutions),{[r]:{width:n,height:i}})})},rtcDisconnected:()=>Object.assign({},ww),rtcDispatcherCreated:(e,t)=>Object.assign(Object.assign({},e),{dispatcherCreated:!0,rtcManagerDispatcher:t.payload}),rtcManagerCreated:(e,t)=>Object.assign(Object.assign({},e),{rtcManager:t.payload,status:"ready"}),rtcManagerDestroyed:e=>Object.assign(Object.assign({},e),{rtcManager:null}),rtcManagerInitialized:e=>Object.assign(Object.assign({},e),{rtcManagerInitialized:!0}),rtcClientConnectionStatusChanged:{reducer:e=>e,prepare:e=>({payload:{},meta:{localParticipantId:e.localParticipantId}})}},extraReducers:e=>{e.addCase(vy,e=>Object.assign(Object.assign({},e),{status:"reconnecting"})),e.addCase(Ub.roomJoined,(e,t)=>"error"in t.payload?e:Object.assign(Object.assign({},e),{status:"reconnecting"===e.status?"ready":e.status}))}}),{resolutionReported:Cw,rtcDispatcherCreated:kw,rtcDisconnected:Tw,rtcManagerCreated:Pw,rtcManagerDestroyed:Rw,rtcManagerInitialized:Ew,isAcceptingStreams:Ow,rtcClientConnectionStatusChanged:xw}=Sw.actions,Iw=()=>(e,t)=>{const r=t(),n=wy(r).socket,i=Nw(r).rtcManagerDispatcher,s=Ky(r),o=Qy(r),a=(e=>e.app.isNodeSdk)(r);if(i||!n)return;const c={getMediaConstraints:()=>({audio:o,video:s}),deferrable(e){const r=W_(t()).find(t=>t.id===e);return function({client:e,breakoutCurrentId:t}){return!(!e||(t||!e.breakoutGroup)&&(e.isAudioEnabled||e.isVideoEnabled))}({client:r,breakoutCurrentId:w_(t())||""})}},d=new fp({emitter:_w(e),serverSocket:n,webrtcProvider:c,features:{isNodeSdk:a,lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,sfuVp9On:!1,h264On:!1,simulcastScreenshareOn:!1}});e(kw(d))},Dw=()=>(e,t)=>{const{rtcManager:r}=Nw(t());r&&r.disconnectAll(),e(Tw())},Mw=e=>(t,r)=>{var n;t(Ow(!0));const i=r(),s=Nw(i).rtcManager,o=H_(i);if(!s)throw new Error("No rtc manager");const a=y_(i),c=null===(n=s.shouldAcceptStreamsFromBothSides)||void 0===n?void 0:n.call(s),d=[];for(const{clientId:t,streamId:r,state:n}of e){const e=o.find(e=>e.id===t);if(e){if("to_accept"===n||"new_accept"===n&&c||"old_accept"===n&&!c)s.acceptNewStream({streamId:"0"===r?t:r,clientId:t,shouldAddLocalVideo:"0"===r,activeBreakout:a});else if("new_accept"===n||"old_accept"===n);else if("to_unaccept"===n)null==s||s.disconnect("0"===r?t:r,a);else if("done_accept"!==n)continue;d.push({clientId:t,streamId:r,state:n.replace(/to_|new_|old_/,"done_")})}}t($_(d)),t(Ow(!1))},jw=({streamId:e,width:t,height:r})=>(n,i)=>{const{reportedStreamResolutions:s,rtcManager:o}=Nw(i()),a=r_(i());if(!o||(null==a?void 0:a.id)===e)return;const c=s[e];c&&c.width===t&&c.height===r||o.updateStreamResolution(e,null,{width:t||1,height:r||1}),n(Cw({streamId:e,width:t,height:r}))},Aw=e=>t=>{const{rtcManager:r}=e;t(Pw(r))},Lw=()=>(e,t)=>{const r=r_(t()),n=Nw(t()).rtcManager,i=Ky(t()),s=Qy(t());r&&n&&n.addNewStream("0",r,!s,!i),e(Ew())},Nw=e=>e.rtcConnection,Fw=e=>e.rtcConnection.rtcManagerInitialized,Bw=e=>e.rtcConnection.rtcManager,zw=e=>e.rtcConnection.status;Eb({actionCreator:Uy.fulfilled,effect:({payload:e},{getState:t})=>{const{replacedTracks:r}=e,{rtcManager:n}=Nw(t()),i=r_(t());null==r||r.forEach(e=>{((e,t)=>{const r=null==i?void 0:i.getTracks().find(t=>t.kind===e);r&&(null==n||n.replaceTrack(t,r))})(e.kind,e)})}}),Eb({actionCreator:Y_.fulfilled,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:n}=Nw(t());null==n||n.addNewStream(r.id,r,!1,!0)}}),Eb({actionCreator:Db,effect:(e,{getState:t})=>{const r=Bw(t());null==r||r.rtcStatsDisconnect()}}),Eb({actionCreator:Q_,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:n}=Nw(t());null==n||n.removeStream(r.id,r,null)}}),Eb({actionCreator:$y.fulfilled,effect:({payload:e},{getState:t})=>{var r;const n=r_(t()),{rtcManager:i}=Nw(t());if(n&&i){const t=(e,t)=>{const r=n.getTracks().find(t=>t.kind===e);return r&&i.replaceTrack(t,r)};null===(r=null==e?void 0:e.replacedTracks)||void 0===r||r.forEach(e=>{t(e.kind,e)})}}}),Eb({actionCreator:j_.clientConnectionStatusChanged,effect:(e,{dispatch:t,getState:r})=>{const n=l_(r());t(xw({localParticipantId:n.id}))}}),Eb({actionCreator:Gy.fulfilled,effect:({payload:e},{getState:t})=>{const{rtcManager:r,rtcManagerInitialized:n}=Nw(t());if(!r||!n)return;const i=Ky(t()),s=Qy(t()),{stream:o}=e;o&&r.addNewStream("0",e.stream,!s,!i)}});Ob([Pg(zw,jb,e=>e.rtcConnection.dispatcherCreated,e=>e.rtcConnection.isCreatingDispatcher,ky,(e,t,r,n,i)=>!(!t||"inactive"!==e||r||n||!i))],({dispatch:e},t)=>{t&&e(Iw())});const Uw=Pg(Bw,Fw,t_,(e,t,r)=>!("started"!==r||!e||t));Ob([Uw],({dispatch:e},t)=>{t&&e(Lw())});Ob([Pg(zw,jb,(e,t)=>!t&&!["inactive","disconnected"].includes(e))],({dispatch:e},t)=>{t&&e(Dw())});const Vw=Pg(zw,H_,w_,bw,e=>e.app.ignoreBreakoutGroups,(e,t,r,n,i)=>{if("ready"!==e)return[];const s=[];for(const e of t){const{streams:t,id:o,newJoiner:a}=e,c=n.find(t=>t.clientId===e.id&&"0"===t.streamId);for(let n=0;n<t.length;n++){let d=t[n].id,l=t[n].state;if((null==t?void 0:t.length)>1&&"0"===t[1].id&&(0===n?(d=t[1].id,l=t[1].state):1===n&&(d=t[0].id,l=t[0].state)),!e.breakoutGroup&&!r||e.breakoutGroup===r||""===e.breakoutGroup&&c||i){if("done_accept"===l)continue;s.push({clientId:o,streamId:d,state:(a&&"0"===d?"new":"to")+"_accept"})}else{if("done_unaccept"===l)continue;s.push({clientId:o,streamId:d,state:"to_unaccept"})}}}return s});Ob([Vw,e=>e.rtcConnection.isAcceptingStreams],({dispatch:e},t,r)=>{0<t.length&&!r&&e(Mw(t))});const $w={running:!1},Gw=uv({name:"connectionMonitor",initialState:$w,reducers:{connectionMonitorStarted:(e,t)=>Object.assign(Object.assign({},e),{running:!0,stopCallbackFunction:t.payload.stopIssueSubscription}),connectionMonitorStopped:()=>Object.assign({},$w)}}),{connectionMonitorStarted:qw,connectionMonitorStopped:Hw}=Gw.actions,Ww=()=>(e,t)=>{var r;r=()=>{const e=t(),r=cw(e).map(e=>{var t,r;return{id:e.id,clientId:e.clientId,isLocalClient:e.isLocalClient,audio:{enabled:e.isAudioEnabled,track:null===(t=e.stream)||void 0===t?void 0:t.getAudioTracks()[0]},video:{enabled:e.isVideoEnabled,track:null===(r=e.stream)||void 0===r?void 0:r.getVideoTracks()[0]},isPresentation:e.isPresentation}});return r},ml.getClients=r;const n=Ep({onUpdatedIssues:e=>{var r;const n=t(),i=Bw(n);if(!i)return;let s=0,o=0,a=0,c=0;Object.entries(e.aggregated.metrics).forEach(([e,t])=>{/loc.*packetloss/.test(e)&&(s=Math.max(s,t.curMax)),/rem.*packetloss/.test(e)&&(o=Math.max(o,t.curMax)),/loc.*bitrate/.test(e)&&(a+=t.curSum),/rem.*bitrate/.test(e)&&(c+=t.curSum)}),i.sendStatsCustomEvent("insightsStats",{ls:Math.round(1e3*s)/1e3,lr:Math.round(1e3*o)/1e3,bs:Math.round(a),br:Math.round(c),cpu:null===(r=e.aggregated.metrics["global-cpu-pressure"])||void 0===r?void 0:r.curSum,_time:Date.now()})}});e(qw({stopIssueSubscription:n.stop}))},Jw=()=>(e,t)=>{const r=t(),n=Qw(r);n&&n(),e(Hw())},Kw=e=>e.connectionMonitor.running,Qw=e=>e.connectionMonitor.stopCallbackFunction,Yw=Pg(D_,Kw,(e,t)=>!t&&"connected"===e),Xw=Pg(D_,Kw,(e,t)=>!(!t||!["kicked","left"].includes(e)));Ob([Yw],({dispatch:e},t)=>{t&&e(Ww())}),Ob([Xw],({dispatch:e},t)=>{t&&e(Jw())});const Zw=uv({name:"localParticipant",initialState:{displayName:"",id:"",breakoutGroup:null,breakoutGroupAssigned:"",isAudioEnabled:!0,isVideoEnabled:!0,isLocalParticipant:!0,stream:void 0,isScreenSharing:!1,roleName:"none",clientClaim:void 0,stickyReaction:void 0,isDialIn:!1},reducers:{setDisplayName:(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}),setBreakoutGroupAssigned:(e,t)=>Object.assign(Object.assign({},e),{breakoutGroupAssigned:t.payload.breakoutGroupAssigned})},extraReducers:e=>{e.addCase(Mb,(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName})),e.addCase(rS.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isAudioEnabled:t.payload})),e.addCase(nS.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isVideoEnabled:t.payload})),e.addCase(iS.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{stickyReaction:t.payload})),e.addCase(Ub.roomJoined,(e,t)=>{var r;if("error"in t.payload)return"room_locked"===t.payload.error?Object.assign(Object.assign({},e),{id:t.payload.selfId}):e;const{room:n,selfId:i,clientClaim:s}=t.payload||{},o=n.clients.find(e=>e.id===i);return Object.assign(Object.assign({},e),{id:i,roleName:(null===(r=null==o?void 0:o.role)||void 0===r?void 0:r.roleName)||"none",clientClaim:s,breakoutGroup:(null==o?void 0:o.breakoutGroup)||null})}),e.addCase(Ub.breakoutGroupJoined,(e,t)=>{var r,n;return(null===(r=t.payload)||void 0===r?void 0:r.clientId)!==e.id?e:Object.assign(Object.assign({},e),{breakoutGroup:null===(n=t.payload)||void 0===n?void 0:n.group})})}}),{setDisplayName:eS,setBreakoutGroupAssigned:tS}=Zw.actions,rS=ny("localParticipant/doEnableAudio",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{dispatch:t,getState:r}){const n=r(),i=wy(n).socket;return null==i||i.emit("enable_audio",{enabled:e.enabled}),e.enabled&&t(iS({enabled:!1})),e.enabled})),nS=ny("localParticipant/doEnableVideo",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t}){const r=t(),n=wy(r).socket;return null==n||n.emit("enable_video",{enabled:e.enabled}),e.enabled})),iS=ny("localParticipant/doSetLocalStickyReaction",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{getState:t,rejectWithValue:r}){var n;const i=t(),s=h_(i),o=Boolean(s),a=null!==(n=e.enabled)&&void 0!==n?n:!o;if(a===o)return r(s);return a?{reaction:"✋",timestamp:(new Date).toISOString()}:null})),sS=ry(()=>(e,t)=>{const r=t(),n=wy(r).socket,i={displayName:p_(r),stickyReaction:h_(r)};null==n||n.emit("send_client_metadata",{type:"UserData",payload:i})});Eb({actionCreator:Iy,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:n}=e,{isVideoEnabled:i}=l_(r());"connected"===D_(r())&&t(nS({enabled:n||!i}))}}),Eb({actionCreator:Dy,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:n}=e,{isAudioEnabled:i}=l_(r());"connected"===D_(r())&&t(rS({enabled:n||!i}))}}),Ob([p_,h_,D_,e=>e.app.isAssistant],({dispatch:e},t,r,n,i)=>{"connected"!==n||i||e(sS())}),Ob([__,ly,l_],({dispatch:e},t,r,n)=>{const i=(null==t?void 0:t[r||""])||"";n.breakoutGroupAssigned!==i&&e(tS({breakoutGroupAssigned:i}))});function oS(e){return Object.assign(Object.assign({},e),{timestamp:Date.now()})}const aS=uv({name:"notifications",initialState:{emitter:new Ro,events:[]},reducers:{addNotification:(e,t)=>Object.assign(Object.assign({},e),{events:[...e.events,Object.assign({},t.payload)]}),doClearNotifications:e=>Object.assign(Object.assign({},e),{events:[]})}}),{doClearNotifications:cS}=aS.actions,dS=e=>(t,r)=>{t(aS.actions.addNotification(e));const n=r(),i=lS(n);i.emit(e.type,e),i.emit("*",e)},lS=e=>e.notifications.emitter;Eb({actionCreator:Ub.chatMessage,effect:({payload:e},{dispatch:t,getState:r})=>{const n=r(),i=W_(n).find(({id:t})=>t===e.senderId);i?t(dS(oS({type:"chatMessageReceived",message:`${i.displayName} says: ${e.text}`,props:{client:i,chatMessage:{senderId:e.senderId,timestamp:e.timestamp,text:e.text}}}))):console.warn("Could not find remote client that sent chat message")}}),Eb({actionCreator:Ub.audioEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:n,requestedByClientId:i}=e,s=r(),o=W_(s).find(({id:e})=>e===i);o?t(dS(oS({type:n?"requestAudioEnable":"requestAudioDisable",message:n?`${o.displayName} has requested for you to speak`:`${o.displayName} has muted your microphone`,props:{client:o,enable:n}}))):console.warn("Could not find remote client that requested a local audio change")}}),Eb({actionCreator:Ub.videoEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:n,requestedByClientId:i}=e,s=r(),o=W_(s).find(({id:e})=>e===i);o?t(dS(oS({type:n?"requestVideoEnable":"requestVideoDisable",message:n?`${o.displayName} has requested for you to start video`:`${o.displayName} has stopped your video`,props:{client:o,enable:n}}))):console.warn("Could not find remote client that requested a local video change")}}),Eb({actionCreator:Ub.clientMetadataReceived,effect:(e,{dispatch:t,getOriginalState:r,getState:n})=>{var i;const{error:s,payload:o}=e.payload;if(s||!o)return;const{clientId:a,stickyReaction:c}=o,d=n();if(!Xb(d))return;const l=W_(d).find(({id:e})=>e===a);if(!l)return void console.warn("Could not find remote client that provided updated metadata");const u=r(),p=W_(u).find(({id:e})=>e===a);(c||(null==p?void 0:p.stickyReaction))&&(null==c?void 0:c.timestamp)!==(null===(i=null==p?void 0:p.stickyReaction)||void 0===i?void 0:i.timestamp)&&t(dS(oS({type:c?"remoteHandRaised":"remoteHandLowered",message:`${l.displayName} ${c?"raised":"lowered"} their hand`,props:{client:l,stickyReaction:c}})))}}),Ob([Cy],({dispatch:e,getState:t},r)=>{const n=t(),i=D_(n);["left","kicked"].includes(i)||("disconnected"===r?e(dS(oS({type:"signalTrouble",message:"Network connection lost. Trying to reconnect you...",props:{}}))):"connected"===r&&e(dS(oS({type:"signalOk",message:"Network connection available",props:{}}))))}),Eb({actionCreator:Ub.clientUnableToJoin,effect:(e,{dispatch:t})=>{var r;"room_full"===(null===(r=e.payload)||void 0===r?void 0:r.error)&&t(dS(oS({type:"clientUnableToJoinFullRoom",message:"Someone tried to join but the room is full and at capacity.",props:{}})))}});const uS=uv({name:"organization",initialState:{data:null,isFetching:!1,error:null},reducers:{},extraReducers:e=>{e.addCase(pS.pending,e=>Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(pS.fulfilled,(e,t)=>t.payload?Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}):Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(pS.rejected,e=>Object.assign(Object.assign({},e),{isFetching:!1,error:!0}))}}),pS=ey("organization/doOrganizationFetch",(e,t)=>oy(void 0,[e,t],void 0,function*(e,{extra:t,getState:r}){try{const e=r().app.roomUrl,n=yield t.services.fetchOrganizationFromRoomUrl(e||"");if(!n)throw new Error("Invalid room url");return n}catch(e){console.error(e)}})),hS=e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.organizationId};Ob([Pg(jb,e=>e.organization,dy,(e,t,r)=>!(!e||t.data||t.isFetching||t.error||r.isFetching))],({dispatch:e},t)=>{t&&e(pS())});const fS=uv({name:"roomConnection",initialState:{session:null,status:"ready",error:null},reducers:{connectionStatusChanged:(e,t)=>Object.assign(Object.assign({},e),{status:t.payload})},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{var r;if("error"in t.payload)return"room_locked"===t.payload.error&&t.payload.isLocked?Object.assign(Object.assign({},e),{status:"room_locked"}):Object.assign(Object.assign({},e),{status:"disconnected",error:t.payload.error});const{room:n}=t.payload;return Object.assign(Object.assign({},e),{status:"connected",session:null!==(r=n.session)&&void 0!==r?r:null})}),e.addCase(Ub.disconnect,e=>["kicked","left"].includes(e.status)?Object.assign({},e):Object.assign(Object.assign({},e),{status:"disconnected"})),e.addCase(Ub.newClient,(e,t)=>{var r,n;return Object.assign(Object.assign({},e),{session:null!==(n=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==n?n:null})}),e.addCase(Ub.roomSessionEnded,(e,t)=>{var r;return(null===(r=e.session)||void 0===r?void 0:r.id)!==t.payload.roomSessionId?e:Object.assign(Object.assign({},e),{session:null})}),e.addCase(Ub.clientKicked,e=>Object.assign(Object.assign({},e),{status:"kicked"})),e.addCase(Ub.roomLeft,e=>Object.assign(Object.assign({},e),{status:"left"})),e.addCase(vy,e=>Object.assign(Object.assign({},e),{status:"reconnecting"}))}}),{connectionStatusChanged:mS}=fS.actions,gS=()=>(e,t)=>{const r=t(),n=wy(r).socket,i=Lb(r),s=qb(r),o=Nb(r),a=Ab(r),c=Fb(r),d=Bb(r),l=hS(r);"room_locked"===D_(r)?(null==n||n.emit("knock_room",{avatarUrl:null,config:{isAudioEnabled:!0,isVideoEnabled:!0},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:a,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:i,userAgent:c,externalId:d}),e(mS("knocking"))):console.warn("Room is not locked, knock aborted")},vS=()=>(e,t)=>{const r=t(),n=wy(r).socket,i=Lb(r),s=qb(r),o=(e=>e.authorization.assistantKey)(r),a=Nb(r),c=Fb(r),d=Bb(r),l=Ab(r),u=hS(r),p=Ky(t()),h=Qy(t()),f=(e=>e.localParticipant.clientClaim)(t());null==n||n.emit("join_room",Object.assign({avatarUrl:null,config:{isAudioEnabled:h,isVideoEnabled:p},deviceCapabilities:{canScreenshare:!0},displayName:a,isCoLocated:!1,isDialIn:l,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:u,roomKey:s,assistantKey:o,roomName:i,userAgent:c,externalId:d},f&&{clientClaim:f})),e(mS("connecting"))};Ob([Pg([jb,hS,D_,Sy,t_,e=>e.roomConnection.error],(e,t,r,n,i,s)=>!(!(e&&"started"===i&&n&&t&&["ready","reconnecting","disconnected"].includes(r))||s))],({dispatch:e},t)=>{t&&e(vS())}),Eb({actionCreator:Ub.knockHandled,effect:({payload:e},{dispatch:t,getState:r})=>{const{clientId:n,resolution:i}=e,s=r();n===u_(s)&&("accepted"===i?(t(Gb(e.metadata.roomKey)),t(vS())):"rejected"===i&&t(mS("knock_rejected")))}}),Eb({actionCreator:Db,effect:(e,{dispatch:t,getState:r})=>{const n=r();if("connected"===D_(n)){const e=wy(n).socket;null==e||e.emit("leave_room"),t(mS("leaving"))}else _y()}});const bS={audioEnabled:{actions:[rS.fulfilled],rtcEventName:"audioEnabled",getValue:e=>Qy(e),getOutput:e=>({enabled:e})},videoEnabled:{actions:[nS.fulfilled],rtcEventName:"videoEnabled",getValue:e=>Ky(e),getOutput:e=>({enabled:e})},localStream:{actions:[Uy.fulfilled],rtcEventName:"localStream",getValue:e=>{var t;return null===(t=r_(e))||void 0===t?void 0:t.getTracks().map(e=>({id:e.id,kind:e.kind,label:e.label}))},getOutput:e=>({stream:e})},localScreenshareStream:{actions:[Y_.fulfilled],rtcEventName:"localScreenshareStream",getValue:e=>{var t;return null===(t=Z_(e))||void 0===t?void 0:t.getTracks().map(e=>({id:e.id,kind:e.kind,label:e.label}))},getOutput:e=>({tracks:e})},localScreenshareStreamStopped:{actions:[Q_],rtcEventName:"localScreenshareStream",getValue:()=>()=>null,getOutput:()=>({})},displayName:{actions:[eS],rtcEventName:"displayName",getValue:e=>{const t=p_(e),r=(e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.preferences})(e);return(null==r?void 0:r.hideInsightsDisplayNames)?"[[redacted]]":t},getOutput:e=>({displayName:e})},clientId:{actions:null,rtcEventName:"clientId",getValue:e=>u_(e),getOutput:e=>({clientId:e})},deviceId:{actions:null,rtcEventName:"deviceId",getValue:e=>ly(e),getOutput:e=>({deviceId:e})},externalId:{actions:null,rtcEventName:"externalId",getValue:e=>Bb(e),getOutput:e=>({externalId:e})},organizationId:{actions:null,rtcEventName:"organizationId",getValue:e=>hS(e),getOutput:e=>({organizationId:e})},signalConnectionStatus:{actions:null,rtcEventName:"signalConnectionStatus",getValue:e=>Cy(e),getOutput:e=>({status:e})},recording:{actions:[Ub.newClient],rtcEventName:"recording",getValue:e=>({local:!1,cloud:!(!x_(e)||!I_(e))}),getOutput:e=>e},roomSessionId:{actions:[Ub.newClient,Ub.roomJoined,Ub.roomSessionEnded,Ub.clientLeft],rtcEventName:"roomSessionId",getValue:e=>(e=>{var t;return null===(t=e.roomConnection.session)||void 0===t?void 0:t.id})(e),getOutput:e=>({roomSessionId:e})},rtcConnectionStatus:{actions:null,rtcEventName:"rtcConnectionStatus",getValue:e=>zw(e),getOutput:e=>({status:e})},userRole:{actions:null,rtcEventName:"userRole",getValue:e=>Hb(e),getOutput:e=>({userRole:e})}},yS=Object.values(bS).flatMap(({actions:e})=>{var t;return null!==(t=null==e?void 0:e.map(e=>e))&&void 0!==t?t:null}).filter(e=>null!==e),_S=e=>"object"==typeof e?JSON.stringify(e):e,wS=uv({name:"rtcAnalytics",initialState:{reportedValues:{}},reducers:{updateReportedValues:(e,t)=>Object.assign(Object.assign({},e),{reportedValues:Object.assign(Object.assign({},e.reportedValues),{[t.payload.rtcEventName]:t.payload.value})})}}),SS=()=>(e,t)=>{const r=t(),n=Nw(r).rtcManager;n&&(n.sendStatsCustomEvent("insightsStats",{_time:Date.now(),ls:0,lr:0,bs:0,br:0,cpu:0}),Object.values(bS).forEach(({rtcEventName:t,getValue:i,getOutput:s})=>{var o;const a=i(r),c=Object.assign(Object.assign({},s(a)),{_time:Date.now()}),d=_S(a);(null===(o=r.rtcAnalytics.reportedValues)||void 0===o?void 0:o[t])!==d&&(n.sendStatsCustomEvent(t,c),e(CS({rtcEventName:t,value:a})))}))},{updateReportedValues:CS}=wS.actions;Eb({matcher:Xg(...yS),effect:({type:e},{getState:t,dispatch:r})=>{var n;const i=t(),s=Nw(i).rtcManager;if(!s)return;const o=Object.values(bS).find(({actions:t})=>null==t?void 0:t.map(e=>e.type).includes(e));if(!o)return;const{getValue:a,getOutput:c,rtcEventName:d}=o,l=a(i),u=_S(l),p=Object.assign(Object.assign({},c(l)),{_time:Date.now()});(null===(n=i.rtcAnalytics.reportedValues)||void 0===n?void 0:n[d])!==u&&(s.sendStatsCustomEvent(d,p),r(CS({rtcEventName:d,value:l})))}}),Ob([Fw],({dispatch:e},t)=>{t&&e(SS())});const kS=uv({name:"streaming",initialState:{isStreaming:!1,error:null,startedAt:void 0},reducers:{doHandleStreamingStarted:e=>Object.assign(Object.assign({},e),{isStreaming:!0,error:null,startedAt:(new Date).getTime()}),doHandleStreamingStopped:e=>Object.assign(Object.assign({},e),{isStreaming:!1})}}),{doHandleStreamingStarted:TS,doHandleStreamingStopped:PS}=kS.actions,RS=uv({name:"waitingParticipants",initialState:{waitingParticipants:[]},reducers:{},extraReducers:e=>{e.addCase(Ub.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r}=t.payload;return r.knockers.length?Object.assign(Object.assign({},e),{waitingParticipants:r.knockers.map(e=>({id:e.clientId,displayName:e.displayName}))}):e}),e.addCase(Ub.roomKnocked,(e,t)=>{const{clientId:r,displayName:n}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:r,displayName:n}]})}),e.addCase(Ub.knockerLeft,(e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter(e=>e.id!==r)})})}}),ES=ry(e=>(t,r)=>{const{participantId:n}=e,i=r(),s=ky(i);null==s||s.emit("handle_knock",{action:"accept",clientId:n,response:{}})}),OS=ry(e=>(t,r)=>{const{participantId:n}=e,i=r(),s=ky(i);null==s||s.emit("handle_knock",{action:"reject",clientId:n,response:{}})}),xS=Cm({app:Ib.reducer,authorization:$b.reducer,breakout:g_.reducer,chat:C_.reducer,cloudRecording:T_.reducer,connectionMonitor:Gw.reducer,deviceCredentials:ay.reducer,localMedia:Py.reducer,localParticipant:Zw.reducer,localScreenshare:K_.reducer,notifications:aS.reducer,organization:uS.reducer,remoteParticipants:z_.reducer,room:rw.reducer,roomConnection:fS.reducer,rtcAnalytics:wS.reducer,rtcConnection:Sw.reducer,signalConnection:uy.reducer,spotlights:hw.reducer,streaming:kS.reducer,waitingParticipants:RS.reducer}),IS=(e,t)=>{var r;if(Mb.match(t)){const n={app:Object.assign(Object.assign({},Ib.getInitialState()),{initialConfig:null===(r=null==e?void 0:e.app)||void 0===r?void 0:r.initialConfig}),localMedia:Object.assign(Object.assign({},Py.getInitialState()),null==e?void 0:e.localMedia)};return xS(n,t)}return xS(e,t)},DS=Pg(cw,yw,J_,(e,t,r)=>({allClientViews:e,spotlightedParticipants:t,numParticipants:r}));class MS extends Ro{constructor(e){super(),this.stateSubscribers=new Set,this.store=e,this.previousState=this.getState(),this.setupEventBridge()}subscribe(e){return this.stateSubscribers.add(e),()=>this.stateSubscribers.delete(e)}setupEventBridge(){this.store.subscribe(()=>{const e=this.getState();e!==this.previousState&&(this.handleStateChanges(e,this.previousState),this.stateSubscribers.forEach(t=>t(e)),this.previousState=e)})}destroy(){this.stateSubscribers.clear(),this.removeAllListeners()}}class jS extends MS{constructor(e){super(e),this.clientViewSubscribers=new Set,this.spotlightedSubscribers=new Set,this.numberOfClientViewsSubscribers=new Set}handleStateChanges(e,t){e.allClientViews!==t.allClientViews&&(this.clientViewSubscribers.forEach(t=>t(e.allClientViews)),this.emit("grid:client-view-changed",e.allClientViews)),e.spotlightedParticipants!==t.spotlightedParticipants&&(this.spotlightedSubscribers.forEach(t=>t(e.spotlightedParticipants)),this.emit("grid:client-view-spotlights-changed",e.spotlightedParticipants)),e.numParticipants!==t.numParticipants&&(this.numberOfClientViewsSubscribers.forEach(t=>t(e.numParticipants)),this.emit("grid:number-of-client-views-changed",e.numParticipants))}getState(){return DS(this.store.getState())}subscribeClientViews(e){return this.clientViewSubscribers.add(e),()=>this.clientViewSubscribers.delete(e)}subscribeSpotlightedParticipants(e){return this.spotlightedSubscribers.add(e),()=>this.spotlightedSubscribers.delete(e)}subscribeNumberOfClientViews(e){return this.numberOfClientViewsSubscribers.add(e),()=>this.numberOfClientViewsSubscribers.delete(e)}spotlightParticipant(e){this.store.dispatch(gw({id:e}))}removeSpotlight(e){this.store.dispatch(vw({id:e}))}destroy(){super.destroy(),this.clientViewSubscribers.clear(),this.spotlightedSubscribers.clear(),this.numberOfClientViewsSubscribers.clear(),this.removeAllListeners()}}const AS=Pg(e=>e.localMedia.cameraDeviceError,o_,Wy,Jy,e=>e.localMedia.currentSpeakerDeviceId,e=>e.localMedia.isSettingCameraDevice,e=>e.localMedia.isSettingMicrophoneDevice,s_,r_,e=>e.localMedia.microphoneDeviceError,a_,c_,e=>e.localMedia.startError,(e,t,r,n,i,s,o,a,c,d,l,u,p)=>({cameraDeviceError:e,cameraDevices:t,currentCameraDeviceId:r,currentMicrophoneDeviceId:n,currentSpeakerDeviceId:i,isSettingCameraDevice:s,isSettingMicrophoneDevice:o,isStarting:a,localStream:c,microphoneDeviceError:d,microphoneDevices:l,speakerDevices:u,startError:p})),LS="local-media:current-speaker-changed";class NS extends MS{constructor(e){super(e),this.cameraDeviceErrorSubscribers=new Set,this.cameraDeviceSubscribers=new Set,this.isSettingCameraDeviceSubscribers=new Set,this.isSettingMicrophoneDeviceSubscribers=new Set,this.microphoneDeviceErrorSubscribers=new Set,this.microphoneDeviceSubscribers=new Set,this.speakerDeviceSubscribers=new Set,this.currentCameraSubscribers=new Set,this.currentMicrophoneSubscribers=new Set,this.currentSpeakerSubscribers=new Set,this.localMediaStartingSubscribers=new Set,this.localStreamSubscribers=new Set,this.localMediaStartErrorSubscribers=new Set}handleStateChanges(e,t){e.cameraDeviceError!==t.cameraDeviceError&&(this.cameraDeviceErrorSubscribers.forEach(t=>t(e.cameraDeviceError)),this.emit("local-media:camera-device-error-changed",e.cameraDeviceError)),e.cameraDevices!==t.cameraDevices&&(this.cameraDeviceSubscribers.forEach(t=>t(e.cameraDevices)),this.emit("local-media:camera-devices-changed",e.cameraDevices)),e.isSettingCameraDevice!==t.isSettingCameraDevice&&(this.isSettingCameraDeviceSubscribers.forEach(t=>t(e.isSettingCameraDevice)),this.emit("local-media:is-setting-camera-device",e.isSettingCameraDevice)),e.isSettingMicrophoneDevice!==t.isSettingMicrophoneDevice&&(this.isSettingMicrophoneDeviceSubscribers.forEach(t=>t(e.isSettingMicrophoneDevice)),this.emit("local-media:is-setting-microphone-device",e.isSettingMicrophoneDevice)),e.microphoneDeviceError!==t.microphoneDeviceError&&(this.microphoneDeviceErrorSubscribers.forEach(t=>t(e.microphoneDeviceError)),this.emit("local-media:microphone-device-error-changed",e.microphoneDeviceError)),e.microphoneDevices!==t.microphoneDevices&&(this.microphoneDeviceSubscribers.forEach(t=>t(e.microphoneDevices)),this.emit("local-media:microphone-devices-changed",e.microphoneDevices)),e.speakerDevices!==t.speakerDevices&&(this.speakerDeviceSubscribers.forEach(t=>t(e.speakerDevices)),this.emit("local-media:speaker-devices-changed",e.speakerDevices)),e.currentCameraDeviceId!==t.currentCameraDeviceId&&(this.currentCameraSubscribers.forEach(t=>t(e.currentCameraDeviceId)),this.emit("local-media:current-camera-changed",e.currentCameraDeviceId)),e.currentMicrophoneDeviceId!==t.currentMicrophoneDeviceId&&(this.currentMicrophoneSubscribers.forEach(t=>t(e.currentMicrophoneDeviceId)),this.emit("local-media:current-microphone-changed",e.currentMicrophoneDeviceId)),e.currentSpeakerDeviceId!==t.currentSpeakerDeviceId&&(this.currentSpeakerSubscribers.forEach(t=>t(e.currentSpeakerDeviceId)),this.emit(LS,e.currentSpeakerDeviceId)),e.isStarting!==t.isStarting&&(this.localMediaStartingSubscribers.forEach(t=>t(e.isStarting)),this.emit("local-media:starting",e.isStarting)),e.localStream!==t.localStream&&(this.localStreamSubscribers.forEach(t=>t(e.localStream)),this.emit("local-media:local-stream-changed",e.localStream)),e.startError!==t.startError&&(this.localMediaStartErrorSubscribers.forEach(t=>t(e.startError)),this.emit("local-media:start-error-changed",e.startError))}getState(){return AS(this.store.getState())}subscribeCameraDeviceError(e){return this.cameraDeviceErrorSubscribers.add(e),()=>this.cameraDeviceErrorSubscribers.delete(e)}subscribeCameraDevices(e){return this.cameraDeviceSubscribers.add(e),()=>this.cameraDeviceSubscribers.delete(e)}subscribeIsSettingCameraDevice(e){return this.isSettingCameraDeviceSubscribers.add(e),()=>this.isSettingCameraDeviceSubscribers.delete(e)}subscribeIsSettingMicrophoneDevice(e){return this.isSettingMicrophoneDeviceSubscribers.add(e),()=>this.isSettingMicrophoneDeviceSubscribers.delete(e)}subscribeMicrophoneDeviceError(e){return this.microphoneDeviceErrorSubscribers.add(e),()=>this.microphoneDeviceErrorSubscribers.delete(e)}subscribeMicrophoneDevices(e){return this.microphoneDeviceSubscribers.add(e),()=>this.microphoneDeviceSubscribers.delete(e)}subscribeSpeakerDevices(e){return this.speakerDeviceSubscribers.add(e),()=>this.speakerDeviceSubscribers.delete(e)}subscribeCurrentCamera(e){return this.currentCameraSubscribers.add(e),()=>this.currentCameraSubscribers.delete(e)}subscribeCurrentMicrophone(e){return this.currentMicrophoneSubscribers.add(e),()=>this.currentMicrophoneSubscribers.delete(e)}subscribeCurrentSpeaker(e){return this.currentSpeakerSubscribers.add(e),()=>this.currentSpeakerSubscribers.delete(e)}subscribeLocalMediaStarting(e){return this.localMediaStartingSubscribers.add(e),()=>this.localMediaStartingSubscribers.delete(e)}subscribeLocalStream(e){return this.localStreamSubscribers.add(e),()=>this.localStreamSubscribers.delete(e)}subscribeLocalMediaStartError(e){return this.localMediaStartErrorSubscribers.add(e),()=>this.localMediaStartErrorSubscribers.delete(e)}startMedia(){return oy(this,arguments,void 0,function*(e={audio:!0,video:!0}){return yield this.store.dispatch(Gy(e))})}toggleCamera(e){this.store.dispatch(Iy({enabled:e}))}toggleMicrophone(e){this.store.dispatch(Dy({enabled:e}))}toggleLowDataMode(e){this.store.dispatch(My({enabled:e}))}setCameraDevice(e){this.store.dispatch(Ey({deviceId:e}))}setMicrophoneDevice(e){this.store.dispatch(Oy({deviceId:e}))}setSpeakerDevice(e){this.store.dispatch(xy({deviceId:e}))}stopMedia(){return this.store.dispatch(qy())}destroy(){super.destroy(),this.stopMedia(),this.removeAllListeners(),this.cameraDeviceSubscribers.clear(),this.microphoneDeviceSubscribers.clear(),this.speakerDeviceSubscribers.clear(),this.currentCameraSubscribers.clear(),this.currentMicrophoneSubscribers.clear(),this.currentSpeakerSubscribers.clear(),this.cameraDeviceErrorSubscribers.clear(),this.microphoneDeviceErrorSubscribers.clear(),this.isSettingCameraDeviceSubscribers.clear(),this.isSettingMicrophoneDeviceSubscribers.clear(),this.localMediaStartingSubscribers.clear(),this.localStreamSubscribers.clear(),this.localMediaStartErrorSubscribers.clear()}}const FS=Pg(e=>e.chat.chatMessages,e=>e.cloudRecording,S_,y_,lw,dw,l_,r_,W_,ow,D_,e=>e.streaming,e=>e.waitingParticipants.waitingParticipants,lS,yw,(e,t,r,n,i,s,o,a,c,d,l,u,p,h,f)=>({chatMessages:e,cloudRecording:t.isRecording?{status:"recording"}:void 0,breakout:{isActive:n,currentGroup:r,groupedParticipants:i,participantsInCurrentGroup:s},connectionStatus:l,events:h,liveStream:u.isStreaming?{status:"streaming",startedAt:u.startedAt}:void 0,localScreenshareStatus:o.isScreenSharing?"active":void 0,localParticipant:Object.assign(Object.assign({},o),{stream:a}),remoteParticipants:c,screenshares:d,waitingParticipants:p,spotlightedParticipants:f}));class BS extends MS{constructor(e){super(e),this.selfId=null,this.chatMessageSubscribers=new Set,this.cloudRecordingSubscribers=new Set,this.breakoutSubscribers=new Set,this.connectionStatusSubscribers=new Set,this.liveStreamSubscribers=new Set,this.localScreenshareStatusSubscribers=new Set,this.localParticipantSubscribers=new Set,this.remoteParticipantsSubscribers=new Set,this.screenshareSubscribers=new Set,this.waitingParticipantsSubscribers=new Set,this.spotlightedParticipantsSubscribers=new Set,this.options={},this.registerAppListeners()}handleStateChanges(e,t){var r;if(e.chatMessages!==t.chatMessages&&this.chatMessageSubscribers.forEach(t=>t(e.chatMessages)),e.cloudRecording!==t.cloudRecording&&(this.cloudRecordingSubscribers.forEach(t=>t(e.cloudRecording?{status:"recording"}:void 0)),this.emit("cloud-recording:status-changed",e.cloudRecording?{status:"recording"}:void 0)),e.breakout!==t.breakout&&(this.breakoutSubscribers.forEach(t=>t(e.breakout)),this.emit("breakout:config-changed",e.breakout)),e.connectionStatus!==t.connectionStatus&&(this.connectionStatusSubscribers.forEach(t=>t(e.connectionStatus)),this.emit("connection:status-changed",e.connectionStatus)),e.liveStream!==t.liveStream&&(this.liveStreamSubscribers.forEach(t=>t(e.liveStream)),"streaming"===(null===(r=e.liveStream)||void 0===r?void 0:r.status)?this.emit("streaming:started",e.liveStream):this.emit("streaming:stopped")),e.localScreenshareStatus!==t.localScreenshareStatus&&(this.localScreenshareStatusSubscribers.forEach(t=>t(e.localScreenshareStatus)),this.emit("local-screenshare:status-changed",e.localScreenshareStatus)),e.localParticipant!==t.localParticipant&&(this.localParticipantSubscribers.forEach(t=>t(e.localParticipant)),this.emit("local-participant:changed",e.localParticipant)),e.remoteParticipants!==t.remoteParticipants&&(this.remoteParticipantsSubscribers.forEach(t=>t(e.remoteParticipants)),this.emit("remote-participants:changed",e.remoteParticipants)),e.screenshares!==t.screenshares){this.screenshareSubscribers.forEach(t=>t(e.screenshares));const r=e.screenshares.filter(e=>!t.screenshares.some(t=>t.id===e.id)),n=t.screenshares.filter(t=>!e.screenshares.some(e=>e.id===t.id));r.forEach(e=>{this.emit("screenshare:started",e)}),n.forEach(e=>{this.emit("screenshare:stopped",e.id)})}if(e.waitingParticipants!==t.waitingParticipants){this.waitingParticipantsSubscribers.forEach(t=>t(e.waitingParticipants));const r=e.waitingParticipants.filter(e=>!t.waitingParticipants.some(t=>t.id===e.id)),n=t.waitingParticipants.filter(t=>!e.waitingParticipants.some(e=>e.id===t.id));r.forEach(e=>{this.emit("waiting-participant:joined",e)}),n.forEach(e=>{this.emit("waiting-participant:left",e.id)})}if(e.spotlightedParticipants!==t.spotlightedParticipants){this.spotlightedParticipantsSubscribers.forEach(t=>t(e.spotlightedParticipants));const r=e.spotlightedParticipants.filter(e=>!t.spotlightedParticipants.some(t=>t.id===e.id)),n=t.spotlightedParticipants.filter(t=>!e.spotlightedParticipants.some(e=>e.id===t.id));r.forEach(e=>{this.emit("spotlight:participant-added",e)}),n.forEach(e=>{this.emit("spotlight:participant-removed",e.id)})}}registerAppListeners(){Eb({actionCreator:Ub.roomJoined,effect:({payload:e})=>{if("error"in e)return void this.emit("room:joined:error",e.error);const{selfId:t}=e;this.selfId=t,this.emit("room:joined",{isLocked:e.room.isLocked,selfId:t})}}),Eb({actionCreator:Ub.chatMessage,effect:({payload:e})=>{this.emit("chat:new-message",e)}})}subscribeToChatMessages(e){return this.chatMessageSubscribers.add(e),()=>this.chatMessageSubscribers.delete(e)}subscribeToCloudRecording(e){return this.cloudRecordingSubscribers.add(e),()=>this.cloudRecordingSubscribers.delete(e)}subscribeToBreakoutConfig(e){return this.breakoutSubscribers.add(e),()=>this.breakoutSubscribers.delete(e)}subscribeToConnectionStatus(e){return this.connectionStatusSubscribers.add(e),()=>this.connectionStatusSubscribers.delete(e)}subscribeToLiveStream(e){return this.liveStreamSubscribers.add(e),()=>this.liveStreamSubscribers.delete(e)}subscribeToLocalScreenshareStatus(e){return this.localScreenshareStatusSubscribers.add(e),()=>this.localScreenshareStatusSubscribers.delete(e)}subscribeToLocalParticipant(e){return this.localParticipantSubscribers.add(e),()=>this.localParticipantSubscribers.delete(e)}subscribeToRemoteParticipants(e){return this.remoteParticipantsSubscribers.add(e),()=>this.remoteParticipantsSubscribers.delete(e)}subscribeToScreenshares(e){return this.screenshareSubscribers.add(e),()=>this.screenshareSubscribers.delete(e)}subscribeToWaitingParticipants(e){return this.waitingParticipantsSubscribers.add(e),()=>this.waitingParticipantsSubscribers.delete(e)}subscribeToSpotlightedParticipants(e){return this.spotlightedParticipantsSubscribers.add(e),()=>this.spotlightedParticipantsSubscribers.delete(e)}getState(){return FS(this.store.getState())}getNotificationsEventEmitter(){return lS(this.store.getState())}initialize(e){this.options=e}joinRoom(){return oy(this,void 0,void 0,function*(){const{roomUrl:e}=this.options;if(!e)throw new Error("Room URL is required to join a room.");const t={localMediaOptions:this.options.localMediaOptions||void 0,displayName:this.options.displayName||"Guest",roomKey:this.options.roomKey||null,externalId:this.options.externalId||null,sdkVersion:`core:${xb}`,roomUrl:e,assistantKey:this.options.assistantKey||null,isNodeSdk:this.options.isNodeSdk||!1};let r,n;this.store.dispatch(Mb(t));const i=new Promise((e,t)=>{r=e,n=t}),s=this.store.dispatch(zv({actionCreator:Ub.roomJoined,effect:({payload:e})=>{s(),"error"in e?null==n||n(e.error):null==r||r(e)}}));return i})}sendChatMessage(e){this.store.dispatch(k_({text:e}))}knock(){this.store.dispatch(gS())}leaveRoom(){this.store.dispatch(Db()),this.selfId=null}setDisplayName(e){this.store.dispatch(eS({displayName:e}))}toggleCamera(e){this.store.dispatch(Iy({enabled:e}))}toggleMicrophone(e){this.store.dispatch(Dy({enabled:e}))}toggleLowDataMode(e){this.store.dispatch(My({enabled:e}))}toggleRaiseHand(e){this.store.dispatch(iS({enabled:e}))}askToSpeak(e){this.store.dispatch(G_({clientIds:[e],enable:!0}))}askToTurnOnCamera(e){this.store.dispatch(q_({clientIds:[e],enable:!0}))}acceptWaitingParticipant(e){this.store.dispatch(ES({participantId:e}))}rejectWaitingParticipant(e){this.store.dispatch(OS({participantId:e}))}startCloudRecording(){this.store.dispatch(R_())}stopCloudRecording(){this.store.dispatch(E_())}startScreenshare(){this.store.dispatch(Y_())}stopScreenshare(){this.store.dispatch(X_())}lockRoom(e){this.store.dispatch(nw({locked:e}))}muteParticipants(e){this.store.dispatch(G_({clientIds:e,enable:!1}))}turnOffParticipantCameras(e){this.store.dispatch(q_({clientIds:e,enable:!1}))}spotlightParticipant(e){this.store.dispatch(gw({id:e}))}removeSpotlight(e){this.store.dispatch(vw({id:e}))}kickParticipant(e){this.store.dispatch(iw({clientId:e}))}endMeeting(e=!1){this.store.dispatch(sw({stayBehind:e}))}joinBreakoutGroup(e){this.store.dispatch(v_({group:e}))}joinBreakoutMainRoom(){this.store.dispatch(v_({group:""}))}reportStreamResolution(e,t,r){this.store.dispatch(jw({streamId:e,width:t,height:r}))}destroy(){super.destroy(),this.store.dispatch(Db()),this.removeAllListeners(),this.selfId=null,this.chatMessageSubscribers.clear(),this.cloudRecordingSubscribers.clear(),this.breakoutSubscribers.clear(),this.connectionStatusSubscribers.clear(),this.liveStreamSubscribers.clear(),this.localScreenshareStatusSubscribers.clear(),this.localParticipantSubscribers.clear(),this.remoteParticipantsSubscribers.clear(),this.screenshareSubscribers.clear(),this.waitingParticipantsSubscribers.clear(),this.spotlightedParticipantsSubscribers.clear()}}class zS{constructor(){this.services=function(){const e=vb.create({baseUrl:Tb}),t=new sb({fetchDeviceCredentials:e.getCredentials.bind(e),baseUrl:Tb}),r=new Cb({apiClient:t});return{credentialsService:e,apiClient:t,organizationService:r,fetchOrganizationFromRoomUrl:e=>{const t=ql({host:new URL(e).host});return new kb({organizationService:r,subdomain:t.subdomain}).fetchOrganization()}}}(),this.store=(({preloadedState:e,injectServices:t})=>Qg({devTools:!1,reducer:IS,middleware:e=>e({thunk:{extraArgument:{services:t}},serializableCheck:!1}).prepend(Rb.middleware),preloadedState:e}))({injectServices:this.services}),this.localMediaClient=new NS(this.store),this.roomConnectionClient=new BS(this.store),this.gridClient=new jS(this.store)}getLocalMedia(){return this.localMediaClient}getRoomConnection(){return this.roomConnectionClient}getGrid(){return this.gridClient}getStore(){return this.store}destroy(){this.localMediaClient.destroy(),this.roomConnectionClient.destroy(),this.gridClient.destroy()}}const US=s.createContext(null);var VS=function(){return VS=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},VS.apply(this,arguments)};function $S(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}"function"==typeof SuppressedError&&SuppressedError;const GS=({stream:e,muted:t})=>{var r,n;const i=s.useRef(null),o=null===(r=s.useContext(US))||void 0===r?void 0:r.getLocalMedia(),[a,c]=s.useState(null!==(n=null==o?void 0:o.getState().currentSpeakerDeviceId)&&void 0!==n?n:"default"),d=s.useCallback(e=>{c(e)},[]);return s.useEffect(()=>(null==o||o.addListener(LS,d),()=>{null==o||o.removeListener(LS,d)}),[o]),s.useEffect(()=>{i.current&&!t&&e&&a&&(i.current.srcObject!==e&&(i.current.srcObject=e),i.current.setSinkId&&i.current.setSinkId(a))},[e,i,a,t]),i},qS=s.forwardRef((e,t)=>{var r,{muted:n,mirror:i=!1,stream:o,onVideoResize:a}=e,c=$S(e,["muted","mirror","stream","onVideoResize"]);const d=null===(r=s.useContext(US))||void 0===r?void 0:r.getRoomConnection(),l=s.useRef(null),u=GS({muted:n,stream:o});return s.useImperativeHandle(t,()=>Object.assign(l.current,{captureAspectRatio:()=>{if(!l.current)return null;const e=l.current.videoHeight,t=l.current.videoWidth;return t&&e&&t+e>20?t/e:null}})),s.useEffect(()=>{if(!l.current)return;const e=new ResizeObserver(Pb(()=>{if(l.current&&(null==o?void 0:o.id)){const e=l.current.clientWidth,t=l.current.clientHeight;null==d||d.reportStreamResolution(o.id,e,t),a&&a({width:e,height:t,stream:o})}},{delay:1e3,edges:!0}));return e.observe(l.current),()=>{e.disconnect()}},[o]),s.useEffect(()=>{l.current&&(l.current.srcObject!==o&&(l.current.srcObject=o),l.current.muted!==n&&(l.current.muted=Boolean(n)))},[n,o,l]),s.createElement(s.Fragment,null,s.createElement("video",Object.assign({ref:l,autoPlay:!0,playsInline:!0},c,{style:Object.assign({transform:i?"scaleX(-1)":"none",width:"100%",height:"100%"},c.style)})),s.createElement("audio",{ref:u,autoPlay:!0,playsInline:!0}))});qS.displayName="VideoView";const HS={chatMessages:[],cloudRecording:void 0,breakout:{isActive:!1,currentGroup:null,groupedParticipants:[],participantsInCurrentGroup:[]},localParticipant:void 0,remoteParticipants:[],screenshares:[],connectionStatus:"ready",waitingParticipants:[],spotlightedParticipants:[]},WS={localMediaOptions:{audio:!0,video:!0}};const JS={cameraDeviceError:null,isStarting:!1,isSettingCameraDevice:!1,isSettingMicrophoneDevice:!1,microphoneDeviceError:null,startError:null,cameraDevices:[],microphoneDevices:[],speakerDevices:[]};var KS={TABLET_BREAKPOINT:750,BOTTOM_TOOLBAR_HEIGHT:82,VIDEO_CONTROLS_MIN_WIDTH:420,SUBGRID_EMPTY_STAGE_MAX_WIDTH:800};function QS({top:e=0,left:t=0}={}){return{top:e,left:t}}function YS({width:e=0,height:t=0}={}){return{width:Math.max(e,0),height:Math.max(t,0)}}function XS({top:e=0,left:t=0,width:r=0,height:n=0}={}){return{bounds:YS({width:r,height:n}),origin:QS({top:e,left:t})}}function ZS({top:e=0,left:t=0,bottom:r=0,right:n=0}={}){return{top:e,left:t,bottom:r,right:n}}function eC(e){return!!e&&!(e.width<=0||e.height<=0)}function tC(e,t){const{width:r,height:n}=t,i=n,s=i*e,o=Math.min(r/s,n/i);return{width:s*o,height:i*o}}const rC=({vertical:e,width:t,height:r,count:n,aspectRatio:i})=>{const s=[1,2,3].map(s=>(({width:e,height:t,rows:r,cols:n,aspectRatio:i})=>{const s=tC(i,{width:e/n,height:t/r});return Math.round(s.width*s.height)})({width:t,height:r,rows:e?Math.ceil(n/s):s,cols:e?s:Math.ceil(n/s),aspectRatio:i})),o=Math.max(...s);return{splits:s.indexOf(o)+1,weight:o}};function nC({count:e,width:t,height:r,aspectRatio:n}){if(e<=1)return{rows:1,cols:1};const{splits:i,vertical:s}=(({width:e,height:t,count:r,aspectRatio:n})=>{const i=rC({vertical:!0,width:e,height:t,count:r,aspectRatio:n}),s=rC({vertical:!1,width:e,height:t,count:r,aspectRatio:n});return i.weight>s.weight?{splits:i.splits,vertical:!0}:{splits:s.splits,vertical:!1}})({width:t,height:r,count:e,aspectRatio:n});return s?{rows:Math.ceil(e/i),cols:i}:{rows:i,cols:Math.ceil(e/i)}}function iC(e){var{aspectRatio:t,children:r,className:n,height:i,style:o,width:a,withRoundedCorners:c=!1,withShadow:d=!0}=e,l=$S(e,["aspectRatio","children","className","height","style","width","withRoundedCorners","withShadow"]);let u=a,p=i,h=0,f=0;t&&(({width:u,height:p}=tC(t,{width:a,height:i})),h=(a-u)/2,f=(i-p)/2);const m=Object.assign({width:`${Math.round(u)}px`,height:`${Math.round(p)}px`},h||f?{transform:`translate3d(${Math.round(h)}px, ${Math.round(f)}px, 0)`}:{});return s.createElement("div",{className:n,style:Object.assign({position:"absolute",top:0,left:0},o)},s.createElement("div",Object.assign({style:m},l),s.cloneElement(r,{contentWidth:u,contentHeight:p,withRoundedCorners:c,withShadow:d})))}function sC({origin:e,bounds:t}){return{top:Math.round(e.top),left:Math.round(e.left),height:Math.round(t.height),width:Math.round(t.width)}}function oC({cell:e,child:t,clientId:r,style:n={},withRoundedCorners:i=!1,withShadow:o=!1}){const a=!eC(e.bounds);return s.createElement(iC,{width:e.bounds.width,height:e.bounds.height,aspectRatio:e.aspectRatio,style:a?{width:0,height:0}:n,withRoundedCorners:i,withShadow:o,key:r},t)}function aC({containerFrame:e,debug:t=!1,featureRoundedCornersOff:r=!1,floatingContent:n,gridContent:i=[],isConstrained:o=!1,layoutOverflowBackdropFrame:a=XS(),layoutVideoStage:c,presentationGridContent:d=[],subgridContent:l=[]}){const u=!r&&!o,p=[];return i.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:n,withShadow:i}){var o;const a=(null===(o=r.videoGrid)||void 0===o?void 0:o.cells)||[],c=e.map((e,o)=>{var c,d;if(!r.videoGrid)return null;const l=a[o],u={top:r.videoGrid.origin.top+r.videoGrid.paddings.top+l.origin.top,left:r.videoGrid.origin.left+r.videoGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return oC({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`video-${o}`}),clientId:h||`video-${o}`,withRoundedCorners:n,style:p,withShadow:i})});return c}({content:i,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),d.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:n,withShadow:i}){var o;const a=(null===(o=r.presentationGrid)||void 0===o?void 0:o.cells)||[];return e.map((e,o)=>{var c,d;if(!r.presentationGrid)return null;const l=a[o],u={top:r.presentationGrid.origin.top+r.presentationGrid.paddings.top+l.origin.top,left:r.presentationGrid.origin.left+r.presentationGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return oC({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`presentation-${o}`}),clientId:h||`presentation-${o}`,style:p,withRoundedCorners:n,withShadow:i})})}({content:d,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),n&&p.push(function({content:e,containerFrame:t,stageLayout:r,withRoundedCorners:n}){var i;if(!r.floatingContent)return null;const o=r.floatingContent,a=o.origin.top,c=o.origin.left,d={width:Math.round(o.bounds.width),height:Math.round(o.bounds.height),transform:`translate3d(${Math.round(t.origin.left+c)}px, ${Math.round(t.origin.top+a)}px, 0)`,position:"fixed",top:o.bounds.height/2,left:0,zIndex:40},l=(null===(i=e.props.client)||void 0===i?void 0:i.id)||"floating";return oC({cell:o,child:s.cloneElement(e,{isSmallCell:o.isSmallCell,isZoomedByDefault:!1,canZoom:!1,key:l,isDraggable:!1}),clientId:l,style:d,withRoundedCorners:n,withShadow:!1})}({content:n,containerFrame:e,stageLayout:c,withRoundedCorners:!r})),l.length&&p.push(...function({content:e,stageLayout:t,withRoundedCorners:r,withShadow:n}){const i=t.subgrid.cells;return e.map((e,o)=>{var a,c,d,l;const u=i[o],p={height:Math.round(u.bounds.height),width:Math.round(u.bounds.width),transform:""},h={top:t.subgrid.origin.top+u.origin.top,left:t.subgrid.origin.left+u.origin.left};p.transform=`translate3d(${Math.round(h.left)}px, ${Math.round(h.top)}px, 0)`;const f=null===(c=null===(a=null==e?void 0:e.props)||void 0===a?void 0:a.participant)||void 0===c?void 0:c.id,m=(null===(d=u.paddings)||void 0===d?void 0:d.left)||0,g=(null===(l=u.paddings)||void 0===l?void 0:l.right)||0;return oC({cell:u,child:s.cloneElement(e,{avatarSize:u.bounds.width-m-g,canZoom:!1,cellPaddings:u.paddings,isSmallCell:u.isSmallCell,isZoomedByDefault:!1,key:f||`subgrid-${o}`,style:p}),clientId:f||`subgrid-${o}`,style:p,withRoundedCorners:r,withShadow:n})})}({content:l,stageLayout:c,withRoundedCorners:!r,withShadow:!0})),s.createElement("div",{key:"video-stage-layout",style:{width:"100%",height:"100%",position:"relative"}},eC(a.bounds)&&s.createElement("div",{style:sC(a)}),p,t&&s.createElement(s.Fragment,null))}const cC=16/9,dC=4/3,lC=({value:e,min:t,max:r})=>Math.min(Math.max(e,t),r);function uC({choices:e=[]}){const t=Math.min(...e),r=Math.max(...e);let n=null;if(t===r)n=t;else{const t=function(...e){return new Set(e).size!==e.length}(e)?(i=e).sort((e,t)=>i.filter(t=>t===e).length-i.filter(e=>e===t).length).pop():r;n=lC({value:t||r,min:dC,max:cC})}var i;return{minAr:t,maxAr:r,chosenAr:n}}const pC="rows",hC="columns";function fC({layoutGrid:e,dim:t,secDim:r,index:n,count:i,gridGap:s}){const o=(t-s*(i-1))*(e.fractions?e.fractions[n]:1/i),a=e.lines[n];return[o,(r-s*(a-1))/a]}function mC({isHorizontal:e,layoutGrid:t,width:r,height:n,gridGap:i}){const s=[],o=0,a=0,c={x:0,y:0},d=t.lines.length,l=e?n:r,u=e?r:n;for(let r=0;r<d;r++){const n=fC({layoutGrid:t,dim:l,secDim:u,index:r,count:d,gridGap:i}),p={width:e?n[1]:n[0],height:e?n[0]:n[1]},h=t.lines[r];for(let t=0;t<h;t++)s.push({origin:Object.assign({},c),bounds:p}),e?c.x+=p.width+i:c.y+=p.height+i;e?(c.y+=p.height+i,c.x=o):(c.x+=p.width+i,c.y=a)}return s}function gC({layoutGrid:e,width:t,height:r,gridGap:n}){switch(e.type){case pC:return function({layoutGrid:e,width:t,height:r,gridGap:n}){return mC({isHorizontal:!0,layoutGrid:e,width:t,height:r,gridGap:n})}({layoutGrid:e,width:t,height:r,gridGap:n});case hC:return function({layoutGrid:e,width:t,height:r,gridGap:n}){return mC({isHorizontal:!1,layoutGrid:e,width:t,height:r,gridGap:n})}({layoutGrid:e,width:t,height:r,gridGap:n})}}function vC({width:e,height:t,cellCount:r,gridGap:n=0,paddings:i=ZS()}){const s=e-(i.left+i.right),o=t-(i.top+i.bottom),a=Math.round(s/o*10)/10<=1?function(e){return{1:{type:pC,lines:[1]},2:{type:pC,lines:[1,1]},3:{type:pC,lines:[2,1]},4:{type:pC,lines:[2,2]},5:{type:pC,lines:[2,2,1]},6:{type:pC,lines:[2,2,2]},7:{type:pC,lines:[3,2,2]},8:{type:pC,lines:[2,2,2,2]},9:{type:pC,lines:[3,2,2,2]},10:{type:pC,lines:[3,3,2,2]},11:{type:pC,lines:[3,3,3,2]},12:{type:pC,lines:[3,3,3,3]},13:{type:pC,lines:[2,2,3,3,3]},14:{type:pC,lines:[2,3,3,3,3]},15:{type:pC,lines:[3,3,3,3,3]},16:{type:pC,lines:[2,2,3,3,3,3]},17:{type:pC,lines:[2,3,3,3,3,3]},18:{type:pC,lines:[3,3,3,3,3,3]},19:{type:pC,lines:[2,2,3,3,3,3,3]},20:{type:pC,lines:[2,3,3,3,3,3,3]},21:{type:pC,lines:[3,3,3,3,3,3,3]},22:{type:pC,lines:[2,2,3,3,3,3,3,3]},23:{type:pC,lines:[2,3,3,3,3,3,3,3]},24:{type:pC,lines:[3,3,3,3,3,3,3,3]}}[e]||{type:pC,lines:[3,3,3,3,3,3,3,3]}}(r):function(e){return{1:{type:hC,lines:[1]},2:{type:hC,lines:[1,1]},3:{type:hC,lines:[2,1]},4:{type:hC,lines:[2,2]},5:{type:pC,lines:[3,2],fractions:[.45,.55]},6:{type:hC,lines:[2,2,2]},7:{type:pC,lines:[4,3],fractions:[.45,.55]},8:{type:hC,lines:[2,2,2,2]},9:{type:hC,lines:[3,2,2,2]},10:{type:hC,lines:[3,3,2,2]},11:{type:hC,lines:[3,3,3,2]},12:{type:hC,lines:[3,3,3,3]},13:{type:hC,lines:[4,3,3,3]},14:{type:hC,lines:[4,4,3,3]},15:{type:hC,lines:[3,3,3,3,3]},16:{type:hC,lines:[4,3,3,3,3]},17:{type:hC,lines:[4,4,3,3,3]},18:{type:hC,lines:[4,4,4,3,3]},19:{type:hC,lines:[4,4,4,4,3]},20:{type:hC,lines:[4,4,4,4,4]},21:{type:hC,lines:[5,4,4,4,4]},22:{type:hC,lines:[5,5,4,4,4]},23:{type:hC,lines:[5,5,5,4,4]},24:{type:hC,lines:[5,5,5,5,4]}}[e]||{type:hC,lines:[5,5,5,5,5]}}(r);return{cellRects:gC({layoutGrid:a,width:s,height:o,gridGap:n})||[],cellCount:r,gridGap:n,extraHorizontalPadding:0,extraVerticalPadding:0,paddings:i}}function bC({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:n,paddings:i=ZS()}){let s=0,o=0,a=0,c=0,d=0,l=0;const u=e.width-i.left-i.right,p=e.height-i.top-i.bottom;return r&&(t?(c=Math.floor(u/n.width),a=Math.ceil(r/c),s=u,o=a*n.height,d=(u-c*n.width)/2):(a=Math.floor(p/n.height),c=Math.ceil(r/a),s=c*n.width,o=p,l=(p-a*n.height)/2)),{isPortrait:t,width:s+i.left+i.right,height:o+i.top+i.bottom,cellBounds:n,cellCount:r,rows:a,cols:c,extraHorizontalPadding:d,extraVerticalPadding:l,paddings:i}}const{BOTTOM_TOOLBAR_HEIGHT:yC,VIDEO_CONTROLS_MIN_WIDTH:_C,TABLET_BREAKPOINT:wC,SUBGRID_EMPTY_STAGE_MAX_WIDTH:SC}=KS,CC=ZS({top:4,bottom:28,left:8,right:8});function kC({hasOverflow:e,hasStage:t}){return e&&t?[80]:[80,60]}function TC({cellCount:e}){const t=e<=6;return YS({width:t?250:300,height:t?150:200})}function PC({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}){const o=function({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}){let o;for(let a=0;a<n.length;a++){const c=n[a];if(o=bC({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:YS({width:c+i.left+i.right,height:c+i.top+i.bottom}),paddings:s}),o.width<=e.width&&o.height<=e.height)return o}return o}({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}),a=o.cellBounds.width-i.left-i.right===n[n.length-1],c=YS({width:Math.min(o.width,e.width),height:Math.min(o.height,e.height)}),d=YS({width:o.width,height:o.height});return 0===r?{bounds:c,contentBounds:d,videoCells:[]}:{bounds:c,contentBounds:d,videoCells:[...Array(r)].map((e,t)=>{const{top:r,left:n,width:s,height:c}=function({index:e,layout:t}){const{isPortrait:r,rows:n,cols:i,cellCount:s,cellBounds:o,extraHorizontalPadding:a,extraVerticalPadding:c,paddings:d}=t,l=r?Math.floor(e/i):Math.floor(e%n),u=r?Math.floor(e%i):Math.floor(e/n),p=function({index:e,isPortrait:t,rows:r,cols:n,cellBounds:i,cellCount:s}){const o=r*n,a=o-s;if(!a)return 0;const c=o-a-1;return e<c-((t?n:r)-a)+1||e>c?0:a*(t?i.width:i.height)/2}({index:e,isPortrait:r,rows:n,cols:i,cellBounds:o,cellCount:s});return{top:d.top+c+l*o.height+(r?0:p),left:d.left+a+u*o.width+(r?p:0),width:o.width,height:o.height}}({index:t,layout:o});return{origin:QS({top:r,left:n}),bounds:YS({width:s,height:c}),paddings:i,isSmallCell:a}})}}function RC({cellPaddings:e,cellSizeOptions:t,containerBounds:r,containerOrigin:n,gridGap:i,hasConstrainedOverflow:s,hasPresentationContent:o,hasVideoContent:a,isConstrained:c,isMaximizeMode:d,isPortrait:l,isSmallScreen:u,maxGridWidth:p,shouldOverflowSubgrid:h,subgridVideos:f}){const{width:m,height:g}=r,v=o||a,b=f.length>0;if(!b&&!v)return{isPortrait:l,videosContainer:XS(),subgrid:Object.assign(Object.assign({},XS()),{contentBounds:YS(),cells:[]}),hasOverflow:!1};if(!b)return{isPortrait:l,videosContainer:XS(Object.assign(Object.assign({},r),n)),subgrid:Object.assign(Object.assign({},XS()),{contentBounds:YS(),cells:[]}),hasOverflow:s};const y=h?20:0;let _=null;if(v)if(h){const n=t[0];let i=d?yC:yC+e.top+(c||u?n/2:n)+e.bottom;r.height-i<200&&(i=0),_=YS({width:r.width,height:i})}else _=YS(d?{width:r.width,height:t[0]+e.top+e.bottom}:l?{width:r.width,height:r.height/2}:{width:r.width/2,height:r.height});else _=YS({width:Math.min(SC,r.width),height:r.height});let w=0;_.width>p&&(w=(_.width-p)/2);const S=PC({containerBounds:_,isPortrait:l,cellCount:f.length,cellSizeOptions:t,cellPaddings:e,paddings:ZS({top:y,left:w,right:w})}),C=YS({width:S.contentBounds.width-_.width,height:S.contentBounds.height-_.height}),k=C.width>0||C.height>0;let T,P=null;P=!v||h||k?S.contentBounds:S.bounds;let R=P;v?(R=YS(h?{width:0,height:_.height+y+i}:l?{width:0,height:S.bounds.height+i}:{width:S.bounds.width+i,height:0}),T=function({bounds:e,fromBounds:t}){return{width:Math.max(t.width-e.width,0),height:Math.max(t.height-e.height,0)}}({bounds:R,fromBounds:r})):T=YS();const E=Object.assign({},n);let O;return O=QS(v?{top:l?Math.max(n.top+g-R.height+i,0):n.top,left:l?n.left:Math.max(n.left+m-P.width,0)}:{top:n.top+Math.max(0,(g-P.height)/2),left:n.left+Math.max(0,(m-P.width)/2)}),{isPortrait:l,videosContainer:XS(Object.assign(Object.assign({},T),E)),subgrid:Object.assign(Object.assign({},XS(Object.assign(Object.assign({},P),O))),{cells:S.videoCells.map((e,t)=>{var r,n;return Object.assign({aspectRatio:(null===(r=f[t])||void 0===r?void 0:r.aspectRatio)||1,type:"video",clientId:null===(n=f[t])||void 0===n?void 0:n.clientId},e)}),contentBounds:S.contentBounds}),hasOverflow:k||h||s,overflowNeedBounds:h?YS():C}}function EC({containerBounds:e,containerOrigin:t,gridGap:r,supersizedContentAspectRatio:n,hasPresentationContent:i,hasPresentationGrid:s,hasVideoContent:o,minGridBounds:a}){const{width:c,height:d}=e;let l=c<=d,u=YS(),p=QS(),h=o?Object.assign({},e):YS(),f=o?Object.assign({},t):QS();if(i){const i=function({bounds:e,aspectRatio:t,minGridContainerBounds:r,hasPresentationGrid:n}){const{width:i,height:s}=e;if(!(r.width>0))return{isPortrait:i<=s,supersizedContentBounds:e};const o=Math.round(i/2),a=Math.round(s/2),c=Math.max(i-r.width,0),d=Math.max(s-r.height,0);let l=c<=d,u=0,p=0;{const e=tC(t,{width:c,height:s}),r=tC(t,{width:i,height:d});if(l=t<=1?r.height>e.height:r.width>e.width,l){const e=d-Math.max(r.height,a);p=Math.max(e,0)}else{const t=c-Math.max(e.width,o);u=Math.max(t,0)}}return{isPortrait:l,supersizedContentBounds:{width:l?i:c-u,height:l?d-p:s}}}({bounds:e,aspectRatio:n,minGridContainerBounds:YS({width:o?a.width+r:0,height:o?a.height+r:0}),hasPresentationGrid:s});l=i.isPortrait,u=i.supersizedContentBounds,p=Object.assign({},t),o&&(h=YS({width:l?e.width:e.width-u.width-r,height:l?e.height-u.height-r:e.height}),f=QS({top:l?t.top+u.height+r:t.top,left:l?t.left:t.left+u.width+r}))}return{isPortrait:l,presentationGrid:Object.assign({},XS(Object.assign(Object.assign({},u),p))),videoGrid:XS(Object.assign(Object.assign({},h),f))}}function OC({containerBounds:e,paddings:t=ZS(),videos:r,isConstrained:n,maxGridWidth:i,gridGap:s}){const{width:o,height:a}=e,c=i?Math.min(o,i):o,d=r.length;let l=null,u=null;if(n){const e=vC({width:o,height:a,cellCount:d,gridGap:s,paddings:t}),n=d>4;u=r.map((t,r)=>{const i=function({index:e,layout:t}){const{cellRects:r}=t,n=r[e]||XS();return{top:n.origin.y,left:n.origin.x,width:n.bounds.width,height:n.bounds.height}}({index:r,layout:e});return{clientId:t.clientId,isDraggable:t.isDraggable,origin:QS({top:i.top,left:i.left}),bounds:YS({width:i.width,height:i.height}),aspectRatio:i.width/i.height,isSmallCell:n,type:"video"}}),l=e}else{const e=r.map(e=>e.aspectRatio||1),i=TC({cellCount:d}),o=function({width:e,height:t,cellCount:r,gridGap:n,cellAspectRatios:i=[dC],paddings:s=ZS()}){if(!r)return{cellCount:r,cellHeight:0,cellWidth:0,cols:0,rows:0,extraHorizontalPadding:0,extraVerticalPadding:0,gridGap:n,paddings:s};const o=e-(s.left+s.right),a=t-(s.top+s.bottom),c=uC({choices:i});let d=c.chosenAr;const{rows:l,cols:u}=nC({count:r,width:o,height:a,aspectRatio:d});1===l?d=lC({value:o/u/a,min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}):1===u&&(d=lC({value:o/(a/l),min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}));const{cellWidth:p,cellHeight:h,extraHorizontalPadding:f,extraVerticalPadding:m}=function({width:e,height:t,rows:r,cols:n,gridGap:i,aspectRatio:s}){const o=(e-(n-1)*i)/n,a=(t-(r-1)*i)/r,c=o/a;let d=0,l=0;return s<c?d=o-a*s:s>c&&(l=a-o/s),{cellWidth:o-d,cellHeight:a-l,extraHorizontalPadding:d*n/2,extraVerticalPadding:l*r/2}}({width:o,height:a,rows:l,cols:u,gridGap:n,aspectRatio:d});return{cellCount:r,cellHeight:h,cellWidth:p,cols:u,rows:l,extraHorizontalPadding:f,extraVerticalPadding:m,gridGap:n,paddings:s}}({width:c,height:a,cellCount:d,gridGap:s,cellAspectRatios:e,paddings:t});u=r.map((e,t)=>{const r=function({index:e,layout:t}){const{cellWidth:r,cellHeight:n,rows:i,cols:s,cellCount:o,gridGap:a}=t,c=Math.floor(e/s),d=Math.floor(e%s),l=function({rows:e,cols:t,cellWidth:r,index:n,cellCount:i,gridGap:s}){const o=e*t,a=o-i;if(!a)return 0;const c=o-a-1;return n>=c-(t-a)+1&&n<=c?a*r/2+s:0}({rows:i,cols:s,cellWidth:r,index:e,cellCount:o,gridGap:a});return{top:c*n+c*a,left:d*r+d*a+l,width:r,height:n}}({index:t,layout:o}),s=o.cellWidth<i.width,a=n||s?o.cellWidth/o.cellHeight:e.aspectRatio||1;return{clientId:e.clientId,isDraggable:e.isDraggable,origin:QS({top:r.top,left:r.left}),bounds:YS({width:r.width,height:r.height}),aspectRatio:a,isSmallCell:s,type:"video"}}),l=o}return{videoCells:u,extraHorizontalPadding:o!==c?l.extraHorizontalPadding+(o-c)/2:l.extraHorizontalPadding,extraVerticalPadding:l.extraVerticalPadding,paddings:l.paddings,gridGap:s}}function xC({a:e,b:t,gridGap:r,isPortrait:n}){const i=n?e.vertical:e.horizontal,s=n?t.vertical:t.horizontal;if(i===s)return{a:0,b:0};const o=i<s?e:t,a=n?o.vertical:o.horizontal,c=(r+(i+s)+a)/2-a;return{a:o===e?c:0,b:o===t?c:0}}function IC({gridGap:e,isConstrained:t,presentationVideos:r,videos:n,videosContainerLayout:i,gridLayoutPaddings:s=ZS(),presentationGridLayoutPaddings:o=ZS(),maxGridWidth:a}){return{gridLayout:OC({containerBounds:i.videoGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:s,videos:n}),presentationGridLayout:OC({containerBounds:i.presentationGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:o,videos:r})}}function DC({floatingVideo:e,frame:t,gridGap:r,isConstrained:n,isMaximizeMode:i=!1,isXLMeetingSize:s=!1,paddings:o=ZS(),presentationVideos:a=[],rebalanceLayout:c=!1,roomBounds:d,roomLayoutHasOverlow:l=!1,subgridCellPaddings:u=CC,subgridVideos:p=[],videoControlsHeight:h=0,videos:f=[],videoGridGap:m}){let g=s&&(!screen||screen.width<=2048);const v=!!a.length,b=a.length>1,y=v&&!b?a[0].aspectRatio:null,_=!!f.length,w=t.bounds.width-o.left-o.right;let S=t.bounds.height-o.top-o.bottom;const C=Math.max(2200,.8*w),k=n&&f.length>12,T=S/4,P=Math.ceil((f.length-12)/3);S=k?S+T*P:S;const R=YS({width:w,height:S}),E=QS({top:o.top,left:o.left}),O=TC({cellCount:f.length}),x=d.width<wC||d.height<wC,I=i||g||!(v||_)||R.width<=R.height,D={cellPaddings:u,containerBounds:R,containerOrigin:E,gridGap:r,hasPresentationContent:v,hasVideoContent:_,isConstrained:n,isMaximizeMode:i,isSmallScreen:x,subgridVideos:p,maxGridWidth:C};let M=RC(Object.assign(Object.assign({},D),{cellSizeOptions:kC({hasOverflow:g,hasStage:v||_}),isPortrait:I,shouldOverflowSubgrid:g,hasConstrainedOverflow:k})),j=!1;if(!g&&l&&!M.hasOverflow){RC(Object.assign(Object.assign({},D),{containerBounds:YS({width:R.width,height:R.height-yC}),cellSizeOptions:kC({hasOverflow:g,hasStage:v||_}),isPortrait:I,shouldOverflowSubgrid:g,hasConstrainedOverflow:k})).hasOverflow&&(j=!0)}(j||M.hasOverflow&&!g)&&(g=!0,M=RC(Object.assign(Object.assign({},D),{cellSizeOptions:kC({hasOverflow:!0,hasStage:v||_}),isPortrait:!0,shouldOverflowSubgrid:g,hasConstrainedOverflow:k})));const A=EC({containerBounds:M.videosContainer.bounds,containerOrigin:M.videosContainer.origin,gridGap:r,supersizedContentAspectRatio:y||1,hasPresentationContent:v,hasPresentationGrid:b,hasVideoContent:_,minGridBounds:O});let{gridLayout:L,presentationGridLayout:N}=IC({gridGap:m||r,isConstrained:n,presentationVideos:a,videos:f,videosContainerLayout:A,maxGridWidth:C});if(M.hasOverflow&&!g){const{vPaddings:e,hPaddings:t}=function({need:e,stageLayout:t,gridLayout:r,presentationGridLayout:n,videosContainerLayout:i}){let s={presentationGrid:0,grid:0},o={presentationGrid:0,grid:0};if(t.isPortrait){const t=Math.min(r.extraVerticalPadding,n.extraVerticalPadding);s={presentationGrid:Math.min(i.isPortrait?n.extraVerticalPadding:t,e.height),grid:Math.min(i.isPortrait?r.extraVerticalPadding:t,e.height)}}else{const t=Math.min(r.extraHorizontalPadding,n.extraHorizontalPadding);o={presentationGrid:Math.min(i.isPortrait?t:n.extraHorizontalPadding,e.width),grid:Math.min(i.isPortrait?t:r.extraHorizontalPadding,e.width)}}return{vPaddings:s,hPaddings:o}}({need:M.overflowNeedBounds||YS(),stageLayout:M,gridLayout:L,presentationGridLayout:N,videosContainerLayout:A});(e.presentationGrid||e.grid||t.presentationGrid||t.grid)&&(!function({vPaddings:e,hPaddings:t,stageLayout:r,videosContainerLayout:n}){if(r.isPortrait&&(e.presentationGrid||e.grid)){const t=n.isPortrait?2*e.presentationGrid+2*e.grid:e.presentationGrid+e.grid;r.videosContainer.bounds.height-=t,r.subgrid.origin.top-=t,r.subgrid.bounds.height+=t,n.presentationGrid.bounds.height-=2*e.presentationGrid,n.videoGrid.bounds.height-=2*e.grid,n.isPortrait&&(n.videoGrid.origin.top-=e.presentationGrid)}if(!r.isPortrait&&(t.presentationGrid||t.grid)){const e=n.isPortrait?t.presentationGrid+t.grid:2*t.presentationGrid+2*t.grid;r.videosContainer.bounds.width-=e,r.subgrid.origin.left-=e,r.subgrid.bounds.width+=e,n.presentationGrid.bounds.width-=2*t.presentationGrid,n.videoGrid.bounds.width-=2*t.grid,n.isPortrait||(n.videoGrid.origin.left-=t.grid)}}({vPaddings:e,hPaddings:t,stageLayout:M,videosContainerLayout:A}),({gridLayout:L,presentationGridLayout:N}=IC({gridGap:m||r,isConstrained:n,presentationVideos:a,videos:f,videosContainerLayout:A,maxGridWidth:C})))}const F=function({roomBounds:e,containerFrame:t,floatingVideo:r,videoControlsHeight:n,margin:i=8}){if(!r)return null;const s=tC(r.aspectRatio||0,{width:200,height:200}),o=!(e.height-t.bounds.height-t.origin.top),a=t.bounds.width-2*(s.width+i)<_C;let c=0;o&&a?c=-1*n:o||a||(c=n);const d=QS({top:t.origin.top+(t.bounds.height-s.height-i)+c,left:t.origin.left+(t.bounds.width-s.width-i)});return{clientId:r.clientId,isDraggable:r.isDraggable,origin:d,bounds:s,aspectRatio:r.aspectRatio,isSmallCell:!0}}({roomBounds:d,containerFrame:t,floatingVideo:e||null,videoControlsHeight:h});c&&function({videosContainerLayout:e,gridLayout:t,presentationGridLayout:r,stageLayout:n,gridGap:i,shouldOverflowSubgrid:s}){const o=e.presentationGrid.bounds.width>0,a=e.videoGrid.bounds.width>0,c=n.subgrid.bounds.width>0,d={vertical:0,horizontal:0};if(o&&a){const n=xC({a:{horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},b:{horizontal:t.extraHorizontalPadding,vertical:t.extraVerticalPadding},gridGap:i,isPortrait:e.isPortrait});e.isPortrait?(e.presentationGrid.origin.top+=n.a,e.videoGrid.origin.top-=n.b,d.vertical=n.b):(e.presentationGrid.origin.left+=n.a,e.videoGrid.origin.left-=n.b,d.horizontal=n.b)}if(c&&(o||a)&&!s){const s={horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},c={horizontal:t.extraHorizontalPadding+d.horizontal,vertical:t.extraVerticalPadding+d.vertical};let l;const u=o&&a;l=u&&e.isPortrait&&!n.isPortrait?s.horizontal<c.horizontal?s:c:u&&!e.isPortrait&&n.isPortrait?s.vertical<c.vertical?s:c:a?c:s;const p=xC({a:l,b:{horizontal:0,vertical:0},gridGap:i,isPortrait:n.isPortrait});n.isPortrait?n.subgrid.origin.top-=p.b:n.subgrid.origin.left-=p.b}}({videosContainerLayout:A,gridLayout:L,presentationGridLayout:N,stageLayout:M,gridGap:r,shouldOverflowSubgrid:g});let B=o.top+M.videosContainer.bounds.height+M.subgrid.bounds.height+o.bottom;return(v||_)&&(B+=r),{isPortrait:M.isPortrait,hasOverflow:M.hasOverflow,videosContainer:Object.assign(Object.assign({},A),{bounds:YS({width:M.videosContainer.bounds.width,height:M.videosContainer.bounds.height}),origin:QS({top:M.videosContainer.origin.top,left:M.videosContainer.origin.left})}),bounds:YS({height:g?B:t.bounds.height,width:t.bounds.width}),gridGap:r,presentationGrid:Object.assign(Object.assign({},A.presentationGrid),{cells:N.videoCells,paddings:ZS({top:N.paddings.top+N.extraVerticalPadding,bottom:N.paddings.bottom+N.extraVerticalPadding,left:N.paddings.left+N.extraHorizontalPadding,right:N.paddings.right+N.extraHorizontalPadding})}),videoGrid:Object.assign(Object.assign({},A.videoGrid),{cells:L.videoCells,paddings:ZS({top:L.paddings.top+L.extraVerticalPadding,bottom:L.paddings.bottom+L.extraVerticalPadding,left:L.paddings.left+L.extraHorizontalPadding,right:L.paddings.right+L.extraHorizontalPadding})}),subgrid:M.subgrid,floatingContent:Object.assign(Object.assign(Object.assign({},F),e),{origin:(null==F?void 0:F.origin)||QS(),bounds:(null==F?void 0:F.bounds)||YS(),aspectRatio:(null==e?void 0:e.aspectRatio)||1})}}function MC({aspectRatio:e,avatarSize:t,cellPaddings:r,client:n,isDraggable:i=!0,isPlaceholder:s=!1,isSubgrid:o=!1}){return{aspectRatio:e||16/9,avatarSize:t,cellPaddings:r,client:n,clientId:(null==n?void 0:n.id)||"",isDraggable:i,isPlaceholder:s,isSubgrid:o,type:"video"}}function jC({activeVideosSubgridTrigger:e=12,stageParticipantLimit:t=12,forceSubgrid:r=!0,enableSubgrid:n=!0,maximizedParticipant:i,floatingParticipant:o,isConstrained:a=!1}={}){var c;const[d,l]=s.useState({allClientViews:[],spotlightedParticipants:[],numParticipants:0}),u=null===(c=s.useContext(US))||void 0===c?void 0:c.getGrid();if(!u)throw new Error("useGridParticipants must be used within a WherebyProvider");const p=s.useCallback(e=>{l(t=>Object.assign(Object.assign({},t),{allClientViews:e}))},[l]),h=s.useCallback(e=>{l(t=>Object.assign(Object.assign({},t),{spotlightedParticipants:e}))},[l]),f=s.useCallback(e=>{l(t=>Object.assign(Object.assign({},t),{numParticipants:e}))},[l]);s.useEffect(()=>{const e=u.subscribeClientViews(p),t=u.subscribeSpotlightedParticipants(h),r=u.subscribeNumberOfClientViews(f);return()=>{e(),t(),r()}},[u]);const m=s.useMemo(()=>d.allClientViews,[d.allClientViews]),g=s.useMemo(()=>d.spotlightedParticipants,[d.spotlightedParticipants]),v=s.useMemo(()=>d.numParticipants,[d.numParticipants]),b=s.useMemo(()=>o,[o]),y=s.useMemo(()=>b?m.filter(e=>e.id!==b.id):m,[m,b]),_=s.useMemo(()=>!!n&&(!!r||v>t),[r,v,t,n]),w=s.useMemo(()=>function({clientViews:e,activeVideosSubgridTrigger:t,shouldShowSubgrid:r,spotlightedParticipants:n,maximizedParticipant:i,isPhoneResolution:s}){if(!r)return[];const o=n.length>0,a=(i?e.filter(e=>e.id!==i.id):e).filter(e=>!e.isPresentation&&!n.includes(e)),c=a.filter(e=>!e.isVideoEnabled),d=a.filter(e=>e.isVideoEnabled).length>t,l=a.filter(e=>!c.includes(e)&&e.isAudioEnabled),u=a.filter(e=>!c.includes(e)&&!e.isAudioEnabled);if(c.length&&o)return[...u,...c];if(s&&a.length>24){const e=[...l,...u],t=e.slice(0,24);return t.length<=24?[...e.filter(e=>!t.includes(e)),...c]:[...u,...c]}if(d&&u.length){const e=[...l,...u].slice(0,t);return e.length<=t?[...u.filter(t=>!e.includes(t)),...c]:[...u,...c]}return c}({clientViews:y,activeVideosSubgridTrigger:e,shouldShowSubgrid:_,spotlightedParticipants:g,maximizedParticipant:i,isPhoneResolution:a}),[y,_,e,g,a]),S=s.useMemo(()=>y.filter(e=>!w.includes(e)),[y,w]),C=s.useMemo(()=>i?[i]:g,[g,i]),k=s.useMemo(()=>S.filter(e=>!C.includes(e)),[S,C]);return{floatingClientView:b,clientViewsInGrid:k,clientViewsInPresentationGrid:C,clientViewsInSubgrid:w,spotlightedParticipants:g}}var AC={exports:{}};const LC=55296,NC=127995,FC=127999,BC=[776,2359,2359,2367,2367,2984,3007,3021,3633,3635,3648,3657,4352,4449,4520];function zC(e){if("string"!=typeof e)throw new Error("string cannot be undefined or null");const t=[];let r=0,n=0;for(;r<e.length;)n+=UC(r+n,e),qC(e[r+n])&&n++,$C(e[r+n])&&n++,GC(e[r+n])&&n++,HC(e[r+n])?n++:(t.push(e.substring(r,r+n)),r+=n,n=0);return t}function UC(e,t){const r=t[e];if(!function(e){return e&&JC(e[0].charCodeAt(0),LC,56319)}(r)||e===t.length-1)return 1;const n=r+t[e+1];let i=t.substring(e+2,e+5);return VC(n)&&VC(i)||function(e){return JC(WC(e),NC,FC)}(i)?4:2}function VC(e){return JC(WC(e),127462,127487)}function $C(e){return"string"==typeof e&&JC(e.charCodeAt(0),65024,65039)}function GC(e){return"string"==typeof e&&JC(e.charCodeAt(0),8400,8447)}function qC(e){return"string"==typeof e&&-1!==BC.indexOf(e.charCodeAt(0))}function HC(e){return"string"==typeof e&&8205===e.charCodeAt(0)}function WC(e){return(e.charCodeAt(0)-LC<<10)+(e.charCodeAt(1)-56320)+65536}function JC(e,t,r){return e>=t&&e<=r}AC.exports=zC,AC.exports.substr=function(e,t,r){const n=zC(e);if(void 0===t)return e;if(t>=n.length)return"";const i=n.length-t;let s=t+(void 0===r?i:r);return s>t+i&&(s=void 0),n.slice(t,s).join("")};var KC=c(AC.exports);const QC=({name:e})=>{const t=((e="")=>{if(e=e.trim())return e.split(/-| /).map(e=>KC(e)[0]).slice(0,3);return[]})(e),r=[0,56,48,40][t.length]||32,n=t.join("").toUpperCase();return s.createElement("svg",{viewBox:"-60 -60 120 120","aria-hidden":"true",style:{height:"100%",pointerEvents:"none",width:"100%"}},s.createElement("text",{x:0,y:0,textAnchor:"middle",dominantBaseline:"central",fontSize:r},n))};function YC(e){var{avatarUrl:t,className:r,size:n=40,name:i,variant:o="round"}=e,a=$S(e,["avatarUrl","className","size","name","variant"]);return s.createElement("div",Object.assign({style:{height:`${n}px`,width:`${n}px`,userSelect:"none",overflow:"hidden",borderRadius:"round"===o?"50%":"4px",backgroundColor:"#f8e3c8"},className:r,title:i},a),!t&&i?s.createElement(QC,{name:i}):s.createElement("img",{src:t||"",alt:"",style:{height:"100%",width:"100%",objectFit:"cover",maxWidth:"initial"}}))}function XC({avatarUrl:e,displayName:t,isSmallCell:r,withRoundedCorners:n,stream:i,muted:o}){const a=GS({stream:i,muted:o});return s.createElement(s.Fragment,null,s.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",position:"absolute",top:0,left:0,height:"100%",width:"100%",borderRadius:n?"8px":"0"}},s.createElement("div",{style:{height:r?60:80,width:r?60:80,pointerEvents:"none",position:"relative"}},s.createElement(YC,{variant:"square",avatarUrl:e,name:t,size:r?60:80}))),s.createElement("audio",{ref:a,autoPlay:!0,playsInline:!0}))}function ZC(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(e?.(n),!1===r||!n.defaultPrevented)return t?.(n)}}function ek(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function tk(...e){return t=>{let r=!1;const n=e.map(e=>{const n=ek(e,t);return r||"function"!=typeof n||(r=!0),n});if(r)return()=>{for(let t=0;t<n.length;t++){const r=n[t];"function"==typeof r?r():ek(e[t],null)}}}}function rk(...e){return s.useCallback(tk(...e),e)}var nk,ik={exports:{}},sk={};ik.exports=(nk||(nk=1,function(){function e(t){if(null==t)return null;if("function"==typeof t)return t.$$typeof===k?null:t.displayName||t.name||null;if("string"==typeof t)return t;switch(t){case h:return"Fragment";case m:return"Profiler";case f:return"StrictMode";case y:return"Suspense";case _:return"SuspenseList";case C:return"Activity"}if("object"==typeof t)switch("number"==typeof t.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case p:return"Portal";case v:return(t.displayName||"Context")+".Provider";case g:return(t._context.displayName||"Context")+".Consumer";case b:var r=t.render;return(t=t.displayName)||(t=""!==(t=r.displayName||r.name||"")?"ForwardRef("+t+")":"ForwardRef"),t;case w:return null!==(r=t.displayName||null)?r:e(t.type)||"Memo";case S:r=t._payload,t=t._init;try{return e(t(r))}catch(e){}}return null}function r(e){return""+e}function n(e){try{r(e);var t=!1}catch(e){t=!0}if(t){var n=(t=console).error,i="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return n.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",i),r(e)}}function i(t){if(t===h)return"<>";if("object"==typeof t&&null!==t&&t.$$typeof===S)return"<...>";try{var r=e(t);return r?"<"+r+">":"<...>"}catch(e){return"<...>"}}function s(){return Error("react-stack-top-frame")}function o(){var t=e(this.type);return O[t]||(O[t]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(t=this.props.ref)?t:null}function a(t,r,i,s,a,l,p,h){var f,m=r.children;if(void 0!==m)if(s)if(R(m)){for(s=0;s<m.length;s++)c(m[s]);Object.freeze&&Object.freeze(m)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else c(m);if(P.call(r,"key")){m=e(t);var g=Object.keys(r).filter(function(e){return"key"!==e});s=0<g.length?"{key: someKey, "+g.join(": ..., ")+": ...}":"{key: someKey}",D[m+s]||(g=0<g.length?"{"+g.join(": ..., ")+": ...}":"{}",console.error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',s,m,g,m),D[m+s]=!0)}if(m=null,void 0!==i&&(n(i),m=""+i),function(e){if(P.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(r)&&(n(r.key),m=""+r.key),"key"in r)for(var v in i={},r)"key"!==v&&(i[v]=r[v]);else i=r;return m&&function(e,t){function r(){d||(d=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}(i,"function"==typeof t?t.displayName||t.name||"Unknown":t),function(e,t,r,n,i,s,a,c){return r=s.ref,e={$$typeof:u,type:e,key:t,props:s,_owner:i},null!==(void 0!==r?r:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:o}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:a}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:c}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}(t,m,l,0,null===(f=T.A)?null:f.getOwner(),i,p,h)}function c(e){"object"==typeof e&&null!==e&&e.$$typeof===u&&e._store&&(e._store.validated=1)}var d,l=t,u=Symbol.for("react.transitional.element"),p=Symbol.for("react.portal"),h=Symbol.for("react.fragment"),f=Symbol.for("react.strict_mode"),m=Symbol.for("react.profiler"),g=Symbol.for("react.consumer"),v=Symbol.for("react.context"),b=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),_=Symbol.for("react.suspense_list"),w=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),C=Symbol.for("react.activity"),k=Symbol.for("react.client.reference"),T=l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,P=Object.prototype.hasOwnProperty,R=Array.isArray,E=console.createTask?console.createTask:function(){return null},O={},x=(l={"react-stack-bottom-frame":function(e){return e()}})["react-stack-bottom-frame"].bind(l,s)(),I=E(i(s)),D={};sk.Fragment=h,sk.jsx=function(e,t,r,n,s){var o=1e4>T.recentlyCreatedOwnerStacks++;return a(e,t,r,!1,0,s,o?Error("react-stack-top-frame"):x,o?E(i(e)):I)},sk.jsxs=function(e,t,r,n,s){var o=1e4>T.recentlyCreatedOwnerStacks++;return a(e,t,r,!0,0,s,o?Error("react-stack-top-frame"):x,o?E(i(e)):I)}}()),sk);var ok=ik.exports;function ak(e,t=[]){let r=[];const n=()=>{const t=r.map(e=>s.createContext(e));return function(r){const n=r?.[e]||t;return s.useMemo(()=>({[`__scope${e}`]:{...r,[e]:n}}),[r,n])}};return n.scopeName=e,[function(t,n){const i=s.createContext(n),o=r.length;r=[...r,n];const a=t=>{const{scope:r,children:n,...a}=t,c=r?.[e]?.[o]||i,d=s.useMemo(()=>a,Object.values(a));return ok.jsx(c.Provider,{value:d,children:n})};return a.displayName=t+"Provider",[a,function(r,a){const c=a?.[e]?.[o]||i,d=s.useContext(c);if(d)return d;if(void 0!==n)return n;throw new Error(`\`${r}\` must be used within \`${t}\``)}]},ck(n,...t)]}function ck(...e){const t=e[0];if(1===e.length)return t;const r=()=>{const r=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const n=r.reduce((t,{useScope:r,scopeName:n})=>({...t,...r(e)[`__scope${n}`]}),{});return s.useMemo(()=>({[`__scope${t.scopeName}`]:n}),[n])}};return r.scopeName=t.scopeName,r}function dk(e){const t=lk(e),r=s.forwardRef((e,r)=>{const{children:n,...i}=e,o=s.Children.toArray(n),a=o.find(pk);if(a){const e=a.props.children,n=o.map(t=>t===a?s.Children.count(e)>1?s.Children.only(null):s.isValidElement(e)?e.props.children:null:t);return ok.jsx(t,{...i,ref:r,children:s.isValidElement(e)?s.cloneElement(e,void 0,n):null})}return ok.jsx(t,{...i,ref:r,children:n})});return r.displayName=`${e}.Slot`,r}function lk(e){const t=s.forwardRef((e,t)=>{const{children:r,...n}=e;if(s.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),i=function(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{const t=s(...e);return i(...e),t}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}(n,r.props);return r.type!==s.Fragment&&(i.ref=t?tk(t,e):e),s.cloneElement(r,i)}return s.Children.count(r)>1?s.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var uk=Symbol("radix.slottable");function pk(e){return s.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===uk}var hk=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=dk(`Primitive.${t}`),n=s.forwardRef((e,n)=>{const{asChild:i,...s}=e,o=i?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),ok.jsx(o,{...s,ref:n})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function fk(e){const t=s.useRef(e);return s.useEffect(()=>{t.current=e}),s.useMemo(()=>(...e)=>t.current?.(...e),[])}var mk,gk="dismissableLayer.update",vk="dismissableLayer.pointerDownOutside",bk="dismissableLayer.focusOutside",yk=s.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),_k=s.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:a,onDismiss:c,...d}=e,l=s.useContext(yk),[u,p]=s.useState(null),h=u?.ownerDocument??globalThis?.document,[,f]=s.useState({}),m=rk(t,e=>p(e)),g=Array.from(l.layers),[v]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),b=g.indexOf(v),y=u?g.indexOf(u):-1,_=l.layersWithOutsidePointerEventsDisabled.size>0,w=y>=b,S=function(e,t=globalThis?.document){const r=fk(e),n=s.useRef(!1),i=s.useRef(()=>{});return s.useEffect(()=>{const e=e=>{if(e.target&&!n.current){let n=function(){Sk(vk,r,s,{discrete:!0})};const s={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",i.current),i.current=n,t.addEventListener("click",i.current,{once:!0})):n()}else t.removeEventListener("click",i.current);n.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",e),t.removeEventListener("click",i.current)}},[t,r]),{onPointerDownCapture:()=>n.current=!0}}(e=>{const t=e.target,r=[...l.branches].some(e=>e.contains(t));w&&!r&&(i?.(e),a?.(e),e.defaultPrevented||c?.())},h),C=function(e,t=globalThis?.document){const r=fk(e),n=s.useRef(!1);return s.useEffect(()=>{const e=e=>{if(e.target&&!n.current){Sk(bk,r,{originalEvent:e},{discrete:!1})}};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}(e=>{const t=e.target;[...l.branches].some(e=>e.contains(t))||(o?.(e),a?.(e),e.defaultPrevented||c?.())},h);return function(e,t=globalThis?.document){const r=fk(e);s.useEffect(()=>{const e=e=>{"Escape"===e.key&&r(e)};return t.addEventListener("keydown",e,{capture:!0}),()=>t.removeEventListener("keydown",e,{capture:!0})},[r,t])}(e=>{y===l.layers.size-1&&(n?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))},h),s.useEffect(()=>{if(u)return r&&(0===l.layersWithOutsidePointerEventsDisabled.size&&(mk=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(u)),l.layers.add(u),wk(),()=>{r&&1===l.layersWithOutsidePointerEventsDisabled.size&&(h.body.style.pointerEvents=mk)}},[u,h,r,l]),s.useEffect(()=>()=>{u&&(l.layers.delete(u),l.layersWithOutsidePointerEventsDisabled.delete(u),wk())},[u,l]),s.useEffect(()=>{const e=()=>f({});return document.addEventListener(gk,e),()=>document.removeEventListener(gk,e)},[]),ok.jsx(hk.div,{...d,ref:m,style:{pointerEvents:_?w?"auto":"none":void 0,...e.style},onFocusCapture:ZC(e.onFocusCapture,C.onFocusCapture),onBlurCapture:ZC(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:ZC(e.onPointerDownCapture,S.onPointerDownCapture)})});_k.displayName="DismissableLayer";function wk(){const e=new CustomEvent(gk);document.dispatchEvent(e)}function Sk(e,t,r,{discrete:n}){const i=r.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&i.addEventListener(e,t,{once:!0}),n?function(e,t){e&&o.flushSync(()=>e.dispatchEvent(t))}(i,s):i.dispatchEvent(s)}s.forwardRef((e,t)=>{const r=s.useContext(yk),n=s.useRef(null),i=rk(t,n);return s.useEffect(()=>{const e=n.current;if(e)return r.branches.add(e),()=>{r.branches.delete(e)}},[r.branches]),ok.jsx(hk.div,{...e,ref:i})}).displayName="DismissableLayerBranch";var Ck=0;function kk(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Tk="focusScope.autoFocusOnMount",Pk="focusScope.autoFocusOnUnmount",Rk={bubbles:!1,cancelable:!0},Ek=s.forwardRef((e,t)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...a}=e,[c,d]=s.useState(null),l=fk(i),u=fk(o),p=s.useRef(null),h=rk(t,e=>d(e)),f=s.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;s.useEffect(()=>{if(n){let e=function(e){if(f.paused||!c)return;const t=e.target;c.contains(t)?p.current=t:Dk(p.current,{select:!0})},t=function(e){if(f.paused||!c)return;const t=e.relatedTarget;null!==t&&(c.contains(t)||Dk(p.current,{select:!0}))},r=function(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&Dk(c)};document.addEventListener("focusin",e),document.addEventListener("focusout",t);const n=new MutationObserver(r);return c&&n.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),n.disconnect()}}},[n,c,f.paused]),s.useEffect(()=>{if(c){Mk.add(f);const t=document.activeElement;if(!c.contains(t)){const r=new CustomEvent(Tk,Rk);c.addEventListener(Tk,l),c.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const n of e)if(Dk(n,{select:t}),document.activeElement!==r)return}((e=Ok(c),e.filter(e=>"A"!==e.tagName)),{select:!0}),document.activeElement===t&&Dk(c))}return()=>{c.removeEventListener(Tk,l),setTimeout(()=>{const e=new CustomEvent(Pk,Rk);c.addEventListener(Pk,u),c.dispatchEvent(e),e.defaultPrevented||Dk(t??document.body,{select:!0}),c.removeEventListener(Pk,u),Mk.remove(f)},0)}}var e},[c,l,u,f]);const m=s.useCallback(e=>{if(!r&&!n)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){const t=e.currentTarget,[n,s]=function(e){const t=Ok(e),r=xk(t,e),n=xk(t.reverse(),e);return[r,n]}(t);n&&s?e.shiftKey||i!==s?e.shiftKey&&i===n&&(e.preventDefault(),r&&Dk(s,{select:!0})):(e.preventDefault(),r&&Dk(n,{select:!0})):i===t&&e.preventDefault()}},[r,n,f.paused]);return ok.jsx(hk.div,{tabIndex:-1,...a,ref:h,onKeyDown:m})});function Ok(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{const t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function xk(e,t){for(const r of e)if(!Ik(r,{upTo:t}))return r}function Ik(e,{upTo:t}){if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==t&&e===t)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function Dk(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&function(e){return e instanceof HTMLInputElement&&"select"in e}(e)&&t&&e.select()}}Ek.displayName="FocusScope";var Mk=function(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=jk(e,t),e.unshift(t)},remove(t){e=jk(e,t),e[0]?.resume()}}}();function jk(e,t){const r=[...e],n=r.indexOf(t);return-1!==n&&r.splice(n,1),r}var Ak=globalThis?.document?s.useLayoutEffect:()=>{},Lk=s[" useId ".trim().toString()]||(()=>{}),Nk=0;function Fk(e){const[t,r]=s.useState(Lk());return Ak(()=>{r(e=>e??String(Nk++))},[e]),e||(t?`radix-${t}`:"")}const Bk=["top","right","bottom","left"],zk=Math.min,Uk=Math.max,Vk=Math.round,$k=Math.floor,Gk=e=>({x:e,y:e}),qk={left:"right",right:"left",bottom:"top",top:"bottom"},Hk={start:"end",end:"start"};function Wk(e,t,r){return Uk(e,zk(t,r))}function Jk(e,t){return"function"==typeof e?e(t):e}function Kk(e){return e.split("-")[0]}function Qk(e){return e.split("-")[1]}function Yk(e){return"x"===e?"y":"x"}function Xk(e){return"y"===e?"height":"width"}const Zk=new Set(["top","bottom"]);function eT(e){return Zk.has(Kk(e))?"y":"x"}function tT(e){return Yk(eT(e))}function rT(e){return e.replace(/start|end/g,e=>Hk[e])}const nT=["left","right"],iT=["right","left"],sT=["top","bottom"],oT=["bottom","top"];function aT(e,t,r,n){const i=Qk(e);let s=function(e,t,r){switch(e){case"top":case"bottom":return r?t?iT:nT:t?nT:iT;case"left":case"right":return t?sT:oT;default:return[]}}(Kk(e),"start"===r,n);return i&&(s=s.map(e=>e+"-"+i),t&&(s=s.concat(s.map(rT)))),s}function cT(e){return e.replace(/left|right|bottom|top/g,e=>qk[e])}function dT(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function lT(e){const{x:t,y:r,width:n,height:i}=e;return{width:n,height:i,top:r,left:t,right:t+n,bottom:r+i,x:t,y:r}}function uT(e,t,r){let{reference:n,floating:i}=e;const s=eT(t),o=tT(t),a=Xk(o),c=Kk(t),d="y"===s,l=n.x+n.width/2-i.width/2,u=n.y+n.height/2-i.height/2,p=n[a]/2-i[a]/2;let h;switch(c){case"top":h={x:l,y:n.y-i.height};break;case"bottom":h={x:l,y:n.y+n.height};break;case"right":h={x:n.x+n.width,y:u};break;case"left":h={x:n.x-i.width,y:u};break;default:h={x:n.x,y:n.y}}switch(Qk(t)){case"start":h[o]-=p*(r&&d?-1:1);break;case"end":h[o]+=p*(r&&d?-1:1)}return h}async function pT(e,t){var r;void 0===t&&(t={});const{x:n,y:i,platform:s,rects:o,elements:a,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:l="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=Jk(t,e),f=dT(h),m=a[p?"floating"===u?"reference":"floating":u],g=lT(await s.getClippingRect({element:null==(r=await(null==s.isElement?void 0:s.isElement(m)))||r?m:m.contextElement||await(null==s.getDocumentElement?void 0:s.getDocumentElement(a.floating)),boundary:d,rootBoundary:l,strategy:c})),v="floating"===u?{x:n,y:i,width:o.floating.width,height:o.floating.height}:o.reference,b=await(null==s.getOffsetParent?void 0:s.getOffsetParent(a.floating)),y=await(null==s.isElement?void 0:s.isElement(b))&&await(null==s.getScale?void 0:s.getScale(b))||{x:1,y:1},_=lT(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:b,strategy:c}):v);return{top:(g.top-_.top+f.top)/y.y,bottom:(_.bottom-g.bottom+f.bottom)/y.y,left:(g.left-_.left+f.left)/y.x,right:(_.right-g.right+f.right)/y.x}}function hT(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function fT(e){return Bk.some(t=>e[t]>=0)}const mT=new Set(["left","top"]);function gT(){return"undefined"!=typeof window}function vT(e){return _T(e)?(e.nodeName||"").toLowerCase():"#document"}function bT(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function yT(e){var t;return null==(t=(_T(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function _T(e){return!!gT()&&(e instanceof Node||e instanceof bT(e).Node)}function wT(e){return!!gT()&&(e instanceof Element||e instanceof bT(e).Element)}function ST(e){return!!gT()&&(e instanceof HTMLElement||e instanceof bT(e).HTMLElement)}function CT(e){return!(!gT()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof bT(e).ShadowRoot)}const kT=new Set(["inline","contents"]);function TT(e){const{overflow:t,overflowX:r,overflowY:n,display:i}=NT(e);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&!kT.has(i)}const PT=new Set(["table","td","th"]);function RT(e){return PT.has(vT(e))}const ET=[":popover-open",":modal"];function OT(e){return ET.some(t=>{try{return e.matches(t)}catch(e){return!1}})}const xT=["transform","translate","scale","rotate","perspective"],IT=["transform","translate","scale","rotate","perspective","filter"],DT=["paint","layout","strict","content"];function MT(e){const t=jT(),r=wT(e)?NT(e):e;return xT.some(e=>!!r[e]&&"none"!==r[e])||!!r.containerType&&"normal"!==r.containerType||!t&&!!r.backdropFilter&&"none"!==r.backdropFilter||!t&&!!r.filter&&"none"!==r.filter||IT.some(e=>(r.willChange||"").includes(e))||DT.some(e=>(r.contain||"").includes(e))}function jT(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const AT=new Set(["html","body","#document"]);function LT(e){return AT.has(vT(e))}function NT(e){return bT(e).getComputedStyle(e)}function FT(e){return wT(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function BT(e){if("html"===vT(e))return e;const t=e.assignedSlot||e.parentNode||CT(e)&&e.host||yT(e);return CT(t)?t.host:t}function zT(e){const t=BT(e);return LT(t)?e.ownerDocument?e.ownerDocument.body:e.body:ST(t)&&TT(t)?t:zT(t)}function UT(e,t,r){var n;void 0===t&&(t=[]),void 0===r&&(r=!0);const i=zT(e),s=i===(null==(n=e.ownerDocument)?void 0:n.body),o=bT(i);if(s){const e=VT(o);return t.concat(o,o.visualViewport||[],TT(i)?i:[],e&&r?UT(e):[])}return t.concat(i,UT(i,[],r))}function VT(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function $T(e){const t=NT(e);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const i=ST(e),s=i?e.offsetWidth:r,o=i?e.offsetHeight:n,a=Vk(r)!==s||Vk(n)!==o;return a&&(r=s,n=o),{width:r,height:n,$:a}}function GT(e){return wT(e)?e:e.contextElement}function qT(e){const t=GT(e);if(!ST(t))return Gk(1);const r=t.getBoundingClientRect(),{width:n,height:i,$:s}=$T(t);let o=(s?Vk(r.width):r.width)/n,a=(s?Vk(r.height):r.height)/i;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}const HT=Gk(0);function WT(e){const t=bT(e);return jT()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:HT}function JT(e,t,r,n){void 0===t&&(t=!1),void 0===r&&(r=!1);const i=e.getBoundingClientRect(),s=GT(e);let o=Gk(1);t&&(n?wT(n)&&(o=qT(n)):o=qT(e));const a=function(e,t,r){return void 0===t&&(t=!1),!(!r||t&&r!==bT(e))&&t}(s,r,n)?WT(s):Gk(0);let c=(i.left+a.x)/o.x,d=(i.top+a.y)/o.y,l=i.width/o.x,u=i.height/o.y;if(s){const e=bT(s),t=n&&wT(n)?bT(n):n;let r=e,i=VT(r);for(;i&&n&&t!==r;){const e=qT(i),t=i.getBoundingClientRect(),n=NT(i),s=t.left+(i.clientLeft+parseFloat(n.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(n.paddingTop))*e.y;c*=e.x,d*=e.y,l*=e.x,u*=e.y,c+=s,d+=o,r=bT(i),i=VT(r)}}return lT({width:l,height:u,x:c,y:d})}function KT(e,t){const r=FT(e).scrollLeft;return t?t.left+r:JT(yT(e)).left+r}function QT(e,t,r){void 0===r&&(r=!1);const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-(r?0:KT(e,n)),y:n.top+t.scrollTop}}const YT=new Set(["absolute","fixed"]);function XT(e,t,r){let n;if("viewport"===t)n=function(e,t){const r=bT(e),n=yT(e),i=r.visualViewport;let s=n.clientWidth,o=n.clientHeight,a=0,c=0;if(i){s=i.width,o=i.height;const e=jT();(!e||e&&"fixed"===t)&&(a=i.offsetLeft,c=i.offsetTop)}return{width:s,height:o,x:a,y:c}}(e,r);else if("document"===t)n=function(e){const t=yT(e),r=FT(e),n=e.ownerDocument.body,i=Uk(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),s=Uk(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let o=-r.scrollLeft+KT(e);const a=-r.scrollTop;return"rtl"===NT(n).direction&&(o+=Uk(t.clientWidth,n.clientWidth)-i),{width:i,height:s,x:o,y:a}}(yT(e));else if(wT(t))n=function(e,t){const r=JT(e,!0,"fixed"===t),n=r.top+e.clientTop,i=r.left+e.clientLeft,s=ST(e)?qT(e):Gk(1);return{width:e.clientWidth*s.x,height:e.clientHeight*s.y,x:i*s.x,y:n*s.y}}(t,r);else{const r=WT(e);n={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return lT(n)}function ZT(e,t){const r=BT(e);return!(r===t||!wT(r)||LT(r))&&("fixed"===NT(r).position||ZT(r,t))}function eP(e,t,r){const n=ST(t),i=yT(t),s="fixed"===r,o=JT(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=Gk(0);function d(){c.x=KT(i)}if(n||!n&&!s)if(("body"!==vT(t)||TT(i))&&(a=FT(t)),n){const e=JT(t,!0,s,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else i&&d();s&&!n&&i&&d();const l=!i||n||s?Gk(0):QT(i,a);return{x:o.left+a.scrollLeft-c.x-l.x,y:o.top+a.scrollTop-c.y-l.y,width:o.width,height:o.height}}function tP(e){return"static"===NT(e).position}function rP(e,t){if(!ST(e)||"fixed"===NT(e).position)return null;if(t)return t(e);let r=e.offsetParent;return yT(e)===r&&(r=r.ownerDocument.body),r}function nP(e,t){const r=bT(e);if(OT(e))return r;if(!ST(e)){let t=BT(e);for(;t&&!LT(t);){if(wT(t)&&!tP(t))return t;t=BT(t)}return r}let n=rP(e,t);for(;n&&RT(n)&&tP(n);)n=rP(n,t);return n&&LT(n)&&tP(n)&&!MT(n)?r:n||function(e){let t=BT(e);for(;ST(t)&&!LT(t);){if(MT(t))return t;if(OT(t))return null;t=BT(t)}return null}(e)||r}const iP={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:r,offsetParent:n,strategy:i}=e;const s="fixed"===i,o=yT(n),a=!!t&&OT(t.floating);if(n===o||a&&s)return r;let c={scrollLeft:0,scrollTop:0},d=Gk(1);const l=Gk(0),u=ST(n);if((u||!u&&!s)&&(("body"!==vT(n)||TT(o))&&(c=FT(n)),ST(n))){const e=JT(n);d=qT(n),l.x=e.x+n.clientLeft,l.y=e.y+n.clientTop}const p=!o||u||s?Gk(0):QT(o,c,!0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+l.x+p.x,y:r.y*d.y-c.scrollTop*d.y+l.y+p.y}},getDocumentElement:yT,getClippingRect:function(e){let{element:t,boundary:r,rootBoundary:n,strategy:i}=e;const s="clippingAncestors"===r?OT(t)?[]:function(e,t){const r=t.get(e);if(r)return r;let n=UT(e,[],!1).filter(e=>wT(e)&&"body"!==vT(e)),i=null;const s="fixed"===NT(e).position;let o=s?BT(e):e;for(;wT(o)&&!LT(o);){const t=NT(o),r=MT(o);r||"fixed"!==t.position||(i=null),(s?!r&&!i:!r&&"static"===t.position&&i&&YT.has(i.position)||TT(o)&&!r&&ZT(e,o))?n=n.filter(e=>e!==o):i=t,o=BT(o)}return t.set(e,n),n}(t,this._c):[].concat(r),o=[...s,n],a=o[0],c=o.reduce((e,r)=>{const n=XT(t,r,i);return e.top=Uk(n.top,e.top),e.right=zk(n.right,e.right),e.bottom=zk(n.bottom,e.bottom),e.left=Uk(n.left,e.left),e},XT(t,a,i));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:nP,getElementRects:async function(e){const t=this.getOffsetParent||nP,r=this.getDimensions,n=await r(e.floating);return{reference:eP(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:r}=$T(e);return{width:t,height:r}},getScale:qT,isElement:wT,isRTL:function(e){return"rtl"===NT(e).direction}};function sP(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function oP(e,t,r,n){void 0===n&&(n={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=n,d=GT(e),l=i||s?[...d?UT(d):[],...UT(t)]:[];l.forEach(e=>{i&&e.addEventListener("scroll",r,{passive:!0}),s&&e.addEventListener("resize",r)});const u=d&&a?function(e,t){let r,n=null;const i=yT(e);function s(){var e;clearTimeout(r),null==(e=n)||e.disconnect(),n=null}return function o(a,c){void 0===a&&(a=!1),void 0===c&&(c=1),s();const d=e.getBoundingClientRect(),{left:l,top:u,width:p,height:h}=d;if(a||t(),!p||!h)return;const f={rootMargin:-$k(u)+"px "+-$k(i.clientWidth-(l+p))+"px "+-$k(i.clientHeight-(u+h))+"px "+-$k(l)+"px",threshold:Uk(0,zk(1,c))||1};let m=!0;function g(t){const n=t[0].intersectionRatio;if(n!==c){if(!m)return o();n?o(!1,n):r=setTimeout(()=>{o(!1,1e-7)},1e3)}1!==n||sP(d,e.getBoundingClientRect())||o(),m=!1}try{n=new IntersectionObserver(g,{...f,root:i.ownerDocument})}catch(e){n=new IntersectionObserver(g,f)}n.observe(e)}(!0),s}(d,r):null;let p,h=-1,f=null;o&&(f=new ResizeObserver(e=>{let[n]=e;n&&n.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),r()}),d&&!c&&f.observe(d),f.observe(t));let m=c?JT(e):null;return c&&function t(){const n=JT(e);m&&!sP(m,n)&&r();m=n,p=requestAnimationFrame(t)}(),r(),()=>{var e;l.forEach(e=>{i&&e.removeEventListener("scroll",r),s&&e.removeEventListener("resize",r)}),null==u||u(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}const aP=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var r,n;const{x:i,y:s,placement:o,middlewareData:a}=t,c=await async function(e,t){const{placement:r,platform:n,elements:i}=e,s=await(null==n.isRTL?void 0:n.isRTL(i.floating)),o=Kk(r),a=Qk(r),c="y"===eT(r),d=mT.has(o)?-1:1,l=s&&c?-1:1,u=Jk(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*l,y:p*d}:{x:p*d,y:h*l}}(t,e);return o===(null==(r=a.offset)?void 0:r.placement)&&null!=(n=a.arrow)&&n.alignmentOffset?{}:{x:i+c.x,y:s+c.y,data:{...c,placement:o}}}}},cP=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:n,placement:i}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:r}=e;return{x:t,y:r}}},...c}=Jk(e,t),d={x:r,y:n},l=await pT(t,c),u=eT(Kk(i)),p=Yk(u);let h=d[p],f=d[u];if(s){const e="y"===p?"bottom":"right";h=Wk(h+l["y"===p?"top":"left"],h,h-l[e])}if(o){const e="y"===u?"bottom":"right";f=Wk(f+l["y"===u?"top":"left"],f,f-l[e])}const m=a.fn({...t,[p]:h,[u]:f});return{...m,data:{x:m.x-r,y:m.y-n,enabled:{[p]:s,[u]:o}}}}}},dP=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var r,n;const{placement:i,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:d}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...g}=Jk(e,t);if(null!=(r=s.arrow)&&r.alignmentOffset)return{};const v=Kk(i),b=eT(a),y=Kk(a)===a,_=await(null==c.isRTL?void 0:c.isRTL(d.floating)),w=p||(y||!m?[cT(a)]:function(e){const t=cT(e);return[rT(e),t,rT(t)]}(a)),S="none"!==f;!p&&S&&w.push(...aT(a,m,f,_));const C=[a,...w],k=await pT(t,g),T=[];let P=(null==(n=s.flip)?void 0:n.overflows)||[];if(l&&T.push(k[v]),u){const e=function(e,t,r){void 0===r&&(r=!1);const n=Qk(e),i=tT(e),s=Xk(i);let o="x"===i?n===(r?"end":"start")?"right":"left":"start"===n?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=cT(o)),[o,cT(o)]}(i,o,_);T.push(k[e[0]],k[e[1]])}if(P=[...P,{placement:i,overflows:T}],!T.every(e=>e<=0)){var R,E;const e=((null==(R=s.flip)?void 0:R.index)||0)+1,t=C[e];if(t){if(!("alignment"===u&&b!==eT(t))||P.every(e=>e.overflows[0]>0&&eT(e.placement)===b))return{data:{index:e,overflows:P},reset:{placement:t}}}let r=null==(E=P.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:E.placement;if(!r)switch(h){case"bestFit":{var O;const e=null==(O=P.filter(e=>{if(S){const t=eT(e.placement);return t===b||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:O[0];e&&(r=e);break}case"initialPlacement":r=a}if(i!==r)return{reset:{placement:r}}}return{}}}},lP=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){var r,n;const{placement:i,rects:s,platform:o,elements:a}=t,{apply:c=()=>{},...d}=Jk(e,t),l=await pT(t,d),u=Kk(i),p=Qk(i),h="y"===eT(i),{width:f,height:m}=s.floating;let g,v;"top"===u||"bottom"===u?(g=u,v=p===(await(null==o.isRTL?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(v=u,g="end"===p?"top":"bottom");const b=m-l.top-l.bottom,y=f-l.left-l.right,_=zk(m-l[g],b),w=zk(f-l[v],y),S=!t.middlewareData.shift;let C=_,k=w;if(null!=(r=t.middlewareData.shift)&&r.enabled.x&&(k=y),null!=(n=t.middlewareData.shift)&&n.enabled.y&&(C=b),S&&!p){const e=Uk(l.left,0),t=Uk(l.right,0),r=Uk(l.top,0),n=Uk(l.bottom,0);h?k=f-2*(0!==e||0!==t?e+t:Uk(l.left,l.right)):C=m-2*(0!==r||0!==n?r+n:Uk(l.top,l.bottom))}await c({...t,availableWidth:k,availableHeight:C});const T=await o.getDimensions(a.floating);return f!==T.width||m!==T.height?{reset:{rects:!0}}:{}}}},uP=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:n="referenceHidden",...i}=Jk(e,t);switch(n){case"referenceHidden":{const e=hT(await pT(t,{...i,elementContext:"reference"}),r.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:fT(e)}}}case"escaped":{const e=hT(await pT(t,{...i,altBoundary:!0}),r.floating);return{data:{escapedOffsets:e,escaped:fT(e)}}}default:return{}}}}},pP=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:n,placement:i,rects:s,platform:o,elements:a,middlewareData:c}=t,{element:d,padding:l=0}=Jk(e,t)||{};if(null==d)return{};const u=dT(l),p={x:r,y:n},h=tT(i),f=Xk(h),m=await o.getDimensions(d),g="y"===h,v=g?"top":"left",b=g?"bottom":"right",y=g?"clientHeight":"clientWidth",_=s.reference[f]+s.reference[h]-p[h]-s.floating[f],w=p[h]-s.reference[h],S=await(null==o.getOffsetParent?void 0:o.getOffsetParent(d));let C=S?S[y]:0;C&&await(null==o.isElement?void 0:o.isElement(S))||(C=a.floating[y]||s.floating[f]);const k=_/2-w/2,T=C/2-m[f]/2-1,P=zk(u[v],T),R=zk(u[b],T),E=P,O=C-m[f]-R,x=C/2-m[f]/2+k,I=Wk(E,x,O),D=!c.arrow&&null!=Qk(i)&&x!==I&&s.reference[f]/2-(x<E?P:R)-m[f]/2<0,M=D?x<E?x-E:x-O:0;return{[h]:p[h]+M,data:{[h]:I,centerOffset:x-I-M,...D&&{alignmentOffset:M}},reset:D}}}),hP=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:r,y:n,placement:i,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:c=!0,crossAxis:d=!0}=Jk(e,t),l={x:r,y:n},u=eT(i),p=Yk(u);let h=l[p],f=l[u];const m=Jk(a,t),g="number"==typeof m?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(c){const e="y"===p?"height":"width",t=s.reference[p]-s.floating[e]+g.mainAxis,r=s.reference[p]+s.reference[e]-g.mainAxis;h<t?h=t:h>r&&(h=r)}if(d){var v,b;const e="y"===p?"width":"height",t=mT.has(Kk(i)),r=s.reference[u]-s.floating[e]+(t&&(null==(v=o.offset)?void 0:v[u])||0)+(t?0:g.crossAxis),n=s.reference[u]+s.reference[e]+(t?0:(null==(b=o.offset)?void 0:b[u])||0)-(t?g.crossAxis:0);f<r?f=r:f>n&&(f=n)}return{[p]:h,[u]:f}}}},fP=(e,t,r)=>{const n=new Map,i={platform:iP,...r},s={...i.platform,_c:n};return(async(e,t,r)=>{const{placement:n="bottom",strategy:i="absolute",middleware:s=[],platform:o}=r,a=s.filter(Boolean),c=await(null==o.isRTL?void 0:o.isRTL(t));let d=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:l,y:u}=uT(d,n,c),p=n,h={},f=0;for(let r=0;r<a.length;r++){const{name:s,fn:m}=a[r],{x:g,y:v,data:b,reset:y}=await m({x:l,y:u,initialPlacement:n,placement:p,strategy:i,middlewareData:h,rects:d,platform:o,elements:{reference:e,floating:t}});l=null!=g?g:l,u=null!=v?v:u,h={...h,[s]:{...h[s],...b}},y&&f<=50&&(f++,"object"==typeof y&&(y.placement&&(p=y.placement),y.rects&&(d=!0===y.rects?await o.getElementRects({reference:e,floating:t,strategy:i}):y.rects),({x:l,y:u}=uT(d,p,c))),r=-1)}return{x:l,y:u,placement:p,strategy:i,middlewareData:h}})(e,t,{...i,platform:s})};var mP="undefined"!=typeof document?t.useLayoutEffect:function(){};function gP(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if("function"==typeof e&&e.toString()===t.toString())return!0;let r,n,i;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(n=r;0!==n--;)if(!gP(e[n],t[n]))return!1;return!0}if(i=Object.keys(e),r=i.length,r!==Object.keys(t).length)return!1;for(n=r;0!==n--;)if(!{}.hasOwnProperty.call(t,i[n]))return!1;for(n=r;0!==n--;){const r=i[n];if(("_owner"!==r||!e.$$typeof)&&!gP(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function vP(e){if("undefined"==typeof window)return 1;return(e.ownerDocument.defaultView||window).devicePixelRatio||1}function bP(e,t){const r=vP(e);return Math.round(t*r)/r}function yP(e){const t=s.useRef(e);return mP(()=>{t.current=e}),t}const _P=e=>({name:"arrow",options:e,fn(t){const{element:r,padding:n}="function"==typeof e?e(t):e;return r&&function(e){return{}.hasOwnProperty.call(e,"current")}(r)?null!=r.current?pP({element:r.current,padding:n}).fn(t):{}:r?pP({element:r,padding:n}).fn(t):{}}}),wP=(e,t)=>({...aP(e),options:[e,t]}),SP=(e,t)=>({...cP(e),options:[e,t]}),CP=(e,t)=>({...hP(e),options:[e,t]}),kP=(e,t)=>({...dP(e),options:[e,t]}),TP=(e,t)=>({...lP(e),options:[e,t]}),PP=(e,t)=>({...uP(e),options:[e,t]}),RP=(e,t)=>({..._P(e),options:[e,t]});var EP=s.forwardRef((e,t)=>{const{children:r,width:n=10,height:i=5,...s}=e;return ok.jsx(hk.svg,{...s,ref:t,width:n,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:ok.jsx("polygon",{points:"0,0 30,0 15,10"})})});EP.displayName="Arrow";var OP=EP;var xP="Popper",[IP,DP]=ak(xP),[MP,jP]=IP(xP),AP=e=>{const{__scopePopper:t,children:r}=e,[n,i]=s.useState(null);return ok.jsx(MP,{scope:t,anchor:n,onAnchorChange:i,children:r})};AP.displayName=xP;var LP="PopperAnchor",NP=s.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:n,...i}=e,o=jP(LP,r),a=s.useRef(null),c=rk(t,a);return s.useEffect(()=>{o.onAnchorChange(n?.current||a.current)}),n?null:ok.jsx(hk.div,{...i,ref:c})});NP.displayName=LP;var FP="PopperContent",[BP,zP]=IP(FP),UP=s.forwardRef((e,t)=>{const{__scopePopper:r,side:n="bottom",sideOffset:i=0,align:a="center",alignOffset:c=0,arrowPadding:d=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:p=0,sticky:h="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:g,...v}=e,b=jP(FP,r),[y,_]=s.useState(null),w=rk(t,e=>_(e)),[S,C]=s.useState(null),k=function(e){const[t,r]=s.useState(void 0);return Ak(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver(t=>{if(!Array.isArray(t))return;if(!t.length)return;const n=t[0];let i,s;if("borderBoxSize"in n){const e=n.borderBoxSize,t=Array.isArray(e)?e[0]:e;i=t.inlineSize,s=t.blockSize}else i=e.offsetWidth,s=e.offsetHeight;r({width:i,height:s})});return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}r(void 0)},[e]),t}(S),T=k?.width??0,P=k?.height??0,R=n+("center"!==a?"-"+a:""),E="number"==typeof p?p:{top:0,right:0,bottom:0,left:0,...p},O=Array.isArray(u)?u:[u],x=O.length>0,I={padding:E,boundary:O.filter(qP),altBoundary:x},{refs:D,floatingStyles:M,placement:j,isPositioned:A,middlewareData:L}=function(e){void 0===e&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:i,elements:{reference:a,floating:c}={},transform:d=!0,whileElementsMounted:l,open:u}=e,[p,h]=s.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=s.useState(n);gP(f,n)||m(n);const[g,v]=s.useState(null),[b,y]=s.useState(null),_=s.useCallback(e=>{e!==k.current&&(k.current=e,v(e))},[]),w=s.useCallback(e=>{e!==T.current&&(T.current=e,y(e))},[]),S=a||g,C=c||b,k=s.useRef(null),T=s.useRef(null),P=s.useRef(p),R=null!=l,E=yP(l),O=yP(i),x=yP(u),I=s.useCallback(()=>{if(!k.current||!T.current)return;const e={placement:t,strategy:r,middleware:f};O.current&&(e.platform=O.current),fP(k.current,T.current,e).then(e=>{const t={...e,isPositioned:!1!==x.current};D.current&&!gP(P.current,t)&&(P.current=t,o.flushSync(()=>{h(t)}))})},[f,t,r,O,x]);mP(()=>{!1===u&&P.current.isPositioned&&(P.current.isPositioned=!1,h(e=>({...e,isPositioned:!1})))},[u]);const D=s.useRef(!1);mP(()=>(D.current=!0,()=>{D.current=!1}),[]),mP(()=>{if(S&&(k.current=S),C&&(T.current=C),S&&C){if(E.current)return E.current(S,C,I);I()}},[S,C,I,E,R]);const M=s.useMemo(()=>({reference:k,floating:T,setReference:_,setFloating:w}),[_,w]),j=s.useMemo(()=>({reference:S,floating:C}),[S,C]),A=s.useMemo(()=>{const e={position:r,left:0,top:0};if(!j.floating)return e;const t=bP(j.floating,p.x),n=bP(j.floating,p.y);return d?{...e,transform:"translate("+t+"px, "+n+"px)",...vP(j.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:t,top:n}},[r,d,j.floating,p.x,p.y]);return s.useMemo(()=>({...p,update:I,refs:M,elements:j,floatingStyles:A}),[p,I,M,j,A])}({strategy:"fixed",placement:R,whileElementsMounted:(...e)=>oP(...e,{animationFrame:"always"===m}),elements:{reference:b.anchor},middleware:[wP({mainAxis:i+P,alignmentAxis:c}),l&&SP({mainAxis:!0,crossAxis:!1,limiter:"partial"===h?CP():void 0,...I}),l&&kP({...I}),TP({...I,apply:({elements:e,rects:t,availableWidth:r,availableHeight:n})=>{const{width:i,height:s}=t.reference,o=e.floating.style;o.setProperty("--radix-popper-available-width",`${r}px`),o.setProperty("--radix-popper-available-height",`${n}px`),o.setProperty("--radix-popper-anchor-width",`${i}px`),o.setProperty("--radix-popper-anchor-height",`${s}px`)}}),S&&RP({element:S,padding:d}),HP({arrowWidth:T,arrowHeight:P}),f&&PP({strategy:"referenceHidden",...I})]}),[N,F]=WP(j),B=fk(g);Ak(()=>{A&&B?.()},[A,B]);const z=L.arrow?.x,U=L.arrow?.y,V=0!==L.arrow?.centerOffset,[$,G]=s.useState();return Ak(()=>{y&&G(window.getComputedStyle(y).zIndex)},[y]),ok.jsx("div",{ref:D.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:A?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:$,"--radix-popper-transform-origin":[L.transformOrigin?.x,L.transformOrigin?.y].join(" "),...L.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:ok.jsx(BP,{scope:r,placedSide:N,onArrowChange:C,arrowX:z,arrowY:U,shouldHideArrow:V,children:ok.jsx(hk.div,{"data-side":N,"data-align":F,...v,ref:w,style:{...v.style,animation:A?void 0:"none"}})})})});UP.displayName=FP;var VP="PopperArrow",$P={top:"bottom",right:"left",bottom:"top",left:"right"},GP=s.forwardRef(function(e,t){const{__scopePopper:r,...n}=e,i=zP(VP,r),s=$P[i.placedSide];return ok.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:ok.jsx(OP,{...n,ref:t,style:{...n.style,display:"block"}})})});function qP(e){return null!==e}GP.displayName=VP;var HP=e=>({name:"transformOrigin",options:e,fn(t){const{placement:r,rects:n,middlewareData:i}=t,s=0!==i.arrow?.centerOffset,o=s?0:e.arrowWidth,a=s?0:e.arrowHeight,[c,d]=WP(r),l={start:"0%",center:"50%",end:"100%"}[d],u=(i.arrow?.x??0)+o/2,p=(i.arrow?.y??0)+a/2;let h="",f="";return"bottom"===c?(h=s?l:`${u}px`,f=-a+"px"):"top"===c?(h=s?l:`${u}px`,f=`${n.floating.height+a}px`):"right"===c?(h=-a+"px",f=s?l:`${p}px`):"left"===c&&(h=`${n.floating.width+a}px`,f=s?l:`${p}px`),{data:{x:h,y:f}}}});function WP(e){const[t,r="center"]=e.split("-");return[t,r]}var JP=AP,KP=NP,QP=UP,YP=GP,XP=s.forwardRef((e,t)=>{const{container:n,...i}=e,[o,a]=s.useState(!1);Ak(()=>a(!0),[]);const c=n||o&&globalThis?.document?.body;return c?r.createPortal(ok.jsx(hk.div,{...i,ref:t}),c):null});XP.displayName="Portal";var ZP=e=>{const{present:t,children:r}=e,n=function(e){const[t,r]=s.useState(),n=s.useRef(null),i=s.useRef(e),o=s.useRef("none"),a=e?"mounted":"unmounted",[c,d]=function(e,t){return s.useReducer((e,r)=>t[e][r]??e,e)}(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return s.useEffect(()=>{const e=eR(n.current);o.current="mounted"===c?e:"none"},[c]),Ak(()=>{const t=n.current,r=i.current;if(r!==e){const n=o.current,s=eR(t);if(e)d("MOUNT");else if("none"===s||"none"===t?.display)d("UNMOUNT");else{d(r&&n!==s?"ANIMATION_OUT":"UNMOUNT")}i.current=e}},[e,d]),Ak(()=>{if(t){let e;const r=t.ownerDocument.defaultView??window,s=s=>{const o=eR(n.current).includes(s.animationName);if(s.target===t&&o&&(d("ANIMATION_END"),!i.current)){const n=t.style.animationFillMode;t.style.animationFillMode="forwards",e=r.setTimeout(()=>{"forwards"===t.style.animationFillMode&&(t.style.animationFillMode=n)})}},a=e=>{e.target===t&&(o.current=eR(n.current))};return t.addEventListener("animationstart",a),t.addEventListener("animationcancel",s),t.addEventListener("animationend",s),()=>{r.clearTimeout(e),t.removeEventListener("animationstart",a),t.removeEventListener("animationcancel",s),t.removeEventListener("animationend",s)}}d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:s.useCallback(e=>{n.current=e?getComputedStyle(e):null,r(e)},[])}}(t),i="function"==typeof r?r({present:n.isPresent}):s.Children.only(r),o=rk(n.ref,function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(i));return"function"==typeof r||n.isPresent?s.cloneElement(i,{ref:o}):null};function eR(e){return e?.animationName||"none"}ZP.displayName="Presence";var tR=s[" useInsertionEffect ".trim().toString()]||Ak;function rR({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){const[i,o,a]=function({defaultProp:e,onChange:t}){const[r,n]=s.useState(e),i=s.useRef(r),o=s.useRef(t);return tR(()=>{o.current=t},[t]),s.useEffect(()=>{i.current!==r&&(o.current?.(r),i.current=r)},[r,i]),[r,n,o]}({defaultProp:t,onChange:r}),c=void 0!==e,d=c?e:i;{const t=s.useRef(void 0!==e);s.useEffect(()=>{const e=t.current;if(e!==c){const t=e?"controlled":"uncontrolled",r=c?"controlled":"uncontrolled";console.warn(`${n} is changing from ${t} to ${r}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`)}t.current=c},[c,n])}const l=s.useCallback(t=>{if(c){const r=function(e){return"function"==typeof e}(t)?t(e):t;r!==e&&a.current?.(r)}else o(t)},[c,e,o,a]);return[d,l]}var nR=new WeakMap,iR=new WeakMap,sR={},oR=0,aR=function(e){return e&&(e.host||aR(e.parentNode))},cR=function(e,t,r,n){var i=function(e,t){return t.map(function(t){if(e.contains(t))return t;var r=aR(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(e){return Boolean(e)})}(t,Array.isArray(e)?e:[e]);sR[r]||(sR[r]=new WeakMap);var s=sR[r],o=[],a=new Set,c=new Set(i),d=function(e){e&&!a.has(e)&&(a.add(e),d(e.parentNode))};i.forEach(d);var l=function(e){e&&!c.has(e)&&Array.prototype.forEach.call(e.children,function(e){if(a.has(e))l(e);else try{var t=e.getAttribute(n),i=null!==t&&"false"!==t,c=(nR.get(e)||0)+1,d=(s.get(e)||0)+1;nR.set(e,c),s.set(e,d),o.push(e),1===c&&i&&iR.set(e,!0),1===d&&e.setAttribute(r,"true"),i||e.setAttribute(n,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}})};return l(t),a.clear(),oR++,function(){o.forEach(function(e){var t=nR.get(e)-1,i=s.get(e)-1;nR.set(e,t),s.set(e,i),t||(iR.has(e)||e.removeAttribute(n),iR.delete(e)),i||e.removeAttribute(r)}),--oR||(nR=new WeakMap,nR=new WeakMap,iR=new WeakMap,sR={})}},dR=function(e,t,r){void 0===r&&(r="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),i=function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live], script"))),cR(n,i,r,"aria-hidden")):function(){return null}},lR="right-scroll-bar-position",uR="width-before-scroll-bar";function pR(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var hR="undefined"!=typeof window?s.useLayoutEffect:s.useEffect,fR=new WeakMap;function mR(e,r){var n,i,s,o=(n=null,i=function(t){return e.forEach(function(e){return pR(e,t)})},s=t.useState(function(){return{value:n,callback:i,facade:{get current(){return s.value},set current(e){var t=s.value;t!==e&&(s.value=e,s.callback(e,t))}}}})[0],s.callback=i,s.facade);return hR(function(){var t=fR.get(o);if(t){var r=new Set(t),n=new Set(e),i=o.current;r.forEach(function(e){n.has(e)||pR(e,null)}),n.forEach(function(e){r.has(e)||pR(e,i)})}fR.set(o,e)},[e]),o}function gR(e){return e}var vR=function(e){var t=e.sideCar,r=$S(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return s.createElement(n,VS({},r))};vR.isSideCarExport=!0;var bR=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=gR);var r=[],n=!1;return{read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(e){var i=t(e,n);return r.push(i),function(){r=r.filter(function(e){return e!==i})}},assignSyncMedium:function(e){for(n=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){n=!0;var t=[];if(r.length){var i=r;r=[],i.forEach(e),t=r}var s=function(){var r=t;t=[],r.forEach(e)},o=function(){return Promise.resolve().then(s)};o(),r={push:function(e){t.push(e),o()},filter:function(e){return t=t.filter(e),r}}}}}(null);return t.options=VS({async:!0,ssr:!1},e),t}(),yR=function(){},_R=s.forwardRef(function(e,t){var r=s.useRef(null),n=s.useState({onScrollCapture:yR,onWheelCapture:yR,onTouchMoveCapture:yR}),i=n[0],o=n[1],a=e.forwardProps,c=e.children,d=e.className,l=e.removeScrollBar,u=e.enabled,p=e.shards,h=e.sideCar,f=e.noRelative,m=e.noIsolation,g=e.inert,v=e.allowPinchZoom,b=e.as,y=void 0===b?"div":b,_=e.gapMode,w=$S(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=h,C=mR([r,t]),k=VS(VS({},w),i);return s.createElement(s.Fragment,null,u&&s.createElement(S,{sideCar:bR,removeScrollBar:l,shards:p,noRelative:f,noIsolation:m,inert:g,setCallbacks:o,allowPinchZoom:!!v,lockRef:r,gapMode:_}),a?s.cloneElement(s.Children.only(c),VS(VS({},k),{ref:C})):s.createElement(y,VS({},k,{className:d,ref:C}),c))});_R.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},_R.classNames={fullWidth:uR,zeroRight:lR};function wR(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=function(){if("undefined"!=typeof __webpack_nonce__)return __webpack_nonce__}();return t&&e.setAttribute("nonce",t),e}var SR=function(){var e=0,t=null;return{add:function(r){var n,i;0==e&&(t=wR())&&(i=r,(n=t).styleSheet?n.styleSheet.cssText=i:n.appendChild(document.createTextNode(i)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},CR=function(){var e,t=(e=SR(),function(t,r){s.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])});return function(e){var r=e.styles,n=e.dynamic;return t(r,n),null}},kR={left:0,top:0,right:0,gap:0},TR=function(e){return parseInt(e||"",10)||0},PR=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return kR;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],n=t["padding"===e?"paddingTop":"marginTop"],i=t["padding"===e?"paddingRight":"marginRight"];return[TR(r),TR(n),TR(i)]}(e),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},RR=CR(),ER="data-scroll-locked",OR=function(e,t,r,n){var i=e.left,s=e.top,o=e.right,a=e.gap;return void 0===r&&(r="margin"),"\n .".concat("with-scroll-bars-hidden"," {\n overflow: hidden ").concat(n,";\n padding-right: ").concat(a,"px ").concat(n,";\n }\n body[").concat(ER,"] {\n overflow: hidden ").concat(n,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(n,";"),"margin"===r&&"\n padding-left: ".concat(i,"px;\n padding-top: ").concat(s,"px;\n padding-right: ").concat(o,"px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(a,"px ").concat(n,";\n "),"padding"===r&&"padding-right: ".concat(a,"px ").concat(n,";")].filter(Boolean).join(""),"\n }\n \n .").concat(lR," {\n right: ").concat(a,"px ").concat(n,";\n }\n \n .").concat(uR," {\n margin-right: ").concat(a,"px ").concat(n,";\n }\n \n .").concat(lR," .").concat(lR," {\n right: 0 ").concat(n,";\n }\n \n .").concat(uR," .").concat(uR," {\n margin-right: 0 ").concat(n,";\n }\n \n body[").concat(ER,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(a,"px;\n }\n")},xR=function(){var e=parseInt(document.body.getAttribute(ER)||"0",10);return isFinite(e)?e:0},IR=function(e){var t=e.noRelative,r=e.noImportant,n=e.gapMode,i=void 0===n?"margin":n;s.useEffect(function(){return document.body.setAttribute(ER,(xR()+1).toString()),function(){var e=xR()-1;e<=0?document.body.removeAttribute(ER):document.body.setAttribute(ER,e.toString())}},[]);var o=s.useMemo(function(){return PR(i)},[i]);return s.createElement(RR,{styles:OR(o,!t,i,r?"":"!important")})},DR=!1;if("undefined"!=typeof window)try{var MR=Object.defineProperty({},"passive",{get:function(){return DR=!0,!0}});window.addEventListener("test",MR,MR),window.removeEventListener("test",MR,MR)}catch(qE){DR=!1}var jR=!!DR&&{passive:!1},AR=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},LR=function(e,t){var r=t.ownerDocument,n=t;do{if("undefined"!=typeof ShadowRoot&&n instanceof ShadowRoot&&(n=n.host),NR(e,n)){var i=FR(e,n);if(i[1]>i[2])return!0}n=n.parentNode}while(n&&n!==r.body);return!1},NR=function(e,t){return"v"===e?function(e){return AR(e,"overflowY")}(t):function(e){return AR(e,"overflowX")}(t)},FR=function(e,t){return"v"===e?function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]}(t):function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]}(t)},BR=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},zR=function(e){return[e.deltaX,e.deltaY]},UR=function(e){return e&&"current"in e?e.current:e},VR=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},$R=0,GR=[];function qR(e){for(var t=null;null!==e;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var HR,WR=(HR=function(e){var t=s.useRef([]),r=s.useRef([0,0]),n=s.useRef(),i=s.useState($R++)[0],o=s.useState(CR)[0],a=s.useRef(e);s.useEffect(function(){a.current=e},[e]),s.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var t=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(UR),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),t.forEach(function(e){return e.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=s.useCallback(function(e,t){if("touches"in e&&2===e.touches.length||"wheel"===e.type&&e.ctrlKey)return!a.current.allowPinchZoom;var i,s=BR(e),o=r.current,c="deltaX"in e?e.deltaX:o[0]-s[0],d="deltaY"in e?e.deltaY:o[1]-s[1],l=e.target,u=Math.abs(c)>Math.abs(d)?"h":"v";if("touches"in e&&"h"===u&&"range"===l.type)return!1;var p=LR(u,l);if(!p)return!0;if(p?i=u:(i="v"===u?"h":"v",p=LR(u,l)),!p)return!1;if(!n.current&&"changedTouches"in e&&(c||d)&&(n.current=i),!i)return!0;var h=n.current||i;return function(e,t,r,n){var i=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),s=i*n,o=r.target,a=t.contains(o),c=!1,d=s>0,l=0,u=0;do{if(!o)break;var p=FR(e,o),h=p[0],f=p[1]-p[2]-i*h;(h||f)&&NR(e,o)&&(l+=f,u+=h);var m=o.parentNode;o=m&&m.nodeType===Node.DOCUMENT_FRAGMENT_NODE?m.host:m}while(!a&&o!==document.body||a&&(t.contains(o)||t===o));return(d&&Math.abs(l)<1||!d&&Math.abs(u)<1)&&(c=!0),c}(h,t,e,"h"===h?c:d)},[]),d=s.useCallback(function(e){var r=e;if(GR.length&&GR[GR.length-1]===o){var n="deltaY"in r?zR(r):BR(r),i=t.current.filter(function(e){return e.name===r.type&&(e.target===r.target||r.target===e.shadowParent)&&(t=e.delta,i=n,t[0]===i[0]&&t[1]===i[1]);var t,i})[0];if(i&&i.should)r.cancelable&&r.preventDefault();else if(!i){var s=(a.current.shards||[]).map(UR).filter(Boolean).filter(function(e){return e.contains(r.target)});(s.length>0?c(r,s[0]):!a.current.noIsolation)&&r.cancelable&&r.preventDefault()}}},[]),l=s.useCallback(function(e,r,n,i){var s={name:e,delta:r,target:n,should:i,shadowParent:qR(n)};t.current.push(s),setTimeout(function(){t.current=t.current.filter(function(e){return e!==s})},1)},[]),u=s.useCallback(function(e){r.current=BR(e),n.current=void 0},[]),p=s.useCallback(function(t){l(t.type,zR(t),t.target,c(t,e.lockRef.current))},[]),h=s.useCallback(function(t){l(t.type,BR(t),t.target,c(t,e.lockRef.current))},[]);s.useEffect(function(){return GR.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:h}),document.addEventListener("wheel",d,jR),document.addEventListener("touchmove",d,jR),document.addEventListener("touchstart",u,jR),function(){GR=GR.filter(function(e){return e!==o}),document.removeEventListener("wheel",d,jR),document.removeEventListener("touchmove",d,jR),document.removeEventListener("touchstart",u,jR)}},[]);var f=e.removeScrollBar,m=e.inert;return s.createElement(s.Fragment,null,m?s.createElement(o,{styles:VR(i)}):null,f?s.createElement(IR,{noRelative:e.noRelative,gapMode:e.gapMode}):null)},bR.useMedium(HR),vR),JR=s.forwardRef(function(e,t){return s.createElement(_R,VS({},e,{ref:t,sideCar:WR}))});JR.classNames=_R.classNames;var KR="Popover",[QR,YR]=ak(KR,[DP]),XR=DP(),[ZR,eE]=QR(KR),tE=e=>{const{__scopePopover:t,children:r,open:n,defaultOpen:i,onOpenChange:o,modal:a=!1}=e,c=XR(t),d=s.useRef(null),[l,u]=s.useState(!1),[p,h]=rR({prop:n,defaultProp:i??!1,onChange:o,caller:KR});return ok.jsx(JP,{...c,children:ok.jsx(ZR,{scope:t,contentId:Fk(),triggerRef:d,open:p,onOpenChange:h,onOpenToggle:s.useCallback(()=>h(e=>!e),[h]),hasCustomAnchor:l,onCustomAnchorAdd:s.useCallback(()=>u(!0),[]),onCustomAnchorRemove:s.useCallback(()=>u(!1),[]),modal:a,children:r})})};tE.displayName=KR;var rE="PopoverAnchor";s.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,i=eE(rE,r),o=XR(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:c}=i;return s.useEffect(()=>(a(),()=>c()),[a,c]),ok.jsx(KP,{...o,...n,ref:t})}).displayName=rE;var nE="PopoverTrigger",iE=s.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,i=eE(nE,r),s=XR(r),o=rk(t,i.triggerRef),a=ok.jsx(hk.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":gE(i.open),...n,ref:o,onClick:ZC(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:ok.jsx(KP,{asChild:!0,...s,children:a})});iE.displayName=nE;var sE="PopoverPortal",[oE,aE]=QR(sE,{forceMount:void 0}),cE=e=>{const{__scopePopover:t,forceMount:r,children:n,container:i}=e,s=eE(sE,t);return ok.jsx(oE,{scope:t,forceMount:r,children:ok.jsx(ZP,{present:r||s.open,children:ok.jsx(XP,{asChild:!0,container:i,children:n})})})};cE.displayName=sE;var dE="PopoverContent",lE=s.forwardRef((e,t)=>{const r=aE(dE,e.__scopePopover),{forceMount:n=r.forceMount,...i}=e,s=eE(dE,e.__scopePopover);return ok.jsx(ZP,{present:n||s.open,children:s.modal?ok.jsx(pE,{...i,ref:t}):ok.jsx(hE,{...i,ref:t})})});lE.displayName=dE;var uE=dk("PopoverContent.RemoveScroll"),pE=s.forwardRef((e,t)=>{const r=eE(dE,e.__scopePopover),n=s.useRef(null),i=rk(t,n),o=s.useRef(!1);return s.useEffect(()=>{const e=n.current;if(e)return dR(e)},[]),ok.jsx(JR,{as:uE,allowPinchZoom:!0,children:ok.jsx(fE,{...e,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ZC(e.onCloseAutoFocus,e=>{e.preventDefault(),o.current||r.triggerRef.current?.focus()}),onPointerDownOutside:ZC(e.onPointerDownOutside,e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey,n=2===t.button||r;o.current=n},{checkForDefaultPrevented:!1}),onFocusOutside:ZC(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})}),hE=s.forwardRef((e,t)=>{const r=eE(dE,e.__scopePopover),n=s.useRef(!1),i=s.useRef(!1);return ok.jsx(fE,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(n.current||r.triggerRef.current?.focus(),t.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(n.current=!0,"pointerdown"===t.detail.originalEvent.type&&(i.current=!0));const s=t.target,o=r.triggerRef.current?.contains(s);o&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&i.current&&t.preventDefault()}})}),fE=s.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:u,...p}=e,h=eE(dE,r),f=XR(r);return s.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??kk()),document.body.insertAdjacentElement("beforeend",e[1]??kk()),Ck++,()=>{1===Ck&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Ck--}},[]),ok.jsx(Ek,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:ok.jsx(_k,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1),children:ok.jsx(QP,{"data-state":gE(h.open),role:"dialog",id:h.contentId,...f,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),mE="PopoverClose";s.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,i=eE(mE,r);return ok.jsx(hk.button,{type:"button",...n,ref:t,onClick:ZC(e.onClick,()=>i.onOpenChange(!1))})}).displayName=mE;function gE(e){return e?"open":"closed"}s.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,i=XR(r);return ok.jsx(YP,{...i,...n,ref:t})}).displayName="PopoverArrow";var vE=cE,bE=lE;const yE=tE,_E=iE,wE=s.forwardRef((e,t)=>{var{style:r,align:n="center",sideOffset:i=4}=e,o=$S(e,["style","align","sideOffset"]);return s.createElement(vE,null,s.createElement(bE,Object.assign({ref:t,align:n,sideOffset:i,style:Object.assign({width:"200px",backgroundColor:"#fff",border:"1px solid #e5e5e5",borderRadius:"0.375rem",boxShadow:"0 1px 2px 0 rgb(0 0 0 / 0.05)",color:"#333",fontSize:"14px",lineHeight:"1.5",padding:"16px",zIndex:50,outline:"none"},r)},o)))});wE.displayName=bE.displayName;const SE=s.createContext({}),CE=s.createContext({}),kE=()=>{const e=s.useContext(SE),t=s.useContext(CE);if(!t)throw new Error("useGridCell must be used within a GridCell");return Object.assign(Object.assign({},e),t)},TE=s.createContext({}),PE=e=>{const{children:t}=e,r=$S(e,["children"]),[n,i]=s.useState(!1);return s.createElement(TE.Provider,{value:{open:n,setOpen:i}},s.createElement(yE,Object.assign({},r,{open:n,onOpenChange:i}),t))},RE=s.forwardRef((e,t)=>{var{children:r,style:n}=e,i=$S(e,["children","style"]);return s.createElement(wE,Object.assign({ref:t,style:Object.assign({display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minWidth:"180px",maxWidth:"300px",maxHeight:"100vh",overflowY:"auto",padding:0},n)},i),r)});RE.displayName="ParticipantMenuContent";const EE=s.forwardRef((e,t)=>{var{children:r,style:n}=e,i=$S(e,["children","style"]);return s.createElement(_E,Object.assign({ref:t,style:Object.assign({position:"absolute",top:"10px",right:"20px",textDecoration:"none",whiteSpace:"nowrap",border:"none",cursor:"pointer"},n)},i),r)});EE.displayName=_E.displayName;const OE=s.forwardRef((e,t)=>{var r,{children:n,style:i,participantAction:o}=e,a=$S(e,["children","style","participantAction"]);const{participant:c,setOpen:d,maximizedParticipant:l,setMaximizedParticipant:u,setFloatingParticipant:p,floatingParticipant:h}=(()=>{const e=s.useContext(TE),t=kE();if(!e)throw new Error("useParticipantMenu must be used within a ParticipantMenu");return Object.assign(Object.assign({},e),t)})(),f=null===(r=s.useContext(US))||void 0===r?void 0:r.getGrid(),{spotlightedParticipants:m}=jC(),g=m.find(e=>e.id===c.id),v=(null==l?void 0:l.id)===c.id,b=(null==h?void 0:h.id)===c.id;let y;switch(o){case"maximize":y=()=>{u(v?null:c),d(!1)};break;case"spotlight":y=()=>{g?null==f||f.removeSpotlight(c.id):null==f||f.spotlightParticipant(c.id),d(!1)};break;case"float":y=()=>{p(b?null:c),d(!1)}}return s.createElement("button",Object.assign({ref:t,role:"menuitem",tabIndex:-1,onClick:null!=y?y:a.onClick,style:Object.assign({alignItems:"stretch",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",height:"40px",lineHeight:"40px",minWidth:"140px",padding:"0 12px",textAlign:"left",textDecoration:"none",whiteSpace:"nowrap",width:"100%"},i)},a),n)});function xE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("g",null,s.createElement("circle",{cx:"6",cy:"12",r:"2"}),s.createElement("circle",{cx:"12",cy:"12",r:"2"}),s.createElement("circle",{cx:"18",cy:"12",r:"2"})))}function IE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m13.875 3c0 .62132.5037 1.125 1.125 1.125h3.284l-4.0795 4.0795c-.4393.43934-.4393 1.15166 0 1.591.4393.4393 1.1517.4393 1.591 0l4.0795-4.07951v3.28401c0 .62132.5037 1.125 1.125 1.125s1.125-.50368 1.125-1.125v-6c0-.15254-.0304-.29799-.0854-.43063-.0536-.12968-.1326-.25135-.2368-.35749l-.0147-.01469c-.203-.19928-.4812-.32219-.7881-.32219h-6c-.6213 0-1.125.50368-1.125 1.125zm-9.75 12c0-.6213-.50368-1.125-1.125-1.125s-1.125.5037-1.125 1.125v6c0 .3069.12291.5851.32219.7881.00486.005.00975.0099.01469.0147.10614.1042.22781.1832.35749.2368.13264.055.27809.0854.43063.0854h6c.62132 0 1.125-.5037 1.125-1.125s-.50368-1.125-1.125-1.125h-3.28401l4.07951-4.0795c.4393-.4393.4393-1.1517 0-1.591-.43934-.4393-1.15166-.4393-1.591 0l-4.0795 4.0795z"}))}function DE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m15.241.146691c-.1011-.1955882-.3809-.1955879-.482 0l-1.1063 2.139639c-.0258.04991-.0665.09058-.1164.11639l-2.1396 1.10629c-.1956.10113-.1956.38085 0 .48198l2.1396 1.10629c.0499.02581.0906.06648.1164.11639l1.1063 2.13964c.1011.19559.3809.19559.482 0l1.1063-2.13964c.0258-.04991.0665-.09058.1164-.11639l2.1396-1.10629c.1956-.10113.1956-.38085 0-.48198l-2.1396-1.10629c-.0499-.02581-.0906-.06648-.1164-.11639zm-13.741 2.900259v14.67495c0 .0511.00116.1018.00345.1523-.00229.0418-.00345.0837-.00345.1258 0 .5674.21005 1.1103.59339 1.6103.24265.3472.55042.6455.90566.8773 1.61225 1.213 4.36988 2.0124 7.50095 2.0124 4.3315 0 7.9484-1.53 8.8068-3.5681.0651-.1472.1148-.3024.1455-.4658.0315-.1532.0477-.3087.0477-.4661 0-.6032-.2374-1.1788-.668-1.7045-.1377-.1975-.2995-.4017-.4877-.6127l-14.22219-13.74809c-.28845-.27884-.67396-.43471-1.07516-.43471-.85436 0-1.54695.69259-1.54695 1.54695zm19.2646 4.59631c.0988-.19101.372-.19101.4708 0l.8546 1.65303c.0253.04874.065.08846.1137.11366l1.653.85465c.1911.0988.1911.372 0 .4708l-1.653.8546c-.0487.0253-.0884.065-.1137.1137l-.8546 1.653c-.0988.1911-.372.1911-.4708 0l-.8546-1.653c-.0253-.0487-.065-.0884-.1137-.1137l-1.653-.8546c-.1911-.0988-.1911-.372 0-.4708l1.653-.85465c.0487-.0252.0884-.06492.1137-.11366zm-3.2651 10.35684c0 .0769-.1144.6851-1.5305 1.3931-1.2964.6482-3.2274 1.1069-5.4695 1.1069s-4.17308-.4587-5.46952-1.1069c-1.41607-.708-1.53047-1.3162-1.53047-1.3931 0-.077.1144-.6851 1.53047-1.3932 1.29644-.6482 3.22742-1.1068 5.46952-1.1068s4.1731.4586 5.4695 1.1068c1.4161.7081 1.5305 1.3162 1.5305 1.3932z"}))}function ME(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm1.875 19.5c0-.6213.5037-1.125 1.125-1.125h3.284l-5.5795-5.5795c-.4393-.4393-.4393-1.1517 0-1.591s1.1517-.4393 1.591 0l5.5795 5.5795v-3.284c0-.6213.5037-1.125 1.125-1.125s1.125.5037 1.125 1.125v6c0 .308-.1238.5872-.3244.7903-.0033.0034-.0067.0068-.0101.0102-.1067.1054-.2292.1851-.3599.2391-.1326.055-.2781.0854-.4306.0854h-6c-.6213 0-1.125-.5037-1.125-1.125z"}))}function jE(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm8.625 12c0 .6213-.5037 1.125-1.125 1.125h-3.284l5.5795 5.5795c.4393.4393.4393 1.1517 0 1.591s-1.1517.4393-1.591 0l-5.5795-5.5795v3.284c0 .6213-.5037 1.125-1.125 1.125s-1.125-.5037-1.125-1.125v-6c0-.3081.1238-.5872.3244-.7904.0034-.0034.0068-.0068.0102-.0102.1067-.1053.2292-.185.3598-.239.1326-.055.2781-.0854.4306-.0854h6c.6213 0 1.125.5037 1.125 1.125z"}))}function AE({participant:e}){const{spotlightedParticipants:t}=jC(),r=t.find(t=>t.id===e.id),{isHovered:n,maximizedParticipant:i,floatingParticipant:o}=kE(),a=(null==i?void 0:i.id)===e.id,c=(null==o?void 0:o.id)===e.id;return n?s.createElement(PE,null,s.createElement(EE,{style:{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"#fff",borderRadius:"6px",padding:"4px"}},s.createElement(xE,{height:20,width:20,transform:"rotate(90)"})),s.createElement(RE,null,e.isLocalClient?s.createElement(OE,{participantAction:"float",style:{display:"flex",alignItems:"center",gap:"10px"}},c?s.createElement(s.Fragment,null,s.createElement(jE,{height:16,width:16}),"Move to grid"):s.createElement(s.Fragment,null,s.createElement(ME,{height:16,width:16}),"Pop out")):null,s.createElement(OE,{participantAction:"maximize",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(IE,{height:16,width:16}),a?"Minimize":"Maximize"),s.createElement(OE,{participantAction:"spotlight",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(DE,{height:16,width:16}),r?"Remove spotlight":"Spotlight"))):null}OE.displayName="ParticipantMenuItem";const LE=s.forwardRef(({className:e,participant:t,children:r},n)=>{const[i,o]=s.useState(!1),a=s.useCallback(()=>{o(!0)},[]),c=s.useCallback(()=>{o(!1)},[]);return s.createElement(CE.Provider,{value:{participant:t,isHovered:i}},s.createElement("div",{ref:n,className:e,onMouseEnter:a,onMouseLeave:c,style:{height:"100%",width:"100%"}},r))});LE.displayName="GridCell";const NE=s.forwardRef((e,t)=>{var{stream:r,style:n}=e,i=$S(e,["stream","style"]);const o=s.useRef(null),{onSetClientAspectRatio:a,clientAspectRatios:c,participant:d,isConstrained:l}=kE();if(!d)return null;const u=c[d.id];s.useImperativeHandle(t,()=>o.current);const p=s.useCallback(()=>{const e=o.current&&o.current.captureAspectRatio();e&&e!==u&&d.id&&a({aspectRatio:e,clientId:d.id})},[c,d.id,a]),h=r||d.stream;return h&&d.isVideoEnabled?s.createElement(qS,Object.assign({ref:o,style:Object.assign(Object.assign({borderRadius:l?0:"8px"},l?{objectFit:"cover"}:{}),n),muted:d.isLocalClient},i,{stream:h,onVideoResize:p})):s.createElement(XC,{isSmallCell:!1,displayName:(null==d?void 0:d.displayName)||"Guest",withRoundedCorners:!0,muted:d.isLocalClient,stream:d.stream})});function FE({cellView:e,enableParticipantMenu:t,render:r}){const n=null==e?void 0:e.client;if(n)return"video"===e.type?s.createElement(LE,{participant:n},s.createElement(s.Fragment,null,r?r({participant:n}):s.createElement(s.Fragment,null,s.createElement(NE,null),t?s.createElement(AE,{participant:n}):null))):void 0}return NE.displayName="GridVideoView",e.GridCell=LE,e.GridVideoView=NE,e.ParticipantMenu=PE,e.ParticipantMenuContent=RE,e.ParticipantMenuItem=OE,e.ParticipantMenuTrigger=EE,e.VideoGrid=function({renderParticipant:e,renderFloatingParticipant:t,stageParticipantLimit:r,gridGap:n,videoGridGap:i,enableSubgrid:o,enableParticipantMenu:a,enableConstrainedGrid:c}){const d=s.useRef(null),{containerFrame:l,cellViewsFloating:u,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,videoStage:g,setContainerBounds:v,setClientAspectRatios:b,maximizedParticipant:y,setMaximizedParticipant:_,isConstrained:w,floatingParticipant:S,setFloatingParticipant:C}=function({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r=12,gridGap:n=8,videoGridGap:i=8,enableSubgrid:o=!0,enableConstrainedGrid:a=!0}={}){const[c,d]=s.useState({width:0,height:0}),[l,u]=s.useState(!1),[p,h]=s.useState({}),[f,m]=s.useState(null),[g,v]=s.useState(null),{clientViewsInGrid:b,clientViewsInPresentationGrid:y,clientViewsInSubgrid:_,floatingClientView:w}=jC({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r,enableSubgrid:o,maximizedParticipant:f,floatingParticipant:g,isConstrained:!!a&&!!l}),S=s.useMemo(()=>w?[MC({client:w,aspectRatio:p[w.id],avatarSize:0,cellPaddings:{top:0,right:0}})]:[],[w,p]),C=s.useMemo(()=>b.map(e=>MC({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})),[b,p]),k=s.useMemo(()=>y.map(e=>MC({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})),[y,p]),T=s.useMemo(()=>_.map(e=>MC({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0},isSubgrid:!0})),[_,p]),P=s.useMemo(()=>XS(c),[c]);s.useEffect(()=>{a&&u(c.width<500||c.height<500)},[c,a]);const R=s.useMemo(()=>DC({floatingVideo:S[0],frame:P,gridGap:n,isConstrained:l,roomBounds:P.bounds,videos:C,videoGridGap:i,presentationVideos:k,subgridVideos:T}),[P,S,C,k,T,n,i]);return{containerFrame:P,cellViewsFloating:S,cellViewsVideoGrid:C,cellViewsInPresentationGrid:k,cellViewsInSubgrid:T,clientAspectRatios:p,videoStage:R,setContainerBounds:d,setClientAspectRatios:h,maximizedParticipant:f,setMaximizedParticipant:m,floatingParticipant:g,setFloatingParticipant:v,isConstrained:l}}({activeVideosSubgridTrigger:12,stageParticipantLimit:r,gridGap:n,videoGridGap:i,enableSubgrid:o,enableConstrainedGrid:c}),k=s.useCallback(({aspectRatio:e,clientId:t})=>{b(r=>Object.assign(Object.assign({},r),{[t]:e}))},[b]),T=s.useMemo(()=>FE(Object.assign({cellView:u[0],enableParticipantMenu:a},t?{render:({participant:e})=>t({participant:e})}:{})),[u]),P=s.useMemo(()=>h.map(t=>FE(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))),[h]),R=s.useMemo(()=>p.map(t=>FE(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))),[p]),E=s.useMemo(()=>f.map(e=>FE({cellView:e,enableParticipantMenu:a})),[f]);return s.useEffect(()=>{if(!d.current)return;const e=new ResizeObserver(Pb(()=>{var e,t,r,n;v({width:null!==(t=null===(e=d.current)||void 0===e?void 0:e.clientWidth)&&void 0!==t?t:640,height:null!==(n=null===(r=d.current)||void 0===r?void 0:r.clientHeight)&&void 0!==n?n:480})},{delay:60,edges:!1}));return e.observe(d.current),()=>{e.disconnect()}},[]),s.createElement(SE.Provider,{value:{onSetClientAspectRatio:k,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,maximizedParticipant:y,setMaximizedParticipant:_,floatingParticipant:S,setFloatingParticipant:C,isConstrained:w}},s.createElement("div",{ref:d,style:{width:"100%",height:"100%",position:"relative"}},s.createElement(aC,{containerFrame:l,floatingContent:T,layoutVideoStage:g,presentationGridContent:P,gridContent:R,subgridContent:E})))},e.VideoView=qS,e.WherebyProvider=function({children:e}){const t=s.useMemo(()=>new zS,[]);return s.useEffect(()=>()=>{t.destroy()},[t]),s.createElement(US.Provider,{value:t},e)},e.useLocalMedia=function(e={audio:!0,video:!0}){var t;const r=null===(t=s.useContext(US))||void 0===t?void 0:t.getLocalMedia(),[n,i]=s.useState(()=>JS);if(!r)throw new Error("WherebyClient is not initialized. Please wrap your component with WherebyProvider.");return s.useEffect(()=>{r.startMedia(e);const t=r.subscribe(e=>{i(t=>Object.assign(Object.assign({},t),e))});return()=>{t(),r.stopMedia()}},[]),{state:n,actions:{setCameraDevice:s.useCallback(e=>r.setCameraDevice(e),[r]),setMicrophoneDevice:s.useCallback(e=>r.setMicrophoneDevice(e),[r]),setSpeakerDevice:s.useCallback(e=>r.setSpeakerDevice(e),[r]),toggleCameraEnabled:s.useCallback(e=>r.toggleCamera(e),[r]),toggleMicrophoneEnabled:s.useCallback(e=>r.toggleMicrophone(e),[r]),toggleLowDataModeEnabled:s.useCallback(e=>r.toggleLowDataMode(e),[r])}}},e.useRoomConnection=function(e,t=WS){var r;const n=null===(r=s.useContext(US))||void 0===r?void 0:r.getRoomConnection(),[i,o]=s.useState(()=>HS);if(!n)throw new Error("WherebyClient is not initialized. Please wrap your component with WherebyProvider.");const a=s.useMemo(()=>{const r=new URL(e),n=new URLSearchParams(r.search),i=t.roomKey||n.get("roomKey");return{displayName:t.displayName||"Guest",localMediaOptions:t.localMedia?void 0:t.localMediaOptions,roomKey:i,roomUrl:e,userAgent:"browser-sdk:3.14.11",externalId:t.externalId||null}},[e,t]);s.useEffect(()=>{const e=n.subscribe(e=>{o(t=>Object.assign(Object.assign({},t),e))}),t=n.getNotificationsEventEmitter();return o(e=>Object.assign(Object.assign({},e),{events:t})),()=>{e(),n.leaveRoom()}},[]);const c=s.useCallback(()=>(n.initialize(a),n.joinRoom()),[n]),d=s.useCallback(e=>n.sendChatMessage(e),[n]),l=s.useCallback(()=>n.knock(),[n]),u=s.useCallback(e=>n.setDisplayName(e),[n]),p=s.useCallback(e=>n.toggleCamera(e),[n]),h=s.useCallback(e=>n.toggleMicrophone(e),[n]),f=s.useCallback(e=>n.toggleLowDataMode(e),[n]),m=s.useCallback(e=>n.toggleRaiseHand(e),[n]),g=s.useCallback(e=>n.askToSpeak(e),[n]),v=s.useCallback(e=>n.askToTurnOnCamera(e),[n]),b=s.useCallback(e=>n.acceptWaitingParticipant(e),[n]),y=s.useCallback(e=>n.rejectWaitingParticipant(e),[n]),_=s.useCallback(()=>n.startCloudRecording(),[n]),w=s.useCallback(()=>n.startScreenshare(),[n]),S=s.useCallback(()=>n.stopCloudRecording(),[n]),C=s.useCallback(()=>n.stopScreenshare(),[n]),k=s.useCallback(()=>n.leaveRoom(),[n]),T=s.useCallback(e=>n.lockRoom(e),[n]),P=s.useCallback(e=>n.muteParticipants(e),[n]),R=s.useCallback(e=>n.turnOffParticipantCameras(e),[n]),E=s.useCallback(e=>n.spotlightParticipant(e),[n]),O=s.useCallback(e=>n.removeSpotlight(e),[n]),x=s.useCallback(e=>n.kickParticipant(e),[n]),I=s.useCallback(e=>n.endMeeting(e),[n]),D=s.useCallback(e=>n.joinBreakoutGroup(e),[n]),M=s.useCallback(()=>n.joinBreakoutMainRoom(),[n]),{events:j}=i;return{state:$S(i,["events"]),events:j,actions:{toggleLowDataMode:f,toggleRaiseHand:m,askToSpeak:g,askToTurnOnCamera:v,acceptWaitingParticipant:b,knock:l,joinRoom:c,leaveRoom:k,lockRoom:T,muteParticipants:P,turnOffParticipantCameras:R,kickParticipant:x,endMeeting:I,rejectWaitingParticipant:y,sendChatMessage:d,setDisplayName:u,startCloudRecording:_,startScreenshare:w,stopCloudRecording:S,stopScreenshare:C,toggleCamera:p,toggleMicrophone:h,spotlightParticipant:E,removeSpotlight:O,joinBreakoutGroup:D,joinBreakoutMainRoom:M}}},e}({},React,ReactDOM);